Merge tag android-5.1.0_r1 into AOSP_5.1_MERGE
Change-Id: I2ba98faa26a248f51ef3f67ffa376bb6f10b1ffb
diff --git a/OWNERS b/OWNERS
index 570953a..a0b7b4b 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,14 +1,13 @@
set noparent
-fischman@webrtc.org
henrike@webrtc.org
hta@webrtc.org
+jiayl@webrtc.org
juberti@webrtc.org
mallinath@webrtc.org
perkj@webrtc.org
pthatcher@webrtc.org
sergeyu@chromium.org
tommi@webrtc.org
-wu@webrtc.org
per-file *.isolate=kjellander@webrtc.org
diff --git a/PRESUBMIT.py b/PRESUBMIT.py
index 8e1a2e3..a7b4851 100644
--- a/PRESUBMIT.py
+++ b/PRESUBMIT.py
@@ -24,24 +24,7 @@
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# List of files that should not be committed to
-DO_NOT_SUBMIT_FILES = [
- "talk/media/base/mutedvideocapturer.cc",
- "talk/media/base/videocapturer.cc",
- "talk/media/base/videocapturer.h",
- "talk/media/base/videocapturer_unittest.cc",
- "talk/media/base/videoengine_unittest.h",
- "talk/media/devices/devicemanager.cc",
- "talk/media/webrtc/fakewebrtcvideoengine.h",
- "talk/media/webrtc/fakewebrtcvoiceengine.h",
- "talk/media/webrtc/webrtcexport.h",
- "talk/media/webrtc/webrtcmediaengine.h",
- "talk/media/webrtc/webrtcvideoengine.cc",
- "talk/media/webrtc/webrtcvideoengine.h",
- "talk/media/webrtc/webrtcvideoengine_unittest.cc",
- "talk/media/webrtc/webrtcvoiceengine.cc",
- "talk/media/webrtc/webrtcvoiceengine.h",
- "talk/media/webrtc/webrtcvoiceengine_unittest.cc",
- "talk/session/media/channel.cc"]
+DO_NOT_SUBMIT_FILES = ["talk/media/webrtc/webrtcvideoengine.cc"]
def _LicenseHeader(input_api):
"""Returns the license header regexp."""
diff --git a/app/webrtc/OWNERS b/app/webrtc/OWNERS
index 967930c..1d30ebd 100644
--- a/app/webrtc/OWNERS
+++ b/app/webrtc/OWNERS
@@ -4,4 +4,5 @@
mallinath@google.com
perkj@google.com
ronghuawu@google.com
+tkchin@webrtc.org
tommi@google.com
diff --git a/app/webrtc/audiotrack.cc b/app/webrtc/audiotrack.cc
index a8d45ba..5ac9b96 100644
--- a/app/webrtc/audiotrack.cc
+++ b/app/webrtc/audiotrack.cc
@@ -42,10 +42,10 @@
return kAudioTrackKind;
}
-talk_base::scoped_refptr<AudioTrack> AudioTrack::Create(
+rtc::scoped_refptr<AudioTrack> AudioTrack::Create(
const std::string& id, AudioSourceInterface* source) {
- talk_base::RefCountedObject<AudioTrack>* track =
- new talk_base::RefCountedObject<AudioTrack>(id, source);
+ rtc::RefCountedObject<AudioTrack>* track =
+ new rtc::RefCountedObject<AudioTrack>(id, source);
return track;
}
diff --git a/app/webrtc/audiotrack.h b/app/webrtc/audiotrack.h
index 2f96527..f0094d3 100644
--- a/app/webrtc/audiotrack.h
+++ b/app/webrtc/audiotrack.h
@@ -31,14 +31,14 @@
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/mediastreamtrack.h"
#include "talk/app/webrtc/notifier.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/scoped_ref_ptr.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/scoped_ref_ptr.h"
namespace webrtc {
class AudioTrack : public MediaStreamTrack<AudioTrackInterface> {
public:
- static talk_base::scoped_refptr<AudioTrack> Create(
+ static rtc::scoped_refptr<AudioTrack> Create(
const std::string& id, AudioSourceInterface* source);
// AudioTrackInterface implementation.
@@ -49,7 +49,7 @@
virtual void AddSink(AudioTrackSinkInterface* sink) OVERRIDE {}
virtual void RemoveSink(AudioTrackSinkInterface* sink) OVERRIDE {}
virtual bool GetSignalLevel(int* level) OVERRIDE { return false; }
- virtual talk_base::scoped_refptr<AudioProcessorInterface> GetAudioProcessor()
+ virtual rtc::scoped_refptr<AudioProcessorInterface> GetAudioProcessor()
OVERRIDE { return NULL; }
virtual cricket::AudioRenderer* GetRenderer() OVERRIDE {
return NULL;
@@ -62,7 +62,7 @@
AudioTrack(const std::string& label, AudioSourceInterface* audio_source);
private:
- talk_base::scoped_refptr<AudioSourceInterface> audio_source_;
+ rtc::scoped_refptr<AudioSourceInterface> audio_source_;
};
} // namespace webrtc
diff --git a/app/webrtc/audiotrackrenderer.cc b/app/webrtc/audiotrackrenderer.cc
index 92d3449..c812697 100644
--- a/app/webrtc/audiotrackrenderer.cc
+++ b/app/webrtc/audiotrackrenderer.cc
@@ -26,7 +26,7 @@
*/
#include "talk/app/webrtc/audiotrackrenderer.h"
-#include "talk/base/common.h"
+#include "webrtc/base/common.h"
namespace webrtc {
diff --git a/app/webrtc/audiotrackrenderer.h b/app/webrtc/audiotrackrenderer.h
index a4c58c4..50da097 100644
--- a/app/webrtc/audiotrackrenderer.h
+++ b/app/webrtc/audiotrackrenderer.h
@@ -28,8 +28,8 @@
#ifndef TALK_APP_WEBRTC_AUDIOTRACKRENDERER_H_
#define TALK_APP_WEBRTC_AUDIOTRACKRENDERER_H_
-#include "talk/base/thread.h"
#include "talk/media/base/audiorenderer.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
diff --git a/app/webrtc/datachannel.cc b/app/webrtc/datachannel.cc
index 14caa41..952f5bf 100644
--- a/app/webrtc/datachannel.cc
+++ b/app/webrtc/datachannel.cc
@@ -30,25 +30,69 @@
#include "talk/app/webrtc/mediastreamprovider.h"
#include "talk/app/webrtc/sctputils.h"
-#include "talk/base/logging.h"
-#include "talk/base/refcount.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/refcount.h"
namespace webrtc {
-static size_t kMaxQueuedReceivedDataPackets = 100;
-static size_t kMaxQueuedSendDataPackets = 100;
+static size_t kMaxQueuedReceivedDataBytes = 16 * 1024 * 1024;
+static size_t kMaxQueuedSendDataBytes = 16 * 1024 * 1024;
enum {
MSG_CHANNELREADY,
};
-talk_base::scoped_refptr<DataChannel> DataChannel::Create(
+DataChannel::PacketQueue::PacketQueue() : byte_count_(0) {}
+
+DataChannel::PacketQueue::~PacketQueue() {
+ Clear();
+}
+
+bool DataChannel::PacketQueue::Empty() const {
+ return packets_.empty();
+}
+
+DataBuffer* DataChannel::PacketQueue::Front() {
+ return packets_.front();
+}
+
+void DataChannel::PacketQueue::Pop() {
+ if (packets_.empty()) {
+ return;
+ }
+
+ byte_count_ -= packets_.front()->size();
+ packets_.pop_front();
+}
+
+void DataChannel::PacketQueue::Push(DataBuffer* packet) {
+ byte_count_ += packet->size();
+ packets_.push_back(packet);
+}
+
+void DataChannel::PacketQueue::Clear() {
+ while (!packets_.empty()) {
+ delete packets_.front();
+ packets_.pop_front();
+ }
+ byte_count_ = 0;
+}
+
+void DataChannel::PacketQueue::Swap(PacketQueue* other) {
+ size_t other_byte_count = other->byte_count_;
+ other->byte_count_ = byte_count_;
+ byte_count_ = other_byte_count;
+
+ other->packets_.swap(packets_);
+}
+
+rtc::scoped_refptr<DataChannel> DataChannel::Create(
DataChannelProviderInterface* provider,
cricket::DataChannelType dct,
const std::string& label,
const InternalDataChannelInit& config) {
- talk_base::scoped_refptr<DataChannel> channel(
- new talk_base::RefCountedObject<DataChannel>(provider, dct, label));
+ rtc::scoped_refptr<DataChannel> channel(
+ new rtc::RefCountedObject<DataChannel>(provider, dct, label));
if (!channel->Init(config)) {
return NULL;
}
@@ -107,18 +151,14 @@
// Chrome glue and WebKit) are not wired up properly until after this
// function returns.
if (provider_->ReadyToSendData()) {
- talk_base::Thread::Current()->Post(this, MSG_CHANNELREADY, NULL);
+ rtc::Thread::Current()->Post(this, MSG_CHANNELREADY, NULL);
}
}
return true;
}
-DataChannel::~DataChannel() {
- ClearQueuedReceivedData();
- ClearQueuedSendData();
- ClearQueuedControlData();
-}
+DataChannel::~DataChannel() {}
void DataChannel::RegisterObserver(DataChannelObserver* observer) {
observer_ = observer;
@@ -139,13 +179,7 @@
}
uint64 DataChannel::buffered_amount() const {
- uint64 buffered_amount = 0;
- for (std::deque<DataBuffer*>::const_iterator it = queued_send_data_.begin();
- it != queued_send_data_.end();
- ++it) {
- buffered_amount += (*it)->size();
- }
- return buffered_amount;
+ return queued_send_data_.byte_count();
}
void DataChannel::Close() {
@@ -161,91 +195,35 @@
if (state_ != kOpen) {
return false;
}
+
+ // TODO(jiayl): the spec is unclear about if the remote side should get the
+ // onmessage event. We need to figure out the expected behavior and change the
+ // code accordingly.
+ if (buffer.size() == 0) {
+ return true;
+ }
+
// If the queue is non-empty, we're waiting for SignalReadyToSend,
// so just add to the end of the queue and keep waiting.
- if (!queued_send_data_.empty()) {
- if (!QueueSendData(buffer)) {
- if (data_channel_type_ == cricket::DCT_RTP) {
- return false;
- }
+ if (!queued_send_data_.Empty()) {
+ // Only SCTP DataChannel queues the outgoing data when the transport is
+ // blocked.
+ ASSERT(data_channel_type_ == cricket::DCT_SCTP);
+ if (!QueueSendDataMessage(buffer)) {
Close();
}
return true;
}
- cricket::SendDataResult send_result;
- if (!InternalSendWithoutQueueing(buffer, &send_result)) {
- if (data_channel_type_ == cricket::DCT_RTP) {
- return false;
- }
- if (send_result != cricket::SDR_BLOCK || !QueueSendData(buffer)) {
- Close();
- }
+ bool success = SendDataMessage(buffer);
+ if (data_channel_type_ == cricket::DCT_RTP) {
+ return success;
}
+
+ // Always return true for SCTP DataChannel per the spec.
return true;
}
-void DataChannel::QueueControl(const talk_base::Buffer* buffer) {
- queued_control_data_.push(buffer);
-}
-
-bool DataChannel::SendOpenMessage(const talk_base::Buffer* raw_buffer) {
- ASSERT(data_channel_type_ == cricket::DCT_SCTP &&
- was_ever_writable_ &&
- config_.id >= 0 &&
- !config_.negotiated);
-
- talk_base::scoped_ptr<const talk_base::Buffer> buffer(raw_buffer);
-
- cricket::SendDataParams send_params;
- send_params.ssrc = config_.id;
- send_params.ordered = true;
- send_params.type = cricket::DMT_CONTROL;
-
- cricket::SendDataResult send_result;
- bool retval = provider_->SendData(send_params, *buffer, &send_result);
- if (retval) {
- LOG(LS_INFO) << "Sent OPEN message on channel " << config_.id;
- // Send data as ordered before we receive any mesage from the remote peer
- // to make sure the remote peer will not receive any data before it receives
- // the OPEN message.
- waiting_for_open_ack_ = true;
- } else if (send_result == cricket::SDR_BLOCK) {
- // Link is congested. Queue for later.
- QueueControl(buffer.release());
- } else {
- LOG(LS_ERROR) << "Failed to send OPEN message with result "
- << send_result << " on channel " << config_.id;
- }
- return retval;
-}
-
-bool DataChannel::SendOpenAckMessage(const talk_base::Buffer* raw_buffer) {
- ASSERT(data_channel_type_ == cricket::DCT_SCTP &&
- was_ever_writable_ &&
- config_.id >= 0);
-
- talk_base::scoped_ptr<const talk_base::Buffer> buffer(raw_buffer);
-
- cricket::SendDataParams send_params;
- send_params.ssrc = config_.id;
- send_params.ordered = config_.ordered;
- send_params.type = cricket::DMT_CONTROL;
-
- cricket::SendDataResult send_result;
- bool retval = provider_->SendData(send_params, *buffer, &send_result);
- if (retval) {
- LOG(LS_INFO) << "Sent OPEN_ACK message on channel " << config_.id;
- } else if (send_result == cricket::SDR_BLOCK) {
- // Link is congested. Queue for later.
- QueueControl(buffer.release());
- } else {
- LOG(LS_ERROR) << "Failed to send OPEN_ACK message with result "
- << send_result << " on channel " << config_.id;
- }
- return retval;
-}
-
void DataChannel::SetReceiveSsrc(uint32 receive_ssrc) {
ASSERT(data_channel_type_ == cricket::DCT_RTP);
@@ -262,6 +240,27 @@
DoClose();
}
+void DataChannel::SetSctpSid(int sid) {
+ ASSERT(config_.id < 0 && sid >= 0 && data_channel_type_ == cricket::DCT_SCTP);
+ if (config_.id == sid)
+ return;
+
+ config_.id = sid;
+ provider_->AddSctpDataStream(sid);
+}
+
+void DataChannel::OnTransportChannelCreated() {
+ ASSERT(data_channel_type_ == cricket::DCT_SCTP);
+ if (!connected_to_provider_) {
+ connected_to_provider_ = provider_->ConnectDataChannel(this);
+ }
+ // The sid may have been unassigned when provider_->ConnectDataChannel was
+ // done. So always add the streams even if connected_to_provider_ is true.
+ if (config_.id >= 0) {
+ provider_->AddSctpDataStream(config_.id);
+ }
+}
+
void DataChannel::SetSendSsrc(uint32 send_ssrc) {
ASSERT(data_channel_type_ == cricket::DCT_RTP);
if (send_ssrc_set_) {
@@ -272,7 +271,7 @@
UpdateState();
}
-void DataChannel::OnMessage(talk_base::Message* msg) {
+void DataChannel::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_CHANNELREADY:
OnChannelReady(true);
@@ -289,7 +288,7 @@
void DataChannel::OnDataReceived(cricket::DataChannel* channel,
const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload) {
+ const rtc::Buffer& payload) {
uint32 expected_ssrc =
(data_channel_type_ == cricket::DCT_RTP) ? receive_ssrc_ : config_.id;
if (params.ssrc != expected_ssrc) {
@@ -326,16 +325,22 @@
waiting_for_open_ack_ = false;
bool binary = (params.type == cricket::DMT_BINARY);
- talk_base::scoped_ptr<DataBuffer> buffer(new DataBuffer(payload, binary));
+ rtc::scoped_ptr<DataBuffer> buffer(new DataBuffer(payload, binary));
if (was_ever_writable_ && observer_) {
observer_->OnMessage(*buffer.get());
} else {
- if (queued_received_data_.size() > kMaxQueuedReceivedDataPackets) {
- LOG(LS_ERROR)
- << "Queued received data exceeds the max number of packets.";
- ClearQueuedReceivedData();
+ if (queued_received_data_.byte_count() + payload.length() >
+ kMaxQueuedReceivedDataBytes) {
+ LOG(LS_ERROR) << "Queued received data exceeds the max buffer size.";
+
+ queued_received_data_.Clear();
+ if (data_channel_type_ != cricket::DCT_RTP) {
+ Close();
+ }
+
+ return;
}
- queued_received_data_.push(buffer.release());
+ queued_received_data_.Push(buffer.release());
}
}
@@ -350,22 +355,27 @@
was_ever_writable_ = true;
if (data_channel_type_ == cricket::DCT_SCTP) {
+ rtc::Buffer payload;
+
if (config_.open_handshake_role == InternalDataChannelInit::kOpener) {
- talk_base::Buffer* payload = new talk_base::Buffer;
- WriteDataChannelOpenMessage(label_, config_, payload);
- SendOpenMessage(payload);
+ WriteDataChannelOpenMessage(label_, config_, &payload);
+ SendControlMessage(payload);
} else if (config_.open_handshake_role ==
- InternalDataChannelInit::kAcker) {
- talk_base::Buffer* payload = new talk_base::Buffer;
- WriteDataChannelOpenAckMessage(payload);
- SendOpenAckMessage(payload);
+ InternalDataChannelInit::kAcker) {
+ WriteDataChannelOpenAckMessage(&payload);
+ SendControlMessage(payload);
}
}
UpdateState();
- ASSERT(queued_send_data_.empty());
+ ASSERT(queued_send_data_.Empty());
} else if (state_ == kOpen) {
- DeliverQueuedSendData();
+ // TODO(jiayl): Sending OPEN message here contradicts with the pre-condition
+ // that the readyState is open. According to the standard, the channel
+ // should not become open before the OPEN message is sent.
+ SendQueuedControlMessages();
+
+ SendQueuedDataMessages();
}
}
@@ -389,7 +399,7 @@
if (was_ever_writable_) {
// TODO(jiayl): Do not transition to kOpen if we failed to send the
// OPEN message.
- DeliverQueuedControlData();
+ SendQueuedControlMessages();
SetState(kOpen);
// If we have received buffers before the channel got writable.
// Deliver them now.
@@ -441,75 +451,27 @@
return;
}
- while (!queued_received_data_.empty()) {
- DataBuffer* buffer = queued_received_data_.front();
+ while (!queued_received_data_.Empty()) {
+ rtc::scoped_ptr<DataBuffer> buffer(queued_received_data_.Front());
observer_->OnMessage(*buffer);
- queued_received_data_.pop();
- delete buffer;
+ queued_received_data_.Pop();
}
}
-void DataChannel::ClearQueuedReceivedData() {
- while (!queued_received_data_.empty()) {
- DataBuffer* buffer = queued_received_data_.front();
- queued_received_data_.pop();
- delete buffer;
- }
-}
-
-void DataChannel::DeliverQueuedSendData() {
+void DataChannel::SendQueuedDataMessages() {
ASSERT(was_ever_writable_ && state_ == kOpen);
- // TODO(jiayl): Sending OPEN message here contradicts with the pre-condition
- // that the readyState is open. According to the standard, the channel should
- // not become open before the OPEN message is sent.
- DeliverQueuedControlData();
+ PacketQueue packet_buffer;
+ packet_buffer.Swap(&queued_send_data_);
- while (!queued_send_data_.empty()) {
- DataBuffer* buffer = queued_send_data_.front();
- cricket::SendDataResult send_result;
- if (!InternalSendWithoutQueueing(*buffer, &send_result)) {
- LOG(LS_WARNING) << "DeliverQueuedSendData aborted due to send_result "
- << send_result;
- break;
- }
- queued_send_data_.pop_front();
- delete buffer;
+ while (!packet_buffer.Empty()) {
+ rtc::scoped_ptr<DataBuffer> buffer(packet_buffer.Front());
+ SendDataMessage(*buffer);
+ packet_buffer.Pop();
}
}
-void DataChannel::ClearQueuedControlData() {
- while (!queued_control_data_.empty()) {
- const talk_base::Buffer *buf = queued_control_data_.front();
- queued_control_data_.pop();
- delete buf;
- }
-}
-
-void DataChannel::DeliverQueuedControlData() {
- ASSERT(was_ever_writable_);
- while (!queued_control_data_.empty()) {
- const talk_base::Buffer* buf = queued_control_data_.front();
- queued_control_data_.pop();
- if (config_.open_handshake_role == InternalDataChannelInit::kOpener) {
- SendOpenMessage(buf);
- } else {
- ASSERT(config_.open_handshake_role == InternalDataChannelInit::kAcker);
- SendOpenAckMessage(buf);
- }
- }
-}
-
-void DataChannel::ClearQueuedSendData() {
- while (!queued_send_data_.empty()) {
- DataBuffer* buffer = queued_send_data_.front();
- queued_send_data_.pop_front();
- delete buffer;
- }
-}
-
-bool DataChannel::InternalSendWithoutQueueing(
- const DataBuffer& buffer, cricket::SendDataResult* send_result) {
+bool DataChannel::SendDataMessage(const DataBuffer& buffer) {
cricket::SendDataParams send_params;
if (data_channel_type_ == cricket::DCT_SCTP) {
@@ -529,34 +491,78 @@
}
send_params.type = buffer.binary ? cricket::DMT_BINARY : cricket::DMT_TEXT;
- return provider_->SendData(send_params, buffer.data, send_result);
+ cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
+ bool success = provider_->SendData(send_params, buffer.data, &send_result);
+
+ if (!success && data_channel_type_ == cricket::DCT_SCTP) {
+ if (send_result != cricket::SDR_BLOCK || !QueueSendDataMessage(buffer)) {
+ LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send data, "
+ << "send_result = " << send_result;
+ Close();
+ }
+ }
+ return success;
}
-bool DataChannel::QueueSendData(const DataBuffer& buffer) {
- if (queued_send_data_.size() >= kMaxQueuedSendDataPackets) {
+bool DataChannel::QueueSendDataMessage(const DataBuffer& buffer) {
+ if (queued_send_data_.byte_count() >= kMaxQueuedSendDataBytes) {
LOG(LS_ERROR) << "Can't buffer any more data for the data channel.";
return false;
}
- queued_send_data_.push_back(new DataBuffer(buffer));
+ queued_send_data_.Push(new DataBuffer(buffer));
return true;
}
-void DataChannel::SetSctpSid(int sid) {
- ASSERT(config_.id < 0 && sid >= 0 && data_channel_type_ == cricket::DCT_SCTP);
- config_.id = sid;
- provider_->AddSctpDataStream(sid);
+void DataChannel::SendQueuedControlMessages() {
+ ASSERT(was_ever_writable_);
+
+ PacketQueue control_packets;
+ control_packets.Swap(&queued_control_data_);
+
+ while (!control_packets.Empty()) {
+ rtc::scoped_ptr<DataBuffer> buf(control_packets.Front());
+ SendControlMessage(buf->data);
+ control_packets.Pop();
+ }
}
-void DataChannel::OnTransportChannelCreated() {
- ASSERT(data_channel_type_ == cricket::DCT_SCTP);
- if (!connected_to_provider_) {
- connected_to_provider_ = provider_->ConnectDataChannel(this);
+void DataChannel::QueueControlMessage(const rtc::Buffer& buffer) {
+ queued_control_data_.Push(new DataBuffer(buffer, true));
+}
+
+bool DataChannel::SendControlMessage(const rtc::Buffer& buffer) {
+ bool is_open_message =
+ (config_.open_handshake_role == InternalDataChannelInit::kOpener);
+
+ ASSERT(data_channel_type_ == cricket::DCT_SCTP &&
+ was_ever_writable_ &&
+ config_.id >= 0 &&
+ (!is_open_message || !config_.negotiated));
+
+ cricket::SendDataParams send_params;
+ send_params.ssrc = config_.id;
+ send_params.ordered = config_.ordered || is_open_message;
+ send_params.type = cricket::DMT_CONTROL;
+
+ cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
+ bool retval = provider_->SendData(send_params, buffer, &send_result);
+ if (retval) {
+ LOG(LS_INFO) << "Sent CONTROL message on channel " << config_.id;
+
+ if (is_open_message) {
+ // Send data as ordered before we receive any message from the remote peer
+ // to make sure the remote peer will not receive any data before it
+ // receives the OPEN message.
+ waiting_for_open_ack_ = true;
+ }
+ } else if (send_result == cricket::SDR_BLOCK) {
+ QueueControlMessage(buffer);
+ } else {
+ LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send"
+ << " the CONTROL message, send_result = " << send_result;
+ Close();
}
- // The sid may have been unassigned when provider_->ConnectDataChannel was
- // done. So always add the streams even if connected_to_provider_ is true.
- if (config_.id >= 0) {
- provider_->AddSctpDataStream(config_.id);
- }
+ return retval;
}
} // namespace webrtc
diff --git a/app/webrtc/datachannel.h b/app/webrtc/datachannel.h
index 9256e0e..728d1df 100644
--- a/app/webrtc/datachannel.h
+++ b/app/webrtc/datachannel.h
@@ -28,16 +28,16 @@
#ifndef TALK_APP_WEBRTC_DATACHANNEL_H_
#define TALK_APP_WEBRTC_DATACHANNEL_H_
+#include <deque>
#include <string>
-#include <queue>
#include "talk/app/webrtc/datachannelinterface.h"
#include "talk/app/webrtc/proxy.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/scoped_ref_ptr.h"
-#include "talk/base/sigslot.h"
#include "talk/media/base/mediachannel.h"
#include "talk/session/media/channel.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/scoped_ref_ptr.h"
+#include "webrtc/base/sigslot.h"
namespace webrtc {
@@ -47,7 +47,7 @@
public:
// Sends the data to the transport.
virtual bool SendData(const cricket::SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
cricket::SendDataResult* result) = 0;
// Connects to the transport signals.
virtual bool ConnectDataChannel(DataChannel* data_channel) = 0;
@@ -100,9 +100,9 @@
// SSRC==0.
class DataChannel : public DataChannelInterface,
public sigslot::has_slots<>,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
- static talk_base::scoped_refptr<DataChannel> Create(
+ static rtc::scoped_refptr<DataChannel> Create(
DataChannelProviderInterface* provider,
cricket::DataChannelType dct,
const std::string& label,
@@ -128,8 +128,8 @@
virtual DataState state() const { return state_; }
virtual bool Send(const DataBuffer& buffer);
- // talk_base::MessageHandler override.
- virtual void OnMessage(talk_base::Message* msg);
+ // rtc::MessageHandler override.
+ virtual void OnMessage(rtc::Message* msg);
// Called if the underlying data engine is closing.
void OnDataEngineClose();
@@ -142,14 +142,15 @@
// Sigslots from cricket::DataChannel
void OnDataReceived(cricket::DataChannel* channel,
const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload);
+ const rtc::Buffer& payload);
// The remote peer request that this channel should be closed.
void RemotePeerRequestClose();
// The following methods are for SCTP only.
- // Sets the SCTP sid and adds to transport layer if not set yet.
+ // Sets the SCTP sid and adds to transport layer if not set yet. Should only
+ // be called once.
void SetSctpSid(int sid);
// Called when the transport channel is created.
void OnTransportChannelCreated();
@@ -175,23 +176,49 @@
virtual ~DataChannel();
private:
+ // A packet queue which tracks the total queued bytes. Queued packets are
+ // owned by this class.
+ class PacketQueue {
+ public:
+ PacketQueue();
+ ~PacketQueue();
+
+ size_t byte_count() const {
+ return byte_count_;
+ }
+
+ bool Empty() const;
+
+ DataBuffer* Front();
+
+ void Pop();
+
+ void Push(DataBuffer* packet);
+
+ void Clear();
+
+ void Swap(PacketQueue* other);
+
+ private:
+ std::deque<DataBuffer*> packets_;
+ size_t byte_count_;
+ };
+
bool Init(const InternalDataChannelInit& config);
void DoClose();
void UpdateState();
void SetState(DataState state);
void DisconnectFromTransport();
- void DeliverQueuedControlData();
- void QueueControl(const talk_base::Buffer* buffer);
- void ClearQueuedControlData();
+
void DeliverQueuedReceivedData();
- void ClearQueuedReceivedData();
- void DeliverQueuedSendData();
- void ClearQueuedSendData();
- bool InternalSendWithoutQueueing(const DataBuffer& buffer,
- cricket::SendDataResult* send_result);
- bool QueueSendData(const DataBuffer& buffer);
- bool SendOpenMessage(const talk_base::Buffer* buffer);
- bool SendOpenAckMessage(const talk_base::Buffer* buffer);
+
+ void SendQueuedDataMessages();
+ bool SendDataMessage(const DataBuffer& buffer);
+ bool QueueSendDataMessage(const DataBuffer& buffer);
+
+ void SendQueuedControlMessages();
+ void QueueControlMessage(const rtc::Buffer& buffer);
+ bool SendControlMessage(const rtc::Buffer& buffer);
std::string label_;
InternalDataChannelInit config_;
@@ -208,14 +235,14 @@
uint32 receive_ssrc_;
// Control messages that always have to get sent out before any queued
// data.
- std::queue<const talk_base::Buffer*> queued_control_data_;
- std::queue<DataBuffer*> queued_received_data_;
- std::deque<DataBuffer*> queued_send_data_;
+ PacketQueue queued_control_data_;
+ PacketQueue queued_received_data_;
+ PacketQueue queued_send_data_;
};
class DataChannelFactory {
public:
- virtual talk_base::scoped_refptr<DataChannel> CreateDataChannel(
+ virtual rtc::scoped_refptr<DataChannel> CreateDataChannel(
const std::string& label,
const InternalDataChannelInit* config) = 0;
diff --git a/app/webrtc/datachannel_unittest.cc b/app/webrtc/datachannel_unittest.cc
index 991ae0c..84a6935 100644
--- a/app/webrtc/datachannel_unittest.cc
+++ b/app/webrtc/datachannel_unittest.cc
@@ -28,7 +28,7 @@
#include "talk/app/webrtc/datachannel.h"
#include "talk/app/webrtc/sctputils.h"
#include "talk/app/webrtc/test/fakedatachannelprovider.h"
-#include "talk/base/gunit.h"
+#include "webrtc/base/gunit.h"
using webrtc::DataChannel;
@@ -86,14 +86,14 @@
webrtc::InternalDataChannelInit init_;
FakeDataChannelProvider provider_;
- talk_base::scoped_ptr<FakeDataChannelObserver> observer_;
- talk_base::scoped_refptr<DataChannel> webrtc_data_channel_;
+ rtc::scoped_ptr<FakeDataChannelObserver> observer_;
+ rtc::scoped_refptr<DataChannel> webrtc_data_channel_;
};
// Verifies that the data channel is connected to the transport after creation.
TEST_F(SctpDataChannelTest, ConnectedToTransportOnCreated) {
provider_.set_transport_available(true);
- talk_base::scoped_refptr<DataChannel> dc = DataChannel::Create(
+ rtc::scoped_refptr<DataChannel> dc = DataChannel::Create(
&provider_, cricket::DCT_SCTP, "test1", init_);
EXPECT_TRUE(provider_.IsConnected(dc.get()));
@@ -174,13 +174,23 @@
static_cast<uint32>(webrtc_data_channel_->id()));
}
+TEST_F(SctpDataChannelTest, QueuedOpenMessageSent) {
+ provider_.set_send_blocked(true);
+ SetChannelReady();
+ provider_.set_send_blocked(false);
+
+ EXPECT_EQ(cricket::DMT_CONTROL, provider_.last_send_data_params().type);
+ EXPECT_EQ(provider_.last_send_data_params().ssrc,
+ static_cast<uint32>(webrtc_data_channel_->id()));
+}
+
// Tests that the DataChannel created after transport gets ready can enter OPEN
// state.
TEST_F(SctpDataChannelTest, LateCreatedChannelTransitionToOpen) {
SetChannelReady();
webrtc::InternalDataChannelInit init;
init.id = 1;
- talk_base::scoped_refptr<DataChannel> dc = DataChannel::Create(
+ rtc::scoped_refptr<DataChannel> dc = DataChannel::Create(
&provider_, cricket::DCT_SCTP, "test1", init);
EXPECT_EQ(webrtc::DataChannelInterface::kConnecting, dc->state());
EXPECT_TRUE_WAIT(webrtc::DataChannelInterface::kOpen == dc->state(),
@@ -194,7 +204,7 @@
webrtc::InternalDataChannelInit init;
init.id = 1;
init.ordered = false;
- talk_base::scoped_refptr<DataChannel> dc = DataChannel::Create(
+ rtc::scoped_refptr<DataChannel> dc = DataChannel::Create(
&provider_, cricket::DCT_SCTP, "test1", init);
EXPECT_EQ_WAIT(webrtc::DataChannelInterface::kOpen, dc->state(), 1000);
@@ -208,7 +218,7 @@
cricket::ReceiveDataParams params;
params.ssrc = init.id;
params.type = cricket::DMT_CONTROL;
- talk_base::Buffer payload;
+ rtc::Buffer payload;
webrtc::WriteDataChannelOpenAckMessage(&payload);
dc->OnDataReceived(NULL, params, payload);
@@ -224,7 +234,7 @@
webrtc::InternalDataChannelInit init;
init.id = 1;
init.ordered = false;
- talk_base::scoped_refptr<DataChannel> dc = DataChannel::Create(
+ rtc::scoped_refptr<DataChannel> dc = DataChannel::Create(
&provider_, cricket::DCT_SCTP, "test1", init);
EXPECT_EQ_WAIT(webrtc::DataChannelInterface::kOpen, dc->state(), 1000);
@@ -289,7 +299,7 @@
config.open_handshake_role = webrtc::InternalDataChannelInit::kNone;
SetChannelReady();
- talk_base::scoped_refptr<DataChannel> dc = DataChannel::Create(
+ rtc::scoped_refptr<DataChannel> dc = DataChannel::Create(
&provider_, cricket::DCT_SCTP, "test1", config);
EXPECT_EQ_WAIT(webrtc::DataChannelInterface::kOpen, dc->state(), 1000);
@@ -305,7 +315,7 @@
config.open_handshake_role = webrtc::InternalDataChannelInit::kAcker;
SetChannelReady();
- talk_base::scoped_refptr<DataChannel> dc = DataChannel::Create(
+ rtc::scoped_refptr<DataChannel> dc = DataChannel::Create(
&provider_, cricket::DCT_SCTP, "test1", config);
EXPECT_EQ_WAIT(webrtc::DataChannelInterface::kOpen, dc->state(), 1000);
@@ -330,11 +340,17 @@
// Tests that the DataChannel is closed if the sending buffer is full.
TEST_F(SctpDataChannelTest, ClosedWhenSendBufferFull) {
SetChannelReady();
- webrtc::DataBuffer buffer("abcd");
+
+ const size_t buffer_size = 1024;
+ rtc::Buffer buffer;
+ buffer.SetLength(buffer_size);
+ memset(buffer.data(), 0, buffer_size);
+
+ webrtc::DataBuffer packet(buffer, true);
provider_.set_send_blocked(true);
- for (size_t i = 0; i < 101; ++i) {
- EXPECT_TRUE(webrtc_data_channel_->Send(buffer));
+ for (size_t i = 0; i < 16 * 1024 + 1; ++i) {
+ EXPECT_TRUE(webrtc_data_channel_->Send(packet));
}
EXPECT_EQ(webrtc::DataChannelInterface::kClosed,
@@ -376,3 +392,34 @@
webrtc_data_channel_->state());
}
+// Tests that the DataChannel is closed if the received buffer is full.
+TEST_F(SctpDataChannelTest, ClosedWhenReceivedBufferFull) {
+ SetChannelReady();
+ const size_t buffer_size = 1024;
+ rtc::Buffer buffer;
+ buffer.SetLength(buffer_size);
+ memset(buffer.data(), 0, buffer_size);
+
+ cricket::ReceiveDataParams params;
+ params.ssrc = 0;
+
+ // Receiving data without having an observer will overflow the buffer.
+ for (size_t i = 0; i < 16 * 1024 + 1; ++i) {
+ webrtc_data_channel_->OnDataReceived(NULL, params, buffer);
+ }
+ EXPECT_EQ(webrtc::DataChannelInterface::kClosed,
+ webrtc_data_channel_->state());
+}
+
+// Tests that sending empty data returns no error and keeps the channel open.
+TEST_F(SctpDataChannelTest, SendEmptyData) {
+ webrtc_data_channel_->SetSctpSid(1);
+ SetChannelReady();
+ EXPECT_EQ(webrtc::DataChannelInterface::kOpen,
+ webrtc_data_channel_->state());
+
+ webrtc::DataBuffer buffer("");
+ EXPECT_TRUE(webrtc_data_channel_->Send(buffer));
+ EXPECT_EQ(webrtc::DataChannelInterface::kOpen,
+ webrtc_data_channel_->state());
+}
diff --git a/app/webrtc/datachannelinterface.h b/app/webrtc/datachannelinterface.h
index 57fe200..5684cc2 100644
--- a/app/webrtc/datachannelinterface.h
+++ b/app/webrtc/datachannelinterface.h
@@ -33,9 +33,9 @@
#include <string>
-#include "talk/base/basictypes.h"
-#include "talk/base/buffer.h"
-#include "talk/base/refcount.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/refcount.h"
namespace webrtc {
@@ -66,7 +66,7 @@
};
struct DataBuffer {
- DataBuffer(const talk_base::Buffer& data, bool binary)
+ DataBuffer(const rtc::Buffer& data, bool binary)
: data(data),
binary(binary) {
}
@@ -77,7 +77,7 @@
}
size_t size() const { return data.length(); }
- talk_base::Buffer data;
+ rtc::Buffer data;
// Indicates if the received data contains UTF-8 or binary data.
// Note that the upper layers are left to verify the UTF-8 encoding.
// TODO(jiayl): prefer to use an enum instead of a bool.
@@ -95,7 +95,7 @@
virtual ~DataChannelObserver() {}
};
-class DataChannelInterface : public talk_base::RefCountInterface {
+class DataChannelInterface : public rtc::RefCountInterface {
public:
// Keep in sync with DataChannel.java:State and
// RTCDataChannel.h:RTCDataChannelState.
diff --git a/app/webrtc/dtmfsender.cc b/app/webrtc/dtmfsender.cc
index 6556acd..4eade16 100644
--- a/app/webrtc/dtmfsender.cc
+++ b/app/webrtc/dtmfsender.cc
@@ -31,8 +31,8 @@
#include <string>
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
@@ -75,21 +75,21 @@
return true;
}
-talk_base::scoped_refptr<DtmfSender> DtmfSender::Create(
+rtc::scoped_refptr<DtmfSender> DtmfSender::Create(
AudioTrackInterface* track,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* signaling_thread,
DtmfProviderInterface* provider) {
if (!track || !signaling_thread) {
return NULL;
}
- talk_base::scoped_refptr<DtmfSender> dtmf_sender(
- new talk_base::RefCountedObject<DtmfSender>(track, signaling_thread,
+ rtc::scoped_refptr<DtmfSender> dtmf_sender(
+ new rtc::RefCountedObject<DtmfSender>(track, signaling_thread,
provider));
return dtmf_sender;
}
DtmfSender::DtmfSender(AudioTrackInterface* track,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* signaling_thread,
DtmfProviderInterface* provider)
: track_(track),
observer_(NULL),
@@ -176,7 +176,7 @@
return inter_tone_gap_;
}
-void DtmfSender::OnMessage(talk_base::Message* msg) {
+void DtmfSender::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_DO_INSERT_DTMF: {
DoInsertDtmf();
diff --git a/app/webrtc/dtmfsender.h b/app/webrtc/dtmfsender.h
index f2bebde..e875d3a 100644
--- a/app/webrtc/dtmfsender.h
+++ b/app/webrtc/dtmfsender.h
@@ -33,15 +33,15 @@
#include "talk/app/webrtc/dtmfsenderinterface.h"
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/proxy.h"
-#include "talk/base/common.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/refcount.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/refcount.h"
// DtmfSender is the native implementation of the RTCDTMFSender defined by
// the WebRTC W3C Editor's Draft.
// http://dev.w3.org/2011/webrtc/editor/webrtc.html
-namespace talk_base {
+namespace rtc {
class Thread;
}
@@ -70,11 +70,11 @@
class DtmfSender
: public DtmfSenderInterface,
public sigslot::has_slots<>,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
- static talk_base::scoped_refptr<DtmfSender> Create(
+ static rtc::scoped_refptr<DtmfSender> Create(
AudioTrackInterface* track,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* signaling_thread,
DtmfProviderInterface* provider);
// Implements DtmfSenderInterface.
@@ -90,7 +90,7 @@
protected:
DtmfSender(AudioTrackInterface* track,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* signaling_thread,
DtmfProviderInterface* provider);
virtual ~DtmfSender();
@@ -98,7 +98,7 @@
DtmfSender();
// Implements MessageHandler.
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
// The DTMF sending task.
void DoInsertDtmf();
@@ -107,9 +107,9 @@
void StopSending();
- talk_base::scoped_refptr<AudioTrackInterface> track_;
+ rtc::scoped_refptr<AudioTrackInterface> track_;
DtmfSenderObserverInterface* observer_;
- talk_base::Thread* signaling_thread_;
+ rtc::Thread* signaling_thread_;
DtmfProviderInterface* provider_;
std::string tones_;
int duration_;
diff --git a/app/webrtc/dtmfsender_unittest.cc b/app/webrtc/dtmfsender_unittest.cc
index a483505..c5b19cc 100644
--- a/app/webrtc/dtmfsender_unittest.cc
+++ b/app/webrtc/dtmfsender_unittest.cc
@@ -32,9 +32,9 @@
#include <vector>
#include "talk/app/webrtc/audiotrack.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/timeutils.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/timeutils.h"
using webrtc::AudioTrackInterface;
using webrtc::AudioTrack;
@@ -97,12 +97,12 @@
virtual bool InsertDtmf(const std::string& track_label,
int code, int duration) OVERRIDE {
int gap = 0;
- // TODO(ronghuawu): Make the timer (basically the talk_base::TimeNanos)
+ // TODO(ronghuawu): Make the timer (basically the rtc::TimeNanos)
// mockable and use a fake timer in the unit tests.
if (last_insert_dtmf_call_ > 0) {
- gap = static_cast<int>(talk_base::Time() - last_insert_dtmf_call_);
+ gap = static_cast<int>(rtc::Time() - last_insert_dtmf_call_);
}
- last_insert_dtmf_call_ = talk_base::Time();
+ last_insert_dtmf_call_ = rtc::Time();
LOG(LS_VERBOSE) << "FakeDtmfProvider::InsertDtmf code=" << code
<< " duration=" << duration
@@ -139,10 +139,10 @@
protected:
DtmfSenderTest()
: track_(AudioTrack::Create(kTestAudioLabel, NULL)),
- observer_(new talk_base::RefCountedObject<FakeDtmfObserver>()),
+ observer_(new rtc::RefCountedObject<FakeDtmfObserver>()),
provider_(new FakeDtmfProvider()) {
provider_->AddCanInsertDtmfTrack(kTestAudioLabel);
- dtmf_ = DtmfSender::Create(track_, talk_base::Thread::Current(),
+ dtmf_ = DtmfSender::Create(track_, rtc::Thread::Current(),
provider_.get());
dtmf_->RegisterObserver(observer_.get());
}
@@ -229,10 +229,10 @@
}
}
- talk_base::scoped_refptr<AudioTrackInterface> track_;
- talk_base::scoped_ptr<FakeDtmfObserver> observer_;
- talk_base::scoped_ptr<FakeDtmfProvider> provider_;
- talk_base::scoped_refptr<DtmfSender> dtmf_;
+ rtc::scoped_refptr<AudioTrackInterface> track_;
+ rtc::scoped_ptr<FakeDtmfObserver> observer_;
+ rtc::scoped_ptr<FakeDtmfProvider> provider_;
+ rtc::scoped_refptr<DtmfSender> dtmf_;
};
TEST_F(DtmfSenderTest, CanInsertDtmf) {
diff --git a/app/webrtc/dtmfsenderinterface.h b/app/webrtc/dtmfsenderinterface.h
index 46f3924..93b4543 100644
--- a/app/webrtc/dtmfsenderinterface.h
+++ b/app/webrtc/dtmfsenderinterface.h
@@ -31,8 +31,8 @@
#include <string>
#include "talk/app/webrtc/mediastreaminterface.h"
-#include "talk/base/common.h"
-#include "talk/base/refcount.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/refcount.h"
// This file contains interfaces for DtmfSender.
@@ -53,7 +53,7 @@
// The interface of native implementation of the RTCDTMFSender defined by the
// WebRTC W3C Editor's Draft.
-class DtmfSenderInterface : public talk_base::RefCountInterface {
+class DtmfSenderInterface : public rtc::RefCountInterface {
public:
virtual void RegisterObserver(DtmfSenderObserverInterface* observer) = 0;
virtual void UnregisterObserver() = 0;
diff --git a/app/webrtc/fakeportallocatorfactory.h b/app/webrtc/fakeportallocatorfactory.h
index c1727ae..eee98b0 100644
--- a/app/webrtc/fakeportallocatorfactory.h
+++ b/app/webrtc/fakeportallocatorfactory.h
@@ -39,8 +39,8 @@
class FakePortAllocatorFactory : public PortAllocatorFactoryInterface {
public:
static FakePortAllocatorFactory* Create() {
- talk_base::RefCountedObject<FakePortAllocatorFactory>* allocator =
- new talk_base::RefCountedObject<FakePortAllocatorFactory>();
+ rtc::RefCountedObject<FakePortAllocatorFactory>* allocator =
+ new rtc::RefCountedObject<FakePortAllocatorFactory>();
return allocator;
}
@@ -49,7 +49,7 @@
const std::vector<TurnConfiguration>& turn_configurations) {
stun_configs_ = stun_configurations;
turn_configs_ = turn_configurations;
- return new cricket::FakePortAllocator(talk_base::Thread::Current(), NULL);
+ return new cricket::FakePortAllocator(rtc::Thread::Current(), NULL);
}
const std::vector<StunConfiguration>& stun_configs() const {
diff --git a/app/webrtc/java/android/org/webrtc/VideoRendererGui.java b/app/webrtc/java/android/org/webrtc/VideoRendererGui.java
index 439f942..af625c0 100644
--- a/app/webrtc/java/android/org/webrtc/VideoRendererGui.java
+++ b/app/webrtc/java/android/org/webrtc/VideoRendererGui.java
@@ -37,6 +37,10 @@
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
+import android.graphics.SurfaceTexture;
+import android.opengl.EGL14;
+import android.opengl.EGLContext;
+import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.util.Log;
@@ -54,14 +58,28 @@
private static VideoRendererGui instance = null;
private static final String TAG = "VideoRendererGui";
private GLSurfaceView surface;
+ private static EGLContext eglContext = null;
// Indicates if SurfaceView.Renderer.onSurfaceCreated was called.
// If true then for every newly created yuv image renderer createTexture()
// should be called. The variable is accessed on multiple threads and
// all accesses are synchronized on yuvImageRenderers' object lock.
private boolean onSurfaceCreatedCalled;
+ private int screenWidth;
+ private int screenHeight;
// List of yuv renderers.
private ArrayList<YuvImageRenderer> yuvImageRenderers;
- private int program;
+ private int yuvProgram;
+ private int oesProgram;
+ // Types of video scaling:
+ // SCALE_ASPECT_FIT - video frame is scaled to fit the size of the view by
+ // maintaining the aspect ratio (black borders may be displayed).
+ // SCALE_ASPECT_FILL - video frame is scaled to fill the size of the view by
+ // maintaining the aspect ratio. Some portion of the video frame may be
+ // clipped.
+ // SCALE_FILL - video frame is scaled to to fill the size of the view. Video
+ // aspect ratio is changed if necessary.
+ private static enum ScalingType
+ { SCALE_ASPECT_FIT, SCALE_ASPECT_FILL, SCALE_FILL };
private final String VERTEX_SHADER_STRING =
"varying vec2 interp_tc;\n" +
@@ -73,7 +91,7 @@
" interp_tc = in_tc;\n" +
"}\n";
- private final String FRAGMENT_SHADER_STRING =
+ private final String YUV_FRAGMENT_SHADER_STRING =
"precision mediump float;\n" +
"varying vec2 interp_tc;\n" +
"\n" +
@@ -91,6 +109,19 @@
" y + 1.77 * u, 1);\n" +
"}\n";
+
+ private static final String OES_FRAGMENT_SHADER_STRING =
+ "#extension GL_OES_EGL_image_external : require\n" +
+ "precision mediump float;\n" +
+ "varying vec2 interp_tc;\n" +
+ "\n" +
+ "uniform samplerExternalOES oes_tex;\n" +
+ "\n" +
+ "void main() {\n" +
+ " gl_FragColor = texture2D(oes_tex, interp_tc);\n" +
+ "}\n";
+
+
private VideoRendererGui(GLSurfaceView surface) {
this.surface = surface;
// Create an OpenGL ES 2.0 context.
@@ -124,23 +155,46 @@
return buffer;
}
- // Compile & attach a |type| shader specified by |source| to |program|.
- private static void addShaderTo(
- int type, String source, int program) {
+ private int loadShader(int shaderType, String source) {
int[] result = new int[] {
GLES20.GL_FALSE
};
- int shader = GLES20.glCreateShader(type);
+ int shader = GLES20.glCreateShader(shaderType);
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, result, 0);
- abortUnless(result[0] == GLES20.GL_TRUE,
- GLES20.glGetShaderInfoLog(shader) + ", source: " + source);
- GLES20.glAttachShader(program, shader);
- GLES20.glDeleteShader(shader);
-
+ if (result[0] != GLES20.GL_TRUE) {
+ Log.e(TAG, "Could not compile shader " + shaderType + ":" +
+ GLES20.glGetShaderInfoLog(shader));
+ throw new RuntimeException(GLES20.glGetShaderInfoLog(shader));
+ }
checkNoGLES2Error();
- }
+ return shader;
+}
+
+
+ private int createProgram(String vertexSource, String fragmentSource) {
+ int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
+ int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
+ int program = GLES20.glCreateProgram();
+ if (program == 0) {
+ throw new RuntimeException("Could not create program");
+ }
+ GLES20.glAttachShader(program, vertexShader);
+ GLES20.glAttachShader(program, fragmentShader);
+ GLES20.glLinkProgram(program);
+ int[] linkStatus = new int[] {
+ GLES20.GL_FALSE
+ };
+ GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
+ if (linkStatus[0] != GLES20.GL_TRUE) {
+ Log.e(TAG, "Could not link program: " +
+ GLES20.glGetProgramInfoLog(program));
+ throw new RuntimeException(GLES20.glGetProgramInfoLog(program));
+ }
+ checkNoGLES2Error();
+ return program;
+}
/**
* Class used to display stream of YUV420 frames at particular location
@@ -149,9 +203,12 @@
*/
private static class YuvImageRenderer implements VideoRenderer.Callbacks {
private GLSurfaceView surface;
- private int program;
- private FloatBuffer textureVertices;
+ private int id;
+ private int yuvProgram;
+ private int oesProgram;
private int[] yuvTextures = { -1, -1, -1 };
+ private int oesTexture = -1;
+ private float[] stMatrix = new float[16];
// Render frame queue - accessed by two threads. renderFrame() call does
// an offer (writing I420Frame to render) and early-returns (recording
@@ -159,8 +216,13 @@
// copies frame to texture and then removes it from a queue using poll().
LinkedBlockingQueue<I420Frame> frameToRenderQueue;
// Local copy of incoming video frame.
- private I420Frame frameToRender;
- // Flag if renderFrame() was ever called
+ private I420Frame yuvFrameToRender;
+ private I420Frame textureFrameToRender;
+ // Type of video frame used for recent frame rendering.
+ private static enum RendererType { RENDERER_YUV, RENDERER_TEXTURE };
+ private RendererType rendererType;
+ private ScalingType scalingType;
+ // Flag if renderFrame() was ever called.
boolean seenFrame;
// Total number of video frames received in renderFrame() call.
private int framesReceived;
@@ -174,40 +236,68 @@
// Time in ns spent in draw() function.
private long drawTimeNs;
// Time in ns spent in renderFrame() function - including copying frame
- // data to rendering planes
+ // data to rendering planes.
private long copyTimeNs;
-
- // Texture Coordinates mapping the entire texture.
- private final FloatBuffer textureCoords = directNativeFloatBuffer(
- new float[] {
- 0, 0, 0, 1, 1, 0, 1, 1
- });
+ // Texture vertices.
+ private float texLeft;
+ private float texRight;
+ private float texTop;
+ private float texBottom;
+ private FloatBuffer textureVertices;
+ // Texture UV coordinates offsets.
+ private float texOffsetU;
+ private float texOffsetV;
+ private FloatBuffer textureCoords;
+ // Flag if texture vertices or coordinates update is needed.
+ private boolean updateTextureProperties;
+ // Viewport dimensions.
+ private int screenWidth;
+ private int screenHeight;
+ // Video dimension.
+ private int videoWidth;
+ private int videoHeight;
private YuvImageRenderer(
- GLSurfaceView surface,
- int x, int y, int width, int height) {
- Log.v(TAG, "YuvImageRenderer.Create");
+ GLSurfaceView surface, int id,
+ int x, int y, int width, int height,
+ ScalingType scalingType) {
+ Log.d(TAG, "YuvImageRenderer.Create id: " + id);
this.surface = surface;
+ this.id = id;
+ this.scalingType = scalingType;
frameToRenderQueue = new LinkedBlockingQueue<I420Frame>(1);
// Create texture vertices.
- float xLeft = (x - 50) / 50.0f;
- float yTop = (50 - y) / 50.0f;
- float xRight = Math.min(1.0f, (x + width - 50) / 50.0f);
- float yBottom = Math.max(-1.0f, (50 - y - height) / 50.0f);
+ texLeft = (x - 50) / 50.0f;
+ texTop = (50 - y) / 50.0f;
+ texRight = Math.min(1.0f, (x + width - 50) / 50.0f);
+ texBottom = Math.max(-1.0f, (50 - y - height) / 50.0f);
float textureVeticesFloat[] = new float[] {
- xLeft, yTop,
- xLeft, yBottom,
- xRight, yTop,
- xRight, yBottom
+ texLeft, texTop,
+ texLeft, texBottom,
+ texRight, texTop,
+ texRight, texBottom
};
textureVertices = directNativeFloatBuffer(textureVeticesFloat);
+ // Create texture UV coordinates.
+ texOffsetU = 0;
+ texOffsetV = 0;
+ float textureCoordinatesFloat[] = new float[] {
+ texOffsetU, texOffsetV, // left top
+ texOffsetU, 1.0f - texOffsetV, // left bottom
+ 1.0f - texOffsetU, texOffsetV, // right top
+ 1.0f - texOffsetU, 1.0f - texOffsetV // right bottom
+ };
+ textureCoords = directNativeFloatBuffer(textureCoordinatesFloat);
+ updateTextureProperties = false;
}
- private void createTextures(int program) {
- Log.v(TAG, " YuvImageRenderer.createTextures");
- this.program = program;
+ private void createTextures(int yuvProgram, int oesProgram) {
+ Log.d(TAG, " YuvImageRenderer.createTextures " + id + " on GL thread:" +
+ Thread.currentThread().getId());
+ this.yuvProgram = yuvProgram;
+ this.oesProgram = oesProgram;
- // Generate 3 texture ids for Y/U/V and place them into |textures|.
+ // Generate 3 texture ids for Y/U/V and place them into |yuvTextures|.
GLES20.glGenTextures(3, yuvTextures, 0);
for (int i = 0; i < 3; i++) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i);
@@ -226,39 +316,139 @@
checkNoGLES2Error();
}
+ private void checkAdjustTextureCoords() {
+ if (!updateTextureProperties ||
+ scalingType == ScalingType.SCALE_FILL) {
+ return;
+ }
+ // Re - calculate texture vertices to preserve video aspect ratio.
+ float texRight = this.texRight;
+ float texLeft = this.texLeft;
+ float texTop = this.texTop;
+ float texBottom = this.texBottom;
+ float displayWidth = (texRight - texLeft) * screenWidth / 2;
+ float displayHeight = (texTop - texBottom) * screenHeight / 2;
+ if (displayWidth > 1 && displayHeight > 1 &&
+ videoWidth > 1 && videoHeight > 1) {
+ float displayAspectRatio = displayWidth / displayHeight;
+ float videoAspectRatio = (float)videoWidth / videoHeight;
+ if (scalingType == ScalingType.SCALE_ASPECT_FIT) {
+ // Need to re-adjust vertices width or height to match video AR.
+ if (displayAspectRatio > videoAspectRatio) {
+ float deltaX = (displayWidth - videoAspectRatio * displayHeight) /
+ instance.screenWidth;
+ texRight -= deltaX;
+ texLeft += deltaX;
+ } else {
+ float deltaY = (displayHeight - displayWidth / videoAspectRatio) /
+ instance.screenHeight;
+ texTop -= deltaY;
+ texBottom += deltaY;
+ }
+ // Re-allocate vertices buffer to adjust to video aspect ratio.
+ float textureVeticesFloat[] = new float[] {
+ texLeft, texTop,
+ texLeft, texBottom,
+ texRight, texTop,
+ texRight, texBottom
+ };
+ textureVertices = directNativeFloatBuffer(textureVeticesFloat);
+ }
+ if (scalingType == ScalingType.SCALE_ASPECT_FILL) {
+ // Need to re-adjust UV coordinates to match display AR.
+ if (displayAspectRatio > videoAspectRatio) {
+ texOffsetV = (1.0f - videoAspectRatio / displayAspectRatio) / 2.0f;
+ } else {
+ texOffsetU = (1.0f - displayAspectRatio / videoAspectRatio) / 2.0f;
+ }
+ // Re-allocate coordinates buffer to adjust to display aspect ratio.
+ float textureCoordinatesFloat[] = new float[] {
+ texOffsetU, texOffsetV, // left top
+ texOffsetU, 1.0f - texOffsetV, // left bottom
+ 1.0f - texOffsetU, texOffsetV, // right top
+ 1.0f - texOffsetU, 1.0f - texOffsetV // right bottom
+ };
+ textureCoords = directNativeFloatBuffer(textureCoordinatesFloat);
+ }
+ }
+ updateTextureProperties = false;
+ }
+
private void draw() {
- long now = System.nanoTime();
if (!seenFrame) {
// No frame received yet - nothing to render.
return;
}
+ // Check if texture vertices/coordinates adjustment is required when
+ // screen orientation changes or video frame size changes.
+ checkAdjustTextureCoords();
+
+ long now = System.nanoTime();
+
I420Frame frameFromQueue;
synchronized (frameToRenderQueue) {
frameFromQueue = frameToRenderQueue.peek();
if (frameFromQueue != null && startTimeNs == -1) {
startTimeNs = now;
}
- for (int i = 0; i < 3; ++i) {
- int w = (i == 0) ? frameToRender.width : frameToRender.width / 2;
- int h = (i == 0) ? frameToRender.height : frameToRender.height / 2;
- GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i);
- GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]);
- if (frameFromQueue != null) {
- GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE,
- w, h, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE,
- frameFromQueue.yuvPlanes[i]);
+
+ if (rendererType == RendererType.RENDERER_YUV) {
+ // YUV textures rendering.
+ GLES20.glUseProgram(yuvProgram);
+
+ for (int i = 0; i < 3; ++i) {
+ GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + i);
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, yuvTextures[i]);
+ if (frameFromQueue != null) {
+ int w = (i == 0) ?
+ frameFromQueue.width : frameFromQueue.width / 2;
+ int h = (i == 0) ?
+ frameFromQueue.height : frameFromQueue.height / 2;
+ GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE,
+ w, h, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE,
+ frameFromQueue.yuvPlanes[i]);
+ }
}
+ } else {
+ // External texture rendering.
+ GLES20.glUseProgram(oesProgram);
+
+ if (frameFromQueue != null) {
+ oesTexture = frameFromQueue.textureId;
+ if (frameFromQueue.textureObject instanceof SurfaceTexture) {
+ SurfaceTexture surfaceTexture =
+ (SurfaceTexture) frameFromQueue.textureObject;
+ surfaceTexture.updateTexImage();
+ surfaceTexture.getTransformMatrix(stMatrix);
+ }
+ }
+ GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
+ GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, oesTexture);
}
+
if (frameFromQueue != null) {
frameToRenderQueue.poll();
}
}
- int posLocation = GLES20.glGetAttribLocation(program, "in_pos");
+
+ if (rendererType == RendererType.RENDERER_YUV) {
+ GLES20.glUniform1i(GLES20.glGetUniformLocation(yuvProgram, "y_tex"), 0);
+ GLES20.glUniform1i(GLES20.glGetUniformLocation(yuvProgram, "u_tex"), 1);
+ GLES20.glUniform1i(GLES20.glGetUniformLocation(yuvProgram, "v_tex"), 2);
+ }
+
+ int posLocation = GLES20.glGetAttribLocation(yuvProgram, "in_pos");
+ if (posLocation == -1) {
+ throw new RuntimeException("Could not get attrib location for in_pos");
+ }
GLES20.glEnableVertexAttribArray(posLocation);
GLES20.glVertexAttribPointer(
posLocation, 2, GLES20.GL_FLOAT, false, 0, textureVertices);
- int texLocation = GLES20.glGetAttribLocation(program, "in_tc");
+ int texLocation = GLES20.glGetAttribLocation(yuvProgram, "in_tc");
+ if (texLocation == -1) {
+ throw new RuntimeException("Could not get attrib location for in_tc");
+ }
GLES20.glEnableVertexAttribArray(texLocation);
GLES20.glVertexAttribPointer(
texLocation, 2, GLES20.GL_FLOAT, false, 0, textureCoords);
@@ -281,29 +471,41 @@
private void logStatistics() {
long timeSinceFirstFrameNs = System.nanoTime() - startTimeNs;
- Log.v(TAG, "Frames received: " + framesReceived + ". Dropped: " +
- framesDropped + ". Rendered: " + framesRendered);
+ Log.d(TAG, "ID: " + id + ". Type: " + rendererType +
+ ". Frames received: " + framesReceived +
+ ". Dropped: " + framesDropped + ". Rendered: " + framesRendered);
if (framesReceived > 0 && framesRendered > 0) {
- Log.v(TAG, "Duration: " + (int)(timeSinceFirstFrameNs / 1e6) +
+ Log.d(TAG, "Duration: " + (int)(timeSinceFirstFrameNs / 1e6) +
" ms. FPS: " + (float)framesRendered * 1e9 / timeSinceFirstFrameNs);
- Log.v(TAG, "Draw time: " +
+ Log.d(TAG, "Draw time: " +
(int) (drawTimeNs / (1000 * framesRendered)) + " us. Copy time: " +
(int) (copyTimeNs / (1000 * framesReceived)) + " us");
}
}
+ public void setScreenSize(final int screenWidth, final int screenHeight) {
+ this.screenWidth = screenWidth;
+ this.screenHeight = screenHeight;
+ updateTextureProperties = true;
+ }
+
@Override
public void setSize(final int width, final int height) {
- Log.v(TAG, "YuvImageRenderer.setSize: " + width + " x " + height);
+ Log.d(TAG, "ID: " + id + ". YuvImageRenderer.setSize: " +
+ width + " x " + height);
+ videoWidth = width;
+ videoHeight = height;
int[] strides = { width, width / 2, width / 2 };
// Frame re-allocation need to be synchronized with copying
// frame to textures in draw() function to avoid re-allocating
// the frame while it is being copied.
synchronized (frameToRenderQueue) {
- // Clear rendering queue
+ // Clear rendering queue.
frameToRenderQueue.poll();
- // Re-allocate / allocate the frame
- frameToRender = new I420Frame(width, height, strides, null);
+ // Re-allocate / allocate the frame.
+ yuvFrameToRender = new I420Frame(width, height, strides, null);
+ textureFrameToRender = new I420Frame(width, height, null, -1);
+ updateTextureProperties = true;
}
}
@@ -311,24 +513,26 @@
public synchronized void renderFrame(I420Frame frame) {
long now = System.nanoTime();
framesReceived++;
- // Check input frame parameters.
- if (!(frame.yuvStrides[0] == frame.width &&
- frame.yuvStrides[1] == frame.width / 2 &&
- frame.yuvStrides[2] == frame.width / 2)) {
- Log.e(TAG, "Incorrect strides " + frame.yuvStrides[0] + ", " +
- frame.yuvStrides[1] + ", " + frame.yuvStrides[2]);
- return;
- }
// Skip rendering of this frame if setSize() was not called.
- if (frameToRender == null) {
+ if (yuvFrameToRender == null || textureFrameToRender == null) {
framesDropped++;
return;
}
- // Check incoming frame dimensions
- if (frame.width != frameToRender.width ||
- frame.height != frameToRender.height) {
- throw new RuntimeException("Wrong frame size " +
- frame.width + " x " + frame.height);
+ // Check input frame parameters.
+ if (frame.yuvFrame) {
+ if (!(frame.yuvStrides[0] == frame.width &&
+ frame.yuvStrides[1] == frame.width / 2 &&
+ frame.yuvStrides[2] == frame.width / 2)) {
+ Log.e(TAG, "Incorrect strides " + frame.yuvStrides[0] + ", " +
+ frame.yuvStrides[1] + ", " + frame.yuvStrides[2]);
+ return;
+ }
+ // Check incoming frame dimensions.
+ if (frame.width != yuvFrameToRender.width ||
+ frame.height != yuvFrameToRender.height) {
+ throw new RuntimeException("Wrong frame size " +
+ frame.width + " x " + frame.height);
+ }
}
if (frameToRenderQueue.size() > 0) {
@@ -336,20 +540,36 @@
framesDropped++;
return;
}
- frameToRender.copyFrom(frame);
+
+ // Create a local copy of the frame.
+ if (frame.yuvFrame) {
+ yuvFrameToRender.copyFrom(frame);
+ rendererType = RendererType.RENDERER_YUV;
+ frameToRenderQueue.offer(yuvFrameToRender);
+ } else {
+ textureFrameToRender.copyFrom(frame);
+ rendererType = RendererType.RENDERER_TEXTURE;
+ frameToRenderQueue.offer(textureFrameToRender);
+ }
copyTimeNs += (System.nanoTime() - now);
- frameToRenderQueue.offer(frameToRender);
seenFrame = true;
+
+ // Request rendering.
surface.requestRender();
}
+
}
/** Passes GLSurfaceView to video renderer. */
public static void setView(GLSurfaceView surface) {
- Log.v(TAG, "VideoRendererGui.setView");
+ Log.d(TAG, "VideoRendererGui.setView");
instance = new VideoRendererGui(surface);
}
+ public static EGLContext getEGLContext() {
+ return eglContext;
+ }
+
/**
* Creates VideoRenderer with top left corner at (x, y) and resolution
* (width, height). All parameters are in percentage of screen resolution.
@@ -360,6 +580,11 @@
return new VideoRenderer(javaGuiRenderer);
}
+ public static VideoRenderer.Callbacks createGuiRenderer(
+ int x, int y, int width, int height) {
+ return create(x, y, width, height);
+ }
+
/**
* Creates VideoRenderer.Callbacks with top left corner at (x, y) and
* resolution (width, height). All parameters are in percentage of
@@ -379,7 +604,8 @@
"Attempt to create yuv renderer before setting GLSurfaceView");
}
final YuvImageRenderer yuvImageRenderer = new YuvImageRenderer(
- instance.surface, x, y, width, height);
+ instance.surface, instance.yuvImageRenderers.size(),
+ x, y, width, height, ScalingType.SCALE_ASPECT_FIT);
synchronized (instance.yuvImageRenderers) {
if (instance.onSurfaceCreatedCalled) {
// onSurfaceCreated has already been called for VideoRendererGui -
@@ -388,7 +614,10 @@
final CountDownLatch countDownLatch = new CountDownLatch(1);
instance.surface.queueEvent(new Runnable() {
public void run() {
- yuvImageRenderer.createTextures(instance.program);
+ yuvImageRenderer.createTextures(
+ instance.yuvProgram, instance.oesProgram);
+ yuvImageRenderer.setScreenSize(
+ instance.screenWidth, instance.screenHeight);
countDownLatch.countDown();
}
});
@@ -407,43 +636,40 @@
@Override
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
- Log.v(TAG, "VideoRendererGui.onSurfaceCreated");
+ Log.d(TAG, "VideoRendererGui.onSurfaceCreated");
+ // Store render EGL context
+ eglContext = EGL14.eglGetCurrentContext();
+ Log.d(TAG, "VideoRendererGui EGL Context: " + eglContext);
- // Create program.
- program = GLES20.glCreateProgram();
- addShaderTo(GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_STRING, program);
- addShaderTo(GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_STRING, program);
-
- GLES20.glLinkProgram(program);
- int[] result = new int[] {
- GLES20.GL_FALSE
- };
- result[0] = GLES20.GL_FALSE;
- GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, result, 0);
- abortUnless(result[0] == GLES20.GL_TRUE,
- GLES20.glGetProgramInfoLog(program));
- GLES20.glUseProgram(program);
-
- GLES20.glUniform1i(GLES20.glGetUniformLocation(program, "y_tex"), 0);
- GLES20.glUniform1i(GLES20.glGetUniformLocation(program, "u_tex"), 1);
- GLES20.glUniform1i(GLES20.glGetUniformLocation(program, "v_tex"), 2);
+ // Create YUV and OES programs.
+ yuvProgram = createProgram(VERTEX_SHADER_STRING,
+ YUV_FRAGMENT_SHADER_STRING);
+ oesProgram = createProgram(VERTEX_SHADER_STRING,
+ OES_FRAGMENT_SHADER_STRING);
synchronized (yuvImageRenderers) {
// Create textures for all images.
for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) {
- yuvImageRenderer.createTextures(program);
+ yuvImageRenderer.createTextures(yuvProgram, oesProgram);
}
onSurfaceCreatedCalled = true;
}
checkNoGLES2Error();
- GLES20.glClearColor(0.0f, 0.0f, 0.3f, 1.0f);
+ GLES20.glClearColor(0.0f, 0.0f, 0.1f, 1.0f);
}
@Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
- Log.v(TAG, "VideoRendererGui.onSurfaceChanged: " +
+ Log.d(TAG, "VideoRendererGui.onSurfaceChanged: " +
width + " x " + height + " ");
+ screenWidth = width;
+ screenHeight = height;
GLES20.glViewport(0, 0, width, height);
+ synchronized (yuvImageRenderers) {
+ for (YuvImageRenderer yuvImageRenderer : yuvImageRenderers) {
+ yuvImageRenderer.setScreenSize(screenWidth, screenHeight);
+ }
+ }
}
@Override
diff --git a/app/webrtc/java/jni/peerconnection_jni.cc b/app/webrtc/java/jni/peerconnection_jni.cc
index 3353de7..27f69e4 100644
--- a/app/webrtc/java/jni/peerconnection_jni.cc
+++ b/app/webrtc/java/jni/peerconnection_jni.cc
@@ -57,43 +57,59 @@
#define JNIEXPORT __attribute__((visibility("default")))
#include <asm/unistd.h>
-#include <limits>
-#include <map>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
+#include <limits>
+#include <map>
#include "talk/app/webrtc/mediaconstraintsinterface.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/videosourceinterface.h"
-#include "talk/base/bind.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/ssladapter.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videorenderer.h"
#include "talk/media/devices/videorendererfactory.h"
#include "talk/media/webrtc/webrtcvideocapturer.h"
+#include "talk/media/webrtc/webrtcvideodecoderfactory.h"
#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
#include "third_party/icu/source/common/unicode/unistr.h"
+#include "third_party/libyuv/include/libyuv/convert.h"
#include "third_party/libyuv/include/libyuv/convert_from.h"
#include "third_party/libyuv/include/libyuv/video_common.h"
+#include "webrtc/base/bind.h"
+#include "webrtc/base/checks.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/common_video/interface/texture_video_frame.h"
#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/system_wrappers/interface/compile_assert.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/video_engine/include/vie_base.h"
#include "webrtc/voice_engine/include/voe_base.h"
-#ifdef ANDROID
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
+#include <android/log.h>
+#include "webrtc/modules/video_capture/video_capture_internal.h"
+#include "webrtc/modules/video_render/video_render_internal.h"
#include "webrtc/system_wrappers/interface/logcat_trace_context.h"
+#include "webrtc/system_wrappers/interface/tick_util.h"
+using webrtc::CodecSpecificInfo;
+using webrtc::DecodedImageCallback;
+using webrtc::EncodedImage;
+using webrtc::I420VideoFrame;
using webrtc::LogcatTraceContext;
+using webrtc::RTPFragmentationHeader;
+using webrtc::TextureVideoFrame;
+using webrtc::TickTime;
+using webrtc::VideoCodec;
#endif
using icu::UnicodeString;
-using talk_base::Bind;
-using talk_base::Thread;
-using talk_base::ThreadManager;
-using talk_base::scoped_ptr;
+using rtc::Bind;
+using rtc::Thread;
+using rtc::ThreadManager;
+using rtc::scoped_ptr;
using webrtc::AudioSourceInterface;
using webrtc::AudioTrackInterface;
using webrtc::AudioTrackVector;
@@ -103,6 +119,7 @@
using webrtc::DataChannelInterface;
using webrtc::DataChannelObserver;
using webrtc::IceCandidateInterface;
+using webrtc::NativeHandle;
using webrtc::MediaConstraintsInterface;
using webrtc::MediaSourceInterface;
using webrtc::MediaStreamInterface;
@@ -120,33 +137,18 @@
using webrtc::VideoTrackVector;
using webrtc::kVideoCodecVP8;
-// Abort the process if |x| is false, emitting |msg|.
-#define CHECK(x, msg) \
- if (x) {} else { \
- LOG(LS_ERROR) << __FILE__ << ":" << __LINE__ << ": " << msg; \
- abort(); \
- }
-// Abort the process if |jni| has a Java exception pending, emitting |msg|.
-#define CHECK_EXCEPTION(jni, msg) \
- if (0) {} else { \
- if (jni->ExceptionCheck()) { \
- jni->ExceptionDescribe(); \
- jni->ExceptionClear(); \
- CHECK(0, msg); \
- } \
- }
+// Abort the process if |jni| has a Java exception pending.
+// This macros uses the comma operator to execute ExceptionDescribe
+// and ExceptionClear ignoring their return values and sending ""
+// to the error stream.
+#define CHECK_EXCEPTION(jni) \
+ CHECK(!jni->ExceptionCheck()) \
+ << (jni->ExceptionDescribe(), jni->ExceptionClear(), "")
-// Helper that calls ptr->Release() and logs a useful message if that didn't
-// actually delete *ptr because of extra refcounts.
-#define CHECK_RELEASE(ptr) \
- do { \
- int count = (ptr)->Release(); \
- if (count != 0) { \
- LOG(LS_ERROR) << "Refcount unexpectedly not 0: " << (ptr) \
- << ": " << count; \
- } \
- CHECK(!count, "Unexpected refcount"); \
- } while (0)
+// Helper that calls ptr->Release() and aborts the process with a useful
+// message if that didn't actually delete *ptr because of extra refcounts.
+#define CHECK_RELEASE(ptr) \
+ CHECK_EQ(0, (ptr)->Release()) << "Unexpected refcount."
namespace {
@@ -158,18 +160,25 @@
// were attached by the JVM because of a Java->native call.
static pthread_key_t g_jni_ptr;
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
+// Set in PeerConnectionFactory_initializeAndroidGlobals().
+static bool factory_static_initialized = false;
+#endif
+
+
// Return thread ID as a string.
static std::string GetThreadId() {
char buf[21]; // Big enough to hold a kuint64max plus terminating NULL.
- CHECK(snprintf(buf, sizeof(buf), "%llu", syscall(__NR_gettid)) <= sizeof(buf),
- "Thread id is bigger than uint64??");
+ CHECK_LT(snprintf(buf, sizeof(buf), "%llu", syscall(__NR_gettid)),
+ sizeof(buf))
+ << "Thread id is bigger than uint64??";
return std::string(buf);
}
// Return the current thread's name.
static std::string GetThreadName() {
char name[17];
- CHECK(prctl(PR_GET_NAME, name) == 0, "prctl(PR_GET_NAME) failed");
+ CHECK_EQ(0, prctl(PR_GET_NAME, name)) << "prctl(PR_GET_NAME) failed";
name[16] = '\0';
return std::string(name);
}
@@ -179,8 +188,8 @@
void* env = NULL;
jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);
CHECK(((env != NULL) && (status == JNI_OK)) ||
- ((env == NULL) && (status == JNI_EDETACHED)),
- "Unexpected GetEnv return: " << status << ":" << env);
+ ((env == NULL) && (status == JNI_EDETACHED)))
+ << "Unexpected GetEnv return: " << status << ":" << env;
return reinterpret_cast<JNIEnv*>(env);
}
@@ -195,16 +204,16 @@
if (!GetEnv())
return;
- CHECK(GetEnv() == prev_jni_ptr,
- "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv());
+ CHECK(GetEnv() == prev_jni_ptr)
+ << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv();
jint status = g_jvm->DetachCurrentThread();
- CHECK(status == JNI_OK, "Failed to detach thread: " << status);
- CHECK(!GetEnv(), "Detaching was a successful no-op???");
+ CHECK(status == JNI_OK) << "Failed to detach thread: " << status;
+ CHECK(!GetEnv()) << "Detaching was a successful no-op???";
}
static void CreateJNIPtrKey() {
- CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor),
- "pthread_key_create");
+ CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))
+ << "pthread_key_create";
}
// Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary.
@@ -212,7 +221,8 @@
JNIEnv* jni = GetEnv();
if (jni)
return jni;
- CHECK(!pthread_getspecific(g_jni_ptr), "TLS has a JNIEnv* but not attached?");
+ CHECK(!pthread_getspecific(g_jni_ptr))
+ << "TLS has a JNIEnv* but not attached?";
char* name = strdup((GetThreadName() + " - " + GetThreadId()).c_str());
JavaVMAttachArgs args;
@@ -225,11 +235,11 @@
#else
JNIEnv* env = NULL;
#endif
- CHECK(!g_jvm->AttachCurrentThread(&env, &args), "Failed to attach thread");
+ CHECK(!g_jvm->AttachCurrentThread(&env, &args)) << "Failed to attach thread";
free(name);
- CHECK(env, "AttachCurrentThread handed back NULL!");
+ CHECK(env) << "AttachCurrentThread handed back NULL!";
jni = reinterpret_cast<JNIEnv*>(env);
- CHECK(!pthread_setspecific(g_jni_ptr, jni), "pthread_setspecific");
+ CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
return jni;
}
@@ -261,9 +271,13 @@
LoadClass(jni, "org/webrtc/DataChannel$Init");
LoadClass(jni, "org/webrtc/DataChannel$State");
LoadClass(jni, "org/webrtc/IceCandidate");
-#ifdef ANDROID
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
+ LoadClass(jni, "android/graphics/SurfaceTexture");
+ LoadClass(jni, "android/opengl/EGLContext");
LoadClass(jni, "org/webrtc/MediaCodecVideoEncoder");
LoadClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
+ LoadClass(jni, "org/webrtc/MediaCodecVideoDecoder");
+ LoadClass(jni, "org/webrtc/MediaCodecVideoDecoder$DecoderOutputBufferInfo");
#endif
LoadClass(jni, "org/webrtc/MediaSource$State");
LoadClass(jni, "org/webrtc/MediaStream");
@@ -280,7 +294,7 @@
}
~ClassReferenceHolder() {
- CHECK(classes_.empty(), "Must call FreeReferences() before dtor!");
+ CHECK(classes_.empty()) << "Must call FreeReferences() before dtor!";
}
void FreeReferences(JNIEnv* jni) {
@@ -293,20 +307,20 @@
jclass GetClass(const std::string& name) {
std::map<std::string, jclass>::iterator it = classes_.find(name);
- CHECK(it != classes_.end(), "Unexpected GetClass() call for: " << name);
+ CHECK(it != classes_.end()) << "Unexpected GetClass() call for: " << name;
return it->second;
}
private:
void LoadClass(JNIEnv* jni, const std::string& name) {
jclass localRef = jni->FindClass(name.c_str());
- CHECK_EXCEPTION(jni, "error during FindClass: " << name);
- CHECK(localRef, name);
+ CHECK_EXCEPTION(jni) << "error during FindClass: " << name;
+ CHECK(localRef) << name;
jclass globalRef = reinterpret_cast<jclass>(jni->NewGlobalRef(localRef));
- CHECK_EXCEPTION(jni, "error during NewGlobalRef: " << name);
- CHECK(globalRef, name);
+ CHECK_EXCEPTION(jni) << "error during NewGlobalRef: " << name;
+ CHECK(globalRef) << name;
bool inserted = classes_.insert(std::make_pair(name, globalRef)).second;
- CHECK(inserted, "Duplicate class name: " << name);
+ CHECK(inserted) << "Duplicate class name: " << name;
}
std::map<std::string, jclass> classes_;
@@ -320,27 +334,26 @@
jmethodID GetMethodID(
JNIEnv* jni, jclass c, const std::string& name, const char* signature) {
jmethodID m = jni->GetMethodID(c, name.c_str(), signature);
- CHECK_EXCEPTION(jni,
- "error during GetMethodID: " << name << ", " << signature);
- CHECK(m, name << ", " << signature);
+ CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", "
+ << signature;
+ CHECK(m) << name << ", " << signature;
return m;
}
jmethodID GetStaticMethodID(
JNIEnv* jni, jclass c, const char* name, const char* signature) {
jmethodID m = jni->GetStaticMethodID(c, name, signature);
- CHECK_EXCEPTION(jni,
- "error during GetStaticMethodID: "
- << name << ", " << signature);
- CHECK(m, name << ", " << signature);
+ CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", "
+ << signature;
+ CHECK(m) << name << ", " << signature;
return m;
}
jfieldID GetFieldID(
JNIEnv* jni, jclass c, const char* name, const char* signature) {
jfieldID f = jni->GetFieldID(c, name, signature);
- CHECK_EXCEPTION(jni, "error during GetFieldID");
- CHECK(f, name << ", " << signature);
+ CHECK_EXCEPTION(jni) << "error during GetFieldID";
+ CHECK(f) << name << ", " << signature;
return f;
}
@@ -352,15 +365,15 @@
jclass GetObjectClass(JNIEnv* jni, jobject object) {
jclass c = jni->GetObjectClass(object);
- CHECK_EXCEPTION(jni, "error during GetObjectClass");
- CHECK(c, "");
+ CHECK_EXCEPTION(jni) << "error during GetObjectClass";
+ CHECK(c) << "GetObjectClass returned NULL";
return c;
}
jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
jobject o = jni->GetObjectField(object, id);
- CHECK_EXCEPTION(jni, "error during GetObjectField");
- CHECK(o, "");
+ CHECK_EXCEPTION(jni) << "error during GetObjectField";
+ CHECK(o) << "GetObjectField returned NULL";
return o;
}
@@ -370,32 +383,32 @@
jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {
jlong l = jni->GetLongField(object, id);
- CHECK_EXCEPTION(jni, "error during GetLongField");
+ CHECK_EXCEPTION(jni) << "error during GetLongField";
return l;
}
jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {
jint i = jni->GetIntField(object, id);
- CHECK_EXCEPTION(jni, "error during GetIntField");
+ CHECK_EXCEPTION(jni) << "error during GetIntField";
return i;
}
bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {
jboolean b = jni->GetBooleanField(object, id);
- CHECK_EXCEPTION(jni, "error during GetBooleanField");
+ CHECK_EXCEPTION(jni) << "error during GetBooleanField";
return b;
}
jobject NewGlobalRef(JNIEnv* jni, jobject o) {
jobject ret = jni->NewGlobalRef(o);
- CHECK_EXCEPTION(jni, "error during NewGlobalRef");
- CHECK(ret, "");
+ CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
+ CHECK(ret);
return ret;
}
void DeleteGlobalRef(JNIEnv* jni, jobject o) {
jni->DeleteGlobalRef(o);
- CHECK_EXCEPTION(jni, "error during DeleteGlobalRef");
+ CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
}
// Given a jweak reference, allocate a (strong) local reference scoped to the
@@ -405,12 +418,12 @@
public:
WeakRef(JNIEnv* jni, jweak ref)
: jni_(jni), obj_(jni_->NewLocalRef(ref)) {
- CHECK_EXCEPTION(jni, "error during NewLocalRef");
+ CHECK_EXCEPTION(jni) << "error during NewLocalRef";
}
~WeakRef() {
if (obj_) {
jni_->DeleteLocalRef(obj_);
- CHECK_EXCEPTION(jni_, "error during DeleteLocalRef");
+ CHECK_EXCEPTION(jni_) << "error during DeleteLocalRef";
}
}
jobject obj() { return obj_; }
@@ -426,7 +439,7 @@
class ScopedLocalRefFrame {
public:
explicit ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
- CHECK(!jni_->PushLocalFrame(0), "Failed to PushLocalFrame");
+ CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
}
~ScopedLocalRefFrame() {
jni_->PopLocalFrame(NULL);
@@ -469,9 +482,9 @@
jni, state_class, "values", ("()[L" + state_class_name + ";").c_str());
jobjectArray state_values = static_cast<jobjectArray>(
jni->CallStaticObjectMethod(state_class, state_values_id));
- CHECK_EXCEPTION(jni, "error during CallStaticObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
jobject ret = jni->GetObjectArrayElement(state_values, index);
- CHECK_EXCEPTION(jni, "error during GetObjectArrayElement");
+ CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
return ret;
}
@@ -479,18 +492,18 @@
static jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
UnicodeString ustr(UnicodeString::fromUTF8(native));
jstring jstr = jni->NewString(ustr.getBuffer(), ustr.length());
- CHECK_EXCEPTION(jni, "error during NewString");
+ CHECK_EXCEPTION(jni) << "error during NewString";
return jstr;
}
// Given a (UTF-16) jstring return a new UTF-8 native string.
static std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
const jchar* jchars = jni->GetStringChars(j_string, NULL);
- CHECK_EXCEPTION(jni, "Error during GetStringChars");
+ CHECK_EXCEPTION(jni) << "Error during GetStringChars";
UnicodeString ustr(jchars, jni->GetStringLength(j_string));
- CHECK_EXCEPTION(jni, "Error during GetStringLength");
+ CHECK_EXCEPTION(jni) << "Error during GetStringLength";
jni->ReleaseStringChars(j_string, jchars);
- CHECK_EXCEPTION(jni, "Error during ReleaseStringChars");
+ CHECK_EXCEPTION(jni) << "Error during ReleaseStringChars";
std::string ret;
return ustr.toUTF8String(ret);
}
@@ -550,7 +563,7 @@
virtual void OnIceCandidate(const IceCandidateInterface* candidate) OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
std::string sdp;
- CHECK(candidate->ToString(&sdp), "got so far: " << sdp);
+ CHECK(candidate->ToString(&sdp)) << "got so far: " << sdp;
jclass candidate_class = FindClass(jni(), "org/webrtc/IceCandidate");
jmethodID ctor = GetMethodID(jni(), candidate_class,
"<init>", "(Ljava/lang/String;ILjava/lang/String;)V");
@@ -558,18 +571,18 @@
jstring j_sdp = JavaStringFromStdString(jni(), sdp);
jobject j_candidate = jni()->NewObject(
candidate_class, ctor, j_mid, candidate->sdp_mline_index(), j_sdp);
- CHECK_EXCEPTION(jni(), "error during NewObject");
+ CHECK_EXCEPTION(jni()) << "error during NewObject";
jmethodID m = GetMethodID(jni(), *j_observer_class_,
"onIceCandidate", "(Lorg/webrtc/IceCandidate;)V");
jni()->CallVoidMethod(*j_observer_global_, m, j_candidate);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnError() OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
jmethodID m = GetMethodID(jni(), *j_observer_class_, "onError", "()V");
jni()->CallVoidMethod(*j_observer_global_, m);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnSignalingChange(
@@ -581,7 +594,7 @@
jobject new_state_enum =
JavaEnumFromIndex(jni(), "PeerConnection$SignalingState", new_state);
jni()->CallVoidMethod(*j_observer_global_, m, new_state_enum);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnIceConnectionChange(
@@ -593,7 +606,7 @@
jobject new_state_enum = JavaEnumFromIndex(
jni(), "PeerConnection$IceConnectionState", new_state);
jni()->CallVoidMethod(*j_observer_global_, m, new_state_enum);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnIceGatheringChange(
@@ -605,14 +618,14 @@
jobject new_state_enum = JavaEnumFromIndex(
jni(), "PeerConnection$IceGatheringState", new_state);
jni()->CallVoidMethod(*j_observer_global_, m, new_state_enum);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnAddStream(MediaStreamInterface* stream) OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
jobject j_stream = jni()->NewObject(
*j_media_stream_class_, j_media_stream_ctor_, (jlong)stream);
- CHECK_EXCEPTION(jni(), "error during NewObject");
+ CHECK_EXCEPTION(jni()) << "error during NewObject";
AudioTrackVector audio_tracks = stream->GetAudioTracks();
for (size_t i = 0; i < audio_tracks.size(); ++i) {
@@ -620,7 +633,7 @@
jstring id = JavaStringFromStdString(jni(), track->id());
jobject j_track = jni()->NewObject(
*j_audio_track_class_, j_audio_track_ctor_, (jlong)track, id);
- CHECK_EXCEPTION(jni(), "error during NewObject");
+ CHECK_EXCEPTION(jni()) << "error during NewObject";
jfieldID audio_tracks_id = GetFieldID(jni(),
*j_media_stream_class_,
"audioTracks",
@@ -631,8 +644,8 @@
"add",
"(Ljava/lang/Object;)Z");
jboolean added = jni()->CallBooleanMethod(audio_tracks, add, j_track);
- CHECK_EXCEPTION(jni(), "error during CallBooleanMethod");
- CHECK(added, "");
+ CHECK_EXCEPTION(jni()) << "error during CallBooleanMethod";
+ CHECK(added);
}
VideoTrackVector video_tracks = stream->GetVideoTracks();
@@ -641,7 +654,7 @@
jstring id = JavaStringFromStdString(jni(), track->id());
jobject j_track = jni()->NewObject(
*j_video_track_class_, j_video_track_ctor_, (jlong)track, id);
- CHECK_EXCEPTION(jni(), "error during NewObject");
+ CHECK_EXCEPTION(jni()) << "error during NewObject";
jfieldID video_tracks_id = GetFieldID(jni(),
*j_media_stream_class_,
"videoTracks",
@@ -652,22 +665,22 @@
"add",
"(Ljava/lang/Object;)Z");
jboolean added = jni()->CallBooleanMethod(video_tracks, add, j_track);
- CHECK_EXCEPTION(jni(), "error during CallBooleanMethod");
- CHECK(added, "");
+ CHECK_EXCEPTION(jni()) << "error during CallBooleanMethod";
+ CHECK(added);
}
streams_[stream] = jni()->NewWeakGlobalRef(j_stream);
- CHECK_EXCEPTION(jni(), "error during NewWeakGlobalRef");
+ CHECK_EXCEPTION(jni()) << "error during NewWeakGlobalRef";
jmethodID m = GetMethodID(jni(), *j_observer_class_, "onAddStream",
"(Lorg/webrtc/MediaStream;)V");
jni()->CallVoidMethod(*j_observer_global_, m, j_stream);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnRemoveStream(MediaStreamInterface* stream) OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
NativeToJavaStreamsMap::iterator it = streams_.find(stream);
- CHECK(it != streams_.end(), "unexpected stream: " << std::hex << stream);
+ CHECK(it != streams_.end()) << "unexpected stream: " << std::hex << stream;
WeakRef s(jni(), it->second);
streams_.erase(it);
@@ -677,14 +690,14 @@
jmethodID m = GetMethodID(jni(), *j_observer_class_, "onRemoveStream",
"(Lorg/webrtc/MediaStream;)V");
jni()->CallVoidMethod(*j_observer_global_, m, s.obj());
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnDataChannel(DataChannelInterface* channel) OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
jobject j_channel = jni()->NewObject(
*j_data_channel_class_, j_data_channel_ctor_, (jlong)channel);
- CHECK_EXCEPTION(jni(), "error during NewObject");
+ CHECK_EXCEPTION(jni()) << "error during NewObject";
jmethodID m = GetMethodID(jni(), *j_observer_class_, "onDataChannel",
"(Lorg/webrtc/DataChannel;)V");
@@ -695,9 +708,9 @@
// CallVoidMethod above as Java code might call back into native code and be
// surprised to see a refcount of 2.
int bumped_count = channel->AddRef();
- CHECK(bumped_count == 2, "Unexpected refcount OnDataChannel");
+ CHECK(bumped_count == 2) << "Unexpected refcount OnDataChannel";
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnRenegotiationNeeded() OVERRIDE {
@@ -705,11 +718,11 @@
jmethodID m =
GetMethodID(jni(), *j_observer_class_, "onRenegotiationNeeded", "()V");
jni()->CallVoidMethod(*j_observer_global_, m);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
void SetConstraints(ConstraintsWrapper* constraints) {
- CHECK(!constraints_.get(), "constraints already set!");
+ CHECK(!constraints_.get()) << "constraints already set!";
constraints_.reset(constraints);
}
@@ -768,29 +781,29 @@
jmethodID j_iterator_id = GetMethodID(jni,
GetObjectClass(jni, j_list), "iterator", "()Ljava/util/Iterator;");
jobject j_iterator = jni->CallObjectMethod(j_list, j_iterator_id);
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
jmethodID j_has_next = GetMethodID(jni,
GetObjectClass(jni, j_iterator), "hasNext", "()Z");
jmethodID j_next = GetMethodID(jni,
GetObjectClass(jni, j_iterator), "next", "()Ljava/lang/Object;");
while (jni->CallBooleanMethod(j_iterator, j_has_next)) {
- CHECK_EXCEPTION(jni, "error during CallBooleanMethod");
+ CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
jobject entry = jni->CallObjectMethod(j_iterator, j_next);
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
jmethodID get_key = GetMethodID(jni,
GetObjectClass(jni, entry), "getKey", "()Ljava/lang/String;");
jstring j_key = reinterpret_cast<jstring>(
jni->CallObjectMethod(entry, get_key));
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
jmethodID get_value = GetMethodID(jni,
GetObjectClass(jni, entry), "getValue", "()Ljava/lang/String;");
jstring j_value = reinterpret_cast<jstring>(
jni->CallObjectMethod(entry, get_value));
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
field->push_back(Constraint(JavaToStdString(jni, j_key),
JavaToStdString(jni, j_value)));
}
- CHECK_EXCEPTION(jni, "error during CallBooleanMethod");
+ CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
}
Constraints mandatory_;
@@ -800,7 +813,7 @@
static jobject JavaSdpFromNativeSdp(
JNIEnv* jni, const SessionDescriptionInterface* desc) {
std::string sdp;
- CHECK(desc->ToString(&sdp), "got so far: " << sdp);
+ CHECK(desc->ToString(&sdp)) << "got so far: " << sdp;
jstring j_description = JavaStringFromStdString(jni, sdp);
jclass j_type_class = FindClass(
@@ -811,7 +824,7 @@
jstring j_type_string = JavaStringFromStdString(jni, desc->type());
jobject j_type = jni->CallStaticObjectMethod(
j_type_class, j_type_from_canonical, j_type_string);
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
jclass j_sdp_class = FindClass(jni, "org/webrtc/SessionDescription");
jmethodID j_sdp_ctor = GetMethodID(
@@ -819,7 +832,7 @@
"(Lorg/webrtc/SessionDescription$Type;Ljava/lang/String;)V");
jobject j_sdp = jni->NewObject(
j_sdp_class, j_sdp_ctor, j_type, j_description);
- CHECK_EXCEPTION(jni, "error during NewObject");
+ CHECK_EXCEPTION(jni) << "error during NewObject";
return j_sdp;
}
@@ -840,7 +853,7 @@
ScopedLocalRefFrame local_ref_frame(jni());
jmethodID m = GetMethodID(jni(), *j_observer_class_, "onSetSuccess", "()V");
jni()->CallVoidMethod(*j_observer_global_, m);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
// Can't mark OVERRIDE because of templating.
@@ -851,7 +864,7 @@
"(Lorg/webrtc/SessionDescription;)V");
jobject j_sdp = JavaSdpFromNativeSdp(jni(), desc);
jni()->CallVoidMethod(*j_observer_global_, m, j_sdp);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
protected:
@@ -862,7 +875,7 @@
"(Ljava/lang/String;)V");
jstring j_error_string = JavaStringFromStdString(jni(), error);
jni()->CallVoidMethod(*j_observer_global_, m, j_error_string);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
JNIEnv* jni() {
@@ -908,11 +921,11 @@
DataChannelObserverWrapper(JNIEnv* jni, jobject j_observer)
: j_observer_global_(jni, j_observer),
j_observer_class_(jni, GetObjectClass(jni, j_observer)),
+ j_buffer_class_(jni, FindClass(jni, "org/webrtc/DataChannel$Buffer")),
j_on_state_change_mid_(GetMethodID(jni, *j_observer_class_,
"onStateChange", "()V")),
j_on_message_mid_(GetMethodID(jni, *j_observer_class_, "onMessage",
"(Lorg/webrtc/DataChannel$Buffer;)V")),
- j_buffer_class_(jni, FindClass(jni, "org/webrtc/DataChannel$Buffer")),
j_buffer_ctor_(GetMethodID(jni, *j_buffer_class_,
"<init>", "(Ljava/nio/ByteBuffer;Z)V")) {
}
@@ -922,7 +935,7 @@
virtual void OnStateChange() OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
jni()->CallVoidMethod(*j_observer_global_, j_on_state_change_mid_);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
virtual void OnMessage(const DataBuffer& buffer) OVERRIDE {
@@ -933,7 +946,7 @@
jobject j_buffer = jni()->NewObject(*j_buffer_class_, j_buffer_ctor_,
byte_buffer, buffer.binary);
jni()->CallVoidMethod(*j_observer_global_, j_on_message_mid_, j_buffer);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
private:
@@ -976,7 +989,7 @@
jmethodID m = GetMethodID(jni(), *j_observer_class_, "onComplete",
"([Lorg/webrtc/StatsReport;)V");
jni()->CallVoidMethod(*j_observer_global_, m, j_reports);
- CHECK_EXCEPTION(jni(), "error during CallVoidMethod");
+ CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
}
private:
@@ -1058,6 +1071,38 @@
scoped_ptr<cricket::VideoRenderer> renderer_;
};
+// Wrapper for texture object in TextureVideoFrame.
+class NativeHandleImpl : public NativeHandle {
+ public:
+ NativeHandleImpl() :
+ ref_count_(0), texture_object_(NULL), texture_id_(-1) {}
+ virtual ~NativeHandleImpl() {}
+ virtual int32_t AddRef() {
+ return ++ref_count_;
+ }
+ virtual int32_t Release() {
+ return --ref_count_;
+ }
+ virtual void* GetHandle() {
+ return texture_object_;
+ }
+ int GetTextureId() {
+ return texture_id_;
+ }
+ void SetTextureObject(void *texture_object, int texture_id) {
+ texture_object_ = reinterpret_cast<jobject>(texture_object);
+ texture_id_ = texture_id;
+ }
+ int32_t ref_count() {
+ return ref_count_;
+ }
+
+ private:
+ int32_t ref_count_;
+ jobject texture_object_;
+ int32_t texture_id_;
+};
+
// Wrapper dispatching webrtc::VideoRendererInterface to a Java VideoRenderer
// instance.
class JavaVideoRendererWrapper : public VideoRendererInterface {
@@ -1071,10 +1116,13 @@
"(Lorg/webrtc/VideoRenderer$I420Frame;)V")),
j_frame_class_(jni,
FindClass(jni, "org/webrtc/VideoRenderer$I420Frame")),
- j_frame_ctor_id_(GetMethodID(
+ j_i420_frame_ctor_id_(GetMethodID(
jni, *j_frame_class_, "<init>", "(II[I[Ljava/nio/ByteBuffer;)V")),
+ j_texture_frame_ctor_id_(GetMethodID(
+ jni, *j_frame_class_, "<init>",
+ "(IILjava/lang/Object;I)V")),
j_byte_buffer_class_(jni, FindClass(jni, "java/nio/ByteBuffer")) {
- CHECK_EXCEPTION(jni, "");
+ CHECK_EXCEPTION(jni);
}
virtual ~JavaVideoRendererWrapper() {}
@@ -1082,19 +1130,25 @@
virtual void SetSize(int width, int height) OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
jni()->CallVoidMethod(*j_callbacks_, j_set_size_id_, width, height);
- CHECK_EXCEPTION(jni(), "");
+ CHECK_EXCEPTION(jni());
}
virtual void RenderFrame(const cricket::VideoFrame* frame) OVERRIDE {
ScopedLocalRefFrame local_ref_frame(jni());
- jobject j_frame = CricketToJavaFrame(frame);
- jni()->CallVoidMethod(*j_callbacks_, j_render_frame_id_, j_frame);
- CHECK_EXCEPTION(jni(), "");
+ if (frame->GetNativeHandle() != NULL) {
+ jobject j_frame = CricketToJavaTextureFrame(frame);
+ jni()->CallVoidMethod(*j_callbacks_, j_render_frame_id_, j_frame);
+ CHECK_EXCEPTION(jni());
+ } else {
+ jobject j_frame = CricketToJavaI420Frame(frame);
+ jni()->CallVoidMethod(*j_callbacks_, j_render_frame_id_, j_frame);
+ CHECK_EXCEPTION(jni());
+ }
}
private:
// Return a VideoRenderer.I420Frame referring to the data in |frame|.
- jobject CricketToJavaFrame(const cricket::VideoFrame* frame) {
+ jobject CricketToJavaI420Frame(const cricket::VideoFrame* frame) {
jintArray strides = jni()->NewIntArray(3);
jint* strides_array = jni()->GetIntArrayElements(strides, NULL);
strides_array[0] = frame->GetYPitch();
@@ -1113,10 +1167,21 @@
jni()->SetObjectArrayElement(planes, 1, u_buffer);
jni()->SetObjectArrayElement(planes, 2, v_buffer);
return jni()->NewObject(
- *j_frame_class_, j_frame_ctor_id_,
+ *j_frame_class_, j_i420_frame_ctor_id_,
frame->GetWidth(), frame->GetHeight(), strides, planes);
}
+ // Return a VideoRenderer.I420Frame referring texture object in |frame|.
+ jobject CricketToJavaTextureFrame(const cricket::VideoFrame* frame) {
+ NativeHandleImpl* handle =
+ reinterpret_cast<NativeHandleImpl*>(frame->GetNativeHandle());
+ jobject texture_object = reinterpret_cast<jobject>(handle->GetHandle());
+ int texture_id = handle->GetTextureId();
+ return jni()->NewObject(
+ *j_frame_class_, j_texture_frame_ctor_id_,
+ frame->GetWidth(), frame->GetHeight(), texture_object, texture_id);
+ }
+
JNIEnv* jni() {
return AttachCurrentThreadIfNeeded();
}
@@ -1125,23 +1190,25 @@
jmethodID j_set_size_id_;
jmethodID j_render_frame_id_;
ScopedGlobalRef<jclass> j_frame_class_;
- jmethodID j_frame_ctor_id_;
+ jmethodID j_i420_frame_ctor_id_;
+ jmethodID j_texture_frame_ctor_id_;
ScopedGlobalRef<jclass> j_byte_buffer_class_;
};
-#ifdef ANDROID
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
// TODO(fischman): consider pulling MediaCodecVideoEncoder out of this file and
// into its own .h/.cc pair, if/when the JNI helper stuff above is extracted
// from this file.
//#define TRACK_BUFFER_TIMING
+#define TAG "MediaCodecVideo"
#ifdef TRACK_BUFFER_TIMING
-#include <android/log.h>
-#define TAG "MediaCodecVideoEncoder"
#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#else
#define ALOGV(...)
#endif
+#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
+#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
// Color formats supported by encoder - should mirror supportedColorList
// from MediaCodecVideoEncoder.java
@@ -1158,6 +1225,14 @@
// Arbitrary interval to poll the codec for new outputs.
enum { kMediaCodecPollMs = 10 };
+// Media codec maximum output buffer ready timeout.
+enum { kMediaCodecTimeoutMs = 500 };
+// Interval to print codec statistics (bitrate, fps, encoding/decoding time).
+enum { kMediaCodecStatisticsIntervalMs = 3000 };
+
+static int64_t GetCurrentTimeMs() {
+ return TickTime::Now().Ticks() / 1000000LL;
+}
// MediaCodecVideoEncoder is a webrtc::VideoEncoder implementation that uses
// Android's MediaCodec SDK API behind the scenes to implement (hopefully)
@@ -1166,7 +1241,7 @@
// MediaCodecVideoEncoder is created, operated, and destroyed on a single
// thread, currently the libjingle Worker thread.
class MediaCodecVideoEncoder : public webrtc::VideoEncoder,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
virtual ~MediaCodecVideoEncoder();
explicit MediaCodecVideoEncoder(JNIEnv* jni);
@@ -1187,8 +1262,8 @@
int /* rtt */) OVERRIDE;
virtual int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) OVERRIDE;
- // talk_base::MessageHandler implementation.
- virtual void OnMessage(talk_base::Message* msg) OVERRIDE;
+ // rtc::MessageHandler implementation.
+ virtual void OnMessage(rtc::Message* msg) OVERRIDE;
private:
// CHECK-fail if not running on |codec_thread_|.
@@ -1213,9 +1288,6 @@
int32_t ReleaseOnCodecThread();
int32_t SetRatesOnCodecThread(uint32_t new_bit_rate, uint32_t frame_rate);
- // Reset parameters valid between InitEncode() & Release() (see below).
- void ResetParameters(JNIEnv* jni);
-
// Helper accessors for MediaCodecVideoEncoder$OutputBufferInfo members.
int GetOutputBufferInfoIndex(JNIEnv* jni, jobject j_output_buffer_info);
jobject GetOutputBufferInfoBuffer(JNIEnv* jni, jobject j_output_buffer_info);
@@ -1254,14 +1326,25 @@
// Touched only on codec_thread_ so no explicit synchronization necessary.
int width_; // Frame width in pixels.
int height_; // Frame height in pixels.
+ bool inited_;
enum libyuv::FourCC encoder_fourcc_; // Encoder color space format.
int last_set_bitrate_kbps_; // Last-requested bitrate in kbps.
int last_set_fps_; // Last-requested frame rate.
- int frames_received_; // Number of frames received by encoder.
- int frames_dropped_; // Number of frames dropped by encoder.
- int frames_in_queue_; // Number of frames in encoder queue.
- int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
- int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
+ int64_t current_timestamp_us_; // Current frame timestamps in us.
+ int frames_received_; // Number of frames received by encoder.
+ int frames_dropped_; // Number of frames dropped by encoder.
+ int frames_resolution_update_; // Number of frames with new codec resolution.
+ int frames_in_queue_; // Number of frames in encoder queue.
+ int64_t start_time_ms_; // Start time for statistics.
+ int current_frames_; // Number of frames in the current statistics interval.
+ int current_bytes_; // Encoded bytes in the current statistics interval.
+ int current_encoding_time_ms_; // Overall encoding time in the current second
+ int64_t last_input_timestamp_ms_; // Timestamp of last received yuv frame.
+ int64_t last_output_timestamp_ms_; // Timestamp of last encoded frame.
+ std::vector<int32_t> timestamps_; // Video frames timestamp queue.
+ std::vector<int64_t> render_times_ms_; // Video frames render time queue.
+ std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
+ // encoder input.
// Frame size in bytes fed to MediaCodec.
int yuv_size_;
// True only when between a callback_->Encoded() call return a positive value
@@ -1272,24 +1355,24 @@
};
MediaCodecVideoEncoder::~MediaCodecVideoEncoder() {
- // We depend on ResetParameters() to ensure no more callbacks to us after we
- // are deleted, so assert it here.
- CHECK(width_ == 0, "Release() should have been called");
+ // Call Release() to ensure no more callbacks to us after we are deleted.
+ Release();
}
MediaCodecVideoEncoder::MediaCodecVideoEncoder(JNIEnv* jni)
- : callback_(NULL),
- codec_thread_(new Thread()),
- j_media_codec_video_encoder_class_(
- jni,
- FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
- j_media_codec_video_encoder_(
- jni,
- jni->NewObject(*j_media_codec_video_encoder_class_,
- GetMethodID(jni,
- *j_media_codec_video_encoder_class_,
- "<init>",
- "()V"))) {
+ : callback_(NULL),
+ inited_(false),
+ codec_thread_(new Thread()),
+ j_media_codec_video_encoder_class_(
+ jni,
+ FindClass(jni, "org/webrtc/MediaCodecVideoEncoder")),
+ j_media_codec_video_encoder_(
+ jni,
+ jni->NewObject(*j_media_codec_video_encoder_class_,
+ GetMethodID(jni,
+ *j_media_codec_video_encoder_class_,
+ "<init>",
+ "()V"))) {
ScopedLocalRefFrame local_ref_frame(jni);
// It would be nice to avoid spinning up a new thread per MediaCodec, and
// instead re-use e.g. the PeerConnectionFactory's |worker_thread_|, but bug
@@ -1299,9 +1382,7 @@
// in the bug, we have a problem. For now work around that with a dedicated
// thread.
codec_thread_->SetName("MediaCodecVideoEncoder", NULL);
- CHECK(codec_thread_->Start(), "Failed to start MediaCodecVideoEncoder");
-
- ResetParameters(jni);
+ CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoEncoder";
jclass j_output_buffer_info_class =
FindClass(jni, "org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo");
@@ -1335,7 +1416,7 @@
GetFieldID(jni, j_output_buffer_info_class, "isKeyFrame", "Z");
j_info_presentation_timestamp_us_field_ = GetFieldID(
jni, j_output_buffer_info_class, "presentationTimestampUs", "J");
- CHECK_EXCEPTION(jni, "MediaCodecVideoEncoder ctor failed");
+ CHECK_EXCEPTION(jni) << "MediaCodecVideoEncoder ctor failed";
}
int32_t MediaCodecVideoEncoder::InitEncode(
@@ -1343,7 +1424,7 @@
int32_t /* number_of_cores */,
uint32_t /* max_payload_size */) {
// Factory should guard against other codecs being used with us.
- CHECK(codec_settings->codecType == kVideoCodecVP8, "Unsupported codec");
+ CHECK(codec_settings->codecType == kVideoCodecVP8) << "Unsupported codec";
return codec_thread_->Invoke<int32_t>(
Bind(&MediaCodecVideoEncoder::InitEncodeOnCodecThread,
@@ -1389,15 +1470,18 @@
frame_rate));
}
-void MediaCodecVideoEncoder::OnMessage(talk_base::Message* msg) {
+void MediaCodecVideoEncoder::OnMessage(rtc::Message* msg) {
JNIEnv* jni = AttachCurrentThreadIfNeeded();
ScopedLocalRefFrame local_ref_frame(jni);
// We only ever send one message to |this| directly (not through a Bind()'d
// functor), so expect no ID/data.
- CHECK(!msg->message_id, "Unexpected message!");
- CHECK(!msg->pdata, "Unexpected message!");
+ CHECK(!msg->message_id) << "Unexpected message!";
+ CHECK(!msg->pdata) << "Unexpected message!";
CheckOnCodecThread();
+ if (!inited_) {
+ return;
+ }
// It would be nice to recover from a failure here if one happened, but it's
// unclear how to signal such a failure to the app, so instead we stay silent
@@ -1407,16 +1491,16 @@
}
void MediaCodecVideoEncoder::CheckOnCodecThread() {
- CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread(),
- "Running on wrong thread!");
+ CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
+ << "Running on wrong thread!";
}
void MediaCodecVideoEncoder::ResetCodec() {
- LOG(LS_ERROR) << "ResetCodec";
+ ALOGE("ResetCodec");
if (Release() != WEBRTC_VIDEO_CODEC_OK ||
codec_thread_->Invoke<int32_t>(Bind(
- &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this, 0, 0, 0, 0))
- != WEBRTC_VIDEO_CODEC_OK) {
+ &MediaCodecVideoEncoder::InitEncodeOnCodecThread, this,
+ width_, height_, 0, 0)) != WEBRTC_VIDEO_CODEC_OK) {
// TODO(fischman): wouldn't it be nice if there was a way to gracefully
// degrade to a SW encoder at this point? There isn't one AFAICT :(
// https://code.google.com/p/webrtc/issues/detail?id=2920
@@ -1428,12 +1512,13 @@
CheckOnCodecThread();
JNIEnv* jni = AttachCurrentThreadIfNeeded();
ScopedLocalRefFrame local_ref_frame(jni);
- LOG(LS_INFO) << "InitEncodeOnCodecThread " << width << " x " << height;
- if (width == 0) {
- width = width_;
- height = height_;
+ ALOGD("InitEncodeOnCodecThread %d x %d. Bitrate: %d kbps. Fps: %d",
+ width, height, kbps, fps);
+ if (kbps == 0) {
kbps = last_set_bitrate_kbps_;
+ }
+ if (fps == 0) {
fps = last_set_fps_;
}
@@ -1444,9 +1529,19 @@
yuv_size_ = width_ * height_ * 3 / 2;
frames_received_ = 0;
frames_dropped_ = 0;
+ frames_resolution_update_ = 0;
frames_in_queue_ = 0;
+ current_timestamp_us_ = 0;
+ start_time_ms_ = GetCurrentTimeMs();
+ current_frames_ = 0;
+ current_bytes_ = 0;
+ current_encoding_time_ms_ = 0;
last_input_timestamp_ms_ = -1;
last_output_timestamp_ms_ = -1;
+ timestamps_.clear();
+ render_times_ms_.clear();
+ frame_rtc_times_ms_.clear();
+ drop_next_input_frame_ = false;
// We enforce no extra stride/padding in the format creation step.
jobjectArray input_buffers = reinterpret_cast<jobjectArray>(
jni->CallObjectMethod(*j_media_codec_video_encoder_,
@@ -1455,10 +1550,11 @@
height_,
kbps,
fps));
- CHECK_EXCEPTION(jni, "");
+ CHECK_EXCEPTION(jni);
if (IsNull(jni, input_buffers))
return WEBRTC_VIDEO_CODEC_ERROR;
+ inited_ = true;
switch (GetIntField(jni, *j_media_codec_video_encoder_,
j_color_format_field_)) {
case COLOR_FormatYUV420Planar:
@@ -1474,17 +1570,18 @@
return WEBRTC_VIDEO_CODEC_ERROR;
}
size_t num_input_buffers = jni->GetArrayLength(input_buffers);
- CHECK(input_buffers_.empty(), "Unexpected double InitEncode without Release");
+ CHECK(input_buffers_.empty())
+ << "Unexpected double InitEncode without Release";
input_buffers_.resize(num_input_buffers);
for (size_t i = 0; i < num_input_buffers; ++i) {
input_buffers_[i] =
jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
int64 yuv_buffer_capacity =
jni->GetDirectBufferCapacity(input_buffers_[i]);
- CHECK_EXCEPTION(jni, "");
- CHECK(yuv_buffer_capacity >= yuv_size_, "Insufficient capacity");
+ CHECK_EXCEPTION(jni);
+ CHECK(yuv_buffer_capacity >= yuv_size_) << "Insufficient capacity";
}
- CHECK_EXCEPTION(jni, "");
+ CHECK_EXCEPTION(jni);
codec_thread_->PostDelayed(kMediaCodecPollMs, this);
return WEBRTC_VIDEO_CODEC_OK;
@@ -1497,6 +1594,9 @@
JNIEnv* jni = AttachCurrentThreadIfNeeded();
ScopedLocalRefFrame local_ref_frame(jni);
+ if (!inited_) {
+ return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
+ }
frames_received_++;
if (!DeliverPendingOutputs(jni)) {
ResetCodec();
@@ -1504,23 +1604,35 @@
}
if (drop_next_input_frame_) {
+ ALOGV("Encoder drop frame - failed callback.");
drop_next_input_frame_ = false;
return WEBRTC_VIDEO_CODEC_OK;
}
- CHECK(frame_types->size() == 1, "Unexpected stream count");
+ CHECK(frame_types->size() == 1) << "Unexpected stream count";
+ if (frame.width() != width_ || frame.height() != height_) {
+ frames_resolution_update_++;
+ ALOGD("Unexpected frame resolution change from %d x %d to %d x %d",
+ width_, height_, frame.width(), frame.height());
+ if (frames_resolution_update_ > 3) {
+ // Reset codec if we received more than 3 frames with new resolution.
+ width_ = frame.width();
+ height_ = frame.height();
+ frames_resolution_update_ = 0;
+ ResetCodec();
+ }
+ return WEBRTC_VIDEO_CODEC_OK;
+ }
+ frames_resolution_update_ = 0;
+
bool key_frame = frame_types->front() != webrtc::kDeltaFrame;
- CHECK(frame.width() == width_, "Unexpected resolution change");
- CHECK(frame.height() == height_, "Unexpected resolution change");
-
// Check if we accumulated too many frames in encoder input buffers
- // so the encoder latency exceeds 100ms and drop frame if so.
- if (frames_in_queue_ > 0 && last_input_timestamp_ms_ > 0 &&
- last_output_timestamp_ms_ > 0) {
+ // or the encoder latency exceeds 70 ms and drop frame if so.
+ if (frames_in_queue_ > 0 && last_input_timestamp_ms_ >= 0) {
int encoder_latency_ms = last_input_timestamp_ms_ -
last_output_timestamp_ms_;
- if (encoder_latency_ms > 100) {
+ if (frames_in_queue_ > 2 || encoder_latency_ms > 70) {
ALOGV("Drop frame - encoder is behind by %d ms. Q size: %d",
encoder_latency_ms, frames_in_queue_);
frames_dropped_++;
@@ -1530,10 +1642,10 @@
int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_encoder_,
j_dequeue_input_buffer_method_);
- CHECK_EXCEPTION(jni, "");
+ CHECK_EXCEPTION(jni);
if (j_input_buffer_index == -1) {
// Video codec falls behind - no input buffer available.
- ALOGV("Drop frame - no input buffers available");
+ ALOGV("Encoder drop frame - no input buffers available");
frames_dropped_++;
return WEBRTC_VIDEO_CODEC_OK; // TODO(fischman): see webrtc bug 2887.
}
@@ -1542,32 +1654,39 @@
return WEBRTC_VIDEO_CODEC_ERROR;
}
- ALOGV("Frame # %d. Buffer # %d. TS: %lld.",
- frames_received_, j_input_buffer_index, frame.render_time_ms());
+ ALOGV("Encode frame # %d. Buffer # %d. TS: %lld.",
+ frames_received_, j_input_buffer_index, current_timestamp_us_ / 1000);
jobject j_input_buffer = input_buffers_[j_input_buffer_index];
uint8* yuv_buffer =
reinterpret_cast<uint8*>(jni->GetDirectBufferAddress(j_input_buffer));
- CHECK_EXCEPTION(jni, "");
- CHECK(yuv_buffer, "Indirect buffer??");
+ CHECK_EXCEPTION(jni);
+ CHECK(yuv_buffer) << "Indirect buffer??";
CHECK(!libyuv::ConvertFromI420(
frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
yuv_buffer, width_,
width_, height_,
- encoder_fourcc_),
- "ConvertFromI420 failed");
- jlong timestamp_us = frame.render_time_ms() * 1000;
- last_input_timestamp_ms_ = frame.render_time_ms();
+ encoder_fourcc_))
+ << "ConvertFromI420 failed";
+ last_input_timestamp_ms_ = current_timestamp_us_ / 1000;
frames_in_queue_++;
+
+ // Save input image timestamps for later output
+ timestamps_.push_back(frame.timestamp());
+ render_times_ms_.push_back(frame.render_time_ms());
+ frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
+
bool encode_status = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
j_encode_method_,
key_frame,
j_input_buffer_index,
yuv_size_,
- timestamp_us);
- CHECK_EXCEPTION(jni, "");
+ current_timestamp_us_);
+ CHECK_EXCEPTION(jni);
+ current_timestamp_us_ += 1000000 / last_set_fps_;
+
if (!encode_status || !DeliverPendingOutputs(jni)) {
ResetCodec();
return WEBRTC_VIDEO_CODEC_ERROR;
@@ -1586,17 +1705,21 @@
}
int32_t MediaCodecVideoEncoder::ReleaseOnCodecThread() {
+ if (!inited_) {
+ return WEBRTC_VIDEO_CODEC_OK;
+ }
CheckOnCodecThread();
JNIEnv* jni = AttachCurrentThreadIfNeeded();
- LOG(LS_INFO) << "Frames received: " << frames_received_ <<
- ". Frames dropped: " << frames_dropped_;
+ ALOGD("EncoderRelease: Frames received: %d. Frames dropped: %d.",
+ frames_received_,frames_dropped_);
ScopedLocalRefFrame local_ref_frame(jni);
for (size_t i = 0; i < input_buffers_.size(); ++i)
jni->DeleteGlobalRef(input_buffers_[i]);
input_buffers_.clear();
jni->CallVoidMethod(*j_media_codec_video_encoder_, j_release_method_);
- ResetParameters(jni);
- CHECK_EXCEPTION(jni, "");
+ CHECK_EXCEPTION(jni);
+ rtc::MessageQueueManager::Clear(this);
+ inited_ = false;
return WEBRTC_VIDEO_CODEC_OK;
}
@@ -1609,13 +1732,17 @@
}
JNIEnv* jni = AttachCurrentThreadIfNeeded();
ScopedLocalRefFrame local_ref_frame(jni);
- last_set_bitrate_kbps_ = new_bit_rate;
- last_set_fps_ = frame_rate;
+ if (new_bit_rate > 0) {
+ last_set_bitrate_kbps_ = new_bit_rate;
+ }
+ if (frame_rate > 0) {
+ last_set_fps_ = frame_rate;
+ }
bool ret = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
j_set_rates_method_,
- new_bit_rate,
- frame_rate);
- CHECK_EXCEPTION(jni, "");
+ last_set_bitrate_kbps_,
+ last_set_fps_);
+ CHECK_EXCEPTION(jni);
if (!ret) {
ResetCodec();
return WEBRTC_VIDEO_CODEC_ERROR;
@@ -1623,16 +1750,6 @@
return WEBRTC_VIDEO_CODEC_OK;
}
-void MediaCodecVideoEncoder::ResetParameters(JNIEnv* jni) {
- talk_base::MessageQueueManager::Clear(this);
- width_ = 0;
- height_ = 0;
- yuv_size_ = 0;
- drop_next_input_frame_ = false;
- CHECK(input_buffers_.empty(),
- "ResetParameters called while holding input_buffers_!");
-}
-
int MediaCodecVideoEncoder::GetOutputBufferInfoIndex(
JNIEnv* jni,
jobject j_output_buffer_info) {
@@ -1662,9 +1779,10 @@
while (true) {
jobject j_output_buffer_info = jni->CallObjectMethod(
*j_media_codec_video_encoder_, j_dequeue_output_buffer_method_);
- CHECK_EXCEPTION(jni, "");
- if (IsNull(jni, j_output_buffer_info))
+ CHECK_EXCEPTION(jni);
+ if (IsNull(jni, j_output_buffer_info)) {
break;
+ }
int output_buffer_index =
GetOutputBufferInfoIndex(jni, j_output_buffer_info);
@@ -1673,31 +1791,62 @@
return false;
}
- jlong capture_time_ms =
+ // Get frame timestamps from a queue.
+ last_output_timestamp_ms_ =
GetOutputBufferInfoPresentationTimestampUs(jni, j_output_buffer_info) /
1000;
- last_output_timestamp_ms_ = capture_time_ms;
+ int32_t timestamp = timestamps_.front();
+ timestamps_.erase(timestamps_.begin());
+ int64_t render_time_ms = render_times_ms_.front();
+ render_times_ms_.erase(render_times_ms_.begin());
+ int64_t frame_encoding_time_ms = GetCurrentTimeMs() -
+ frame_rtc_times_ms_.front();
+ frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
frames_in_queue_--;
- ALOGV("Got output buffer # %d. TS: %lld. Latency: %lld",
- output_buffer_index, last_output_timestamp_ms_,
- last_input_timestamp_ms_ - last_output_timestamp_ms_);
+ // Extract payload and key frame flag.
int32_t callback_status = 0;
+ jobject j_output_buffer =
+ GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
+ bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
+ size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
+ uint8* payload = reinterpret_cast<uint8_t*>(
+ jni->GetDirectBufferAddress(j_output_buffer));
+ CHECK_EXCEPTION(jni);
+
+ ALOGV("Encoder got output buffer # %d. Size: %d. TS: %lld. Latency: %lld."
+ " EncTime: %lld",
+ output_buffer_index, payload_size, last_output_timestamp_ms_,
+ last_input_timestamp_ms_ - last_output_timestamp_ms_,
+ frame_encoding_time_ms);
+
+ // Calculate and print encoding statistics - every 3 seconds.
+ current_frames_++;
+ current_bytes_ += payload_size;
+ current_encoding_time_ms_ += frame_encoding_time_ms;
+ int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
+ if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
+ current_frames_ > 0) {
+ ALOGD("Encoder bitrate: %d, target: %d kbps, fps: %d,"
+ " encTime: %d for last %d ms",
+ current_bytes_ * 8 / statistic_time_ms,
+ last_set_bitrate_kbps_,
+ (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms,
+ current_encoding_time_ms_ / current_frames_, statistic_time_ms);
+ start_time_ms_ = GetCurrentTimeMs();
+ current_frames_ = 0;
+ current_bytes_= 0;
+ current_encoding_time_ms_ = 0;
+ }
+
+ // Callback - return encoded frame.
if (callback_) {
- jobject j_output_buffer =
- GetOutputBufferInfoBuffer(jni, j_output_buffer_info);
- bool key_frame = GetOutputBufferInfoIsKeyFrame(jni, j_output_buffer_info);
- size_t payload_size = jni->GetDirectBufferCapacity(j_output_buffer);
- uint8* payload = reinterpret_cast<uint8_t*>(
- jni->GetDirectBufferAddress(j_output_buffer));
- CHECK_EXCEPTION(jni, "");
scoped_ptr<webrtc::EncodedImage> image(
new webrtc::EncodedImage(payload, payload_size, payload_size));
image->_encodedWidth = width_;
image->_encodedHeight = height_;
- // Convert capture time to 90 kHz RTP timestamp.
- image->_timeStamp = static_cast<uint32_t>(90 * capture_time_ms);
- image->capture_time_ms_ = capture_time_ms;
+ image->_timeStamp = timestamp;
+ image->capture_time_ms_ = render_time_ms;
image->_frameType = (key_frame ? webrtc::kKeyFrame : webrtc::kDeltaFrame);
image->_completeFrame = true;
@@ -1720,19 +1869,21 @@
callback_status = callback_->Encoded(*image, &info, &header);
}
+ // Return output buffer back to the encoder.
bool success = jni->CallBooleanMethod(*j_media_codec_video_encoder_,
j_release_output_buffer_method_,
output_buffer_index);
- CHECK_EXCEPTION(jni, "");
+ CHECK_EXCEPTION(jni);
if (!success) {
ResetCodec();
return false;
}
- if (callback_status > 0)
+ if (callback_status > 0) {
drop_next_input_frame_ = true;
// Theoretically could handle callback_status<0 here, but unclear what that
// would mean for us.
+ }
}
return true;
@@ -1766,7 +1917,7 @@
bool is_platform_supported = jni->CallStaticBooleanMethod(
j_encoder_class,
GetStaticMethodID(jni, j_encoder_class, "isPlatformSupported", "()Z"));
- CHECK_EXCEPTION(jni, "");
+ CHECK_EXCEPTION(jni);
if (!is_platform_supported)
return;
@@ -1774,7 +1925,7 @@
// encoder? Sure would be. Too bad it doesn't. So we hard-code some
// reasonable defaults.
supported_codecs_.push_back(
- VideoCodec(kVideoCodecVP8, "VP8", 1920, 1088, 30));
+ VideoCodec(kVideoCodecVP8, "VP8", 1280, 1280, 30));
}
MediaCodecVideoEncoderFactory::~MediaCodecVideoEncoderFactory() {}
@@ -1801,7 +1952,652 @@
delete encoder;
}
-#endif // ANDROID
+class MediaCodecVideoDecoder : public webrtc::VideoDecoder,
+ public rtc::MessageHandler {
+ public:
+ explicit MediaCodecVideoDecoder(JNIEnv* jni);
+ virtual ~MediaCodecVideoDecoder();
+
+ static int SetAndroidObjects(JNIEnv* jni, jobject render_egl_context);
+
+ virtual int32_t InitDecode(const VideoCodec* codecSettings,
+ int32_t numberOfCores) OVERRIDE;
+
+ virtual int32_t
+ Decode(const EncodedImage& inputImage, bool missingFrames,
+ const RTPFragmentationHeader* fragmentation,
+ const CodecSpecificInfo* codecSpecificInfo = NULL,
+ int64_t renderTimeMs = -1) OVERRIDE;
+
+ virtual int32_t RegisterDecodeCompleteCallback(
+ DecodedImageCallback* callback) OVERRIDE;
+
+ virtual int32_t Release() OVERRIDE;
+
+ virtual int32_t Reset() OVERRIDE;
+ // rtc::MessageHandler implementation.
+ virtual void OnMessage(rtc::Message* msg) OVERRIDE;
+
+ private:
+ // CHECK-fail if not running on |codec_thread_|.
+ void CheckOnCodecThread();
+
+ int32_t InitDecodeOnCodecThread();
+ int32_t ReleaseOnCodecThread();
+ int32_t DecodeOnCodecThread(const EncodedImage& inputImage);
+ // Deliver any outputs pending in the MediaCodec to our |callback_| and return
+ // true on success.
+ bool DeliverPendingOutputs(JNIEnv* jni, int dequeue_timeout_us);
+
+
+ bool key_frame_required_;
+ bool inited_;
+ bool use_surface_;
+ VideoCodec codec_;
+ I420VideoFrame decoded_image_;
+ NativeHandleImpl native_handle_;
+ DecodedImageCallback* callback_;
+ int frames_received_; // Number of frames received by decoder.
+ int frames_decoded_; // Number of frames decoded by decoder
+ int64_t start_time_ms_; // Start time for statistics.
+ int current_frames_; // Number of frames in the current statistics interval.
+ int current_bytes_; // Encoded bytes in the current statistics interval.
+ int current_decoding_time_ms_; // Overall decoding time in the current second
+ uint32_t max_pending_frames_; // Maximum number of pending input frames
+ std::vector<int32_t> timestamps_;
+ std::vector<int64_t> ntp_times_ms_;
+ std::vector<int64_t> frame_rtc_times_ms_; // Time when video frame is sent to
+ // decoder input.
+
+ // State that is constant for the lifetime of this object once the ctor
+ // returns.
+ scoped_ptr<Thread> codec_thread_; // Thread on which to operate MediaCodec.
+ ScopedGlobalRef<jclass> j_media_codec_video_decoder_class_;
+ ScopedGlobalRef<jobject> j_media_codec_video_decoder_;
+ jmethodID j_init_decode_method_;
+ jmethodID j_release_method_;
+ jmethodID j_dequeue_input_buffer_method_;
+ jmethodID j_queue_input_buffer_method_;
+ jmethodID j_dequeue_output_buffer_method_;
+ jmethodID j_release_output_buffer_method_;
+ // MediaCodecVideoDecoder fields.
+ jfieldID j_input_buffers_field_;
+ jfieldID j_output_buffers_field_;
+ jfieldID j_color_format_field_;
+ jfieldID j_width_field_;
+ jfieldID j_height_field_;
+ jfieldID j_stride_field_;
+ jfieldID j_slice_height_field_;
+ jfieldID j_surface_texture_field_;
+ jfieldID j_textureID_field_;
+ // MediaCodecVideoDecoder.DecoderOutputBufferInfo fields.
+ jfieldID j_info_index_field_;
+ jfieldID j_info_offset_field_;
+ jfieldID j_info_size_field_;
+ jfieldID j_info_presentation_timestamp_us_field_;
+
+ // Global references; must be deleted in Release().
+ std::vector<jobject> input_buffers_;
+ jobject surface_texture_;
+
+ // Render EGL context.
+ static jobject render_egl_context_;
+};
+
+jobject MediaCodecVideoDecoder::render_egl_context_ = NULL;
+
+int MediaCodecVideoDecoder::SetAndroidObjects(JNIEnv* jni,
+ jobject render_egl_context) {
+ if (render_egl_context_) {
+ jni->DeleteGlobalRef(render_egl_context_);
+ }
+ if (IsNull(jni, render_egl_context)) {
+ render_egl_context_ = NULL;
+ } else {
+ render_egl_context_ = jni->NewGlobalRef(render_egl_context);
+ }
+ ALOGD("VideoDecoder EGL context set.");
+ return 0;
+}
+
+MediaCodecVideoDecoder::MediaCodecVideoDecoder(JNIEnv* jni)
+ : key_frame_required_(true),
+ inited_(false),
+ codec_thread_(new Thread()),
+ j_media_codec_video_decoder_class_(
+ jni,
+ FindClass(jni, "org/webrtc/MediaCodecVideoDecoder")),
+ j_media_codec_video_decoder_(
+ jni,
+ jni->NewObject(*j_media_codec_video_decoder_class_,
+ GetMethodID(jni,
+ *j_media_codec_video_decoder_class_,
+ "<init>",
+ "()V"))) {
+ ScopedLocalRefFrame local_ref_frame(jni);
+ codec_thread_->SetName("MediaCodecVideoDecoder", NULL);
+ CHECK(codec_thread_->Start()) << "Failed to start MediaCodecVideoDecoder";
+
+ j_init_decode_method_ = GetMethodID(
+ jni, *j_media_codec_video_decoder_class_, "initDecode",
+ "(IIZLandroid/opengl/EGLContext;)Z");
+ j_release_method_ =
+ GetMethodID(jni, *j_media_codec_video_decoder_class_, "release", "()V");
+ j_dequeue_input_buffer_method_ = GetMethodID(
+ jni, *j_media_codec_video_decoder_class_, "dequeueInputBuffer", "()I");
+ j_queue_input_buffer_method_ = GetMethodID(
+ jni, *j_media_codec_video_decoder_class_, "queueInputBuffer", "(IIJ)Z");
+ j_dequeue_output_buffer_method_ = GetMethodID(
+ jni, *j_media_codec_video_decoder_class_, "dequeueOutputBuffer",
+ "(I)Lorg/webrtc/MediaCodecVideoDecoder$DecoderOutputBufferInfo;");
+ j_release_output_buffer_method_ = GetMethodID(
+ jni, *j_media_codec_video_decoder_class_, "releaseOutputBuffer", "(IZ)Z");
+
+ j_input_buffers_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_,
+ "inputBuffers", "[Ljava/nio/ByteBuffer;");
+ j_output_buffers_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_,
+ "outputBuffers", "[Ljava/nio/ByteBuffer;");
+ j_color_format_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_, "colorFormat", "I");
+ j_width_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_, "width", "I");
+ j_height_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_, "height", "I");
+ j_stride_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_, "stride", "I");
+ j_slice_height_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_, "sliceHeight", "I");
+ j_textureID_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_, "textureID", "I");
+ j_surface_texture_field_ = GetFieldID(
+ jni, *j_media_codec_video_decoder_class_, "surfaceTexture",
+ "Landroid/graphics/SurfaceTexture;");
+
+ jclass j_decoder_output_buffer_info_class = FindClass(jni,
+ "org/webrtc/MediaCodecVideoDecoder$DecoderOutputBufferInfo");
+ j_info_index_field_ = GetFieldID(
+ jni, j_decoder_output_buffer_info_class, "index", "I");
+ j_info_offset_field_ = GetFieldID(
+ jni, j_decoder_output_buffer_info_class, "offset", "I");
+ j_info_size_field_ = GetFieldID(
+ jni, j_decoder_output_buffer_info_class, "size", "I");
+ j_info_presentation_timestamp_us_field_ = GetFieldID(
+ jni, j_decoder_output_buffer_info_class, "presentationTimestampUs", "J");
+
+ CHECK_EXCEPTION(jni) << "MediaCodecVideoDecoder ctor failed";
+ use_surface_ = true;
+ if (render_egl_context_ == NULL)
+ use_surface_ = false;
+ memset(&codec_, 0, sizeof(codec_));
+}
+
+MediaCodecVideoDecoder::~MediaCodecVideoDecoder() {
+ // Call Release() to ensure no more callbacks to us after we are deleted.
+ Release();
+}
+
+int32_t MediaCodecVideoDecoder::InitDecode(const VideoCodec* inst,
+ int32_t numberOfCores) {
+ if (inst == NULL) {
+ return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
+ }
+ int ret_val = Release();
+ if (ret_val < 0) {
+ return ret_val;
+ }
+ // Save VideoCodec instance for later.
+ if (&codec_ != inst) {
+ codec_ = *inst;
+ }
+ codec_.maxFramerate = (codec_.maxFramerate >= 1) ? codec_.maxFramerate : 1;
+
+ // Always start with a complete key frame.
+ key_frame_required_ = true;
+ frames_received_ = 0;
+ frames_decoded_ = 0;
+
+ // Call Java init.
+ return codec_thread_->Invoke<int32_t>(
+ Bind(&MediaCodecVideoDecoder::InitDecodeOnCodecThread, this));
+}
+
+int32_t MediaCodecVideoDecoder::InitDecodeOnCodecThread() {
+ CheckOnCodecThread();
+ JNIEnv* jni = AttachCurrentThreadIfNeeded();
+ ScopedLocalRefFrame local_ref_frame(jni);
+ ALOGD("InitDecodeOnCodecThread: %d x %d. fps: %d",
+ codec_.width, codec_.height, codec_.maxFramerate);
+
+ bool success = jni->CallBooleanMethod(*j_media_codec_video_decoder_,
+ j_init_decode_method_,
+ codec_.width,
+ codec_.height,
+ use_surface_,
+ render_egl_context_);
+ CHECK_EXCEPTION(jni);
+ if (!success) {
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+ inited_ = true;
+
+ max_pending_frames_ = 0;
+ if (use_surface_) {
+ max_pending_frames_ = 1;
+ }
+ start_time_ms_ = GetCurrentTimeMs();
+ current_frames_ = 0;
+ current_bytes_ = 0;
+ current_decoding_time_ms_ = 0;
+ timestamps_.clear();
+ ntp_times_ms_.clear();
+ frame_rtc_times_ms_.clear();
+
+ jobjectArray input_buffers = (jobjectArray)GetObjectField(
+ jni, *j_media_codec_video_decoder_, j_input_buffers_field_);
+ size_t num_input_buffers = jni->GetArrayLength(input_buffers);
+ input_buffers_.resize(num_input_buffers);
+ for (size_t i = 0; i < num_input_buffers; ++i) {
+ input_buffers_[i] =
+ jni->NewGlobalRef(jni->GetObjectArrayElement(input_buffers, i));
+ CHECK_EXCEPTION(jni);
+ }
+
+ if (use_surface_) {
+ jobject surface_texture = GetObjectField(
+ jni, *j_media_codec_video_decoder_, j_surface_texture_field_);
+ surface_texture_ = jni->NewGlobalRef(surface_texture);
+ }
+ codec_thread_->PostDelayed(kMediaCodecPollMs, this);
+
+ return WEBRTC_VIDEO_CODEC_OK;
+}
+
+int32_t MediaCodecVideoDecoder::Release() {
+ return codec_thread_->Invoke<int32_t>(
+ Bind(&MediaCodecVideoDecoder::ReleaseOnCodecThread, this));
+}
+
+int32_t MediaCodecVideoDecoder::ReleaseOnCodecThread() {
+ if (!inited_) {
+ return WEBRTC_VIDEO_CODEC_OK;
+ }
+ CheckOnCodecThread();
+ JNIEnv* jni = AttachCurrentThreadIfNeeded();
+ ALOGD("DecoderRelease: Frames received: %d.", frames_received_);
+ ScopedLocalRefFrame local_ref_frame(jni);
+ for (size_t i = 0; i < input_buffers_.size(); i++) {
+ jni->DeleteGlobalRef(input_buffers_[i]);
+ }
+ input_buffers_.clear();
+ if (use_surface_) {
+ // Before deleting texture object make sure it is no longer referenced
+ // by any TextureVideoFrame.
+ int32_t waitTimeoutUs = 3000000; // 3 second wait
+ while (waitTimeoutUs > 0 && native_handle_.ref_count() > 0) {
+ ALOGD("Current Texture RefCnt: %d", native_handle_.ref_count());
+ usleep(30000);
+ waitTimeoutUs -= 30000;
+ }
+ ALOGD("TextureRefCnt: %d", native_handle_.ref_count());
+ jni->DeleteGlobalRef(surface_texture_);
+ }
+ jni->CallVoidMethod(*j_media_codec_video_decoder_, j_release_method_);
+ CHECK_EXCEPTION(jni);
+ rtc::MessageQueueManager::Clear(this);
+ inited_ = false;
+ return WEBRTC_VIDEO_CODEC_OK;
+}
+
+
+void MediaCodecVideoDecoder::CheckOnCodecThread() {
+ CHECK(codec_thread_ == ThreadManager::Instance()->CurrentThread())
+ << "Running on wrong thread!";
+}
+
+int32_t MediaCodecVideoDecoder::Decode(
+ const EncodedImage& inputImage,
+ bool missingFrames,
+ const RTPFragmentationHeader* fragmentation,
+ const CodecSpecificInfo* codecSpecificInfo,
+ int64_t renderTimeMs) {
+ if (!inited_) {
+ return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
+ }
+ if (callback_ == NULL) {
+ return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
+ }
+ if (inputImage._buffer == NULL && inputImage._length > 0) {
+ return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
+ }
+ // Check if encoded frame dimension has changed.
+ if ((inputImage._encodedWidth * inputImage._encodedHeight > 0) &&
+ (inputImage._encodedWidth != codec_.width ||
+ inputImage._encodedHeight != codec_.height)) {
+ codec_.width = inputImage._encodedWidth;
+ codec_.height = inputImage._encodedHeight;
+ InitDecode(&codec_, 1);
+ }
+
+ // Always start with a complete key frame.
+ if (key_frame_required_) {
+ if (inputImage._frameType != webrtc::kKeyFrame) {
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+ if (!inputImage._completeFrame) {
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+ key_frame_required_ = false;
+ }
+ if (inputImage._length == 0) {
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+
+ return codec_thread_->Invoke<int32_t>(Bind(
+ &MediaCodecVideoDecoder::DecodeOnCodecThread, this, inputImage));
+}
+
+int32_t MediaCodecVideoDecoder::DecodeOnCodecThread(
+ const EncodedImage& inputImage) {
+ static uint8_t yVal_ = 0x7f;
+
+ CheckOnCodecThread();
+ JNIEnv* jni = AttachCurrentThreadIfNeeded();
+ ScopedLocalRefFrame local_ref_frame(jni);
+
+ // Try to drain the decoder and wait until output is not too
+ // much behind the input.
+ if (frames_received_ > frames_decoded_ + max_pending_frames_) {
+ ALOGV("Wait for output...");
+ if (!DeliverPendingOutputs(jni, kMediaCodecTimeoutMs * 1000)) {
+ Reset();
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+ if (frames_received_ > frames_decoded_ + max_pending_frames_) {
+ ALOGE("Output buffer dequeue timeout");
+ Reset();
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+ }
+
+ // Get input buffer.
+ int j_input_buffer_index = jni->CallIntMethod(*j_media_codec_video_decoder_,
+ j_dequeue_input_buffer_method_);
+ CHECK_EXCEPTION(jni);
+ if (j_input_buffer_index < 0) {
+ ALOGE("dequeueInputBuffer error");
+ Reset();
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+
+ // Copy encoded data to Java ByteBuffer.
+ jobject j_input_buffer = input_buffers_[j_input_buffer_index];
+ uint8* buffer =
+ reinterpret_cast<uint8*>(jni->GetDirectBufferAddress(j_input_buffer));
+ CHECK(buffer) << "Indirect buffer??";
+ int64 buffer_capacity = jni->GetDirectBufferCapacity(j_input_buffer);
+ CHECK_EXCEPTION(jni);
+ if (buffer_capacity < inputImage._length) {
+ ALOGE("Input frame size %d is bigger than buffer size %d.",
+ inputImage._length, buffer_capacity);
+ Reset();
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+ ALOGV("Decoder frame in # %d. Buffer # %d. Size: %d",
+ frames_received_, j_input_buffer_index, inputImage._length);
+ memcpy(buffer, inputImage._buffer, inputImage._length);
+
+ // Save input image timestamps for later output.
+ frames_received_++;
+ current_bytes_ += inputImage._length;
+ timestamps_.push_back(inputImage._timeStamp);
+ ntp_times_ms_.push_back(inputImage.ntp_time_ms_);
+ frame_rtc_times_ms_.push_back(GetCurrentTimeMs());
+
+ // Feed input to decoder.
+ jlong timestamp_us = (frames_received_ * 1000000) / codec_.maxFramerate;
+ bool success = jni->CallBooleanMethod(*j_media_codec_video_decoder_,
+ j_queue_input_buffer_method_,
+ j_input_buffer_index,
+ inputImage._length,
+ timestamp_us);
+ CHECK_EXCEPTION(jni);
+ if (!success) {
+ ALOGE("queueInputBuffer error");
+ Reset();
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+
+ // Try to drain the decoder
+ if (!DeliverPendingOutputs(jni, 0)) {
+ ALOGE("DeliverPendingOutputs error");
+ Reset();
+ return WEBRTC_VIDEO_CODEC_ERROR;
+ }
+
+ return WEBRTC_VIDEO_CODEC_OK;
+}
+
+bool MediaCodecVideoDecoder::DeliverPendingOutputs(
+ JNIEnv* jni, int dequeue_timeout_us) {
+ if (frames_received_ <= frames_decoded_) {
+ // No need to query for output buffers - decoder is drained.
+ return true;
+ }
+ // Get decoder output.
+ jobject j_decoder_output_buffer_info = jni->CallObjectMethod(
+ *j_media_codec_video_decoder_,
+ j_dequeue_output_buffer_method_,
+ dequeue_timeout_us);
+
+ CHECK_EXCEPTION(jni);
+ if (IsNull(jni, j_decoder_output_buffer_info)) {
+ return true;
+ }
+
+ // Extract output buffer info from Java DecoderOutputBufferInfo.
+ int output_buffer_index =
+ GetIntField(jni, j_decoder_output_buffer_info, j_info_index_field_);
+ if (output_buffer_index < 0) {
+ ALOGE("dequeueOutputBuffer error : %d", output_buffer_index);
+ Reset();
+ return false;
+ }
+ int output_buffer_offset =
+ GetIntField(jni, j_decoder_output_buffer_info, j_info_offset_field_);
+ int output_buffer_size =
+ GetIntField(jni, j_decoder_output_buffer_info, j_info_size_field_);
+ CHECK_EXCEPTION(jni);
+
+ // Get decoded video frame properties.
+ int color_format = GetIntField(jni, *j_media_codec_video_decoder_,
+ j_color_format_field_);
+ int width = GetIntField(jni, *j_media_codec_video_decoder_, j_width_field_);
+ int height = GetIntField(jni, *j_media_codec_video_decoder_, j_height_field_);
+ int stride = GetIntField(jni, *j_media_codec_video_decoder_, j_stride_field_);
+ int slice_height = GetIntField(jni, *j_media_codec_video_decoder_,
+ j_slice_height_field_);
+ int texture_id = GetIntField(jni, *j_media_codec_video_decoder_,
+ j_textureID_field_);
+
+ // Extract data from Java ByteBuffer and create output yuv420 frame -
+ // for non surface decoding only.
+ if (!use_surface_) {
+ if (output_buffer_size < width * height * 3 / 2) {
+ ALOGE("Insufficient output buffer size: %d", output_buffer_size);
+ Reset();
+ return false;
+ }
+ jobjectArray output_buffers = reinterpret_cast<jobjectArray>(GetObjectField(
+ jni, *j_media_codec_video_decoder_, j_output_buffers_field_));
+ jobject output_buffer =
+ jni->GetObjectArrayElement(output_buffers, output_buffer_index);
+ uint8_t* payload = reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(
+ output_buffer));
+ CHECK_EXCEPTION(jni);
+ payload += output_buffer_offset;
+
+ // Create yuv420 frame.
+ if (color_format == COLOR_FormatYUV420Planar) {
+ decoded_image_.CreateFrame(
+ stride * slice_height, payload,
+ (stride * slice_height) / 4, payload + (stride * slice_height),
+ (stride * slice_height) / 4, payload + (5 * stride * slice_height / 4),
+ width, height,
+ stride, stride / 2, stride / 2);
+ } else {
+ // All other supported formats are nv12.
+ decoded_image_.CreateEmptyFrame(width, height, width,
+ width / 2, width / 2);
+ libyuv::NV12ToI420(
+ payload, stride,
+ payload + stride * slice_height, stride,
+ decoded_image_.buffer(webrtc::kYPlane),
+ decoded_image_.stride(webrtc::kYPlane),
+ decoded_image_.buffer(webrtc::kUPlane),
+ decoded_image_.stride(webrtc::kUPlane),
+ decoded_image_.buffer(webrtc::kVPlane),
+ decoded_image_.stride(webrtc::kVPlane),
+ width, height);
+ }
+ }
+
+ // Get frame timestamps from a queue.
+ int32_t timestamp = timestamps_.front();
+ timestamps_.erase(timestamps_.begin());
+ int64_t ntp_time_ms = ntp_times_ms_.front();
+ ntp_times_ms_.erase(ntp_times_ms_.begin());
+ int64_t frame_decoding_time_ms = GetCurrentTimeMs() -
+ frame_rtc_times_ms_.front();
+ frame_rtc_times_ms_.erase(frame_rtc_times_ms_.begin());
+
+ ALOGV("Decoder frame out # %d. %d x %d. %d x %d. Color: 0x%x. Size: %d."
+ " DecTime: %lld", frames_decoded_, width, height, stride, slice_height,
+ color_format, output_buffer_size, frame_decoding_time_ms);
+
+ // Return output buffer back to codec.
+ bool success = jni->CallBooleanMethod(
+ *j_media_codec_video_decoder_,
+ j_release_output_buffer_method_,
+ output_buffer_index,
+ use_surface_);
+ CHECK_EXCEPTION(jni);
+ if (!success) {
+ ALOGE("releaseOutputBuffer error");
+ Reset();
+ return false;
+ }
+
+ // Calculate and print decoding statistics - every 3 seconds.
+ frames_decoded_++;
+ current_frames_++;
+ current_decoding_time_ms_ += frame_decoding_time_ms;
+ int statistic_time_ms = GetCurrentTimeMs() - start_time_ms_;
+ if (statistic_time_ms >= kMediaCodecStatisticsIntervalMs &&
+ current_frames_ > 0) {
+ ALOGD("Decoder bitrate: %d kbps, fps: %d, decTime: %d for last %d ms",
+ current_bytes_ * 8 / statistic_time_ms,
+ (current_frames_ * 1000 + statistic_time_ms / 2) / statistic_time_ms,
+ current_decoding_time_ms_ / current_frames_, statistic_time_ms);
+ start_time_ms_ = GetCurrentTimeMs();
+ current_frames_ = 0;
+ current_bytes_= 0;
+ current_decoding_time_ms_ = 0;
+ }
+
+ // Callback - output decoded frame.
+ int32_t callback_status = WEBRTC_VIDEO_CODEC_OK;
+ if (use_surface_) {
+ native_handle_.SetTextureObject(surface_texture_, texture_id);
+ TextureVideoFrame texture_image(
+ &native_handle_, width, height, timestamp, 0);
+ texture_image.set_ntp_time_ms(ntp_time_ms);
+ callback_status = callback_->Decoded(texture_image);
+ } else {
+ decoded_image_.set_timestamp(timestamp);
+ decoded_image_.set_ntp_time_ms(ntp_time_ms);
+ callback_status = callback_->Decoded(decoded_image_);
+ }
+ if (callback_status > 0) {
+ ALOGE("callback error");
+ }
+
+ return true;
+}
+
+int32_t MediaCodecVideoDecoder::RegisterDecodeCompleteCallback(
+ DecodedImageCallback* callback) {
+ callback_ = callback;
+ return WEBRTC_VIDEO_CODEC_OK;
+}
+
+int32_t MediaCodecVideoDecoder::Reset() {
+ ALOGD("DecoderReset");
+ if (!inited_) {
+ return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
+ }
+ return InitDecode(&codec_, 1);
+}
+
+void MediaCodecVideoDecoder::OnMessage(rtc::Message* msg) {
+ JNIEnv* jni = AttachCurrentThreadIfNeeded();
+ ScopedLocalRefFrame local_ref_frame(jni);
+ if (!inited_) {
+ return;
+ }
+ // We only ever send one message to |this| directly (not through a Bind()'d
+ // functor), so expect no ID/data.
+ CHECK(!msg->message_id) << "Unexpected message!";
+ CHECK(!msg->pdata) << "Unexpected message!";
+ CheckOnCodecThread();
+
+ DeliverPendingOutputs(jni, 0);
+ codec_thread_->PostDelayed(kMediaCodecPollMs, this);
+}
+
+class MediaCodecVideoDecoderFactory
+ : public cricket::WebRtcVideoDecoderFactory {
+ public:
+ MediaCodecVideoDecoderFactory();
+ virtual ~MediaCodecVideoDecoderFactory();
+ // WebRtcVideoDecoderFactory implementation.
+ virtual webrtc::VideoDecoder* CreateVideoDecoder(
+ webrtc::VideoCodecType type) OVERRIDE;
+
+ virtual void DestroyVideoDecoder(webrtc::VideoDecoder* decoder) OVERRIDE;
+
+ private:
+ bool is_platform_supported_;
+};
+
+MediaCodecVideoDecoderFactory::MediaCodecVideoDecoderFactory() {
+ JNIEnv* jni = AttachCurrentThreadIfNeeded();
+ ScopedLocalRefFrame local_ref_frame(jni);
+ jclass j_decoder_class = FindClass(jni, "org/webrtc/MediaCodecVideoDecoder");
+ is_platform_supported_ = jni->CallStaticBooleanMethod(
+ j_decoder_class,
+ GetStaticMethodID(jni, j_decoder_class, "isPlatformSupported", "()Z"));
+ CHECK_EXCEPTION(jni);
+}
+
+MediaCodecVideoDecoderFactory::~MediaCodecVideoDecoderFactory() {}
+
+webrtc::VideoDecoder* MediaCodecVideoDecoderFactory::CreateVideoDecoder(
+ webrtc::VideoCodecType type) {
+ if (type != kVideoCodecVP8 || !is_platform_supported_) {
+ return NULL;
+ }
+ return new MediaCodecVideoDecoder(AttachCurrentThreadIfNeeded());
+}
+
+
+void MediaCodecVideoDecoderFactory::DestroyVideoDecoder(
+ webrtc::VideoDecoder* decoder) {
+ delete decoder;
+}
+
+#endif // #if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
} // anonymous namespace
@@ -1811,13 +2607,13 @@
Java_org_webrtc_##name
extern "C" jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
- CHECK(!g_jvm, "JNI_OnLoad called more than once!");
+ CHECK(!g_jvm) << "JNI_OnLoad called more than once!";
g_jvm = jvm;
- CHECK(g_jvm, "JNI_OnLoad handed NULL?");
+ CHECK(g_jvm) << "JNI_OnLoad handed NULL?";
- CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey), "pthread_once");
+ CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once";
- CHECK(talk_base::InitializeSSL(), "Failed to InitializeSSL()");
+ CHECK(rtc::InitializeSSL()) << "Failed to InitializeSSL()";
JNIEnv* jni;
if (jvm->GetEnv(reinterpret_cast<void**>(&jni), JNI_VERSION_1_6) != JNI_OK)
@@ -1831,7 +2627,7 @@
g_class_reference_holder->FreeReferences(AttachCurrentThreadIfNeeded());
delete g_class_reference_holder;
g_class_reference_holder = NULL;
- CHECK(talk_base::CleanupSSL(), "Failed to CleanupSSL()");
+ CHECK(rtc::CleanupSSL()) << "Failed to CleanupSSL()";
g_jvm = NULL;
}
@@ -1867,8 +2663,8 @@
JOW(jlong, DataChannel_bufferedAmount)(JNIEnv* jni, jobject j_dc) {
uint64 buffered_amount = ExtractNativeDC(jni, j_dc)->buffered_amount();
- CHECK(buffered_amount <= std::numeric_limits<int64>::max(),
- "buffered_amount overflowed jlong!");
+ CHECK_LE(buffered_amount, std::numeric_limits<int64>::max())
+ << "buffered_amount overflowed jlong!";
return static_cast<jlong>(buffered_amount);
}
@@ -1880,7 +2676,7 @@
jbyteArray data, jboolean binary) {
jbyte* bytes = jni->GetByteArrayElements(data, NULL);
bool ret = ExtractNativeDC(jni, j_dc)->Send(DataBuffer(
- talk_base::Buffer(bytes, jni->GetArrayLength(data)),
+ rtc::Buffer(bytes, jni->GetArrayLength(data)),
binary));
jni->ReleaseByteArrayElements(data, bytes, JNI_ABORT);
return ret;
@@ -1896,12 +2692,12 @@
std::string path = JavaToStdString(jni, j_path);
if (nativeLevels != webrtc::kTraceNone) {
webrtc::Trace::set_level_filter(nativeLevels);
-#ifdef ANDROID
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
if (path != "logcat:") {
#endif
- CHECK(webrtc::Trace::SetTraceFile(path.c_str(), false) == 0,
- "SetTraceFile failed");
-#ifdef ANDROID
+ CHECK_EQ(0, webrtc::Trace::SetTraceFile(path.c_str(), false))
+ << "SetTraceFile failed";
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
} else {
// Intentionally leak this to avoid needing to reason about its lifecycle.
// It keeps no state and functions only as a dispatch point.
@@ -1909,7 +2705,7 @@
}
#endif
}
- talk_base::LogMessage::LogToDebug(nativeSeverity);
+ rtc::LogMessage::LogToDebug(nativeSeverity);
}
JOW(void, PeerConnection_freePeerConnection)(JNIEnv*, jclass, jlong j_p) {
@@ -1929,10 +2725,14 @@
delete reinterpret_cast<cricket::VideoCapturer*>(j_p);
}
-JOW(void, VideoRenderer_free)(JNIEnv*, jclass, jlong j_p) {
+JOW(void, VideoRenderer_freeGuiVideoRenderer)(JNIEnv*, jclass, jlong j_p) {
delete reinterpret_cast<VideoRendererWrapper*>(j_p);
}
+JOW(void, VideoRenderer_freeWrappedVideoRenderer)(JNIEnv*, jclass, jlong j_p) {
+ delete reinterpret_cast<JavaVideoRendererWrapper*>(j_p);
+}
+
JOW(void, MediaStreamTrack_free)(JNIEnv*, jclass, jlong j_p) {
CHECK_RELEASE(reinterpret_cast<MediaStreamTrackInterface*>(j_p));
}
@@ -1975,19 +2775,28 @@
return (jlong)new PCOJava(jni, j_observer);
}
-#ifdef ANDROID
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
JOW(jboolean, PeerConnectionFactory_initializeAndroidGlobals)(
JNIEnv* jni, jclass, jobject context,
- jboolean initialize_audio, jboolean initialize_video) {
- CHECK(g_jvm, "JNI_OnLoad failed to run?");
+ jboolean initialize_audio, jboolean initialize_video,
+ jobject render_egl_context) {
+ CHECK(g_jvm) << "JNI_OnLoad failed to run?";
bool failure = false;
+ if (!factory_static_initialized) {
+ if (initialize_video) {
+ failure |= webrtc::SetCaptureAndroidVM(g_jvm, context);
+ failure |= webrtc::SetRenderAndroidVM(g_jvm);
+ }
+ if (initialize_audio)
+ failure |= webrtc::VoiceEngine::SetAndroidObjects(g_jvm, jni, context);
+ factory_static_initialized = true;
+ }
if (initialize_video)
- failure |= webrtc::VideoEngine::SetAndroidObjects(g_jvm, context);
- if (initialize_audio)
- failure |= webrtc::VoiceEngine::SetAndroidObjects(g_jvm, jni, context);
+ failure |= MediaCodecVideoDecoder::SetAndroidObjects(jni,
+ render_egl_context);
return !failure;
}
-#endif // ANDROID
+#endif // defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
// Helper struct for working around the fact that CreatePeerConnectionFactory()
// comes in two flavors: either entirely automagical (constructing its own
@@ -2019,26 +2828,28 @@
// talk/ assumes pretty widely that the current Thread is ThreadManager'd, but
// ThreadManager only WrapCurrentThread()s the thread where it is first
// created. Since the semantics around when auto-wrapping happens in
- // talk/base/ are convoluted, we simply wrap here to avoid having to think
+ // webrtc/base/ are convoluted, we simply wrap here to avoid having to think
// about ramifications of auto-wrapping there.
- talk_base::ThreadManager::Instance()->WrapCurrentThread();
+ rtc::ThreadManager::Instance()->WrapCurrentThread();
webrtc::Trace::CreateTrace();
Thread* worker_thread = new Thread();
worker_thread->SetName("worker_thread", NULL);
Thread* signaling_thread = new Thread();
signaling_thread->SetName("signaling_thread", NULL);
- CHECK(worker_thread->Start() && signaling_thread->Start(),
- "Failed to start threads");
+ CHECK(worker_thread->Start() && signaling_thread->Start())
+ << "Failed to start threads";
scoped_ptr<cricket::WebRtcVideoEncoderFactory> encoder_factory;
-#ifdef ANDROID
+ scoped_ptr<cricket::WebRtcVideoDecoderFactory> decoder_factory;
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
encoder_factory.reset(new MediaCodecVideoEncoderFactory());
+ decoder_factory.reset(new MediaCodecVideoDecoderFactory());
#endif
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
webrtc::CreatePeerConnectionFactory(worker_thread,
signaling_thread,
NULL,
encoder_factory.release(),
- NULL));
+ decoder_factory.release()));
OwnedFactoryAndThreads* owned_factory = new OwnedFactoryAndThreads(
worker_thread, signaling_thread, factory.release());
return jlongFromPointer(owned_factory);
@@ -2055,9 +2866,9 @@
JOW(jlong, PeerConnectionFactory_nativeCreateLocalMediaStream)(
JNIEnv* jni, jclass, jlong native_factory, jstring label) {
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
factoryFromJava(native_factory));
- talk_base::scoped_refptr<MediaStreamInterface> stream(
+ rtc::scoped_refptr<MediaStreamInterface> stream(
factory->CreateLocalMediaStream(JavaToStdString(jni, label)));
return (jlong)stream.release();
}
@@ -2067,9 +2878,9 @@
jobject j_constraints) {
scoped_ptr<ConstraintsWrapper> constraints(
new ConstraintsWrapper(jni, j_constraints));
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
factoryFromJava(native_factory));
- talk_base::scoped_refptr<VideoSourceInterface> source(
+ rtc::scoped_refptr<VideoSourceInterface> source(
factory->CreateVideoSource(
reinterpret_cast<cricket::VideoCapturer*>(native_capturer),
constraints.get()));
@@ -2079,9 +2890,9 @@
JOW(jlong, PeerConnectionFactory_nativeCreateVideoTrack)(
JNIEnv* jni, jclass, jlong native_factory, jstring id,
jlong native_source) {
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
factoryFromJava(native_factory));
- talk_base::scoped_refptr<VideoTrackInterface> track(
+ rtc::scoped_refptr<VideoTrackInterface> track(
factory->CreateVideoTrack(
JavaToStdString(jni, id),
reinterpret_cast<VideoSourceInterface*>(native_source)));
@@ -2092,9 +2903,9 @@
JNIEnv* jni, jclass, jlong native_factory, jobject j_constraints) {
scoped_ptr<ConstraintsWrapper> constraints(
new ConstraintsWrapper(jni, j_constraints));
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
factoryFromJava(native_factory));
- talk_base::scoped_refptr<AudioSourceInterface> source(
+ rtc::scoped_refptr<AudioSourceInterface> source(
factory->CreateAudioSource(constraints.get()));
return (jlong)source.release();
}
@@ -2102,9 +2913,9 @@
JOW(jlong, PeerConnectionFactory_nativeCreateAudioTrack)(
JNIEnv* jni, jclass, jlong native_factory, jstring id,
jlong native_source) {
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
factoryFromJava(native_factory));
- talk_base::scoped_refptr<AudioTrackInterface> track(factory->CreateAudioTrack(
+ rtc::scoped_refptr<AudioTrackInterface> track(factory->CreateAudioTrack(
JavaToStdString(jni, id),
reinterpret_cast<AudioSourceInterface*>(native_source)));
return (jlong)track.release();
@@ -2117,15 +2928,15 @@
jmethodID iterator_id = GetMethodID(
jni, list_class, "iterator", "()Ljava/util/Iterator;");
jobject iterator = jni->CallObjectMethod(j_ice_servers, iterator_id);
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
jmethodID iterator_has_next = GetMethodID(
jni, GetObjectClass(jni, iterator), "hasNext", "()Z");
jmethodID iterator_next = GetMethodID(
jni, GetObjectClass(jni, iterator), "next", "()Ljava/lang/Object;");
while (jni->CallBooleanMethod(iterator, iterator_has_next)) {
- CHECK_EXCEPTION(jni, "error during CallBooleanMethod");
+ CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
jobject j_ice_server = jni->CallObjectMethod(iterator, iterator_next);
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
jclass j_ice_server_class = GetObjectClass(jni, j_ice_server);
jfieldID j_ice_server_uri_id =
GetFieldID(jni, j_ice_server_class, "uri", "Ljava/lang/String;");
@@ -2145,30 +2956,30 @@
server.password = JavaToStdString(jni, password);
ice_servers->push_back(server);
}
- CHECK_EXCEPTION(jni, "error during CallBooleanMethod");
+ CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
}
JOW(jlong, PeerConnectionFactory_nativeCreatePeerConnection)(
JNIEnv *jni, jclass, jlong factory, jobject j_ice_servers,
jobject j_constraints, jlong observer_p) {
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> f(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> f(
reinterpret_cast<PeerConnectionFactoryInterface*>(
factoryFromJava(factory)));
PeerConnectionInterface::IceServers servers;
JavaIceServersToJsepIceServers(jni, j_ice_servers, &servers);
PCOJava* observer = reinterpret_cast<PCOJava*>(observer_p);
observer->SetConstraints(new ConstraintsWrapper(jni, j_constraints));
- talk_base::scoped_refptr<PeerConnectionInterface> pc(f->CreatePeerConnection(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(f->CreatePeerConnection(
servers, observer->constraints(), NULL, NULL, observer));
return (jlong)pc.release();
}
-static talk_base::scoped_refptr<PeerConnectionInterface> ExtractNativePC(
+static rtc::scoped_refptr<PeerConnectionInterface> ExtractNativePC(
JNIEnv* jni, jobject j_pc) {
jfieldID native_pc_id = GetFieldID(jni,
GetObjectClass(jni, j_pc), "nativePeerConnection", "J");
jlong j_p = GetLongField(jni, j_pc, native_pc_id);
- return talk_base::scoped_refptr<PeerConnectionInterface>(
+ return rtc::scoped_refptr<PeerConnectionInterface>(
reinterpret_cast<PeerConnectionInterface*>(j_p));
}
@@ -2187,23 +2998,23 @@
JOW(jobject, PeerConnection_createDataChannel)(
JNIEnv* jni, jobject j_pc, jstring j_label, jobject j_init) {
DataChannelInit init = JavaDataChannelInitToNative(jni, j_init);
- talk_base::scoped_refptr<DataChannelInterface> channel(
+ rtc::scoped_refptr<DataChannelInterface> channel(
ExtractNativePC(jni, j_pc)->CreateDataChannel(
JavaToStdString(jni, j_label), &init));
// Mustn't pass channel.get() directly through NewObject to avoid reading its
// vararg parameter as 64-bit and reading memory that doesn't belong to the
// 32-bit parameter.
jlong nativeChannelPtr = jlongFromPointer(channel.get());
- CHECK(nativeChannelPtr, "Failed to create DataChannel");
+ CHECK(nativeChannelPtr) << "Failed to create DataChannel";
jclass j_data_channel_class = FindClass(jni, "org/webrtc/DataChannel");
jmethodID j_data_channel_ctor = GetMethodID(
jni, j_data_channel_class, "<init>", "(J)V");
jobject j_channel = jni->NewObject(
j_data_channel_class, j_data_channel_ctor, nativeChannelPtr);
- CHECK_EXCEPTION(jni, "error during NewObject");
+ CHECK_EXCEPTION(jni) << "error during NewObject";
// Channel is now owned by Java object, and will be freed from there.
int bumped_count = channel->AddRef();
- CHECK(bumped_count == 2, "Unexpected refcount");
+ CHECK(bumped_count == 2) << "Unexpected refcount";
return j_channel;
}
@@ -2211,8 +3022,8 @@
JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_constraints) {
ConstraintsWrapper* constraints =
new ConstraintsWrapper(jni, j_constraints);
- talk_base::scoped_refptr<CreateSdpObserverWrapper> observer(
- new talk_base::RefCountedObject<CreateSdpObserverWrapper>(
+ rtc::scoped_refptr<CreateSdpObserverWrapper> observer(
+ new rtc::RefCountedObject<CreateSdpObserverWrapper>(
jni, j_observer, constraints));
ExtractNativePC(jni, j_pc)->CreateOffer(observer, constraints);
}
@@ -2221,8 +3032,8 @@
JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_constraints) {
ConstraintsWrapper* constraints =
new ConstraintsWrapper(jni, j_constraints);
- talk_base::scoped_refptr<CreateSdpObserverWrapper> observer(
- new talk_base::RefCountedObject<CreateSdpObserverWrapper>(
+ rtc::scoped_refptr<CreateSdpObserverWrapper> observer(
+ new rtc::RefCountedObject<CreateSdpObserverWrapper>(
jni, j_observer, constraints));
ExtractNativePC(jni, j_pc)->CreateAnswer(observer, constraints);
}
@@ -2239,7 +3050,7 @@
"()Ljava/lang/String;");
jstring j_type_string = (jstring)jni->CallObjectMethod(
j_type, j_canonical_form_id);
- CHECK_EXCEPTION(jni, "error during CallObjectMethod");
+ CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
std::string std_type = JavaToStdString(jni, j_type_string);
jfieldID j_description_id = GetFieldID(
@@ -2254,8 +3065,8 @@
JOW(void, PeerConnection_setLocalDescription)(
JNIEnv* jni, jobject j_pc,
jobject j_observer, jobject j_sdp) {
- talk_base::scoped_refptr<SetSdpObserverWrapper> observer(
- new talk_base::RefCountedObject<SetSdpObserverWrapper>(
+ rtc::scoped_refptr<SetSdpObserverWrapper> observer(
+ new rtc::RefCountedObject<SetSdpObserverWrapper>(
jni, j_observer, reinterpret_cast<ConstraintsWrapper*>(NULL)));
ExtractNativePC(jni, j_pc)->SetLocalDescription(
observer, JavaSdpToNativeSdp(jni, j_sdp));
@@ -2264,8 +3075,8 @@
JOW(void, PeerConnection_setRemoteDescription)(
JNIEnv* jni, jobject j_pc,
jobject j_observer, jobject j_sdp) {
- talk_base::scoped_refptr<SetSdpObserverWrapper> observer(
- new talk_base::RefCountedObject<SetSdpObserverWrapper>(
+ rtc::scoped_refptr<SetSdpObserverWrapper> observer(
+ new rtc::RefCountedObject<SetSdpObserverWrapper>(
jni, j_observer, reinterpret_cast<ConstraintsWrapper*>(NULL)));
ExtractNativePC(jni, j_pc)->SetRemoteDescription(
observer, JavaSdpToNativeSdp(jni, j_sdp));
@@ -2307,8 +3118,8 @@
JOW(bool, PeerConnection_nativeGetStats)(
JNIEnv* jni, jobject j_pc, jobject j_observer, jlong native_track) {
- talk_base::scoped_refptr<StatsObserverWrapper> observer(
- new talk_base::RefCountedObject<StatsObserverWrapper>(jni, j_observer));
+ rtc::scoped_refptr<StatsObserverWrapper> observer(
+ new rtc::RefCountedObject<StatsObserverWrapper>(jni, j_observer));
return ExtractNativePC(jni, j_pc)->GetStats(
observer,
reinterpret_cast<MediaStreamTrackInterface*>(native_track),
@@ -2339,7 +3150,7 @@
}
JOW(jobject, MediaSource_nativeState)(JNIEnv* jni, jclass, jlong j_p) {
- talk_base::scoped_refptr<MediaSourceInterface> p(
+ rtc::scoped_refptr<MediaSourceInterface> p(
reinterpret_cast<MediaSourceInterface*>(j_p));
return JavaEnumFromIndex(jni, "MediaSource$State", p->state());
}
@@ -2349,7 +3160,7 @@
std::string device_name = JavaToStdString(jni, j_device_name);
scoped_ptr<cricket::DeviceManagerInterface> device_manager(
cricket::DeviceManagerFactory::Create());
- CHECK(device_manager->Init(), "DeviceManager::Init() failed");
+ CHECK(device_manager->Init()) << "DeviceManager::Init() failed";
cricket::Device device;
if (!device_manager->GetVideoCaptureDevice(device_name, &device)) {
LOG(LS_ERROR) << "GetVideoCaptureDevice failed for " << device_name;
@@ -2385,8 +3196,8 @@
JOW(void, VideoSource_restart)(
JNIEnv* jni, jclass, jlong j_p_source, jlong j_p_format) {
- CHECK(j_p_source, "");
- CHECK(j_p_format, "");
+ CHECK(j_p_source);
+ CHECK(j_p_format);
scoped_ptr<cricket::VideoFormatPod> format(
reinterpret_cast<cricket::VideoFormatPod*>(j_p_format));
reinterpret_cast<VideoSourceInterface*>(j_p_source)->GetVideoCapturer()->
diff --git a/app/webrtc/java/src/org/webrtc/Logging.java b/app/webrtc/java/src/org/webrtc/Logging.java
index 8b23daf..b8d6c6e 100644
--- a/app/webrtc/java/src/org/webrtc/Logging.java
+++ b/app/webrtc/java/src/org/webrtc/Logging.java
@@ -59,7 +59,7 @@
}
};
- // Keep in sync with talk/base/logging.h:LoggingSeverity.
+ // Keep in sync with webrtc/base/logging.h:LoggingSeverity.
public enum Severity {
LS_SENSITIVE, LS_VERBOSE, LS_INFO, LS_WARNING, LS_ERROR,
};
diff --git a/app/webrtc/java/src/org/webrtc/MediaCodecVideoDecoder.java b/app/webrtc/java/src/org/webrtc/MediaCodecVideoDecoder.java
new file mode 100644
index 0000000..9280743
--- /dev/null
+++ b/app/webrtc/java/src/org/webrtc/MediaCodecVideoDecoder.java
@@ -0,0 +1,488 @@
+/*
+ * libjingle
+ * Copyright 2014, Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.webrtc;
+
+import android.graphics.SurfaceTexture;
+import android.media.MediaCodec;
+import android.media.MediaCodecInfo;
+import android.media.MediaCodecInfo.CodecCapabilities;
+import android.media.MediaCodecList;
+import android.media.MediaFormat;
+import android.opengl.EGL14;
+import android.opengl.EGLConfig;
+import android.opengl.EGLContext;
+import android.opengl.EGLDisplay;
+import android.opengl.EGLSurface;
+import android.opengl.GLES11Ext;
+import android.opengl.GLES20;
+import android.os.Build;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.Surface;
+
+import java.nio.ByteBuffer;
+
+// Java-side of peerconnection_jni.cc:MediaCodecVideoDecoder.
+// This class is an implementation detail of the Java PeerConnection API.
+// MediaCodec is thread-hostile so this class must be operated on a single
+// thread.
+class MediaCodecVideoDecoder {
+ // This class is constructed, operated, and destroyed by its C++ incarnation,
+ // so the class and its methods have non-public visibility. The API this
+ // class exposes aims to mimic the webrtc::VideoDecoder API as closely as
+ // possibly to minimize the amount of translation work necessary.
+
+ private static final String TAG = "MediaCodecVideoDecoder";
+
+ private static final int DEQUEUE_INPUT_TIMEOUT = 500000; // 500 ms timeout.
+ private Thread mediaCodecThread;
+ private MediaCodec mediaCodec;
+ private ByteBuffer[] inputBuffers;
+ private ByteBuffer[] outputBuffers;
+ private static final String VP8_MIME_TYPE = "video/x-vnd.on2.vp8";
+ // List of supported HW VP8 decoders.
+ private static final String[] supportedHwCodecPrefixes =
+ {"OMX.qcom.", "OMX.Nvidia." };
+ // NV12 color format supported by QCOM codec, but not declared in MediaCodec -
+ // see /hardware/qcom/media/mm-core/inc/OMX_QCOMExtns.h
+ private static final int
+ COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m = 0x7FA30C04;
+ // Allowable color formats supported by codec - in order of preference.
+ private static final int[] supportedColorList = {
+ CodecCapabilities.COLOR_FormatYUV420Planar,
+ CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
+ CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar,
+ COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m
+ };
+ private int colorFormat;
+ private int width;
+ private int height;
+ private int stride;
+ private int sliceHeight;
+ private boolean useSurface;
+ private int textureID = -1;
+ private SurfaceTexture surfaceTexture = null;
+ private Surface surface = null;
+ private float[] stMatrix = new float[16];
+ private EGLDisplay eglDisplay = EGL14.EGL_NO_DISPLAY;
+ private EGLContext eglContext = EGL14.EGL_NO_CONTEXT;
+ private EGLSurface eglSurface = EGL14.EGL_NO_SURFACE;
+
+
+ private MediaCodecVideoDecoder() { }
+
+ // Helper struct for findVp8HwDecoder() below.
+ private static class DecoderProperties {
+ public DecoderProperties(String codecName, int colorFormat) {
+ this.codecName = codecName;
+ this.colorFormat = colorFormat;
+ }
+ public final String codecName; // OpenMax component name for VP8 codec.
+ public final int colorFormat; // Color format supported by codec.
+ }
+
+ private static DecoderProperties findVp8HwDecoder() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
+ return null; // MediaCodec.setParameters is missing.
+
+ for (int i = 0; i < MediaCodecList.getCodecCount(); ++i) {
+ MediaCodecInfo info = MediaCodecList.getCodecInfoAt(i);
+ if (info.isEncoder()) {
+ continue;
+ }
+ String name = null;
+ for (String mimeType : info.getSupportedTypes()) {
+ if (mimeType.equals(VP8_MIME_TYPE)) {
+ name = info.getName();
+ break;
+ }
+ }
+ if (name == null) {
+ continue; // No VP8 support in this codec; try the next one.
+ }
+ Log.d(TAG, "Found candidate decoder " + name);
+
+ // Check if this is supported HW decoder.
+ boolean supportedCodec = false;
+ for (String hwCodecPrefix : supportedHwCodecPrefixes) {
+ if (name.startsWith(hwCodecPrefix)) {
+ supportedCodec = true;
+ break;
+ }
+ }
+ if (!supportedCodec) {
+ continue;
+ }
+
+ // Check if codec supports either yuv420 or nv12.
+ CodecCapabilities capabilities =
+ info.getCapabilitiesForType(VP8_MIME_TYPE);
+ for (int colorFormat : capabilities.colorFormats) {
+ Log.d(TAG, " Color: 0x" + Integer.toHexString(colorFormat));
+ }
+ for (int supportedColorFormat : supportedColorList) {
+ for (int codecColorFormat : capabilities.colorFormats) {
+ if (codecColorFormat == supportedColorFormat) {
+ // Found supported HW VP8 decoder.
+ Log.d(TAG, "Found target decoder " + name +
+ ". Color: 0x" + Integer.toHexString(codecColorFormat));
+ return new DecoderProperties(name, codecColorFormat);
+ }
+ }
+ }
+ }
+ return null; // No HW VP8 decoder.
+ }
+
+ private static boolean isPlatformSupported() {
+ return findVp8HwDecoder() != null;
+ }
+
+ private void checkOnMediaCodecThread() {
+ if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
+ throw new RuntimeException(
+ "MediaCodecVideoDecoder previously operated on " + mediaCodecThread +
+ " but is now called on " + Thread.currentThread());
+ }
+ }
+
+ private void checkEglError(String msg) {
+ int error;
+ if ((error = EGL14.eglGetError()) != EGL14.EGL_SUCCESS) {
+ Log.e(TAG, msg + ": EGL Error: 0x" + Integer.toHexString(error));
+ throw new RuntimeException(
+ msg + ": EGL error: 0x" + Integer.toHexString(error));
+ }
+ }
+
+ private void checkGlError(String msg) {
+ int error;
+ if ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
+ Log.e(TAG, msg + ": GL Error: 0x" + Integer.toHexString(error));
+ throw new RuntimeException(
+ msg + ": GL Error: 0x " + Integer.toHexString(error));
+ }
+ }
+
+ private void eglSetup(EGLContext sharedContext, int width, int height) {
+ Log.d(TAG, "EGL setup");
+ if (sharedContext == null) {
+ sharedContext = EGL14.EGL_NO_CONTEXT;
+ }
+ eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
+ if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
+ throw new RuntimeException("Unable to get EGL14 display");
+ }
+ int[] version = new int[2];
+ if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) {
+ throw new RuntimeException("Unable to initialize EGL14");
+ }
+
+ // Configure EGL for pbuffer and OpenGL ES 2.0.
+ int[] attribList = {
+ EGL14.EGL_RED_SIZE, 8,
+ EGL14.EGL_GREEN_SIZE, 8,
+ EGL14.EGL_BLUE_SIZE, 8,
+ EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
+ EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT,
+ EGL14.EGL_NONE
+ };
+ EGLConfig[] configs = new EGLConfig[1];
+ int[] numConfigs = new int[1];
+ if (!EGL14.eglChooseConfig(eglDisplay, attribList, 0, configs, 0,
+ configs.length, numConfigs, 0)) {
+ throw new RuntimeException("Unable to find RGB888 EGL config");
+ }
+
+ // Configure context for OpenGL ES 2.0.
+ int[] attrib_list = {
+ EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
+ EGL14.EGL_NONE
+ };
+ eglContext = EGL14.eglCreateContext(eglDisplay, configs[0], sharedContext,
+ attrib_list, 0);
+ checkEglError("eglCreateContext");
+ if (eglContext == null) {
+ throw new RuntimeException("Null EGL context");
+ }
+
+ // Create a pbuffer surface.
+ int[] surfaceAttribs = {
+ EGL14.EGL_WIDTH, width,
+ EGL14.EGL_HEIGHT, height,
+ EGL14.EGL_NONE
+ };
+ eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, configs[0],
+ surfaceAttribs, 0);
+ checkEglError("eglCreatePbufferSurface");
+ if (eglSurface == null) {
+ throw new RuntimeException("EGL surface was null");
+ }
+ }
+
+ private void eglRelease() {
+ Log.d(TAG, "EGL release");
+ if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
+ EGL14.eglDestroySurface(eglDisplay, eglSurface);
+ EGL14.eglDestroyContext(eglDisplay, eglContext);
+ EGL14.eglReleaseThread();
+ EGL14.eglTerminate(eglDisplay);
+ }
+ eglDisplay = EGL14.EGL_NO_DISPLAY;
+ eglContext = EGL14.EGL_NO_CONTEXT;
+ eglSurface = EGL14.EGL_NO_SURFACE;
+ }
+
+
+ private void makeCurrent() {
+ if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
+ throw new RuntimeException("eglMakeCurrent failed");
+ }
+ }
+
+ private boolean initDecode(int width, int height, boolean useSurface,
+ EGLContext sharedContext) {
+ if (mediaCodecThread != null) {
+ throw new RuntimeException("Forgot to release()?");
+ }
+ if (useSurface && sharedContext == null) {
+ throw new RuntimeException("No shared EGL context.");
+ }
+ DecoderProperties properties = findVp8HwDecoder();
+ if (properties == null) {
+ throw new RuntimeException("Cannot find HW VP8 decoder");
+ }
+ Log.d(TAG, "Java initDecode: " + width + " x " + height +
+ ". Color: 0x" + Integer.toHexString(properties.colorFormat) +
+ ". Use Surface: " + useSurface );
+ if (sharedContext != null) {
+ Log.d(TAG, "Decoder shared EGL Context: " + sharedContext);
+ }
+ mediaCodecThread = Thread.currentThread();
+ try {
+ Surface decodeSurface = null;
+ this.width = width;
+ this.height = height;
+ this.useSurface = useSurface;
+ stride = width;
+ sliceHeight = height;
+
+ if (useSurface) {
+ // Create shared EGL context.
+ eglSetup(sharedContext, width, height);
+ makeCurrent();
+
+ // Create output surface
+ int[] textures = new int[1];
+ GLES20.glGenTextures(1, textures, 0);
+ checkGlError("glGenTextures");
+ textureID = textures[0];
+ GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureID);
+ checkGlError("glBindTexture mTextureID");
+
+ GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
+ GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
+ GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
+ GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
+ GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
+ GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
+ GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
+ GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
+ checkGlError("glTexParameter");
+ Log.d(TAG, "Video decoder TextureID = " + textureID);
+ surfaceTexture = new SurfaceTexture(textureID);
+ surface = new Surface(surfaceTexture);
+ decodeSurface = surface;
+ }
+
+ MediaFormat format =
+ MediaFormat.createVideoFormat(VP8_MIME_TYPE, width, height);
+ if (!useSurface) {
+ format.setInteger(MediaFormat.KEY_COLOR_FORMAT, properties.colorFormat);
+ }
+ Log.d(TAG, " Format: " + format);
+ mediaCodec = MediaCodec.createByCodecName(properties.codecName);
+ if (mediaCodec == null) {
+ return false;
+ }
+ mediaCodec.configure(format, decodeSurface, null, 0);
+ mediaCodec.start();
+ colorFormat = properties.colorFormat;
+ outputBuffers = mediaCodec.getOutputBuffers();
+ inputBuffers = mediaCodec.getInputBuffers();
+ Log.d(TAG, "Input buffers: " + inputBuffers.length +
+ ". Output buffers: " + outputBuffers.length);
+ return true;
+ } catch (IllegalStateException e) {
+ Log.e(TAG, "initDecode failed", e);
+ return false;
+ }
+ }
+
+ private void release() {
+ Log.d(TAG, "Java releaseDecoder");
+ checkOnMediaCodecThread();
+ try {
+ mediaCodec.stop();
+ mediaCodec.release();
+ } catch (IllegalStateException e) {
+ Log.e(TAG, "release failed", e);
+ }
+ mediaCodec = null;
+ mediaCodecThread = null;
+ if (useSurface) {
+ surface.release();
+ surface = null;
+ surfaceTexture = null;
+ if (textureID >= 0) {
+ int[] textures = new int[1];
+ textures[0] = textureID;
+ Log.d(TAG, "Delete video decoder TextureID " + textureID);
+ GLES20.glDeleteTextures(1, textures, 0);
+ checkGlError("glDeleteTextures");
+ }
+ eglRelease();
+ }
+ }
+
+ // Dequeue an input buffer and return its index, -1 if no input buffer is
+ // available, or -2 if the codec is no longer operative.
+ private int dequeueInputBuffer() {
+ checkOnMediaCodecThread();
+ try {
+ return mediaCodec.dequeueInputBuffer(DEQUEUE_INPUT_TIMEOUT);
+ } catch (IllegalStateException e) {
+ Log.e(TAG, "dequeueIntputBuffer failed", e);
+ return -2;
+ }
+ }
+
+ private boolean queueInputBuffer(
+ int inputBufferIndex, int size, long timestampUs) {
+ checkOnMediaCodecThread();
+ try {
+ inputBuffers[inputBufferIndex].position(0);
+ inputBuffers[inputBufferIndex].limit(size);
+ mediaCodec.queueInputBuffer(inputBufferIndex, 0, size, timestampUs, 0);
+ return true;
+ }
+ catch (IllegalStateException e) {
+ Log.e(TAG, "decode failed", e);
+ return false;
+ }
+ }
+
+ // Helper struct for dequeueOutputBuffer() below.
+ private static class DecoderOutputBufferInfo {
+ public DecoderOutputBufferInfo(
+ int index, int offset, int size, long presentationTimestampUs) {
+ this.index = index;
+ this.offset = offset;
+ this.size = size;
+ this.presentationTimestampUs = presentationTimestampUs;
+ }
+
+ private final int index;
+ private final int offset;
+ private final int size;
+ private final long presentationTimestampUs;
+ }
+
+ // Dequeue and return an output buffer index, -1 if no output
+ // buffer available or -2 if error happened.
+ private DecoderOutputBufferInfo dequeueOutputBuffer(int dequeueTimeoutUs) {
+ checkOnMediaCodecThread();
+ try {
+ MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
+ int result = mediaCodec.dequeueOutputBuffer(info, dequeueTimeoutUs);
+ while (result == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED ||
+ result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+ if (result == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
+ outputBuffers = mediaCodec.getOutputBuffers();
+ Log.d(TAG, "Output buffers changed: " + outputBuffers.length);
+ } else if (result == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+ MediaFormat format = mediaCodec.getOutputFormat();
+ Log.d(TAG, "Format changed: " + format.toString());
+ width = format.getInteger(MediaFormat.KEY_WIDTH);
+ height = format.getInteger(MediaFormat.KEY_HEIGHT);
+ if (!useSurface && format.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
+ colorFormat = format.getInteger(MediaFormat.KEY_COLOR_FORMAT);
+ Log.d(TAG, "Color: 0x" + Integer.toHexString(colorFormat));
+ // Check if new color space is supported.
+ boolean validColorFormat = false;
+ for (int supportedColorFormat : supportedColorList) {
+ if (colorFormat == supportedColorFormat) {
+ validColorFormat = true;
+ break;
+ }
+ }
+ if (!validColorFormat) {
+ Log.e(TAG, "Non supported color format");
+ return new DecoderOutputBufferInfo(-1, 0, 0, -1);
+ }
+ }
+ if (format.containsKey("stride")) {
+ stride = format.getInteger("stride");
+ }
+ if (format.containsKey("slice-height")) {
+ sliceHeight = format.getInteger("slice-height");
+ }
+ Log.d(TAG, "Frame stride and slice height: "
+ + stride + " x " + sliceHeight);
+ stride = Math.max(width, stride);
+ sliceHeight = Math.max(height, sliceHeight);
+ }
+ result = mediaCodec.dequeueOutputBuffer(info, dequeueTimeoutUs);
+ }
+ if (result >= 0) {
+ return new DecoderOutputBufferInfo(result, info.offset, info.size,
+ info.presentationTimeUs);
+ }
+ return null;
+ } catch (IllegalStateException e) {
+ Log.e(TAG, "dequeueOutputBuffer failed", e);
+ return new DecoderOutputBufferInfo(-1, 0, 0, -1);
+ }
+ }
+
+ // Release a dequeued output buffer back to the codec for re-use. Return
+ // false if the codec is no longer operable.
+ private boolean releaseOutputBuffer(int index, boolean render) {
+ checkOnMediaCodecThread();
+ try {
+ if (!useSurface) {
+ render = false;
+ }
+ mediaCodec.releaseOutputBuffer(index, render);
+ return true;
+ } catch (IllegalStateException e) {
+ Log.e(TAG, "releaseOutputBuffer failed", e);
+ return false;
+ }
+ }
+}
diff --git a/app/webrtc/java/src/org/webrtc/MediaCodecVideoEncoder.java b/app/webrtc/java/src/org/webrtc/MediaCodecVideoEncoder.java
index 971c427..cf11573 100644
--- a/app/webrtc/java/src/org/webrtc/MediaCodecVideoEncoder.java
+++ b/app/webrtc/java/src/org/webrtc/MediaCodecVideoEncoder.java
@@ -29,10 +29,10 @@
package org.webrtc;
import android.media.MediaCodec;
+import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
-import android.media.MediaCodecInfo.CodecCapabilities;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
@@ -78,7 +78,7 @@
// Helper struct for findVp8HwEncoder() below.
private static class EncoderProperties {
- EncoderProperties(String codecName, int colorFormat) {
+ public EncoderProperties(String codecName, int colorFormat) {
this.codecName = codecName;
this.colorFormat = colorFormat;
}
@@ -106,26 +106,33 @@
continue; // No VP8 support in this codec; try the next one.
}
Log.d(TAG, "Found candidate encoder " + name);
+
+ // Check if this is supported HW encoder.
+ boolean supportedCodec = false;
+ for (String hwCodecPrefix : supportedHwCodecPrefixes) {
+ if (name.startsWith(hwCodecPrefix)) {
+ supportedCodec = true;
+ break;
+ }
+ }
+ if (!supportedCodec) {
+ continue;
+ }
+
CodecCapabilities capabilities =
info.getCapabilitiesForType(VP8_MIME_TYPE);
for (int colorFormat : capabilities.colorFormats) {
Log.d(TAG, " Color: 0x" + Integer.toHexString(colorFormat));
}
- // Check if this is supported HW encoder
- for (String hwCodecPrefix : supportedHwCodecPrefixes) {
- if (!name.startsWith(hwCodecPrefix)) {
- continue;
- }
- // Check if codec supports either yuv420 or nv12
- for (int supportedColorFormat : supportedColorList) {
- for (int codecColorFormat : capabilities.colorFormats) {
- if (codecColorFormat == supportedColorFormat) {
- // Found supported HW VP8 encoder
- Log.d(TAG, "Found target encoder " + name +
- ". Color: 0x" + Integer.toHexString(codecColorFormat));
- return new EncoderProperties(name, codecColorFormat);
- }
+ // Check if codec supports either yuv420 or nv12.
+ for (int supportedColorFormat : supportedColorList) {
+ for (int codecColorFormat : capabilities.colorFormats) {
+ if (codecColorFormat == supportedColorFormat) {
+ // Found supported HW VP8 encoder.
+ Log.d(TAG, "Found target encoder " + name +
+ ". Color: 0x" + Integer.toHexString(codecColorFormat));
+ return new EncoderProperties(name, codecColorFormat);
}
}
}
@@ -137,15 +144,6 @@
return findVp8HwEncoder() != null;
}
- private static int bitRate(int kbps) {
- // webrtc "kilo" means 1000, not 1024. Apparently.
- // (and the price for overshooting is frame-dropping as webrtc enforces its
- // bandwidth estimation, which is unpleasant).
- // Since the HW encoder in the N5 overshoots, we clamp to a bit less than
- // the requested rate. Sad but true. Bug 3194.
- return kbps * 950;
- }
-
private void checkOnMediaCodecThread() {
if (mediaCodecThread.getId() != Thread.currentThread().getId()) {
throw new RuntimeException(
@@ -156,7 +154,7 @@
// Return the array of input buffers, or null on failure.
private ByteBuffer[] initEncode(int width, int height, int kbps, int fps) {
- Log.d(TAG, "initEncode: " + width + " x " + height +
+ Log.d(TAG, "Java initEncode: " + width + " x " + height +
". @ " + kbps + " kbps. Fps: " + fps +
". Color: 0x" + Integer.toHexString(colorFormat));
if (mediaCodecThread != null) {
@@ -170,7 +168,7 @@
try {
MediaFormat format =
MediaFormat.createVideoFormat(VP8_MIME_TYPE, width, height);
- format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate(kbps));
+ format.setInteger(MediaFormat.KEY_BIT_RATE, 1000 * kbps);
format.setInteger("bitrate-mode", VIDEO_ControlRateConstant);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, properties.colorFormat);
// Default WebRTC settings
@@ -222,7 +220,7 @@
}
private void release() {
- Log.d(TAG, "release");
+ Log.d(TAG, "Java releaseEncoder");
checkOnMediaCodecThread();
try {
mediaCodec.stop();
@@ -241,7 +239,7 @@
Log.v(TAG, "setRates: " + kbps + " kbps. Fps: " + frameRateIgnored);
try {
Bundle params = new Bundle();
- params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, bitRate(kbps));
+ params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, 1000 * kbps);
mediaCodec.setParameters(params);
return true;
} catch (IllegalStateException e) {
diff --git a/app/webrtc/java/src/org/webrtc/PeerConnectionFactory.java b/app/webrtc/java/src/org/webrtc/PeerConnectionFactory.java
index 441f37b..f9f96e7 100644
--- a/app/webrtc/java/src/org/webrtc/PeerConnectionFactory.java
+++ b/app/webrtc/java/src/org/webrtc/PeerConnectionFactory.java
@@ -46,8 +46,12 @@
// Callers may specify either |initializeAudio| or |initializeVideo| as false
// to skip initializing the respective engine (and avoid the need for the
// respective permissions).
+ // |renderEGLContext| can be provided to suport HW video decoding to
+ // texture and will be used to create a shared EGL context on video
+ // decoding thread.
public static native boolean initializeAndroidGlobals(
- Object context, boolean initializeAudio, boolean initializeVideo);
+ Object context, boolean initializeAudio, boolean initializeVideo,
+ Object renderEGLContext);
public PeerConnectionFactory() {
nativeFactory = nativeCreatePeerConnectionFactory();
diff --git a/app/webrtc/java/src/org/webrtc/VideoRenderer.java b/app/webrtc/java/src/org/webrtc/VideoRenderer.java
index 4cc341a..19df137 100644
--- a/app/webrtc/java/src/org/webrtc/VideoRenderer.java
+++ b/app/webrtc/java/src/org/webrtc/VideoRenderer.java
@@ -44,6 +44,9 @@
public final int height;
public final int[] yuvStrides;
public final ByteBuffer[] yuvPlanes;
+ public final boolean yuvFrame;
+ public Object textureObject;
+ public int textureId;
/**
* Construct a frame of the given dimensions with the specified planar
@@ -62,25 +65,72 @@
yuvPlanes[2] = ByteBuffer.allocateDirect(yuvStrides[2] * height);
}
this.yuvPlanes = yuvPlanes;
+ this.yuvFrame = true;
+ }
+
+ /**
+ * Construct a texture frame of the given dimensions with data in SurfaceTexture
+ */
+ public I420Frame(
+ int width, int height, Object textureObject, int textureId) {
+ this.width = width;
+ this.height = height;
+ this.yuvStrides = null;
+ this.yuvPlanes = null;
+ this.textureObject = textureObject;
+ this.textureId = textureId;
+ this.yuvFrame = false;
}
/**
* Copy the planes out of |source| into |this| and return |this|. Calling
- * this with mismatched frame dimensions is a programming error and will
- * likely crash.
+ * this with mismatched frame dimensions or frame type is a programming
+ * error and will likely crash.
*/
public I420Frame copyFrom(I420Frame source) {
- if (!Arrays.equals(yuvStrides, source.yuvStrides) ||
- width != source.width || height != source.height) {
- throw new RuntimeException("Mismatched dimensions! Source: " +
+ if (source.yuvFrame && yuvFrame) {
+ if (!Arrays.equals(yuvStrides, source.yuvStrides) ||
+ width != source.width || height != source.height) {
+ throw new RuntimeException("Mismatched dimensions! Source: " +
+ source.toString() + ", destination: " + toString());
+ }
+ copyPlane(source.yuvPlanes[0], yuvPlanes[0]);
+ copyPlane(source.yuvPlanes[1], yuvPlanes[1]);
+ copyPlane(source.yuvPlanes[2], yuvPlanes[2]);
+ return this;
+ } else if (!source.yuvFrame && !yuvFrame) {
+ textureObject = source.textureObject;
+ textureId = source.textureId;
+ return this;
+ } else {
+ throw new RuntimeException("Mismatched frame types! Source: " +
source.toString() + ", destination: " + toString());
}
- copyPlane(source.yuvPlanes[0], yuvPlanes[0]);
- copyPlane(source.yuvPlanes[1], yuvPlanes[1]);
- copyPlane(source.yuvPlanes[2], yuvPlanes[2]);
- return this;
}
+ public I420Frame copyFrom(byte[] yuvData) {
+ if (yuvData.length < width * height * 3 / 2) {
+ throw new RuntimeException("Wrong arrays size: " + yuvData.length);
+ }
+ if (!yuvFrame) {
+ throw new RuntimeException("Can not feed yuv data to texture frame");
+ }
+ int planeSize = width * height;
+ ByteBuffer[] planes = new ByteBuffer[3];
+ planes[0] = ByteBuffer.wrap(yuvData, 0, planeSize);
+ planes[1] = ByteBuffer.wrap(yuvData, planeSize, planeSize / 4);
+ planes[2] = ByteBuffer.wrap(yuvData, planeSize + planeSize / 4,
+ planeSize / 4);
+ for (int i = 0; i < 3; i++) {
+ yuvPlanes[i].position(0);
+ yuvPlanes[i].put(planes[i]);
+ yuvPlanes[i].position(0);
+ yuvPlanes[i].limit(yuvPlanes[i].capacity());
+ }
+ return this;
+ }
+
+
@Override
public String toString() {
return width + "x" + height + ":" + yuvStrides[0] + ":" + yuvStrides[1] +
@@ -126,11 +176,16 @@
}
public void dispose() {
- free(nativeVideoRenderer);
+ if (callbacks == null) {
+ freeGuiVideoRenderer(nativeVideoRenderer);
+ } else {
+ freeWrappedVideoRenderer(nativeVideoRenderer);
+ }
}
private static native long nativeCreateGuiVideoRenderer(int x, int y);
private static native long nativeWrapVideoRenderer(Callbacks callbacks);
- private static native void free(long nativeVideoRenderer);
+ private static native void freeGuiVideoRenderer(long nativeVideoRenderer);
+ private static native void freeWrappedVideoRenderer(long nativeVideoRenderer);
}
diff --git a/app/webrtc/jsep.h b/app/webrtc/jsep.h
index 5f28fc8..e748da1 100644
--- a/app/webrtc/jsep.h
+++ b/app/webrtc/jsep.h
@@ -33,8 +33,8 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/refcount.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/refcount.h"
namespace cricket {
class SessionDescription;
@@ -138,7 +138,7 @@
SdpParseError* error);
// Jsep CreateOffer and CreateAnswer callback interface.
-class CreateSessionDescriptionObserver : public talk_base::RefCountInterface {
+class CreateSessionDescriptionObserver : public rtc::RefCountInterface {
public:
// The implementation of the CreateSessionDescriptionObserver takes
// the ownership of the |desc|.
@@ -150,7 +150,7 @@
};
// Jsep SetLocalDescription and SetRemoteDescription callback interface.
-class SetSessionDescriptionObserver : public talk_base::RefCountInterface {
+class SetSessionDescriptionObserver : public rtc::RefCountInterface {
public:
virtual void OnSuccess() = 0;
virtual void OnFailure(const std::string& error) = 0;
diff --git a/app/webrtc/jsepicecandidate.cc b/app/webrtc/jsepicecandidate.cc
index 13cc812..755403e 100644
--- a/app/webrtc/jsepicecandidate.cc
+++ b/app/webrtc/jsepicecandidate.cc
@@ -30,7 +30,7 @@
#include <vector>
#include "talk/app/webrtc/webrtcsdp.h"
-#include "talk/base/stringencode.h"
+#include "webrtc/base/stringencode.h"
namespace webrtc {
diff --git a/app/webrtc/jsepicecandidate.h b/app/webrtc/jsepicecandidate.h
index 54de950..7be420c 100644
--- a/app/webrtc/jsepicecandidate.h
+++ b/app/webrtc/jsepicecandidate.h
@@ -33,8 +33,8 @@
#include <string>
#include "talk/app/webrtc/jsep.h"
-#include "talk/base/constructormagic.h"
#include "talk/p2p/base/candidate.h"
+#include "webrtc/base/constructormagic.h"
namespace webrtc {
diff --git a/app/webrtc/jsepsessiondescription.cc b/app/webrtc/jsepsessiondescription.cc
index d7b37b5..c318d91 100644
--- a/app/webrtc/jsepsessiondescription.cc
+++ b/app/webrtc/jsepsessiondescription.cc
@@ -27,10 +27,10 @@
#include "talk/app/webrtc/jsepsessiondescription.h"
#include "talk/app/webrtc/webrtcsdp.h"
-#include "talk/base/stringencode.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/stringencode.h"
-using talk_base::scoped_ptr;
+using rtc::scoped_ptr;
using cricket::SessionDescription;
namespace webrtc {
@@ -57,10 +57,19 @@
const char SessionDescriptionInterface::kAnswer[] = "answer";
const int JsepSessionDescription::kDefaultVideoCodecId = 100;
-const int JsepSessionDescription::kDefaultVideoCodecFramerate = 30;
+// This is effectively a max value of the frame rate. 30 is default from camera.
+const int JsepSessionDescription::kDefaultVideoCodecFramerate = 60;
const char JsepSessionDescription::kDefaultVideoCodecName[] = "VP8";
+// Used as default max video codec size before we have it in signaling.
+#if defined(ANDROID)
+// Limit default max video codec size for Android to avoid
+// HW VP8 codec initialization failure for resolution higher than 720p.
const int JsepSessionDescription::kMaxVideoCodecWidth = 1280;
const int JsepSessionDescription::kMaxVideoCodecHeight = 720;
+#else
+const int JsepSessionDescription::kMaxVideoCodecWidth = 1920;
+const int JsepSessionDescription::kMaxVideoCodecHeight = 1080;
+#endif
const int JsepSessionDescription::kDefaultVideoCodecPreference = 1;
SessionDescriptionInterface* CreateSessionDescription(const std::string& type,
diff --git a/app/webrtc/jsepsessiondescription.h b/app/webrtc/jsepsessiondescription.h
index 7ca7a22..07d13a3 100644
--- a/app/webrtc/jsepsessiondescription.h
+++ b/app/webrtc/jsepsessiondescription.h
@@ -35,7 +35,7 @@
#include "talk/app/webrtc/jsep.h"
#include "talk/app/webrtc/jsepicecandidate.h"
-#include "talk/base/scoped_ptr.h"
+#include "webrtc/base/scoped_ptr.h"
namespace cricket {
class SessionDescription;
@@ -89,7 +89,7 @@
static const int kDefaultVideoCodecPreference;
private:
- talk_base::scoped_ptr<cricket::SessionDescription> description_;
+ rtc::scoped_ptr<cricket::SessionDescription> description_;
std::string session_id_;
std::string session_version_;
std::string type_;
diff --git a/app/webrtc/jsepsessiondescription_unittest.cc b/app/webrtc/jsepsessiondescription_unittest.cc
index 55eb3d5..5f5d808 100644
--- a/app/webrtc/jsepsessiondescription_unittest.cc
+++ b/app/webrtc/jsepsessiondescription_unittest.cc
@@ -29,22 +29,22 @@
#include "talk/app/webrtc/jsepicecandidate.h"
#include "talk/app/webrtc/jsepsessiondescription.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/stringencode.h"
using webrtc::IceCandidateCollection;
using webrtc::IceCandidateInterface;
using webrtc::JsepIceCandidate;
using webrtc::JsepSessionDescription;
using webrtc::SessionDescriptionInterface;
-using talk_base::scoped_ptr;
+using rtc::scoped_ptr;
static const char kCandidateUfrag[] = "ufrag";
static const char kCandidatePwd[] = "pwd";
@@ -98,24 +98,24 @@
class JsepSessionDescriptionTest : public testing::Test {
protected:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
virtual void SetUp() {
int port = 1234;
- talk_base::SocketAddress address("127.0.0.1", port++);
+ rtc::SocketAddress address("127.0.0.1", port++);
cricket::Candidate candidate("rtp", cricket::ICE_CANDIDATE_COMPONENT_RTP,
"udp", address, 1, "",
"", "local", "eth0", 0, "1");
candidate_ = candidate;
const std::string session_id =
- talk_base::ToString(talk_base::CreateRandomId64());
+ rtc::ToString(rtc::CreateRandomId64());
const std::string session_version =
- talk_base::ToString(talk_base::CreateRandomId());
+ rtc::ToString(rtc::CreateRandomId());
jsep_desc_.reset(new JsepSessionDescription("dummy"));
ASSERT_TRUE(jsep_desc_->Initialize(CreateCricketSessionDescription(),
session_id, session_version));
@@ -135,7 +135,7 @@
}
cricket::Candidate candidate_;
- talk_base::scoped_ptr<JsepSessionDescription> jsep_desc_;
+ rtc::scoped_ptr<JsepSessionDescription> jsep_desc_;
};
// Test that number_of_mediasections() returns the number of media contents in
diff --git a/app/webrtc/localaudiosource.cc b/app/webrtc/localaudiosource.cc
index ab9ae4f..6d3b89f 100644
--- a/app/webrtc/localaudiosource.cc
+++ b/app/webrtc/localaudiosource.cc
@@ -29,8 +29,8 @@
#include <vector>
-#include "talk/media/base/mediaengine.h"
#include "talk/app/webrtc/mediaconstraintsinterface.h"
+#include "talk/media/base/mediaengine.h"
using webrtc::MediaConstraintsInterface;
using webrtc::MediaSourceInterface;
@@ -41,9 +41,8 @@
// Convert constraints to audio options. Return false if constraints are
// invalid.
-bool FromConstraints(const MediaConstraintsInterface::Constraints& constraints,
+void FromConstraints(const MediaConstraintsInterface::Constraints& constraints,
cricket::AudioOptions* options) {
- bool success = true;
MediaConstraintsInterface::Constraints::const_iterator iter;
// This design relies on the fact that all the audio constraints are actually
@@ -53,10 +52,8 @@
for (iter = constraints.begin(); iter != constraints.end(); ++iter) {
bool value = false;
- if (!talk_base::FromString(iter->value, &value)) {
- success = false;
+ if (!rtc::FromString(iter->value, &value))
continue;
- }
if (iter->key == MediaConstraintsInterface::kEchoCancellation)
options->echo_cancellation.Set(value);
@@ -79,19 +76,16 @@
options->typing_detection.Set(value);
else if (iter->key == MediaConstraintsInterface::kAudioMirroring)
options->stereo_swapping.Set(value);
- else
- success = false;
}
- return success;
}
} // namespace
-talk_base::scoped_refptr<LocalAudioSource> LocalAudioSource::Create(
+rtc::scoped_refptr<LocalAudioSource> LocalAudioSource::Create(
const PeerConnectionFactoryInterface::Options& options,
const MediaConstraintsInterface* constraints) {
- talk_base::scoped_refptr<LocalAudioSource> source(
- new talk_base::RefCountedObject<LocalAudioSource>());
+ rtc::scoped_refptr<LocalAudioSource> source(
+ new rtc::RefCountedObject<LocalAudioSource>());
source->Initialize(options, constraints);
return source;
}
@@ -106,12 +100,9 @@
// constraints.
FromConstraints(constraints->GetOptional(), &options_);
- cricket::AudioOptions audio_options;
- if (!FromConstraints(constraints->GetMandatory(), &audio_options)) {
- source_state_ = kEnded;
- return;
- }
- options_.SetAll(audio_options);
+ cricket::AudioOptions mandatory_options;
+ FromConstraints(constraints->GetMandatory(), &mandatory_options);
+ options_.SetAll(mandatory_options);
source_state_ = kLive;
}
diff --git a/app/webrtc/localaudiosource.h b/app/webrtc/localaudiosource.h
index fb769ed..51ab387 100644
--- a/app/webrtc/localaudiosource.h
+++ b/app/webrtc/localaudiosource.h
@@ -31,8 +31,8 @@
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/notifier.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/mediachannel.h"
+#include "webrtc/base/scoped_ptr.h"
// LocalAudioSource implements AudioSourceInterface.
// This contains settings for switching audio processing on and off.
@@ -44,7 +44,7 @@
class LocalAudioSource : public Notifier<AudioSourceInterface> {
public:
// Creates an instance of LocalAudioSource.
- static talk_base::scoped_refptr<LocalAudioSource> Create(
+ static rtc::scoped_refptr<LocalAudioSource> Create(
const PeerConnectionFactoryInterface::Options& options,
const MediaConstraintsInterface* constraints);
diff --git a/app/webrtc/localaudiosource_unittest.cc b/app/webrtc/localaudiosource_unittest.cc
index f8880e0..c3618aa 100644
--- a/app/webrtc/localaudiosource_unittest.cc
+++ b/app/webrtc/localaudiosource_unittest.cc
@@ -31,10 +31,10 @@
#include <vector>
#include "talk/app/webrtc/test/fakeconstraints.h"
-#include "talk/base/gunit.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/fakevideorenderer.h"
#include "talk/media/devices/fakedevicemanager.h"
+#include "webrtc/base/gunit.h"
using webrtc::LocalAudioSource;
using webrtc::MediaConstraintsInterface;
@@ -52,7 +52,7 @@
constraints.AddMandatory(MediaConstraintsInterface::kNoiseSuppression, false);
constraints.AddOptional(MediaConstraintsInterface::kHighpassFilter, true);
- talk_base::scoped_refptr<LocalAudioSource> source =
+ rtc::scoped_refptr<LocalAudioSource> source =
LocalAudioSource::Create(PeerConnectionFactoryInterface::Options(),
&constraints);
@@ -73,7 +73,7 @@
TEST(LocalAudioSourceTest, OptionNotSet) {
webrtc::FakeConstraints constraints;
- talk_base::scoped_refptr<LocalAudioSource> source =
+ rtc::scoped_refptr<LocalAudioSource> source =
LocalAudioSource::Create(PeerConnectionFactoryInterface::Options(),
&constraints);
bool value;
@@ -85,7 +85,7 @@
constraints.AddMandatory(MediaConstraintsInterface::kEchoCancellation, false);
constraints.AddOptional(MediaConstraintsInterface::kEchoCancellation, true);
- talk_base::scoped_refptr<LocalAudioSource> source =
+ rtc::scoped_refptr<LocalAudioSource> source =
LocalAudioSource::Create(PeerConnectionFactoryInterface::Options(),
&constraints);
@@ -99,7 +99,7 @@
constraints.AddOptional(MediaConstraintsInterface::kHighpassFilter, false);
constraints.AddOptional("invalidKey", false);
- talk_base::scoped_refptr<LocalAudioSource> source =
+ rtc::scoped_refptr<LocalAudioSource> source =
LocalAudioSource::Create(PeerConnectionFactoryInterface::Options(),
&constraints);
@@ -114,11 +114,12 @@
constraints.AddMandatory(MediaConstraintsInterface::kHighpassFilter, false);
constraints.AddMandatory("invalidKey", false);
- talk_base::scoped_refptr<LocalAudioSource> source =
+ rtc::scoped_refptr<LocalAudioSource> source =
LocalAudioSource::Create(PeerConnectionFactoryInterface::Options(),
&constraints);
- EXPECT_EQ(MediaSourceInterface::kEnded, source->state());
+ EXPECT_EQ(MediaSourceInterface::kLive, source->state());
bool value;
- EXPECT_FALSE(source->options().highpass_filter.Get(&value));
+ EXPECT_TRUE(source->options().highpass_filter.Get(&value));
+ EXPECT_FALSE(value);
}
diff --git a/app/webrtc/mediaconstraintsinterface.cc b/app/webrtc/mediaconstraintsinterface.cc
index 0ecadd6..a7b88aa 100644
--- a/app/webrtc/mediaconstraintsinterface.cc
+++ b/app/webrtc/mediaconstraintsinterface.cc
@@ -27,7 +27,7 @@
#include "talk/app/webrtc/mediaconstraintsinterface.h"
-#include "talk/base/stringencode.h"
+#include "webrtc/base/stringencode.h"
namespace webrtc {
@@ -93,12 +93,12 @@
const char MediaConstraintsInterface::kEnableIPv6[] = "googIPv6";
const char MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate[] =
"googSuspendBelowMinBitrate";
-const char MediaConstraintsInterface::kImprovedWifiBwe[] =
- "googImprovedWifiBwe";
+const char MediaConstraintsInterface::kNumUnsignalledRecvStreams[] =
+ "googNumUnsignalledRecvStreams";
+const char MediaConstraintsInterface::kCombinedAudioVideoBwe[] =
+ "googCombinedAudioVideoBwe";
const char MediaConstraintsInterface::kScreencastMinBitrate[] =
"googScreencastMinBitrate";
-const char MediaConstraintsInterface::kSkipEncodingUnusedStreams[] =
- "googSkipEncodingUnusedStreams";
// TODO(ronghuawu): Remove once cpu overuse detection is stable.
const char MediaConstraintsInterface::kCpuOveruseDetection[] =
"googCpuOveruseDetection";
@@ -119,7 +119,6 @@
const char MediaConstraintsInterface::kVeryHighBitrate[] =
"googVeryHighBitrate";
const char MediaConstraintsInterface::kPayloadPadding[] = "googPayloadPadding";
-const char MediaConstraintsInterface::kOpusFec[] = "googOpusFec";
// Set |value| to the value associated with the first appearance of |key|, or
@@ -155,10 +154,10 @@
if (constraints->GetMandatory().FindFirst(key, &string_value)) {
if (mandatory_constraints)
++*mandatory_constraints;
- return talk_base::FromString(string_value, value);
+ return rtc::FromString(string_value, value);
}
if (constraints->GetOptional().FindFirst(key, &string_value)) {
- return talk_base::FromString(string_value, value);
+ return rtc::FromString(string_value, value);
}
return false;
}
diff --git a/app/webrtc/mediaconstraintsinterface.h b/app/webrtc/mediaconstraintsinterface.h
index 36257db..045da79 100644
--- a/app/webrtc/mediaconstraintsinterface.h
+++ b/app/webrtc/mediaconstraintsinterface.h
@@ -115,10 +115,11 @@
// Temporary constraint to enable suspend below min bitrate feature.
static const char kEnableVideoSuspendBelowMinBitrate[];
// googSuspendBelowMinBitrate
- static const char kImprovedWifiBwe[]; // googImprovedWifiBwe
+ static const char kNumUnsignalledRecvStreams[];
+ // googNumUnsignalledRecvStreams
+ // Constraint to enable combined audio+video bandwidth estimation.
+ static const char kCombinedAudioVideoBwe[]; // googCombinedAudioVideoBwe
static const char kScreencastMinBitrate[]; // googScreencastMinBitrate
- static const char kSkipEncodingUnusedStreams[];
- // googSkipEncodingUnusedStreams
static const char kCpuOveruseDetection[]; // googCpuOveruseDetection
static const char kCpuUnderuseThreshold[]; // googCpuUnderuseThreshold
static const char kCpuOveruseThreshold[]; // googCpuOveruseThreshold
@@ -134,11 +135,6 @@
static const char kVeryHighBitrate[]; // googVeryHighBitrate
static const char kPayloadPadding[]; // googPayloadPadding
- // PeerConnection codec constraint keys. This should be combined with the
- // values above.
- // kOpusFec controls whether we ask the other side to turn on FEC for Opus.
- static const char kOpusFec[]; // googOpusFec
-
// The prefix of internal-only constraints whose JS set values should be
// stripped by Chrome before passed down to Libjingle.
static const char kInternalConstraintPrefix[];
diff --git a/app/webrtc/mediastream.cc b/app/webrtc/mediastream.cc
index aad8e85..2bd5b53 100644
--- a/app/webrtc/mediastream.cc
+++ b/app/webrtc/mediastream.cc
@@ -26,7 +26,7 @@
*/
#include "talk/app/webrtc/mediastream.h"
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
namespace webrtc {
@@ -42,10 +42,10 @@
return it;
};
-talk_base::scoped_refptr<MediaStream> MediaStream::Create(
+rtc::scoped_refptr<MediaStream> MediaStream::Create(
const std::string& label) {
- talk_base::RefCountedObject<MediaStream>* stream =
- new talk_base::RefCountedObject<MediaStream>(label);
+ rtc::RefCountedObject<MediaStream>* stream =
+ new rtc::RefCountedObject<MediaStream>(label);
return stream;
}
@@ -69,7 +69,7 @@
return RemoveTrack<VideoTrackVector>(&video_tracks_, track);
}
-talk_base::scoped_refptr<AudioTrackInterface>
+rtc::scoped_refptr<AudioTrackInterface>
MediaStream::FindAudioTrack(const std::string& track_id) {
AudioTrackVector::iterator it = FindTrack(&audio_tracks_, track_id);
if (it == audio_tracks_.end())
@@ -77,7 +77,7 @@
return *it;
}
-talk_base::scoped_refptr<VideoTrackInterface>
+rtc::scoped_refptr<VideoTrackInterface>
MediaStream::FindVideoTrack(const std::string& track_id) {
VideoTrackVector::iterator it = FindTrack(&video_tracks_, track_id);
if (it == video_tracks_.end())
diff --git a/app/webrtc/mediastream.h b/app/webrtc/mediastream.h
index e5ac6eb..c8e0bcc 100644
--- a/app/webrtc/mediastream.h
+++ b/app/webrtc/mediastream.h
@@ -40,7 +40,7 @@
class MediaStream : public Notifier<MediaStreamInterface> {
public:
- static talk_base::scoped_refptr<MediaStream> Create(const std::string& label);
+ static rtc::scoped_refptr<MediaStream> Create(const std::string& label);
virtual std::string label() const OVERRIDE { return label_; }
@@ -48,9 +48,9 @@
virtual bool AddTrack(VideoTrackInterface* track) OVERRIDE;
virtual bool RemoveTrack(AudioTrackInterface* track) OVERRIDE;
virtual bool RemoveTrack(VideoTrackInterface* track) OVERRIDE;
- virtual talk_base::scoped_refptr<AudioTrackInterface>
+ virtual rtc::scoped_refptr<AudioTrackInterface>
FindAudioTrack(const std::string& track_id);
- virtual talk_base::scoped_refptr<VideoTrackInterface>
+ virtual rtc::scoped_refptr<VideoTrackInterface>
FindVideoTrack(const std::string& track_id);
virtual AudioTrackVector GetAudioTracks() OVERRIDE { return audio_tracks_; }
diff --git a/app/webrtc/mediastream_unittest.cc b/app/webrtc/mediastream_unittest.cc
index 113242f..bb1a73f 100644
--- a/app/webrtc/mediastream_unittest.cc
+++ b/app/webrtc/mediastream_unittest.cc
@@ -30,17 +30,17 @@
#include "talk/app/webrtc/audiotrack.h"
#include "talk/app/webrtc/mediastream.h"
#include "talk/app/webrtc/videotrack.h"
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/gunit.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/refcount.h"
+#include "webrtc/base/scoped_ptr.h"
static const char kStreamLabel1[] = "local_stream_1";
static const char kVideoTrackId[] = "dummy_video_cam_1";
static const char kAudioTrackId[] = "dummy_microphone_1";
-using talk_base::scoped_refptr;
+using rtc::scoped_refptr;
using ::testing::Exactly;
namespace webrtc {
diff --git a/app/webrtc/mediastreamhandler.cc b/app/webrtc/mediastreamhandler.cc
index ca28cf4..57aa4f5 100644
--- a/app/webrtc/mediastreamhandler.cc
+++ b/app/webrtc/mediastreamhandler.cc
@@ -59,7 +59,7 @@
LocalAudioSinkAdapter::LocalAudioSinkAdapter() : sink_(NULL) {}
LocalAudioSinkAdapter::~LocalAudioSinkAdapter() {
- talk_base::CritScope lock(&lock_);
+ rtc::CritScope lock(&lock_);
if (sink_)
sink_->OnClose();
}
@@ -69,7 +69,7 @@
int sample_rate,
int number_of_channels,
int number_of_frames) {
- talk_base::CritScope lock(&lock_);
+ rtc::CritScope lock(&lock_);
if (sink_) {
sink_->OnData(audio_data, bits_per_sample, sample_rate,
number_of_channels, number_of_frames);
@@ -77,7 +77,7 @@
}
void LocalAudioSinkAdapter::SetSink(cricket::AudioRenderer::Sink* sink) {
- talk_base::CritScope lock(&lock_);
+ rtc::CritScope lock(&lock_);
ASSERT(!sink || !sink_);
sink_ = sink;
}
diff --git a/app/webrtc/mediastreamhandler.h b/app/webrtc/mediastreamhandler.h
index 53afd55..c75bb9d 100644
--- a/app/webrtc/mediastreamhandler.h
+++ b/app/webrtc/mediastreamhandler.h
@@ -39,8 +39,8 @@
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/mediastreamprovider.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
-#include "talk/base/thread.h"
#include "talk/media/base/audiorenderer.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
@@ -62,7 +62,7 @@
virtual void OnEnabledChanged() = 0;
private:
- talk_base::scoped_refptr<MediaStreamTrackInterface> track_;
+ rtc::scoped_refptr<MediaStreamTrackInterface> track_;
uint32 ssrc_;
MediaStreamTrackInterface::TrackState state_;
bool enabled_;
@@ -87,7 +87,7 @@
cricket::AudioRenderer::Sink* sink_;
// Critical section protecting |sink_|.
- talk_base::CriticalSection lock_;
+ rtc::CriticalSection lock_;
};
// LocalAudioTrackHandler listen to events on a local AudioTrack instance
@@ -112,7 +112,7 @@
// Used to pass the data callback from the |audio_track_| to the other
// end of cricket::AudioRenderer.
- talk_base::scoped_ptr<LocalAudioSinkAdapter> sink_adapter_;
+ rtc::scoped_ptr<LocalAudioSinkAdapter> sink_adapter_;
};
// RemoteAudioTrackHandler listen to events on a remote AudioTrack instance
@@ -196,7 +196,7 @@
protected:
TrackHandler* FindTrackHandler(MediaStreamTrackInterface* track);
- talk_base::scoped_refptr<MediaStreamInterface> stream_;
+ rtc::scoped_refptr<MediaStreamInterface> stream_;
AudioProviderInterface* audio_provider_;
VideoProviderInterface* video_provider_;
typedef std::vector<TrackHandler*> TrackHandlers;
diff --git a/app/webrtc/mediastreamhandler_unittest.cc b/app/webrtc/mediastreamhandler_unittest.cc
index 9a53f35..61dbfe0 100644
--- a/app/webrtc/mediastreamhandler_unittest.cc
+++ b/app/webrtc/mediastreamhandler_unittest.cc
@@ -35,11 +35,11 @@
#include "talk/app/webrtc/streamcollection.h"
#include "talk/app/webrtc/videosource.h"
#include "talk/app/webrtc/videotrack.h"
-#include "talk/base/gunit.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/base/mediachannel.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "webrtc/base/gunit.h"
using ::testing::_;
using ::testing::Exactly;
@@ -79,8 +79,8 @@
class FakeVideoSource : public Notifier<VideoSourceInterface> {
public:
- static talk_base::scoped_refptr<FakeVideoSource> Create() {
- return new talk_base::RefCountedObject<FakeVideoSource>();
+ static rtc::scoped_refptr<FakeVideoSource> Create() {
+ return new rtc::RefCountedObject<FakeVideoSource>();
}
virtual cricket::VideoCapturer* GetVideoCapturer() {
return &fake_capturer_;
@@ -109,7 +109,7 @@
virtual void SetUp() {
stream_ = MediaStream::Create(kStreamLabel1);
- talk_base::scoped_refptr<VideoSourceInterface> source(
+ rtc::scoped_refptr<VideoSourceInterface> source(
FakeVideoSource::Create());
video_track_ = VideoTrack::Create(kVideoTrackId, source);
EXPECT_TRUE(stream_->AddTrack(video_track_));
@@ -175,9 +175,9 @@
MockAudioProvider audio_provider_;
MockVideoProvider video_provider_;
MediaStreamHandlerContainer handlers_;
- talk_base::scoped_refptr<MediaStreamInterface> stream_;
- talk_base::scoped_refptr<VideoTrackInterface> video_track_;
- talk_base::scoped_refptr<AudioTrackInterface> audio_track_;
+ rtc::scoped_refptr<MediaStreamInterface> stream_;
+ rtc::scoped_refptr<VideoTrackInterface> video_track_;
+ rtc::scoped_refptr<AudioTrackInterface> audio_track_;
};
// Test that |audio_provider_| is notified when an audio track is associated
diff --git a/app/webrtc/mediastreaminterface.h b/app/webrtc/mediastreaminterface.h
index a3439c5..5d6c659 100644
--- a/app/webrtc/mediastreaminterface.h
+++ b/app/webrtc/mediastreaminterface.h
@@ -37,9 +37,9 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ref_ptr.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/refcount.h"
+#include "webrtc/base/scoped_ref_ptr.h"
namespace cricket {
@@ -73,7 +73,7 @@
// provide media. A source can be shared with multiple tracks.
// TODO(perkj): Implement sources for local and remote audio tracks and
// remote video tracks.
-class MediaSourceInterface : public talk_base::RefCountInterface,
+class MediaSourceInterface : public rtc::RefCountInterface,
public NotifierInterface {
public:
enum SourceState {
@@ -90,7 +90,7 @@
};
// Information about a track.
-class MediaStreamTrackInterface : public talk_base::RefCountInterface,
+class MediaStreamTrackInterface : public rtc::RefCountInterface,
public NotifierInterface {
public:
enum TrackState {
@@ -176,7 +176,7 @@
// Interface of the audio processor used by the audio track to collect
// statistics.
-class AudioProcessorInterface : public talk_base::RefCountInterface {
+class AudioProcessorInterface : public rtc::RefCountInterface {
public:
struct AudioProcessorStats {
AudioProcessorStats() : typing_noise_detected(false),
@@ -220,7 +220,7 @@
// Get the audio processor used by the audio track. Return NULL if the track
// does not have any processor.
// TODO(xians): Make the interface pure virtual.
- virtual talk_base::scoped_refptr<AudioProcessorInterface>
+ virtual rtc::scoped_refptr<AudioProcessorInterface>
GetAudioProcessor() { return NULL; }
// Get a pointer to the audio renderer of this AudioTrack.
@@ -233,21 +233,21 @@
virtual ~AudioTrackInterface() {}
};
-typedef std::vector<talk_base::scoped_refptr<AudioTrackInterface> >
+typedef std::vector<rtc::scoped_refptr<AudioTrackInterface> >
AudioTrackVector;
-typedef std::vector<talk_base::scoped_refptr<VideoTrackInterface> >
+typedef std::vector<rtc::scoped_refptr<VideoTrackInterface> >
VideoTrackVector;
-class MediaStreamInterface : public talk_base::RefCountInterface,
+class MediaStreamInterface : public rtc::RefCountInterface,
public NotifierInterface {
public:
virtual std::string label() const = 0;
virtual AudioTrackVector GetAudioTracks() = 0;
virtual VideoTrackVector GetVideoTracks() = 0;
- virtual talk_base::scoped_refptr<AudioTrackInterface>
+ virtual rtc::scoped_refptr<AudioTrackInterface>
FindAudioTrack(const std::string& track_id) = 0;
- virtual talk_base::scoped_refptr<VideoTrackInterface>
+ virtual rtc::scoped_refptr<VideoTrackInterface>
FindVideoTrack(const std::string& track_id) = 0;
virtual bool AddTrack(AudioTrackInterface* track) = 0;
diff --git a/app/webrtc/mediastreamproxy.h b/app/webrtc/mediastreamproxy.h
index 7d018d5..484690e 100644
--- a/app/webrtc/mediastreamproxy.h
+++ b/app/webrtc/mediastreamproxy.h
@@ -37,9 +37,9 @@
PROXY_CONSTMETHOD0(std::string, label)
PROXY_METHOD0(AudioTrackVector, GetAudioTracks)
PROXY_METHOD0(VideoTrackVector, GetVideoTracks)
- PROXY_METHOD1(talk_base::scoped_refptr<AudioTrackInterface>,
+ PROXY_METHOD1(rtc::scoped_refptr<AudioTrackInterface>,
FindAudioTrack, const std::string&)
- PROXY_METHOD1(talk_base::scoped_refptr<VideoTrackInterface>,
+ PROXY_METHOD1(rtc::scoped_refptr<VideoTrackInterface>,
FindVideoTrack, const std::string&)
PROXY_METHOD1(bool, AddTrack, AudioTrackInterface*)
PROXY_METHOD1(bool, AddTrack, VideoTrackInterface*)
diff --git a/app/webrtc/mediastreamsignaling.cc b/app/webrtc/mediastreamsignaling.cc
index 99f627a..df51ba1 100644
--- a/app/webrtc/mediastreamsignaling.cc
+++ b/app/webrtc/mediastreamsignaling.cc
@@ -30,17 +30,17 @@
#include <vector>
#include "talk/app/webrtc/audiotrack.h"
-#include "talk/app/webrtc/mediastreamproxy.h"
#include "talk/app/webrtc/mediaconstraintsinterface.h"
+#include "talk/app/webrtc/mediastreamproxy.h"
#include "talk/app/webrtc/mediastreamtrackproxy.h"
#include "talk/app/webrtc/remoteaudiosource.h"
#include "talk/app/webrtc/remotevideocapturer.h"
#include "talk/app/webrtc/sctputils.h"
#include "talk/app/webrtc/videosource.h"
#include "talk/app/webrtc/videotrack.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/stringutils.h"
#include "talk/media/sctp/sctpdataengine.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/stringutils.h"
static const char kDefaultStreamLabel[] = "default";
static const char kDefaultAudioTrackLabel[] = "defaulta0";
@@ -48,12 +48,12 @@
namespace webrtc {
-using talk_base::scoped_ptr;
-using talk_base::scoped_refptr;
+using rtc::scoped_ptr;
+using rtc::scoped_refptr;
-static bool ParseConstraints(
+static bool ParseConstraintsForAnswer(
const MediaConstraintsInterface* constraints,
- cricket::MediaSessionOptions* options, bool is_answer) {
+ cricket::MediaSessionOptions* options) {
bool value;
size_t mandatory_constraints_satisfied = 0;
@@ -82,7 +82,7 @@
// kOfferToReceiveVideo defaults to false according to spec. But
// if it is an answer and video is offered, we should still accept video
// per default.
- options->has_video |= is_answer;
+ options->has_video = true;
}
if (FindConstraint(constraints,
@@ -123,16 +123,75 @@
(options.has_audio || options.has_video || options.has_data());
}
+static bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
+ return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
+}
+
+static bool IsValidOfferToReceiveMedia(int value) {
+ typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
+ return (value >= Options::kUndefined) &&
+ (value <= Options::kMaxOfferToReceiveMedia);
+}
+
+// Add the stream and RTP data channel info to |session_options|.
+static void SetStreams(
+ cricket::MediaSessionOptions* session_options,
+ rtc::scoped_refptr<StreamCollection> streams,
+ const MediaStreamSignaling::RtpDataChannels& rtp_data_channels) {
+ session_options->streams.clear();
+ if (streams != NULL) {
+ for (size_t i = 0; i < streams->count(); ++i) {
+ MediaStreamInterface* stream = streams->at(i);
+
+ AudioTrackVector audio_tracks(stream->GetAudioTracks());
+
+ // For each audio track in the stream, add it to the MediaSessionOptions.
+ for (size_t j = 0; j < audio_tracks.size(); ++j) {
+ scoped_refptr<MediaStreamTrackInterface> track(audio_tracks[j]);
+ session_options->AddStream(
+ cricket::MEDIA_TYPE_AUDIO, track->id(), stream->label());
+ }
+
+ VideoTrackVector video_tracks(stream->GetVideoTracks());
+
+ // For each video track in the stream, add it to the MediaSessionOptions.
+ for (size_t j = 0; j < video_tracks.size(); ++j) {
+ scoped_refptr<MediaStreamTrackInterface> track(video_tracks[j]);
+ session_options->AddStream(
+ cricket::MEDIA_TYPE_VIDEO, track->id(), stream->label());
+ }
+ }
+ }
+
+ // Check for data channels.
+ MediaStreamSignaling::RtpDataChannels::const_iterator data_channel_it =
+ rtp_data_channels.begin();
+ for (; data_channel_it != rtp_data_channels.end(); ++data_channel_it) {
+ const DataChannel* channel = data_channel_it->second;
+ if (channel->state() == DataChannel::kConnecting ||
+ channel->state() == DataChannel::kOpen) {
+ // |streamid| and |sync_label| are both set to the DataChannel label
+ // here so they can be signaled the same way as MediaStreams and Tracks.
+ // For MediaStreams, the sync_label is the MediaStream label and the
+ // track label is the same as |streamid|.
+ const std::string& streamid = channel->label();
+ const std::string& sync_label = channel->label();
+ session_options->AddStream(
+ cricket::MEDIA_TYPE_DATA, streamid, sync_label);
+ }
+ }
+}
+
// Factory class for creating remote MediaStreams and MediaStreamTracks.
class RemoteMediaStreamFactory {
public:
- explicit RemoteMediaStreamFactory(talk_base::Thread* signaling_thread,
+ explicit RemoteMediaStreamFactory(rtc::Thread* signaling_thread,
cricket::ChannelManager* channel_manager)
: signaling_thread_(signaling_thread),
channel_manager_(channel_manager) {
}
- talk_base::scoped_refptr<MediaStreamInterface> CreateMediaStream(
+ rtc::scoped_refptr<MediaStreamInterface> CreateMediaStream(
const std::string& stream_label) {
return MediaStreamProxy::Create(
signaling_thread_, MediaStream::Create(stream_label));
@@ -156,7 +215,7 @@
template <typename TI, typename T, typename TP, typename S>
TI* AddTrack(MediaStreamInterface* stream, const std::string& track_id,
S* source) {
- talk_base::scoped_refptr<TI> track(
+ rtc::scoped_refptr<TI> track(
TP::Create(signaling_thread_, T::Create(track_id, source)));
track->set_state(webrtc::MediaStreamTrackInterface::kLive);
if (stream->AddTrack(track)) {
@@ -165,12 +224,12 @@
return NULL;
}
- talk_base::Thread* signaling_thread_;
+ rtc::Thread* signaling_thread_;
cricket::ChannelManager* channel_manager_;
};
MediaStreamSignaling::MediaStreamSignaling(
- talk_base::Thread* signaling_thread,
+ rtc::Thread* signaling_thread,
MediaStreamSignalingObserver* stream_observer,
cricket::ChannelManager* channel_manager)
: signaling_thread_(signaling_thread),
@@ -182,8 +241,6 @@
channel_manager)),
last_allocated_sctp_even_sid_(-2),
last_allocated_sctp_odd_sid_(-1) {
- options_.has_video = false;
- options_.has_audio = false;
}
MediaStreamSignaling::~MediaStreamSignaling() {
@@ -206,8 +263,8 @@
// SSL_CLIENT, the allocated id starts from 0 and takes even numbers; otherwise,
// the id starts from 1 and takes odd numbers. Returns false if no id can be
// allocated.
-bool MediaStreamSignaling::AllocateSctpSid(talk_base::SSLRole role, int* sid) {
- int& last_id = (role == talk_base::SSL_CLIENT) ?
+bool MediaStreamSignaling::AllocateSctpSid(rtc::SSLRole role, int* sid) {
+ int& last_id = (role == rtc::SSL_CLIENT) ?
last_allocated_sctp_even_sid_ : last_allocated_sctp_odd_sid_;
do {
@@ -246,7 +303,7 @@
bool MediaStreamSignaling::AddDataChannelFromOpenMessage(
const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload) {
+ const rtc::Buffer& payload) {
if (!data_channel_factory_) {
LOG(LS_WARNING) << "Remote peer requested a DataChannel but DataChannels "
<< "are not supported.";
@@ -269,21 +326,22 @@
LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
return false;
}
- sctp_data_channels_.push_back(channel);
+
stream_observer_->OnAddDataChannel(channel);
return true;
}
void MediaStreamSignaling::RemoveSctpDataChannel(int sid) {
+ ASSERT(sid >= 0);
for (SctpDataChannels::iterator iter = sctp_data_channels_.begin();
iter != sctp_data_channels_.end();
++iter) {
if ((*iter)->id() == sid) {
sctp_data_channels_.erase(iter);
- if (talk_base::IsEven(sid) && sid <= last_allocated_sctp_even_sid_) {
+ if (rtc::IsEven(sid) && sid <= last_allocated_sctp_even_sid_) {
last_allocated_sctp_even_sid_ = sid - 2;
- } else if (talk_base::IsOdd(sid) && sid <= last_allocated_sctp_odd_sid_) {
+ } else if (rtc::IsOdd(sid) && sid <= last_allocated_sctp_odd_sid_) {
last_allocated_sctp_odd_sid_ = sid - 2;
}
return;
@@ -359,30 +417,46 @@
}
bool MediaStreamSignaling::GetOptionsForOffer(
- const MediaConstraintsInterface* constraints,
- cricket::MediaSessionOptions* options) {
- UpdateSessionOptions();
- if (!ParseConstraints(constraints, &options_, false)) {
+ const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
+ cricket::MediaSessionOptions* session_options) {
+ typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
+ if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
+ !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
return false;
}
- options_.bundle_enabled = EvaluateNeedForBundle(options_);
- *options = options_;
+
+ session_options->has_audio = false;
+ session_options->has_video = false;
+ SetStreams(session_options, local_streams_, rtp_data_channels_);
+
+ // If |offer_to_receive_[audio/video]| is undefined, respect the flags set
+ // from SetStreams. Otherwise, overwrite it based on |rtc_options|.
+ if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
+ session_options->has_audio = rtc_options.offer_to_receive_audio > 0;
+ }
+ if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
+ session_options->has_video = rtc_options.offer_to_receive_video > 0;
+ }
+
+ session_options->vad_enabled = rtc_options.voice_activity_detection;
+ session_options->transport_options.ice_restart = rtc_options.ice_restart;
+ session_options->bundle_enabled = rtc_options.use_rtp_mux;
+
+ session_options->bundle_enabled = EvaluateNeedForBundle(*session_options);
return true;
}
bool MediaStreamSignaling::GetOptionsForAnswer(
const MediaConstraintsInterface* constraints,
cricket::MediaSessionOptions* options) {
- UpdateSessionOptions();
+ options->has_audio = false;
+ options->has_video = false;
+ SetStreams(options, local_streams_, rtp_data_channels_);
- // Copy the |options_| to not let the flag MediaSessionOptions::has_audio and
- // MediaSessionOptions::has_video affect subsequent offers.
- cricket::MediaSessionOptions current_options = options_;
- if (!ParseConstraints(constraints, ¤t_options, true)) {
+ if (!ParseConstraintsForAnswer(constraints, options)) {
return false;
}
- current_options.bundle_enabled = EvaluateNeedForBundle(current_options);
- *options = current_options;
+ options->bundle_enabled = EvaluateNeedForBundle(*options);
return true;
}
@@ -394,7 +468,7 @@
void MediaStreamSignaling::OnRemoteDescriptionChanged(
const SessionDescriptionInterface* desc) {
const cricket::SessionDescription* remote_desc = desc->description();
- talk_base::scoped_refptr<StreamCollection> new_streams(
+ rtc::scoped_refptr<StreamCollection> new_streams(
StreamCollection::Create());
// Find all audio rtp streams and create corresponding remote AudioTracks
@@ -406,7 +480,8 @@
audio_content->description);
UpdateRemoteStreamsList(desc->streams(), desc->type(), new_streams);
remote_info_.default_audio_track_needed =
- desc->direction() == cricket::MD_SENDRECV && desc->streams().empty();
+ MediaContentDirectionHasSend(desc->direction()) &&
+ desc->streams().empty();
}
// Find all video rtp streams and create corresponding remote VideoTracks
@@ -418,7 +493,8 @@
video_content->description);
UpdateRemoteStreamsList(desc->streams(), desc->type(), new_streams);
remote_info_.default_video_track_needed =
- desc->direction() == cricket::MD_SENDRECV && desc->streams().empty();
+ MediaContentDirectionHasSend(desc->direction()) &&
+ desc->streams().empty();
}
// Update the DataChannels with the information from the remote peer.
@@ -427,7 +503,7 @@
const cricket::DataContentDescription* data_desc =
static_cast<const cricket::DataContentDescription*>(
data_content->description);
- if (talk_base::starts_with(
+ if (rtc::starts_with(
data_desc->protocol().data(), cricket::kMediaProtocolRtpPrefix)) {
UpdateRemoteRtpDataChannels(data_desc->streams());
}
@@ -482,7 +558,7 @@
const cricket::DataContentDescription* data_desc =
static_cast<const cricket::DataContentDescription*>(
data_content->description);
- if (talk_base::starts_with(
+ if (rtc::starts_with(
data_desc->protocol().data(), cricket::kMediaProtocolRtpPrefix)) {
UpdateLocalRtpDataChannels(data_desc->streams());
}
@@ -515,54 +591,6 @@
}
}
-void MediaStreamSignaling::UpdateSessionOptions() {
- options_.streams.clear();
- if (local_streams_ != NULL) {
- for (size_t i = 0; i < local_streams_->count(); ++i) {
- MediaStreamInterface* stream = local_streams_->at(i);
-
- AudioTrackVector audio_tracks(stream->GetAudioTracks());
- if (!audio_tracks.empty()) {
- options_.has_audio = true;
- }
-
- // For each audio track in the stream, add it to the MediaSessionOptions.
- for (size_t j = 0; j < audio_tracks.size(); ++j) {
- scoped_refptr<MediaStreamTrackInterface> track(audio_tracks[j]);
- options_.AddStream(cricket::MEDIA_TYPE_AUDIO, track->id(),
- stream->label());
- }
-
- VideoTrackVector video_tracks(stream->GetVideoTracks());
- if (!video_tracks.empty()) {
- options_.has_video = true;
- }
- // For each video track in the stream, add it to the MediaSessionOptions.
- for (size_t j = 0; j < video_tracks.size(); ++j) {
- scoped_refptr<MediaStreamTrackInterface> track(video_tracks[j]);
- options_.AddStream(cricket::MEDIA_TYPE_VIDEO, track->id(),
- stream->label());
- }
- }
- }
-
- // Check for data channels.
- RtpDataChannels::const_iterator data_channel_it = rtp_data_channels_.begin();
- for (; data_channel_it != rtp_data_channels_.end(); ++data_channel_it) {
- const DataChannel* channel = data_channel_it->second;
- if (channel->state() == DataChannel::kConnecting ||
- channel->state() == DataChannel::kOpen) {
- // |streamid| and |sync_label| are both set to the DataChannel label
- // here so they can be signaled the same way as MediaStreams and Tracks.
- // For MediaStreams, the sync_label is the MediaStream label and the
- // track label is the same as |streamid|.
- const std::string& streamid = channel->label();
- const std::string& sync_label = channel->label();
- options_.AddStream(cricket::MEDIA_TYPE_DATA, streamid, sync_label);
- }
- }
-}
-
void MediaStreamSignaling::UpdateRemoteStreamsList(
const cricket::StreamParamsVec& streams,
cricket::MediaType media_type,
@@ -593,7 +621,7 @@
const std::string& track_id = it->id;
uint32 ssrc = it->first_ssrc();
- talk_base::scoped_refptr<MediaStreamInterface> stream =
+ rtc::scoped_refptr<MediaStreamInterface> stream =
remote_streams_->find(stream_label);
if (!stream) {
// This is a new MediaStream. Create a new remote MediaStream.
@@ -637,7 +665,7 @@
MediaStreamInterface* stream = remote_streams_->find(stream_label);
if (media_type == cricket::MEDIA_TYPE_AUDIO) {
- talk_base::scoped_refptr<AudioTrackInterface> audio_track =
+ rtc::scoped_refptr<AudioTrackInterface> audio_track =
stream->FindAudioTrack(track_id);
if (audio_track) {
audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
@@ -645,7 +673,7 @@
stream_observer_->OnRemoveRemoteAudioTrack(stream, audio_track);
}
} else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
- talk_base::scoped_refptr<VideoTrackInterface> video_track =
+ rtc::scoped_refptr<VideoTrackInterface> video_track =
stream->FindVideoTrack(track_id);
if (video_track) {
video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
@@ -892,7 +920,7 @@
// The data channel label is either the mslabel or the SSRC if the mslabel
// does not exist. Ex a=ssrc:444330170 mslabel:test1.
std::string label = it->sync_label.empty() ?
- talk_base::ToString(it->first_ssrc()) : it->sync_label;
+ rtc::ToString(it->first_ssrc()) : it->sync_label;
RtpDataChannels::iterator data_channel_it =
rtp_data_channels_.find(label);
if (data_channel_it == rtp_data_channels_.end()) {
@@ -957,7 +985,7 @@
}
}
-void MediaStreamSignaling::OnDtlsRoleReadyForSctp(talk_base::SSLRole role) {
+void MediaStreamSignaling::OnDtlsRoleReadyForSctp(rtc::SSLRole role) {
SctpDataChannels::iterator it = sctp_data_channels_.begin();
for (; it != sctp_data_channels_.end(); ++it) {
if ((*it)->id() < 0) {
diff --git a/app/webrtc/mediastreamsignaling.h b/app/webrtc/mediastreamsignaling.h
index 7378166..d4b1be8 100644
--- a/app/webrtc/mediastreamsignaling.h
+++ b/app/webrtc/mediastreamsignaling.h
@@ -28,21 +28,21 @@
#ifndef TALK_APP_WEBRTC_MEDIASTREAMSIGNALING_H_
#define TALK_APP_WEBRTC_MEDIASTREAMSIGNALING_H_
+#include <map>
#include <string>
#include <vector>
-#include <map>
#include "talk/app/webrtc/datachannel.h"
#include "talk/app/webrtc/mediastream.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/streamcollection.h"
-#include "talk/base/scoped_ref_ptr.h"
-#include "talk/base/sigslot.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/scoped_ref_ptr.h"
+#include "webrtc/base/sigslot.h"
-namespace talk_base {
+namespace rtc {
class Thread;
-} // namespace talk_base
+} // namespace rtc
namespace webrtc {
@@ -160,7 +160,10 @@
class MediaStreamSignaling : public sigslot::has_slots<> {
public:
- MediaStreamSignaling(talk_base::Thread* signaling_thread,
+ typedef std::map<std::string, rtc::scoped_refptr<DataChannel> >
+ RtpDataChannels;
+
+ MediaStreamSignaling(rtc::Thread* signaling_thread,
MediaStreamSignalingObserver* stream_observer,
cricket::ChannelManager* channel_manager);
virtual ~MediaStreamSignaling();
@@ -180,7 +183,7 @@
// Gets the first available SCTP id that is not assigned to any existing
// data channels.
- bool AllocateSctpSid(talk_base::SSLRole role, int* sid);
+ bool AllocateSctpSid(rtc::SSLRole role, int* sid);
// Adds |local_stream| to the collection of known MediaStreams that will be
// offered in a SessionDescription.
@@ -197,14 +200,14 @@
bool AddDataChannel(DataChannel* data_channel);
// After we receive an OPEN message, create a data channel and add it.
bool AddDataChannelFromOpenMessage(const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload);
+ const rtc::Buffer& payload);
void RemoveSctpDataChannel(int sid);
- // Returns a MediaSessionOptions struct with options decided by |constraints|,
+ // Returns a MediaSessionOptions struct with options decided by |options|,
// the local MediaStreams and DataChannels.
virtual bool GetOptionsForOffer(
- const MediaConstraintsInterface* constraints,
- cricket::MediaSessionOptions* options);
+ const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
+ cricket::MediaSessionOptions* session_options);
// Returns a MediaSessionOptions struct with options decided by
// |constraints|, the local MediaStreams and DataChannels.
@@ -249,7 +252,7 @@
return remote_streams_.get();
}
void OnDataTransportCreatedForSctp();
- void OnDtlsRoleReadyForSctp(talk_base::SSLRole role);
+ void OnDtlsRoleReadyForSctp(rtc::SSLRole role);
void OnRemoteSctpDataChannelClosed(uint32 sid);
private:
@@ -289,8 +292,6 @@
};
typedef std::vector<TrackInfo> TrackInfos;
- void UpdateSessionOptions();
-
// Makes sure a MediaStream Track is created for each StreamParam in
// |streams|. |media_type| is the type of the |streams| and can be either
// audio or video.
@@ -376,13 +377,12 @@
int FindDataChannelBySid(int sid) const;
RemotePeerInfo remote_info_;
- talk_base::Thread* signaling_thread_;
+ rtc::Thread* signaling_thread_;
DataChannelFactory* data_channel_factory_;
- cricket::MediaSessionOptions options_;
MediaStreamSignalingObserver* stream_observer_;
- talk_base::scoped_refptr<StreamCollection> local_streams_;
- talk_base::scoped_refptr<StreamCollection> remote_streams_;
- talk_base::scoped_ptr<RemoteMediaStreamFactory> remote_stream_factory_;
+ rtc::scoped_refptr<StreamCollection> local_streams_;
+ rtc::scoped_refptr<StreamCollection> remote_streams_;
+ rtc::scoped_ptr<RemoteMediaStreamFactory> remote_stream_factory_;
TrackInfos remote_audio_tracks_;
TrackInfos remote_video_tracks_;
@@ -392,9 +392,7 @@
int last_allocated_sctp_even_sid_;
int last_allocated_sctp_odd_sid_;
- typedef std::map<std::string, talk_base::scoped_refptr<DataChannel> >
- RtpDataChannels;
- typedef std::vector<talk_base::scoped_refptr<DataChannel> > SctpDataChannels;
+ typedef std::vector<rtc::scoped_refptr<DataChannel> > SctpDataChannels;
RtpDataChannels rtp_data_channels_;
SctpDataChannels sctp_data_channels_;
diff --git a/app/webrtc/mediastreamsignaling_unittest.cc b/app/webrtc/mediastreamsignaling_unittest.cc
index 150058e..84f67b9 100644
--- a/app/webrtc/mediastreamsignaling_unittest.cc
+++ b/app/webrtc/mediastreamsignaling_unittest.cc
@@ -36,15 +36,15 @@
#include "talk/app/webrtc/test/fakeconstraints.h"
#include "talk/app/webrtc/test/fakedatachannelprovider.h"
#include "talk/app/webrtc/videotrack.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/devices/fakedevicemanager.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/session/media/channelmanager.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
static const char kStreams[][8] = {"stream1", "stream2"};
static const char kAudioTracks[][32] = {"audiotrack0", "audiotrack1"};
@@ -62,11 +62,14 @@
using webrtc::MediaConstraintsInterface;
using webrtc::MediaStreamInterface;
using webrtc::MediaStreamTrackInterface;
+using webrtc::PeerConnectionInterface;
using webrtc::SdpParseError;
using webrtc::SessionDescriptionInterface;
using webrtc::StreamCollection;
using webrtc::StreamCollectionInterface;
+typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
+
// Reference SDP with a MediaStream with label "stream1" and audio track with
// id "audio_1" and a video track with id "video_1;
static const char kSdpStringWithStream1[] =
@@ -148,6 +151,21 @@
"a=mid:audio\r\n"
"a=rtpmap:103 ISAC/16000\r\n";
+// Reference SENDONLY SDP without MediaStreams. Msid is not supported.
+static const char kSdpStringSendOnlyWithWithoutStreams[] =
+ "v=0\r\n"
+ "o=- 0 0 IN IP4 127.0.0.1\r\n"
+ "s=-\r\n"
+ "t=0 0\r\n"
+ "m=audio 1 RTP/AVPF 103\r\n"
+ "a=mid:audio\r\n"
+ "a=sendonly"
+ "a=rtpmap:103 ISAC/16000\r\n"
+ "m=video 1 RTP/AVPF 120\r\n"
+ "a=mid:video\r\n"
+ "a=sendonly"
+ "a=rtpmap:120 VP8/90000\r\n";
+
static const char kSdpStringInit[] =
"v=0\r\n"
"o=- 0 0 IN IP4 127.0.0.1\r\n"
@@ -243,14 +261,20 @@
class FakeDataChannelFactory : public webrtc::DataChannelFactory {
public:
FakeDataChannelFactory(FakeDataChannelProvider* provider,
- cricket::DataChannelType dct)
- : provider_(provider), type_(dct) {}
+ cricket::DataChannelType dct,
+ webrtc::MediaStreamSignaling* media_stream_signaling)
+ : provider_(provider),
+ type_(dct),
+ media_stream_signaling_(media_stream_signaling) {}
- virtual talk_base::scoped_refptr<webrtc::DataChannel> CreateDataChannel(
+ virtual rtc::scoped_refptr<webrtc::DataChannel> CreateDataChannel(
const std::string& label,
const webrtc::InternalDataChannelInit* config) {
last_init_ = *config;
- return webrtc::DataChannel::Create(provider_, type_, label, *config);
+ rtc::scoped_refptr<webrtc::DataChannel> data_channel =
+ webrtc::DataChannel::Create(provider_, type_, label, *config);
+ media_stream_signaling_->AddDataChannel(data_channel);
+ return data_channel;
}
const webrtc::InternalDataChannelInit& last_init() const {
@@ -260,6 +284,7 @@
private:
FakeDataChannelProvider* provider_;
cricket::DataChannelType type_;
+ webrtc::MediaStreamSignaling* media_stream_signaling_;
webrtc::InternalDataChannelInit last_init_;
};
@@ -434,14 +459,14 @@
TrackInfos local_audio_tracks_;
TrackInfos local_video_tracks_;
- talk_base::scoped_refptr<StreamCollection> remote_media_streams_;
+ rtc::scoped_refptr<StreamCollection> remote_media_streams_;
};
class MediaStreamSignalingForTest : public webrtc::MediaStreamSignaling {
public:
MediaStreamSignalingForTest(MockSignalingObserver* observer,
cricket::ChannelManager* channel_manager)
- : webrtc::MediaStreamSignaling(talk_base::Thread::Current(), observer,
+ : webrtc::MediaStreamSignaling(rtc::Thread::Current(), observer,
channel_manager) {
};
@@ -458,7 +483,7 @@
channel_manager_.reset(
new cricket::ChannelManager(new cricket::FakeMediaEngine(),
new cricket::FakeDeviceManager(),
- talk_base::Thread::Current()));
+ rtc::Thread::Current()));
signaling_.reset(new MediaStreamSignalingForTest(observer_.get(),
channel_manager_.get()));
data_channel_provider_.reset(new FakeDataChannelProvider());
@@ -468,22 +493,22 @@
// CreateStreamCollection(1) creates a collection that
// correspond to kSdpString1.
// CreateStreamCollection(2) correspond to kSdpString2.
- talk_base::scoped_refptr<StreamCollection>
+ rtc::scoped_refptr<StreamCollection>
CreateStreamCollection(int number_of_streams) {
- talk_base::scoped_refptr<StreamCollection> local_collection(
+ rtc::scoped_refptr<StreamCollection> local_collection(
StreamCollection::Create());
for (int i = 0; i < number_of_streams; ++i) {
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream(
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream(
webrtc::MediaStream::Create(kStreams[i]));
// Add a local audio track.
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
webrtc::AudioTrack::Create(kAudioTracks[i], NULL));
stream->AddTrack(audio_track);
// Add a local video track.
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> video_track(
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
webrtc::VideoTrack::Create(kVideoTracks[i], NULL));
stream->AddTrack(video_track);
@@ -510,7 +535,7 @@
std::string mediastream_label = kStreams[0];
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream(
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream(
webrtc::MediaStream::Create(mediastream_label));
reference_collection_->AddStream(stream);
@@ -540,23 +565,23 @@
void AddAudioTrack(const std::string& track_id,
MediaStreamInterface* stream) {
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
webrtc::AudioTrack::Create(track_id, NULL));
ASSERT_TRUE(stream->AddTrack(audio_track));
}
void AddVideoTrack(const std::string& track_id,
MediaStreamInterface* stream) {
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> video_track(
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
webrtc::VideoTrack::Create(track_id, NULL));
ASSERT_TRUE(stream->AddTrack(video_track));
}
- talk_base::scoped_refptr<webrtc::DataChannel> AddDataChannel(
+ rtc::scoped_refptr<webrtc::DataChannel> AddDataChannel(
cricket::DataChannelType type, const std::string& label, int id) {
webrtc::InternalDataChannelInit config;
config.id = id;
- talk_base::scoped_refptr<webrtc::DataChannel> data_channel(
+ rtc::scoped_refptr<webrtc::DataChannel> data_channel(
webrtc::DataChannel::Create(
data_channel_provider_.get(), type, label, config));
EXPECT_TRUE(data_channel.get() != NULL);
@@ -566,122 +591,144 @@
// ChannelManager is used by VideoSource, so it should be released after all
// the video tracks. Put it as the first private variable should ensure that.
- talk_base::scoped_ptr<cricket::ChannelManager> channel_manager_;
- talk_base::scoped_refptr<StreamCollection> reference_collection_;
- talk_base::scoped_ptr<MockSignalingObserver> observer_;
- talk_base::scoped_ptr<MediaStreamSignalingForTest> signaling_;
- talk_base::scoped_ptr<FakeDataChannelProvider> data_channel_provider_;
+ rtc::scoped_ptr<cricket::ChannelManager> channel_manager_;
+ rtc::scoped_refptr<StreamCollection> reference_collection_;
+ rtc::scoped_ptr<MockSignalingObserver> observer_;
+ rtc::scoped_ptr<MediaStreamSignalingForTest> signaling_;
+ rtc::scoped_ptr<FakeDataChannelProvider> data_channel_provider_;
};
+TEST_F(MediaStreamSignalingTest, GetOptionsForOfferWithInvalidAudioOption) {
+ RTCOfferAnswerOptions rtc_options;
+ rtc_options.offer_to_receive_audio = RTCOfferAnswerOptions::kUndefined - 1;
+
+ cricket::MediaSessionOptions options;
+ EXPECT_FALSE(signaling_->GetOptionsForOffer(rtc_options, &options));
+
+ rtc_options.offer_to_receive_audio =
+ RTCOfferAnswerOptions::kMaxOfferToReceiveMedia + 1;
+ EXPECT_FALSE(signaling_->GetOptionsForOffer(rtc_options, &options));
+}
+
+
+TEST_F(MediaStreamSignalingTest, GetOptionsForOfferWithInvalidVideoOption) {
+ RTCOfferAnswerOptions rtc_options;
+ rtc_options.offer_to_receive_video =
+ RTCOfferAnswerOptions::kUndefined - 1;
+
+ cricket::MediaSessionOptions options;
+ EXPECT_FALSE(signaling_->GetOptionsForOffer(rtc_options, &options));
+
+ rtc_options.offer_to_receive_video =
+ RTCOfferAnswerOptions::kMaxOfferToReceiveMedia + 1;
+ EXPECT_FALSE(signaling_->GetOptionsForOffer(rtc_options, &options));
+}
+
// Test that a MediaSessionOptions is created for an offer if
-// kOfferToReceiveAudio and kOfferToReceiveVideo constraints are set but no
+// OfferToReceiveAudio and OfferToReceiveVideo options are set but no
// MediaStreams are sent.
TEST_F(MediaStreamSignalingTest, GetMediaSessionOptionsForOfferWithAudioVideo) {
- FakeConstraints constraints;
- constraints.SetMandatoryReceiveAudio(true);
- constraints.SetMandatoryReceiveVideo(true);
+ RTCOfferAnswerOptions rtc_options;
+ rtc_options.offer_to_receive_audio = 1;
+ rtc_options.offer_to_receive_video = 1;
+
cricket::MediaSessionOptions options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&constraints, &options));
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
EXPECT_TRUE(options.has_audio);
EXPECT_TRUE(options.has_video);
EXPECT_TRUE(options.bundle_enabled);
}
// Test that a correct MediaSessionOptions is created for an offer if
-// kOfferToReceiveAudio constraints is set but no MediaStreams are sent.
+// OfferToReceiveAudio is set but no MediaStreams are sent.
TEST_F(MediaStreamSignalingTest, GetMediaSessionOptionsForOfferWithAudio) {
- FakeConstraints constraints;
- constraints.SetMandatoryReceiveAudio(true);
+ RTCOfferAnswerOptions rtc_options;
+ rtc_options.offer_to_receive_audio = 1;
+
cricket::MediaSessionOptions options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&constraints, &options));
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
EXPECT_TRUE(options.has_audio);
EXPECT_FALSE(options.has_video);
EXPECT_TRUE(options.bundle_enabled);
}
// Test that a correct MediaSessionOptions is created for an offer if
-// no constraints or MediaStreams are sent.
+// the default OfferOptons is used or MediaStreams are sent.
TEST_F(MediaStreamSignalingTest, GetDefaultMediaSessionOptionsForOffer) {
+ RTCOfferAnswerOptions rtc_options;
+
cricket::MediaSessionOptions options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(NULL, &options));
- EXPECT_TRUE(options.has_audio);
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
+ EXPECT_FALSE(options.has_audio);
EXPECT_FALSE(options.has_video);
- EXPECT_TRUE(options.bundle_enabled);
+ EXPECT_FALSE(options.bundle_enabled);
+ EXPECT_TRUE(options.vad_enabled);
+ EXPECT_FALSE(options.transport_options.ice_restart);
}
// Test that a correct MediaSessionOptions is created for an offer if
-// kOfferToReceiveVideo constraints is set but no MediaStreams are sent.
+// OfferToReceiveVideo is set but no MediaStreams are sent.
TEST_F(MediaStreamSignalingTest, GetMediaSessionOptionsForOfferWithVideo) {
- FakeConstraints constraints;
- constraints.SetMandatoryReceiveAudio(false);
- constraints.SetMandatoryReceiveVideo(true);
+ RTCOfferAnswerOptions rtc_options;
+ rtc_options.offer_to_receive_audio = 0;
+ rtc_options.offer_to_receive_video = 1;
+
cricket::MediaSessionOptions options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&constraints, &options));
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
EXPECT_FALSE(options.has_audio);
EXPECT_TRUE(options.has_video);
EXPECT_TRUE(options.bundle_enabled);
}
// Test that a correct MediaSessionOptions is created for an offer if
-// kUseRtpMux constraints is set to false.
+// UseRtpMux is set to false.
TEST_F(MediaStreamSignalingTest,
GetMediaSessionOptionsForOfferWithBundleDisabled) {
- FakeConstraints constraints;
- constraints.SetMandatoryReceiveAudio(true);
- constraints.SetMandatoryReceiveVideo(true);
- constraints.SetMandatoryUseRtpMux(false);
+ RTCOfferAnswerOptions rtc_options;
+ rtc_options.offer_to_receive_audio = 1;
+ rtc_options.offer_to_receive_video = 1;
+ rtc_options.use_rtp_mux = false;
+
cricket::MediaSessionOptions options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&constraints, &options));
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
EXPECT_TRUE(options.has_audio);
EXPECT_TRUE(options.has_video);
EXPECT_FALSE(options.bundle_enabled);
}
// Test that a correct MediaSessionOptions is created to restart ice if
-// kIceRestart constraints is set. It also tests that subsequent
-// MediaSessionOptions don't have |transport_options.ice_restart| set.
+// IceRestart is set. It also tests that subsequent MediaSessionOptions don't
+// have |transport_options.ice_restart| set.
TEST_F(MediaStreamSignalingTest,
GetMediaSessionOptionsForOfferWithIceRestart) {
- FakeConstraints constraints;
- constraints.SetMandatoryIceRestart(true);
+ RTCOfferAnswerOptions rtc_options;
+ rtc_options.ice_restart = true;
+
cricket::MediaSessionOptions options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&constraints, &options));
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
EXPECT_TRUE(options.transport_options.ice_restart);
- EXPECT_TRUE(signaling_->GetOptionsForOffer(NULL, &options));
+ rtc_options = RTCOfferAnswerOptions();
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
EXPECT_FALSE(options.transport_options.ice_restart);
}
-// Test that GetMediaSessionOptionsForOffer and GetOptionsForAnswer work as
-// expected if unknown constraints are used.
-TEST_F(MediaStreamSignalingTest, GetMediaSessionOptionsWithBadConstraints) {
- FakeConstraints mandatory;
- mandatory.AddMandatory("bad_key", "bad_value");
- cricket::MediaSessionOptions options;
- EXPECT_FALSE(signaling_->GetOptionsForOffer(&mandatory, &options));
- EXPECT_FALSE(signaling_->GetOptionsForAnswer(&mandatory, &options));
-
- FakeConstraints optional;
- optional.AddOptional("bad_key", "bad_value");
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&optional, &options));
- EXPECT_TRUE(signaling_->GetOptionsForAnswer(&optional, &options));
-}
-
// Test that a correct MediaSessionOptions are created for an offer if
// a MediaStream is sent and later updated with a new track.
// MediaConstraints are not used.
TEST_F(MediaStreamSignalingTest, AddTrackToLocalMediaStream) {
- talk_base::scoped_refptr<StreamCollection> local_streams(
+ RTCOfferAnswerOptions rtc_options;
+ rtc::scoped_refptr<StreamCollection> local_streams(
CreateStreamCollection(1));
MediaStreamInterface* local_stream = local_streams->at(0);
EXPECT_TRUE(signaling_->AddLocalStream(local_stream));
cricket::MediaSessionOptions options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(NULL, &options));
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
VerifyMediaOptions(local_streams, options);
cricket::MediaSessionOptions updated_options;
local_stream->AddTrack(AudioTrack::Create(kAudioTracks[1], NULL));
- EXPECT_TRUE(signaling_->GetOptionsForOffer(NULL, &options));
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(rtc_options, &options));
VerifyMediaOptions(local_streams, options);
}
@@ -699,21 +746,20 @@
EXPECT_TRUE(answer_options.has_audio);
EXPECT_TRUE(answer_options.has_video);
- FakeConstraints offer_c;
- offer_c.SetMandatoryReceiveAudio(false);
- offer_c.SetMandatoryReceiveVideo(false);
+ RTCOfferAnswerOptions rtc_offer_optoins;
cricket::MediaSessionOptions offer_options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&offer_c, &offer_options));
+ EXPECT_TRUE(
+ signaling_->GetOptionsForOffer(rtc_offer_optoins, &offer_options));
EXPECT_FALSE(offer_options.has_audio);
EXPECT_FALSE(offer_options.has_video);
- FakeConstraints updated_offer_c;
- updated_offer_c.SetMandatoryReceiveAudio(true);
- updated_offer_c.SetMandatoryReceiveVideo(true);
+ RTCOfferAnswerOptions updated_rtc_offer_optoins;
+ updated_rtc_offer_optoins.offer_to_receive_audio = 1;
+ updated_rtc_offer_optoins.offer_to_receive_video = 1;
cricket::MediaSessionOptions updated_offer_options;
- EXPECT_TRUE(signaling_->GetOptionsForOffer(&updated_offer_c,
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(updated_rtc_offer_optoins,
&updated_offer_options));
EXPECT_TRUE(updated_offer_options.has_audio);
EXPECT_TRUE(updated_offer_options.has_video);
@@ -733,23 +779,26 @@
EXPECT_TRUE(updated_answer_options.has_audio);
EXPECT_TRUE(updated_answer_options.has_video);
- EXPECT_TRUE(signaling_->GetOptionsForOffer(NULL,
+ RTCOfferAnswerOptions default_rtc_options;
+ EXPECT_TRUE(signaling_->GetOptionsForOffer(default_rtc_options,
&updated_offer_options));
- EXPECT_TRUE(updated_offer_options.has_audio);
- EXPECT_TRUE(updated_offer_options.has_video);
+ // By default, |has_audio| or |has_video| are false if there is no media
+ // track.
+ EXPECT_FALSE(updated_offer_options.has_audio);
+ EXPECT_FALSE(updated_offer_options.has_video);
}
// This test verifies that the remote MediaStreams corresponding to a received
// SDP string is created. In this test the two separate MediaStreams are
// signaled.
TEST_F(MediaStreamSignalingTest, UpdateRemoteStreams) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithStream1, NULL));
EXPECT_TRUE(desc != NULL);
signaling_->OnRemoteDescriptionChanged(desc.get());
- talk_base::scoped_refptr<StreamCollection> reference(
+ rtc::scoped_refptr<StreamCollection> reference(
CreateStreamCollection(1));
EXPECT_TRUE(CompareStreamCollections(signaling_->remote_streams(),
reference.get()));
@@ -765,13 +814,13 @@
// Create a session description based on another SDP with another
// MediaStream.
- talk_base::scoped_ptr<SessionDescriptionInterface> update_desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> update_desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWith2Stream, NULL));
EXPECT_TRUE(update_desc != NULL);
signaling_->OnRemoteDescriptionChanged(update_desc.get());
- talk_base::scoped_refptr<StreamCollection> reference2(
+ rtc::scoped_refptr<StreamCollection> reference2(
CreateStreamCollection(2));
EXPECT_TRUE(CompareStreamCollections(signaling_->remote_streams(),
reference2.get()));
@@ -790,14 +839,14 @@
// SDP string is created. In this test the same remote MediaStream is signaled
// but MediaStream tracks are added and removed.
TEST_F(MediaStreamSignalingTest, AddRemoveTrackFromExistingRemoteMediaStream) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_ms1;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_ms1;
CreateSessionDescriptionAndReference(1, 1, desc_ms1.use());
signaling_->OnRemoteDescriptionChanged(desc_ms1.get());
EXPECT_TRUE(CompareStreamCollections(signaling_->remote_streams(),
reference_collection_));
// Add extra audio and video tracks to the same MediaStream.
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_ms1_two_tracks;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_ms1_two_tracks;
CreateSessionDescriptionAndReference(2, 2, desc_ms1_two_tracks.use());
signaling_->OnRemoteDescriptionChanged(desc_ms1_two_tracks.get());
EXPECT_TRUE(CompareStreamCollections(signaling_->remote_streams(),
@@ -806,7 +855,7 @@
reference_collection_));
// Remove the extra audio and video tracks again.
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_ms2;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_ms2;
CreateSessionDescriptionAndReference(1, 1, desc_ms2.use());
signaling_->OnRemoteDescriptionChanged(desc_ms2.get());
EXPECT_TRUE(CompareStreamCollections(signaling_->remote_streams(),
@@ -818,7 +867,7 @@
// This test that remote tracks are ended if a
// local session description is set that rejects the media content type.
TEST_F(MediaStreamSignalingTest, RejectMediaContent) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithStream1, NULL));
EXPECT_TRUE(desc != NULL);
@@ -829,10 +878,10 @@
ASSERT_EQ(1u, remote_stream->GetVideoTracks().size());
ASSERT_EQ(1u, remote_stream->GetAudioTracks().size());
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> remote_video =
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> remote_video =
remote_stream->GetVideoTracks()[0];
EXPECT_EQ(webrtc::MediaStreamTrackInterface::kLive, remote_video->state());
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> remote_audio =
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> remote_audio =
remote_stream->GetAudioTracks()[0];
EXPECT_EQ(webrtc::MediaStreamTrackInterface::kLive, remote_audio->state());
@@ -856,7 +905,7 @@
// of MediaStreamSignaling and then MediaStreamSignaling tries to reject
// this track.
TEST_F(MediaStreamSignalingTest, RemoveTrackThenRejectMediaContent) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithStream1, NULL));
EXPECT_TRUE(desc != NULL);
@@ -884,7 +933,7 @@
// It also tests that the default stream is updated if a video m-line is added
// in a subsequent session description.
TEST_F(MediaStreamSignalingTest, SdpWithoutMsidCreatesDefaultStream) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_audio_only(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_audio_only(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithoutStreamsAudioOnly,
NULL));
@@ -899,7 +948,7 @@
EXPECT_EQ(0u, remote_stream->GetVideoTracks().size());
EXPECT_EQ("default", remote_stream->label());
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithoutStreams, NULL));
ASSERT_TRUE(desc != NULL);
@@ -913,10 +962,29 @@
observer_->VerifyRemoteVideoTrack("default", "defaultv0", 0);
}
+// This tests that a default MediaStream is created if a remote session
+// description doesn't contain any streams and media direction is send only.
+TEST_F(MediaStreamSignalingTest, RecvOnlySdpWithoutMsidCreatesDefaultStream) {
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
+ webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
+ kSdpStringSendOnlyWithWithoutStreams,
+ NULL));
+ ASSERT_TRUE(desc != NULL);
+ signaling_->OnRemoteDescriptionChanged(desc.get());
+
+ EXPECT_EQ(1u, signaling_->remote_streams()->count());
+ ASSERT_EQ(1u, observer_->remote_streams()->count());
+ MediaStreamInterface* remote_stream = observer_->remote_streams()->at(0);
+
+ EXPECT_EQ(1u, remote_stream->GetAudioTracks().size());
+ EXPECT_EQ(1u, remote_stream->GetVideoTracks().size());
+ EXPECT_EQ("default", remote_stream->label());
+}
+
// This tests that it won't crash when MediaStreamSignaling tries to remove
// a remote track that as already been removed from the mediastream.
TEST_F(MediaStreamSignalingTest, RemoveAlreadyGoneRemoteStream) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_audio_only(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_audio_only(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithoutStreams,
NULL));
@@ -926,7 +994,7 @@
remote_stream->RemoveTrack(remote_stream->GetAudioTracks()[0]);
remote_stream->RemoveTrack(remote_stream->GetVideoTracks()[0]);
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithoutStreams, NULL));
ASSERT_TRUE(desc != NULL);
@@ -940,7 +1008,7 @@
// MSID is supported.
TEST_F(MediaStreamSignalingTest,
SdpWithoutMsidAndStreamsCreatesDefaultStream) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithoutStreams,
NULL));
@@ -956,7 +1024,7 @@
// This tests that a default MediaStream is not created if the remote session
// description doesn't contain any streams but does support MSID.
TEST_F(MediaStreamSignalingTest, SdpWitMsidDontCreatesDefaultStream) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_msid_without_streams(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_msid_without_streams(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithMsidWithoutStreams,
NULL));
@@ -967,18 +1035,18 @@
// This test that a default MediaStream is not created if a remote session
// description is updated to not have any MediaStreams.
TEST_F(MediaStreamSignalingTest, VerifyDefaultStreamIsNotCreated) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithStream1,
NULL));
ASSERT_TRUE(desc != NULL);
signaling_->OnRemoteDescriptionChanged(desc.get());
- talk_base::scoped_refptr<StreamCollection> reference(
+ rtc::scoped_refptr<StreamCollection> reference(
CreateStreamCollection(1));
EXPECT_TRUE(CompareStreamCollections(observer_->remote_streams(),
reference.get()));
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_without_streams(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_without_streams(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
kSdpStringWithoutStreams,
NULL));
@@ -990,7 +1058,7 @@
// when MediaStreamSignaling::OnLocalDescriptionChanged is called with an
// updated local session description.
TEST_F(MediaStreamSignalingTest, LocalDescriptionChanged) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_1;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_1;
CreateSessionDescriptionAndReference(2, 2, desc_1.use());
signaling_->AddLocalStream(reference_collection_->at(0));
@@ -1003,7 +1071,7 @@
observer_->VerifyLocalVideoTrack(kStreams[0], kVideoTracks[1], 4);
// Remove an audio and video track.
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_2;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_2;
CreateSessionDescriptionAndReference(1, 1, desc_2.use());
signaling_->OnLocalDescriptionChanged(desc_2.get());
EXPECT_EQ(1u, observer_->NumberOfLocalAudioTracks());
@@ -1016,7 +1084,7 @@
// when MediaStreamSignaling::AddLocalStream is called after
// MediaStreamSignaling::OnLocalDescriptionChanged is called.
TEST_F(MediaStreamSignalingTest, AddLocalStreamAfterLocalDescriptionChanged) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_1;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_1;
CreateSessionDescriptionAndReference(2, 2, desc_1.use());
signaling_->OnLocalDescriptionChanged(desc_1.get());
@@ -1036,7 +1104,7 @@
// if the ssrc on a local track is changed when
// MediaStreamSignaling::OnLocalDescriptionChanged is called.
TEST_F(MediaStreamSignalingTest, ChangeSsrcOnTrackInLocalSessionDescription) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc;
CreateSessionDescriptionAndReference(1, 1, desc.use());
signaling_->AddLocalStream(reference_collection_->at(0));
@@ -1051,15 +1119,15 @@
desc->ToString(&sdp);
std::string ssrc_org = "a=ssrc:1";
std::string ssrc_to = "a=ssrc:97";
- talk_base::replace_substrs(ssrc_org.c_str(), ssrc_org.length(),
+ rtc::replace_substrs(ssrc_org.c_str(), ssrc_org.length(),
ssrc_to.c_str(), ssrc_to.length(),
&sdp);
ssrc_org = "a=ssrc:2";
ssrc_to = "a=ssrc:98";
- talk_base::replace_substrs(ssrc_org.c_str(), ssrc_org.length(),
+ rtc::replace_substrs(ssrc_org.c_str(), ssrc_org.length(),
ssrc_to.c_str(), ssrc_to.length(),
&sdp);
- talk_base::scoped_ptr<SessionDescriptionInterface> updated_desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> updated_desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
sdp, NULL));
@@ -1074,7 +1142,7 @@
// if a new session description is set with the same tracks but they are now
// sent on a another MediaStream.
TEST_F(MediaStreamSignalingTest, SignalSameTracksInSeparateMediaStream) {
- talk_base::scoped_ptr<SessionDescriptionInterface> desc;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc;
CreateSessionDescriptionAndReference(1, 1, desc.use());
signaling_->AddLocalStream(reference_collection_->at(0));
@@ -1088,7 +1156,7 @@
// Add a new MediaStream but with the same tracks as in the first stream.
std::string stream_label_1 = kStreams[1];
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream_1(
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream_1(
webrtc::MediaStream::Create(kStreams[1]));
stream_1->AddTrack(reference_collection_->at(0)->GetVideoTracks()[0]);
stream_1->AddTrack(reference_collection_->at(0)->GetAudioTracks()[0]);
@@ -1097,10 +1165,10 @@
// Replace msid in the original SDP.
std::string sdp;
desc->ToString(&sdp);
- talk_base::replace_substrs(
+ rtc::replace_substrs(
kStreams[0], strlen(kStreams[0]), kStreams[1], strlen(kStreams[1]), &sdp);
- talk_base::scoped_ptr<SessionDescriptionInterface> updated_desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> updated_desc(
webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
sdp, NULL));
@@ -1115,13 +1183,13 @@
// SSL_SERVER.
TEST_F(MediaStreamSignalingTest, SctpIdAllocationBasedOnRole) {
int id;
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_SERVER, &id));
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_SERVER, &id));
EXPECT_EQ(1, id);
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_CLIENT, &id));
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_CLIENT, &id));
EXPECT_EQ(0, id);
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_SERVER, &id));
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_SERVER, &id));
EXPECT_EQ(3, id);
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_CLIENT, &id));
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_CLIENT, &id));
EXPECT_EQ(2, id);
}
@@ -1131,13 +1199,13 @@
AddDataChannel(cricket::DCT_SCTP, "a", old_id);
int new_id;
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_SERVER, &new_id));
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_SERVER, &new_id));
EXPECT_NE(old_id, new_id);
// Creates a DataChannel with id 0.
old_id = 0;
AddDataChannel(cricket::DCT_SCTP, "a", old_id);
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_CLIENT, &new_id));
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_CLIENT, &new_id));
EXPECT_NE(old_id, new_id);
}
@@ -1149,12 +1217,12 @@
AddDataChannel(cricket::DCT_SCTP, "a", even_id);
int allocated_id = -1;
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_SERVER,
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_SERVER,
&allocated_id));
EXPECT_EQ(odd_id + 2, allocated_id);
AddDataChannel(cricket::DCT_SCTP, "a", allocated_id);
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_CLIENT,
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_CLIENT,
&allocated_id));
EXPECT_EQ(even_id + 2, allocated_id);
AddDataChannel(cricket::DCT_SCTP, "a", allocated_id);
@@ -1163,20 +1231,20 @@
signaling_->RemoveSctpDataChannel(even_id);
// Verifies that removed DataChannel ids are reused.
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_SERVER,
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_SERVER,
&allocated_id));
EXPECT_EQ(odd_id, allocated_id);
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_CLIENT,
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_CLIENT,
&allocated_id));
EXPECT_EQ(even_id, allocated_id);
// Verifies that used higher DataChannel ids are not reused.
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_SERVER,
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_SERVER,
&allocated_id));
EXPECT_NE(odd_id + 2, allocated_id);
- ASSERT_TRUE(signaling_->AllocateSctpSid(talk_base::SSL_CLIENT,
+ ASSERT_TRUE(signaling_->AllocateSctpSid(rtc::SSL_CLIENT,
&allocated_id));
EXPECT_NE(even_id + 2, allocated_id);
@@ -1187,7 +1255,7 @@
AddDataChannel(cricket::DCT_RTP, "a", -1);
webrtc::InternalDataChannelInit config;
- talk_base::scoped_refptr<webrtc::DataChannel> data_channel =
+ rtc::scoped_refptr<webrtc::DataChannel> data_channel =
webrtc::DataChannel::Create(
data_channel_provider_.get(), cricket::DCT_RTP, "a", config);
ASSERT_TRUE(data_channel.get() != NULL);
@@ -1204,11 +1272,12 @@
// message.
TEST_F(MediaStreamSignalingTest, CreateDataChannelFromOpenMessage) {
FakeDataChannelFactory fake_factory(data_channel_provider_.get(),
- cricket::DCT_SCTP);
+ cricket::DCT_SCTP,
+ signaling_.get());
signaling_->SetDataChannelFactory(&fake_factory);
webrtc::DataChannelInit config;
config.id = 1;
- talk_base::Buffer payload;
+ rtc::Buffer payload;
webrtc::WriteDataChannelOpenMessage("a", config, &payload);
cricket::ReceiveDataParams params;
params.ssrc = config.id;
@@ -1224,11 +1293,12 @@
AddDataChannel(cricket::DCT_SCTP, "a", -1);
FakeDataChannelFactory fake_factory(data_channel_provider_.get(),
- cricket::DCT_SCTP);
+ cricket::DCT_SCTP,
+ signaling_.get());
signaling_->SetDataChannelFactory(&fake_factory);
webrtc::DataChannelInit config;
config.id = 0;
- talk_base::Buffer payload;
+ rtc::Buffer payload;
webrtc::WriteDataChannelOpenMessage("a", config, &payload);
cricket::ReceiveDataParams params;
params.ssrc = config.id;
@@ -1241,7 +1311,7 @@
webrtc::InternalDataChannelInit config;
config.id = 0;
- talk_base::scoped_refptr<webrtc::DataChannel> data_channel =
+ rtc::scoped_refptr<webrtc::DataChannel> data_channel =
webrtc::DataChannel::Create(
data_channel_provider_.get(), cricket::DCT_SCTP, "a", config);
ASSERT_TRUE(data_channel.get() != NULL);
@@ -1253,3 +1323,24 @@
signaling_->OnRemoteSctpDataChannelClosed(config.id);
EXPECT_EQ(webrtc::DataChannelInterface::kClosed, data_channel->state());
}
+
+// Verifies that DataChannel added from OPEN message is added to
+// MediaStreamSignaling only once (webrtc issue 3778).
+TEST_F(MediaStreamSignalingTest, DataChannelFromOpenMessageAddedOnce) {
+ FakeDataChannelFactory fake_factory(data_channel_provider_.get(),
+ cricket::DCT_SCTP,
+ signaling_.get());
+ signaling_->SetDataChannelFactory(&fake_factory);
+ webrtc::DataChannelInit config;
+ config.id = 1;
+ rtc::Buffer payload;
+ webrtc::WriteDataChannelOpenMessage("a", config, &payload);
+ cricket::ReceiveDataParams params;
+ params.ssrc = config.id;
+ EXPECT_TRUE(signaling_->AddDataChannelFromOpenMessage(params, payload));
+ EXPECT_TRUE(signaling_->HasDataChannels());
+
+ // Removes the DataChannel and verifies that no DataChannel is left.
+ signaling_->RemoveSctpDataChannel(config.id);
+ EXPECT_FALSE(signaling_->HasDataChannels());
+}
diff --git a/app/webrtc/mediastreamtrackproxy.h b/app/webrtc/mediastreamtrackproxy.h
index 19750b0..56ad1e3 100644
--- a/app/webrtc/mediastreamtrackproxy.h
+++ b/app/webrtc/mediastreamtrackproxy.h
@@ -45,7 +45,7 @@
PROXY_METHOD1(void, AddSink, AudioTrackSinkInterface*)
PROXY_METHOD1(void, RemoveSink, AudioTrackSinkInterface*)
PROXY_METHOD1(bool, GetSignalLevel, int*)
- PROXY_METHOD0(talk_base::scoped_refptr<AudioProcessorInterface>,
+ PROXY_METHOD0(rtc::scoped_refptr<AudioProcessorInterface>,
GetAudioProcessor)
PROXY_METHOD0(cricket::AudioRenderer*, GetRenderer)
diff --git a/app/webrtc/notifier.h b/app/webrtc/notifier.h
index eaa0063..1d2c333 100644
--- a/app/webrtc/notifier.h
+++ b/app/webrtc/notifier.h
@@ -30,8 +30,8 @@
#include <list>
-#include "talk/base/common.h"
#include "talk/app/webrtc/mediastreaminterface.h"
+#include "webrtc/base/common.h"
namespace webrtc {
diff --git a/app/webrtc/objc/RTCAudioTrack+Internal.h b/app/webrtc/objc/RTCAudioTrack+Internal.h
index 17d2723..60e40bf 100644
--- a/app/webrtc/objc/RTCAudioTrack+Internal.h
+++ b/app/webrtc/objc/RTCAudioTrack+Internal.h
@@ -32,6 +32,6 @@
@interface RTCAudioTrack (Internal)
@property(nonatomic, assign, readonly)
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> audioTrack;
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> audioTrack;
@end
diff --git a/app/webrtc/objc/RTCAudioTrack.mm b/app/webrtc/objc/RTCAudioTrack.mm
index 2364c29..bdc89b5 100644
--- a/app/webrtc/objc/RTCAudioTrack.mm
+++ b/app/webrtc/objc/RTCAudioTrack.mm
@@ -38,7 +38,7 @@
@implementation RTCAudioTrack (Internal)
-- (talk_base::scoped_refptr<webrtc::AudioTrackInterface>)audioTrack {
+- (rtc::scoped_refptr<webrtc::AudioTrackInterface>)audioTrack {
return static_cast<webrtc::AudioTrackInterface*>(self.mediaTrack.get());
}
diff --git a/app/webrtc/objc/RTCDataChannel+Internal.h b/app/webrtc/objc/RTCDataChannel+Internal.h
index a550891..0a8079b 100644
--- a/app/webrtc/objc/RTCDataChannel+Internal.h
+++ b/app/webrtc/objc/RTCDataChannel+Internal.h
@@ -28,7 +28,7 @@
#import "RTCDataChannel.h"
#include "talk/app/webrtc/datachannelinterface.h"
-#include "talk/base/scoped_ref_ptr.h"
+#include "webrtc/base/scoped_ref_ptr.h"
@interface RTCDataBuffer (Internal)
@@ -47,9 +47,9 @@
@interface RTCDataChannel (Internal)
@property(nonatomic, readonly)
- talk_base::scoped_refptr<webrtc::DataChannelInterface> dataChannel;
+ rtc::scoped_refptr<webrtc::DataChannelInterface> dataChannel;
- (instancetype)initWithDataChannel:
- (talk_base::scoped_refptr<webrtc::DataChannelInterface>)dataChannel;
+ (rtc::scoped_refptr<webrtc::DataChannelInterface>)dataChannel;
@end
diff --git a/app/webrtc/objc/RTCDataChannel.mm b/app/webrtc/objc/RTCDataChannel.mm
index 0837940..2cf8bf8 100644
--- a/app/webrtc/objc/RTCDataChannel.mm
+++ b/app/webrtc/objc/RTCDataChannel.mm
@@ -135,13 +135,13 @@
@end
@implementation RTCDataBuffer {
- talk_base::scoped_ptr<webrtc::DataBuffer> _dataBuffer;
+ rtc::scoped_ptr<webrtc::DataBuffer> _dataBuffer;
}
- (instancetype)initWithData:(NSData*)data isBinary:(BOOL)isBinary {
NSAssert(data, @"data cannot be nil");
if (self = [super init]) {
- talk_base::Buffer buffer([data bytes], [data length]);
+ rtc::Buffer buffer([data bytes], [data length]);
_dataBuffer.reset(new webrtc::DataBuffer(buffer, isBinary));
}
return self;
@@ -174,8 +174,8 @@
@end
@implementation RTCDataChannel {
- talk_base::scoped_refptr<webrtc::DataChannelInterface> _dataChannel;
- talk_base::scoped_ptr<webrtc::RTCDataChannelObserver> _observer;
+ rtc::scoped_refptr<webrtc::DataChannelInterface> _dataChannel;
+ rtc::scoped_ptr<webrtc::RTCDataChannelObserver> _observer;
BOOL _isObserverRegistered;
}
@@ -256,7 +256,7 @@
@implementation RTCDataChannel (Internal)
- (instancetype)initWithDataChannel:
- (talk_base::scoped_refptr<webrtc::DataChannelInterface>)
+ (rtc::scoped_refptr<webrtc::DataChannelInterface>)
dataChannel {
NSAssert(dataChannel != NULL, @"dataChannel cannot be NULL");
if (self = [super init]) {
@@ -266,7 +266,7 @@
return self;
}
-- (talk_base::scoped_refptr<webrtc::DataChannelInterface>)dataChannel {
+- (rtc::scoped_refptr<webrtc::DataChannelInterface>)dataChannel {
return _dataChannel;
}
diff --git a/app/webrtc/objc/RTCEAGLVideoView.m b/app/webrtc/objc/RTCEAGLVideoView.m
index 5365d98..faacef6 100644
--- a/app/webrtc/objc/RTCEAGLVideoView.m
+++ b/app/webrtc/objc/RTCEAGLVideoView.m
@@ -173,6 +173,7 @@
return;
}
[_videoTrack removeRenderer:_videoRenderer];
+ self.i420Frame = nil;
_videoTrack = videoTrack;
[_videoTrack addRenderer:_videoRenderer];
// TODO(tkchin): potentially handle changes in track state - e.g. render
@@ -191,11 +192,9 @@
// This method is called when the GLKView's content is dirty and needs to be
// redrawn. This occurs on main thread.
- (void)glkView:(GLKView*)view drawInRect:(CGRect)rect {
- if (self.i420Frame) {
- // The renderer will draw the frame to the framebuffer corresponding to the
- // one used by |view|.
- [_glRenderer drawFrame:self.i420Frame];
- }
+ // The renderer will draw the frame to the framebuffer corresponding to the
+ // one used by |view|.
+ [_glRenderer drawFrame:self.i420Frame];
}
#pragma mark - Private
diff --git a/app/webrtc/objc/RTCI420Frame.mm b/app/webrtc/objc/RTCI420Frame.mm
index eff3102..0b50691 100644
--- a/app/webrtc/objc/RTCI420Frame.mm
+++ b/app/webrtc/objc/RTCI420Frame.mm
@@ -27,11 +27,11 @@
#import "RTCI420Frame.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/scoped_ptr.h"
@implementation RTCI420Frame {
- talk_base::scoped_ptr<cricket::VideoFrame> _videoFrame;
+ rtc::scoped_ptr<cricket::VideoFrame> _videoFrame;
}
- (NSUInteger)width {
diff --git a/app/webrtc/objc/RTCMediaConstraints.mm b/app/webrtc/objc/RTCMediaConstraints.mm
index a1cc5a5..e44dd59 100644
--- a/app/webrtc/objc/RTCMediaConstraints.mm
+++ b/app/webrtc/objc/RTCMediaConstraints.mm
@@ -33,13 +33,13 @@
#import "RTCPair.h"
-#include "talk/base/scoped_ptr.h"
+#include "webrtc/base/scoped_ptr.h"
// TODO(hughv): Add accessors for mandatory and optional constraints.
// TODO(hughv): Add description.
@implementation RTCMediaConstraints {
- talk_base::scoped_ptr<webrtc::RTCMediaConstraintsNative> _constraints;
+ rtc::scoped_ptr<webrtc::RTCMediaConstraintsNative> _constraints;
webrtc::MediaConstraintsInterface::Constraints _mandatory;
webrtc::MediaConstraintsInterface::Constraints _optional;
}
diff --git a/app/webrtc/objc/RTCMediaSource+Internal.h b/app/webrtc/objc/RTCMediaSource+Internal.h
index 98f8e9c..96341f2 100644
--- a/app/webrtc/objc/RTCMediaSource+Internal.h
+++ b/app/webrtc/objc/RTCMediaSource+Internal.h
@@ -32,9 +32,9 @@
@interface RTCMediaSource (Internal)
@property(nonatomic, assign, readonly)
- talk_base::scoped_refptr<webrtc::MediaSourceInterface> mediaSource;
+ rtc::scoped_refptr<webrtc::MediaSourceInterface> mediaSource;
- (id)initWithMediaSource:
- (talk_base::scoped_refptr<webrtc::MediaSourceInterface>)mediaSource;
+ (rtc::scoped_refptr<webrtc::MediaSourceInterface>)mediaSource;
@end
diff --git a/app/webrtc/objc/RTCMediaSource.mm b/app/webrtc/objc/RTCMediaSource.mm
index 28af3ad..b94bf05 100644
--- a/app/webrtc/objc/RTCMediaSource.mm
+++ b/app/webrtc/objc/RTCMediaSource.mm
@@ -34,7 +34,7 @@
#import "RTCEnumConverter.h"
@implementation RTCMediaSource {
- talk_base::scoped_refptr<webrtc::MediaSourceInterface> _mediaSource;
+ rtc::scoped_refptr<webrtc::MediaSourceInterface> _mediaSource;
}
- (RTCSourceState)state {
@@ -46,7 +46,7 @@
@implementation RTCMediaSource (Internal)
- (id)initWithMediaSource:
- (talk_base::scoped_refptr<webrtc::MediaSourceInterface>)mediaSource {
+ (rtc::scoped_refptr<webrtc::MediaSourceInterface>)mediaSource {
if (!mediaSource) {
NSAssert(NO, @"nil arguments not allowed");
self = nil;
@@ -58,7 +58,7 @@
return self;
}
-- (talk_base::scoped_refptr<webrtc::MediaSourceInterface>)mediaSource {
+- (rtc::scoped_refptr<webrtc::MediaSourceInterface>)mediaSource {
return _mediaSource;
}
diff --git a/app/webrtc/objc/RTCMediaStream+Internal.h b/app/webrtc/objc/RTCMediaStream+Internal.h
index 2123c2d..bde7631 100644
--- a/app/webrtc/objc/RTCMediaStream+Internal.h
+++ b/app/webrtc/objc/RTCMediaStream+Internal.h
@@ -32,9 +32,9 @@
@interface RTCMediaStream (Internal)
@property(nonatomic, assign, readonly)
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> mediaStream;
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> mediaStream;
- (id)initWithMediaStream:
- (talk_base::scoped_refptr<webrtc::MediaStreamInterface>)mediaStream;
+ (rtc::scoped_refptr<webrtc::MediaStreamInterface>)mediaStream;
@end
diff --git a/app/webrtc/objc/RTCMediaStream.mm b/app/webrtc/objc/RTCMediaStream.mm
index 94e14fc..27d20b8 100644
--- a/app/webrtc/objc/RTCMediaStream.mm
+++ b/app/webrtc/objc/RTCMediaStream.mm
@@ -40,7 +40,7 @@
@implementation RTCMediaStream {
NSMutableArray* _audioTracks;
NSMutableArray* _videoTracks;
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> _mediaStream;
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> _mediaStream;
}
- (NSString*)description {
@@ -105,7 +105,7 @@
@implementation RTCMediaStream (Internal)
- (id)initWithMediaStream:
- (talk_base::scoped_refptr<webrtc::MediaStreamInterface>)mediaStream {
+ (rtc::scoped_refptr<webrtc::MediaStreamInterface>)mediaStream {
if (!mediaStream) {
NSAssert(NO, @"nil arguments not allowed");
self = nil;
@@ -120,7 +120,7 @@
_mediaStream = mediaStream;
for (size_t i = 0; i < audio_tracks.size(); ++i) {
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> track =
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
audio_tracks[i];
RTCAudioTrack* audioTrack =
[[RTCAudioTrack alloc] initWithMediaTrack:track];
@@ -128,7 +128,7 @@
}
for (size_t i = 0; i < video_tracks.size(); ++i) {
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> track =
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> track =
video_tracks[i];
RTCVideoTrack* videoTrack =
[[RTCVideoTrack alloc] initWithMediaTrack:track];
@@ -138,7 +138,7 @@
return self;
}
-- (talk_base::scoped_refptr<webrtc::MediaStreamInterface>)mediaStream {
+- (rtc::scoped_refptr<webrtc::MediaStreamInterface>)mediaStream {
return _mediaStream;
}
diff --git a/app/webrtc/objc/RTCMediaStreamTrack+Internal.h b/app/webrtc/objc/RTCMediaStreamTrack+Internal.h
index 9a0cab3..d815c79 100644
--- a/app/webrtc/objc/RTCMediaStreamTrack+Internal.h
+++ b/app/webrtc/objc/RTCMediaStreamTrack+Internal.h
@@ -32,9 +32,9 @@
@interface RTCMediaStreamTrack (Internal)
@property(nonatomic, assign, readonly)
- talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface> mediaTrack;
+ rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> mediaTrack;
- (id)initWithMediaTrack:
- (talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface>)mediaTrack;
+ (rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>)mediaTrack;
@end
diff --git a/app/webrtc/objc/RTCMediaStreamTrack.mm b/app/webrtc/objc/RTCMediaStreamTrack.mm
index 5931312..57a9fde 100644
--- a/app/webrtc/objc/RTCMediaStreamTrack.mm
+++ b/app/webrtc/objc/RTCMediaStreamTrack.mm
@@ -29,8 +29,8 @@
#error "This file requires ARC support."
#endif
-#import "RTCMediaStreamTrack+Internal.h"
#import "RTCEnumConverter.h"
+#import "RTCMediaStreamTrack+Internal.h"
namespace webrtc {
@@ -48,8 +48,8 @@
}
@implementation RTCMediaStreamTrack {
- talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface> _mediaTrack;
- talk_base::scoped_ptr<webrtc::RTCMediaStreamTrackObserver> _observer;
+ rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> _mediaTrack;
+ rtc::scoped_ptr<webrtc::RTCMediaStreamTrackObserver> _observer;
}
@synthesize label;
@@ -100,7 +100,7 @@
@implementation RTCMediaStreamTrack (Internal)
- (id)initWithMediaTrack:
- (talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface>)
+ (rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>)
mediaTrack {
if (!mediaTrack) {
NSAssert(NO, @"nil arguments not allowed");
@@ -120,7 +120,7 @@
_mediaTrack->UnregisterObserver(_observer.get());
}
-- (talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface>)mediaTrack {
+- (rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>)mediaTrack {
return _mediaTrack;
}
diff --git a/app/webrtc/objc/RTCNSGLVideoView.m b/app/webrtc/objc/RTCNSGLVideoView.m
index 39f3678..292e792 100644
--- a/app/webrtc/objc/RTCNSGLVideoView.m
+++ b/app/webrtc/objc/RTCNSGLVideoView.m
@@ -116,6 +116,9 @@
if (_videoTrack) {
[_videoTrack removeRenderer:_videoRenderer];
CVDisplayLinkStop(_displayLink);
+ // Clear contents.
+ self.i420Frame = nil;
+ [self drawFrame];
}
_videoTrack = videoTrack;
if (_videoTrack) {
@@ -144,7 +147,7 @@
- (void)drawFrame {
RTCI420Frame* i420Frame = self.i420Frame;
- if (i420Frame && self.glRenderer.lastDrawnFrame != i420Frame) {
+ if (self.glRenderer.lastDrawnFrame != i420Frame) {
// This method may be called from CVDisplayLink callback which isn't on the
// main thread so we have to lock the GL context before drawing.
CGLLockContext([[self openGLContext] CGLContextObj]);
diff --git a/app/webrtc/objc/RTCOpenGLVideoRenderer.mm b/app/webrtc/objc/RTCOpenGLVideoRenderer.mm
index 9ee0216..5a24cf0 100644
--- a/app/webrtc/objc/RTCOpenGLVideoRenderer.mm
+++ b/app/webrtc/objc/RTCOpenGLVideoRenderer.mm
@@ -205,16 +205,18 @@
return NO;
}
[self ensureGLContext];
- if (![self updateTextureSizesForFrame:frame] ||
- ![self updateTextureDataForFrame:frame]) {
- return NO;
- }
glClear(GL_COLOR_BUFFER_BIT);
+ if (frame) {
+ if (![self updateTextureSizesForFrame:frame] ||
+ ![self updateTextureDataForFrame:frame]) {
+ return NO;
+ }
#if !TARGET_OS_IPHONE
- glBindVertexArray(_vertexArray);
+ glBindVertexArray(_vertexArray);
#endif
- glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
- glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
+ glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
+ }
#if !TARGET_OS_IPHONE
[_context flushBuffer];
#endif
@@ -238,7 +240,6 @@
}
glUseProgram(_program);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- glClearColor(0, 0, 0, 1);
_isInitialized = YES;
}
diff --git a/app/webrtc/objc/RTCPeerConnection+Internal.h b/app/webrtc/objc/RTCPeerConnection+Internal.h
index ad1c334..305bd5e 100644
--- a/app/webrtc/objc/RTCPeerConnection+Internal.h
+++ b/app/webrtc/objc/RTCPeerConnection+Internal.h
@@ -34,7 +34,7 @@
@interface RTCPeerConnection (Internal)
@property(nonatomic, assign, readonly)
- talk_base::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection;
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection;
- (instancetype)initWithFactory:(webrtc::PeerConnectionFactoryInterface*)factory
iceServers:(const webrtc::PeerConnectionInterface::IceServers&)iceServers
diff --git a/app/webrtc/objc/RTCPeerConnection.mm b/app/webrtc/objc/RTCPeerConnection.mm
index 738fb31..72ba373 100644
--- a/app/webrtc/objc/RTCPeerConnection.mm
+++ b/app/webrtc/objc/RTCPeerConnection.mm
@@ -40,8 +40,8 @@
#import "RTCMediaStreamTrack+Internal.h"
#import "RTCPeerConnectionObserver.h"
#import "RTCSessionDescription+Internal.h"
-#import "RTCSessionDescriptionDelegate.h"
#import "RTCSessionDescription.h"
+#import "RTCSessionDescriptionDelegate.h"
#import "RTCStatsDelegate.h"
#import "RTCStatsReport+Internal.h"
@@ -141,12 +141,12 @@
@implementation RTCPeerConnection {
NSMutableArray* _localStreams;
- talk_base::scoped_ptr<webrtc::RTCPeerConnectionObserver> _observer;
- talk_base::scoped_refptr<webrtc::PeerConnectionInterface> _peerConnection;
+ rtc::scoped_ptr<webrtc::RTCPeerConnectionObserver> _observer;
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> _peerConnection;
}
- (BOOL)addICECandidate:(RTCICECandidate*)candidate {
- talk_base::scoped_ptr<const webrtc::IceCandidateInterface> iceCandidate(
+ rtc::scoped_ptr<const webrtc::IceCandidateInterface> iceCandidate(
candidate.candidate);
return self.peerConnection->AddIceCandidate(iceCandidate.get());
}
@@ -165,7 +165,7 @@
- (RTCDataChannel*)createDataChannelWithLabel:(NSString*)label
config:(RTCDataChannelInit*)config {
std::string labelString([label UTF8String]);
- talk_base::scoped_refptr<webrtc::DataChannelInterface> dataChannel =
+ rtc::scoped_refptr<webrtc::DataChannelInterface> dataChannel =
self.peerConnection->CreateDataChannel(labelString,
config.dataChannelInit);
return [[RTCDataChannel alloc] initWithDataChannel:dataChannel];
@@ -173,16 +173,16 @@
- (void)createAnswerWithDelegate:(id<RTCSessionDescriptionDelegate>)delegate
constraints:(RTCMediaConstraints*)constraints {
- talk_base::scoped_refptr<webrtc::RTCCreateSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<webrtc::RTCCreateSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
webrtc::RTCCreateSessionDescriptionObserver>(delegate, self));
self.peerConnection->CreateAnswer(observer, constraints.constraints);
}
- (void)createOfferWithDelegate:(id<RTCSessionDescriptionDelegate>)delegate
constraints:(RTCMediaConstraints*)constraints {
- talk_base::scoped_refptr<webrtc::RTCCreateSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<webrtc::RTCCreateSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
webrtc::RTCCreateSessionDescriptionObserver>(delegate, self));
self.peerConnection->CreateOffer(observer, constraints.constraints);
}
@@ -195,8 +195,8 @@
- (void)setLocalDescriptionWithDelegate:
(id<RTCSessionDescriptionDelegate>)delegate
sessionDescription:(RTCSessionDescription*)sdp {
- talk_base::scoped_refptr<webrtc::RTCSetSessionDescriptionObserver> observer(
- new talk_base::RefCountedObject<webrtc::RTCSetSessionDescriptionObserver>(
+ rtc::scoped_refptr<webrtc::RTCSetSessionDescriptionObserver> observer(
+ new rtc::RefCountedObject<webrtc::RTCSetSessionDescriptionObserver>(
delegate, self));
self.peerConnection->SetLocalDescription(observer, sdp.sessionDescription);
}
@@ -204,8 +204,8 @@
- (void)setRemoteDescriptionWithDelegate:
(id<RTCSessionDescriptionDelegate>)delegate
sessionDescription:(RTCSessionDescription*)sdp {
- talk_base::scoped_refptr<webrtc::RTCSetSessionDescriptionObserver> observer(
- new talk_base::RefCountedObject<webrtc::RTCSetSessionDescriptionObserver>(
+ rtc::scoped_refptr<webrtc::RTCSetSessionDescriptionObserver> observer(
+ new rtc::RefCountedObject<webrtc::RTCSetSessionDescriptionObserver>(
delegate, self));
self.peerConnection->SetRemoteDescription(observer, sdp.sessionDescription);
}
@@ -261,8 +261,8 @@
- (BOOL)getStatsWithDelegate:(id<RTCStatsDelegate>)delegate
mediaStreamTrack:(RTCMediaStreamTrack*)mediaStreamTrack
statsOutputLevel:(RTCStatsOutputLevel)statsOutputLevel {
- talk_base::scoped_refptr<webrtc::RTCStatsObserver> observer(
- new talk_base::RefCountedObject<webrtc::RTCStatsObserver>(delegate,
+ rtc::scoped_refptr<webrtc::RTCStatsObserver> observer(
+ new rtc::RefCountedObject<webrtc::RTCStatsObserver>(delegate,
self));
webrtc::PeerConnectionInterface::StatsOutputLevel nativeOutputLevel =
[RTCEnumConverter convertStatsOutputLevelToNative:statsOutputLevel];
@@ -287,7 +287,7 @@
return self;
}
-- (talk_base::scoped_refptr<webrtc::PeerConnectionInterface>)peerConnection {
+- (rtc::scoped_refptr<webrtc::PeerConnectionInterface>)peerConnection {
return _peerConnection;
}
diff --git a/app/webrtc/objc/RTCPeerConnectionFactory.mm b/app/webrtc/objc/RTCPeerConnectionFactory.mm
index 8ada166..b7d2ce3 100644
--- a/app/webrtc/objc/RTCPeerConnectionFactory.mm
+++ b/app/webrtc/objc/RTCPeerConnectionFactory.mm
@@ -51,12 +51,12 @@
#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/app/webrtc/videotrack.h"
-#include "talk/base/logging.h"
-#include "talk/base/ssladapter.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/ssladapter.h"
@interface RTCPeerConnectionFactory ()
-@property(nonatomic, assign) talk_base::scoped_refptr<
+@property(nonatomic, assign) rtc::scoped_refptr<
webrtc::PeerConnectionFactoryInterface> nativeFactory;
@end
@@ -66,12 +66,12 @@
@synthesize nativeFactory = _nativeFactory;
+ (void)initializeSSL {
- BOOL initialized = talk_base::InitializeSSL();
+ BOOL initialized = rtc::InitializeSSL();
NSAssert(initialized, @"Failed to initialize SSL library");
}
+ (void)deinitializeSSL {
- BOOL deinitialized = talk_base::CleanupSSL();
+ BOOL deinitialized = rtc::CleanupSSL();
NSAssert(deinitialized, @"Failed to deinitialize SSL library");
}
@@ -80,7 +80,7 @@
_nativeFactory = webrtc::CreatePeerConnectionFactory();
NSAssert(_nativeFactory, @"Failed to initialize PeerConnectionFactory!");
// Uncomment to get sensitive logs emitted (to stderr or logcat).
- // talk_base::LogMessage::LogToDebug(talk_base::LS_SENSITIVE);
+ // rtc::LogMessage::LogToDebug(rtc::LS_SENSITIVE);
}
return self;
}
@@ -102,7 +102,7 @@
}
- (RTCMediaStream*)mediaStreamWithLabel:(NSString*)label {
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> nativeMediaStream =
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> nativeMediaStream =
self.nativeFactory->CreateLocalMediaStream([label UTF8String]);
return [[RTCMediaStream alloc] initWithMediaStream:nativeMediaStream];
}
@@ -112,7 +112,7 @@
if (!capturer) {
return nil;
}
- talk_base::scoped_refptr<webrtc::VideoSourceInterface> source =
+ rtc::scoped_refptr<webrtc::VideoSourceInterface> source =
self.nativeFactory->CreateVideoSource([capturer takeNativeCapturer],
constraints.constraints);
return [[RTCVideoSource alloc] initWithMediaSource:source];
@@ -120,14 +120,14 @@
- (RTCVideoTrack*)videoTrackWithID:(NSString*)videoId
source:(RTCVideoSource*)source {
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> track =
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> track =
self.nativeFactory->CreateVideoTrack([videoId UTF8String],
source.videoSource);
return [[RTCVideoTrack alloc] initWithMediaTrack:track];
}
- (RTCAudioTrack*)audioTrackWithID:(NSString*)audioId {
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> track =
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
self.nativeFactory->CreateAudioTrack([audioId UTF8String], NULL);
return [[RTCAudioTrack alloc] initWithMediaTrack:track];
}
diff --git a/app/webrtc/objc/RTCPeerConnectionObserver.mm b/app/webrtc/objc/RTCPeerConnectionObserver.mm
index 061ccf0..a0206e5 100644
--- a/app/webrtc/objc/RTCPeerConnectionObserver.mm
+++ b/app/webrtc/objc/RTCPeerConnectionObserver.mm
@@ -32,9 +32,9 @@
#import "RTCPeerConnectionObserver.h"
#import "RTCDataChannel+Internal.h"
+#import "RTCEnumConverter.h"
#import "RTCICECandidate+Internal.h"
#import "RTCMediaStream+Internal.h"
-#import "RTCEnumConverter.h"
namespace webrtc {
diff --git a/app/webrtc/objc/RTCStatsReport.mm b/app/webrtc/objc/RTCStatsReport.mm
index 8da4b46..98cf654 100644
--- a/app/webrtc/objc/RTCStatsReport.mm
+++ b/app/webrtc/objc/RTCStatsReport.mm
@@ -57,7 +57,7 @@
[NSMutableArray arrayWithCapacity:statsReport.values.size()];
webrtc::StatsReport::Values::const_iterator it = statsReport.values.begin();
for (; it != statsReport.values.end(); ++it) {
- RTCPair* pair = [[RTCPair alloc] initWithKey:@(it->name.c_str())
+ RTCPair* pair = [[RTCPair alloc] initWithKey:@(it->display_name())
value:@(it->value.c_str())];
[values addObject:pair];
}
diff --git a/app/webrtc/objc/RTCVideoCapturer.mm b/app/webrtc/objc/RTCVideoCapturer.mm
index d947f02..ea8e7ad 100644
--- a/app/webrtc/objc/RTCVideoCapturer.mm
+++ b/app/webrtc/objc/RTCVideoCapturer.mm
@@ -35,12 +35,12 @@
#include "talk/media/devices/devicemanager.h"
@implementation RTCVideoCapturer {
- talk_base::scoped_ptr<cricket::VideoCapturer> _capturer;
+ rtc::scoped_ptr<cricket::VideoCapturer> _capturer;
}
+ (RTCVideoCapturer*)capturerWithDeviceName:(NSString*)deviceName {
const std::string& device_name = std::string([deviceName UTF8String]);
- talk_base::scoped_ptr<cricket::DeviceManagerInterface> device_manager(
+ rtc::scoped_ptr<cricket::DeviceManagerInterface> device_manager(
cricket::DeviceManagerFactory::Create());
bool initialized = device_manager->Init();
NSAssert(initialized, @"DeviceManager::Init() failed");
@@ -49,7 +49,7 @@
LOG(LS_ERROR) << "GetVideoCaptureDevice failed";
return 0;
}
- talk_base::scoped_ptr<cricket::VideoCapturer> capturer(
+ rtc::scoped_ptr<cricket::VideoCapturer> capturer(
device_manager->CreateVideoCapturer(device));
RTCVideoCapturer* rtcCapturer =
[[RTCVideoCapturer alloc] initWithCapturer:capturer.release()];
diff --git a/app/webrtc/objc/RTCVideoRenderer.mm b/app/webrtc/objc/RTCVideoRenderer.mm
index 0704181..4cfe43a 100644
--- a/app/webrtc/objc/RTCVideoRenderer.mm
+++ b/app/webrtc/objc/RTCVideoRenderer.mm
@@ -30,10 +30,6 @@
#endif
#import "RTCVideoRenderer+Internal.h"
-
-#if TARGET_OS_IPHONE
-#import "RTCEAGLVideoView+Internal.h"
-#endif
#import "RTCI420Frame+Internal.h"
namespace webrtc {
@@ -61,10 +57,7 @@
}
@implementation RTCVideoRenderer {
- talk_base::scoped_ptr<webrtc::RTCVideoRendererAdapter> _adapter;
-#if TARGET_OS_IPHONE
- RTCEAGLVideoView* _videoView;
-#endif
+ rtc::scoped_ptr<webrtc::RTCVideoRendererAdapter> _adapter;
}
- (instancetype)initWithDelegate:(id<RTCVideoRendererDelegate>)delegate {
@@ -75,22 +68,6 @@
return self;
}
-#if TARGET_OS_IPHONE
-// TODO(tkchin): remove shim for deprecated method.
-- (instancetype)initWithView:(UIView*)view {
- if (self = [super init]) {
- _videoView = [[RTCEAGLVideoView alloc] initWithFrame:view.bounds];
- _videoView.autoresizingMask =
- UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
- _videoView.translatesAutoresizingMaskIntoConstraints = YES;
- [view addSubview:_videoView];
- self.delegate = _videoView;
- _adapter.reset(new webrtc::RTCVideoRendererAdapter(self));
- }
- return self;
-}
-#endif
-
@end
@implementation RTCVideoRenderer (Internal)
diff --git a/app/webrtc/objc/RTCVideoSource+Internal.h b/app/webrtc/objc/RTCVideoSource+Internal.h
index 1d3c4c9..962fa43 100644
--- a/app/webrtc/objc/RTCVideoSource+Internal.h
+++ b/app/webrtc/objc/RTCVideoSource+Internal.h
@@ -32,6 +32,6 @@
@interface RTCVideoSource (Internal)
@property(nonatomic, assign, readonly)
- talk_base::scoped_refptr<webrtc::VideoSourceInterface>videoSource;
+ rtc::scoped_refptr<webrtc::VideoSourceInterface>videoSource;
@end
diff --git a/app/webrtc/objc/RTCVideoSource.mm b/app/webrtc/objc/RTCVideoSource.mm
index b4554e0..f573309 100644
--- a/app/webrtc/objc/RTCVideoSource.mm
+++ b/app/webrtc/objc/RTCVideoSource.mm
@@ -29,15 +29,15 @@
#error "This file requires ARC support."
#endif
-#import "RTCVideoSource+Internal.h"
#import "RTCMediaSource+Internal.h"
+#import "RTCVideoSource+Internal.h"
@implementation RTCVideoSource
@end
@implementation RTCVideoSource (Internal)
-- (talk_base::scoped_refptr<webrtc::VideoSourceInterface>)videoSource {
+- (rtc::scoped_refptr<webrtc::VideoSourceInterface>)videoSource {
return static_cast<webrtc::VideoSourceInterface*>(self.mediaSource.get());
}
diff --git a/app/webrtc/objc/RTCVideoTrack+Internal.h b/app/webrtc/objc/RTCVideoTrack+Internal.h
index b5da54b..03c8f95 100644
--- a/app/webrtc/objc/RTCVideoTrack+Internal.h
+++ b/app/webrtc/objc/RTCVideoTrack+Internal.h
@@ -35,6 +35,6 @@
@interface RTCVideoTrack (Internal)
@property(nonatomic, assign, readonly)
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> videoTrack;
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> videoTrack;
@end
diff --git a/app/webrtc/objc/RTCVideoTrack.mm b/app/webrtc/objc/RTCVideoTrack.mm
index d6c8ed8..beebde0 100644
--- a/app/webrtc/objc/RTCVideoTrack.mm
+++ b/app/webrtc/objc/RTCVideoTrack.mm
@@ -39,7 +39,7 @@
}
- (id)initWithMediaTrack:
- (talk_base::scoped_refptr<webrtc::MediaStreamTrackInterface>)
+ (rtc::scoped_refptr<webrtc::MediaStreamTrackInterface>)
mediaTrack {
if (self = [super initWithMediaTrack:mediaTrack]) {
_rendererArray = [NSMutableArray array];
@@ -71,7 +71,7 @@
@implementation RTCVideoTrack (Internal)
-- (talk_base::scoped_refptr<webrtc::VideoTrackInterface>)videoTrack {
+- (rtc::scoped_refptr<webrtc::VideoTrackInterface>)videoTrack {
return static_cast<webrtc::VideoTrackInterface*>(self.mediaTrack.get());
}
diff --git a/app/webrtc/objc/public/RTCVideoRenderer.h b/app/webrtc/objc/public/RTCVideoRenderer.h
index f78746c..37977ce 100644
--- a/app/webrtc/objc/public/RTCVideoRenderer.h
+++ b/app/webrtc/objc/public/RTCVideoRenderer.h
@@ -55,12 +55,6 @@
// of frames.
- (instancetype)initWithDelegate:(id<RTCVideoRendererDelegate>)delegate;
-#if TARGET_OS_IPHONE
-// DEPRECATED. See https://code.google.com/p/webrtc/issues/detail?id=3341 for
-// details.
-- (instancetype)initWithView:(UIView*)view;
-#endif
-
#ifndef DOXYGEN_SHOULD_SKIP_THIS
// Disallow init and don't add to documentation
- (id)init __attribute__((
diff --git a/app/webrtc/objctests/RTCPeerConnectionTest.mm b/app/webrtc/objctests/RTCPeerConnectionTest.mm
index 7a178f3..909503a 100644
--- a/app/webrtc/objctests/RTCPeerConnectionTest.mm
+++ b/app/webrtc/objctests/RTCPeerConnectionTest.mm
@@ -39,8 +39,8 @@
#import "RTCVideoRenderer.h"
#import "RTCVideoTrack.h"
-#include "talk/base/gunit.h"
-#include "talk/base/ssladapter.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/ssladapter.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
@@ -299,7 +299,7 @@
// a TestBase since it's not.
TEST(RTCPeerConnectionTest, SessionTest) {
@autoreleasepool {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
// Since |factory| will own the signaling & worker threads, it's important
// that it outlive the created PeerConnections since they self-delete on the
// signaling thread, and if |factory| is freed first then a last refcount on
@@ -312,6 +312,6 @@
RTCPeerConnectionTest* pcTest = [[RTCPeerConnectionTest alloc] init];
[pcTest testCompleteSessionWithFactory:factory];
}
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
}
diff --git a/app/webrtc/objctests/mac/main.mm b/app/webrtc/objctests/mac/main.mm
index 4995b7f..7af1a2b 100644
--- a/app/webrtc/objctests/mac/main.mm
+++ b/app/webrtc/objctests/mac/main.mm
@@ -25,7 +25,7 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
+#include "webrtc/base/gunit.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
diff --git a/app/webrtc/peerconnection.cc b/app/webrtc/peerconnection.cc
index 0839977..d939f98 100644
--- a/app/webrtc/peerconnection.cc
+++ b/app/webrtc/peerconnection.cc
@@ -35,10 +35,11 @@
#include "talk/app/webrtc/mediaconstraintsinterface.h"
#include "talk/app/webrtc/mediastreamhandler.h"
#include "talk/app/webrtc/streamcollection.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/client/basicportallocator.h"
#include "talk/session/media/channelmanager.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/system_wrappers/interface/field_trial.h"
namespace {
@@ -74,22 +75,23 @@
MSG_GETSTATS,
};
-struct SetSessionDescriptionMsg : public talk_base::MessageData {
+struct SetSessionDescriptionMsg : public rtc::MessageData {
explicit SetSessionDescriptionMsg(
webrtc::SetSessionDescriptionObserver* observer)
: observer(observer) {
}
- talk_base::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
+ rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
std::string error;
};
-struct GetStatsMsg : public talk_base::MessageData {
- explicit GetStatsMsg(webrtc::StatsObserver* observer)
- : observer(observer) {
+struct GetStatsMsg : public rtc::MessageData {
+ GetStatsMsg(webrtc::StatsObserver* observer,
+ webrtc::MediaStreamTrackInterface* track)
+ : observer(observer), track(track) {
}
- webrtc::StatsReports reports;
- talk_base::scoped_refptr<webrtc::StatsObserver> observer;
+ rtc::scoped_refptr<webrtc::StatsObserver> observer;
+ rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
};
// |in_str| should be of format
@@ -136,7 +138,7 @@
*host = in_str.substr(1, closebracket - 1);
std::string::size_type colonpos = in_str.find(':', closebracket);
if (std::string::npos != colonpos) {
- if (!talk_base::FromString(
+ if (!rtc::FromString(
in_str.substr(closebracket + 2, std::string::npos), port)) {
return false;
}
@@ -148,7 +150,7 @@
std::string::size_type colonpos = in_str.find(':');
if (std::string::npos != colonpos) {
*host = in_str.substr(0, colonpos);
- if (!talk_base::FromString(
+ if (!rtc::FromString(
in_str.substr(colonpos + 1, std::string::npos), port)) {
return false;
}
@@ -189,12 +191,12 @@
}
std::vector<std::string> tokens;
std::string turn_transport_type = kUdpTransportType;
- talk_base::tokenize(server.uri, '?', &tokens);
+ rtc::tokenize(server.uri, '?', &tokens);
std::string uri_without_transport = tokens[0];
// Let's look into transport= param, if it exists.
if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
std::string uri_transport_param = tokens[1];
- talk_base::tokenize(uri_transport_param, '=', &tokens);
+ rtc::tokenize(uri_transport_param, '=', &tokens);
if (tokens[0] == kTransport) {
// As per above grammar transport param will be consist of lower case
// letters.
@@ -218,10 +220,10 @@
// Let's break hostname.
tokens.clear();
- talk_base::tokenize(hoststring, '@', &tokens);
+ rtc::tokenize(hoststring, '@', &tokens);
hoststring = tokens[0];
if (tokens.size() == kTurnHostTokensNum) {
- server.username = talk_base::s_url_decode(tokens[0]);
+ server.username = rtc::s_url_decode(tokens[0]);
hoststring = tokens[1];
}
@@ -253,9 +255,9 @@
if (server.username.empty()) {
// Turn url example from the spec |url:"turn:user@turn.example.org"|.
std::vector<std::string> turn_tokens;
- talk_base::tokenize(address, '@', &turn_tokens);
+ rtc::tokenize(address, '@', &turn_tokens);
if (turn_tokens.size() == kTurnHostTokensNum) {
- server.username = talk_base::s_url_decode(turn_tokens[0]);
+ server.username = rtc::s_url_decode(turn_tokens[0]);
address = turn_tokens[1];
}
}
@@ -352,10 +354,14 @@
cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET;
bool value;
+ // If IPv6 flag was specified, we'll not override it by experiment.
if (FindConstraint(
- constraints,
- MediaConstraintsInterface::kEnableIPv6,
- &value, NULL) && value) {
+ constraints, MediaConstraintsInterface::kEnableIPv6, &value, NULL)) {
+ if (value) {
+ portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_IPV6;
+ }
+ } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default") ==
+ "Enabled") {
portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_IPV6;
}
@@ -373,7 +379,7 @@
mediastream_signaling_.get()));
stream_handler_container_.reset(new MediaStreamHandlerContainer(
session_.get(), session_.get()));
- stats_.set_session(session_.get());
+ stats_.reset(new StatsCollector(session_.get()));
// Initialize the WebRtcSession. It creates transport channels etc.
if (!session_->Initialize(factory_->options(), constraints,
@@ -387,12 +393,12 @@
return true;
}
-talk_base::scoped_refptr<StreamCollectionInterface>
+rtc::scoped_refptr<StreamCollectionInterface>
PeerConnection::local_streams() {
return mediastream_signaling_->local_streams();
}
-talk_base::scoped_refptr<StreamCollectionInterface>
+rtc::scoped_refptr<StreamCollectionInterface>
PeerConnection::remote_streams() {
return mediastream_signaling_->remote_streams();
}
@@ -410,7 +416,7 @@
if (!mediastream_signaling_->AddLocalStream(local_stream)) {
return false;
}
- stats_.AddStream(local_stream);
+ stats_->AddStream(local_stream);
observer_->OnRenegotiationNeeded();
return true;
}
@@ -423,7 +429,7 @@
observer_->OnRenegotiationNeeded();
}
-talk_base::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
+rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
AudioTrackInterface* track) {
if (!track) {
LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
@@ -434,7 +440,7 @@
return NULL;
}
- talk_base::scoped_refptr<DtmfSenderInterface> sender(
+ rtc::scoped_refptr<DtmfSenderInterface> sender(
DtmfSender::Create(track, signaling_thread(), session_.get()));
if (!sender.get()) {
LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
@@ -446,17 +452,15 @@
bool PeerConnection::GetStats(StatsObserver* observer,
MediaStreamTrackInterface* track,
StatsOutputLevel level) {
+ ASSERT(signaling_thread()->IsCurrent());
if (!VERIFY(observer != NULL)) {
LOG(LS_ERROR) << "GetStats - observer is NULL.";
return false;
}
- stats_.UpdateStats(level);
- talk_base::scoped_ptr<GetStatsMsg> msg(new GetStatsMsg(observer));
- if (!stats_.GetStats(track, &(msg->reports))) {
- return false;
- }
- signaling_thread()->Post(this, MSG_GETSTATS, msg.release());
+ stats_->UpdateStats(level);
+ signaling_thread()->Post(this, MSG_GETSTATS,
+ new GetStatsMsg(observer, track));
return true;
}
@@ -478,17 +482,17 @@
return ice_gathering_state_;
}
-talk_base::scoped_refptr<DataChannelInterface>
+rtc::scoped_refptr<DataChannelInterface>
PeerConnection::CreateDataChannel(
const std::string& label,
const DataChannelInit* config) {
bool first_datachannel = !mediastream_signaling_->HasDataChannels();
- talk_base::scoped_ptr<InternalDataChannelInit> internal_config;
+ rtc::scoped_ptr<InternalDataChannelInit> internal_config;
if (config) {
internal_config.reset(new InternalDataChannelInit(*config));
}
- talk_base::scoped_refptr<DataChannelInterface> channel(
+ rtc::scoped_refptr<DataChannelInterface> channel(
session_->CreateDataChannel(label, internal_config.get()));
if (!channel.get())
return NULL;
@@ -508,7 +512,58 @@
LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
return;
}
- session_->CreateOffer(observer, constraints);
+ RTCOfferAnswerOptions options;
+
+ bool value;
+ size_t mandatory_constraints = 0;
+
+ if (FindConstraint(constraints,
+ MediaConstraintsInterface::kOfferToReceiveAudio,
+ &value,
+ &mandatory_constraints)) {
+ options.offer_to_receive_audio =
+ value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
+ }
+
+ if (FindConstraint(constraints,
+ MediaConstraintsInterface::kOfferToReceiveVideo,
+ &value,
+ &mandatory_constraints)) {
+ options.offer_to_receive_video =
+ value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
+ }
+
+ if (FindConstraint(constraints,
+ MediaConstraintsInterface::kVoiceActivityDetection,
+ &value,
+ &mandatory_constraints)) {
+ options.voice_activity_detection = value;
+ }
+
+ if (FindConstraint(constraints,
+ MediaConstraintsInterface::kIceRestart,
+ &value,
+ &mandatory_constraints)) {
+ options.ice_restart = value;
+ }
+
+ if (FindConstraint(constraints,
+ MediaConstraintsInterface::kUseRtpMux,
+ &value,
+ &mandatory_constraints)) {
+ options.use_rtp_mux = value;
+ }
+
+ CreateOffer(observer, options);
+}
+
+void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
+ const RTCOfferAnswerOptions& options) {
+ if (!VERIFY(observer != NULL)) {
+ LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
+ return;
+ }
+ session_->CreateOffer(observer, options);
}
void PeerConnection::CreateAnswer(
@@ -534,7 +589,7 @@
}
// Update stats here so that we have the most recent stats for tracks and
// streams that might be removed by updating the session description.
- stats_.UpdateStats(kStatsOutputLevelStandard);
+ stats_->UpdateStats(kStatsOutputLevelStandard);
std::string error;
if (!session_->SetLocalDescription(desc, &error)) {
PostSetSessionDescriptionFailure(observer, error);
@@ -557,7 +612,7 @@
}
// Update stats here so that we have the most recent stats for tracks and
// streams that might be removed by updating the session description.
- stats_.UpdateStats(kStatsOutputLevelStandard);
+ stats_->UpdateStats(kStatsOutputLevelStandard);
std::string error;
if (!session_->SetRemoteDescription(desc, &error)) {
PostSetSessionDescriptionFailure(observer, error);
@@ -588,13 +643,13 @@
return false;
}
- std::vector<talk_base::SocketAddress> stun_hosts;
+ std::vector<rtc::SocketAddress> stun_hosts;
typedef std::vector<StunConfiguration>::const_iterator StunIt;
for (StunIt stun_it = stuns.begin(); stun_it != stuns.end(); ++stun_it) {
stun_hosts.push_back(stun_it->server);
}
- talk_base::SocketAddress stun_addr;
+ rtc::SocketAddress stun_addr;
if (!stun_hosts.empty()) {
stun_addr = stun_hosts.front();
LOG(LS_INFO) << "UpdateIce: StunServer Address: " << stun_addr.ToString();
@@ -618,7 +673,7 @@
}
}
}
- return session_->UpdateIce(config.type);
+ return session_->SetIceTransports(config.type);
}
bool PeerConnection::AddIceCandidate(
@@ -649,7 +704,7 @@
void PeerConnection::Close() {
// Update stats here so that we have the most recent stats for tracks and
// streams before the channels are closed.
- stats_.UpdateStats(kStatsOutputLevelStandard);
+ stats_->UpdateStats(kStatsOutputLevelStandard);
session_->Terminate();
}
@@ -684,7 +739,7 @@
}
}
-void PeerConnection::OnMessage(talk_base::Message* msg) {
+void PeerConnection::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
SetSessionDescriptionMsg* param =
@@ -702,7 +757,9 @@
}
case MSG_GETSTATS: {
GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
- param->observer->OnComplete(param->reports);
+ StatsReports reports;
+ stats_->GetStats(param->track, &reports);
+ param->observer->OnComplete(reports);
delete param;
break;
}
@@ -713,7 +770,7 @@
}
void PeerConnection::OnAddRemoteStream(MediaStreamInterface* stream) {
- stats_.AddStream(stream);
+ stats_->AddStream(stream);
observer_->OnAddStream(stream);
}
@@ -754,7 +811,7 @@
AudioTrackInterface* audio_track,
uint32 ssrc) {
stream_handler_container_->AddLocalAudioTrack(stream, audio_track, ssrc);
- stats_.AddLocalAudioTrack(audio_track, ssrc);
+ stats_->AddLocalAudioTrack(audio_track, ssrc);
}
void PeerConnection::OnAddLocalVideoTrack(MediaStreamInterface* stream,
VideoTrackInterface* video_track,
@@ -766,7 +823,7 @@
AudioTrackInterface* audio_track,
uint32 ssrc) {
stream_handler_container_->RemoveLocalTrack(stream, audio_track);
- stats_.RemoveLocalAudioTrack(audio_track, ssrc);
+ stats_->RemoveLocalAudioTrack(audio_track, ssrc);
}
void PeerConnection::OnRemoveLocalVideoTrack(MediaStreamInterface* stream,
diff --git a/app/webrtc/peerconnection.h b/app/webrtc/peerconnection.h
index 4a428ef..fb03802 100644
--- a/app/webrtc/peerconnection.h
+++ b/app/webrtc/peerconnection.h
@@ -31,12 +31,12 @@
#include <string>
#include "talk/app/webrtc/mediastreamsignaling.h"
-#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/peerconnectionfactory.h"
+#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/statscollector.h"
#include "talk/app/webrtc/streamcollection.h"
#include "talk/app/webrtc/webrtcsession.h"
-#include "talk/base/scoped_ptr.h"
+#include "webrtc/base/scoped_ptr.h"
namespace webrtc {
class MediaStreamHandlerContainer;
@@ -52,7 +52,7 @@
class PeerConnection : public PeerConnectionInterface,
public MediaStreamSignalingObserver,
public IceObserver,
- public talk_base::MessageHandler,
+ public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
explicit PeerConnection(PeerConnectionFactory* factory);
@@ -63,16 +63,16 @@
PortAllocatorFactoryInterface* allocator_factory,
DTLSIdentityServiceInterface* dtls_identity_service,
PeerConnectionObserver* observer);
- virtual talk_base::scoped_refptr<StreamCollectionInterface> local_streams();
- virtual talk_base::scoped_refptr<StreamCollectionInterface> remote_streams();
+ virtual rtc::scoped_refptr<StreamCollectionInterface> local_streams();
+ virtual rtc::scoped_refptr<StreamCollectionInterface> remote_streams();
virtual bool AddStream(MediaStreamInterface* local_stream,
const MediaConstraintsInterface* constraints);
virtual void RemoveStream(MediaStreamInterface* local_stream);
- virtual talk_base::scoped_refptr<DtmfSenderInterface> CreateDtmfSender(
+ virtual rtc::scoped_refptr<DtmfSenderInterface> CreateDtmfSender(
AudioTrackInterface* track);
- virtual talk_base::scoped_refptr<DataChannelInterface> CreateDataChannel(
+ virtual rtc::scoped_refptr<DataChannelInterface> CreateDataChannel(
const std::string& label,
const DataChannelInit* config);
virtual bool GetStats(StatsObserver* observer,
@@ -92,6 +92,8 @@
// JSEP01
virtual void CreateOffer(CreateSessionDescriptionObserver* observer,
const MediaConstraintsInterface* constraints);
+ virtual void CreateOffer(CreateSessionDescriptionObserver* observer,
+ const RTCOfferAnswerOptions& options);
virtual void CreateAnswer(CreateSessionDescriptionObserver* observer,
const MediaConstraintsInterface* constraints);
virtual void SetLocalDescription(SetSessionDescriptionObserver* observer,
@@ -114,7 +116,7 @@
private:
// Implements MessageHandler.
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
// Implements MediaStreamSignalingObserver.
virtual void OnAddRemoteStream(MediaStreamInterface* stream) OVERRIDE;
@@ -166,7 +168,7 @@
DTLSIdentityServiceInterface* dtls_identity_service,
PeerConnectionObserver* observer);
- talk_base::Thread* signaling_thread() const {
+ rtc::Thread* signaling_thread() const {
return factory_->signaling_thread();
}
@@ -183,7 +185,7 @@
// However, since the reference counting is done in the
// PeerConnectionFactoryInteface all instances created using the raw pointer
// will refer to the same reference count.
- talk_base::scoped_refptr<PeerConnectionFactory> factory_;
+ rtc::scoped_refptr<PeerConnectionFactory> factory_;
PeerConnectionObserver* observer_;
UMAObserver* uma_observer_;
SignalingState signaling_state_;
@@ -192,11 +194,11 @@
IceConnectionState ice_connection_state_;
IceGatheringState ice_gathering_state_;
- talk_base::scoped_ptr<cricket::PortAllocator> port_allocator_;
- talk_base::scoped_ptr<WebRtcSession> session_;
- talk_base::scoped_ptr<MediaStreamSignaling> mediastream_signaling_;
- talk_base::scoped_ptr<MediaStreamHandlerContainer> stream_handler_container_;
- StatsCollector stats_;
+ rtc::scoped_ptr<cricket::PortAllocator> port_allocator_;
+ rtc::scoped_ptr<WebRtcSession> session_;
+ rtc::scoped_ptr<MediaStreamSignaling> mediastream_signaling_;
+ rtc::scoped_ptr<MediaStreamHandlerContainer> stream_handler_container_;
+ rtc::scoped_ptr<StatsCollector> stats_;
};
} // namespace webrtc
diff --git a/app/webrtc/peerconnection_unittest.cc b/app/webrtc/peerconnection_unittest.cc
index 0c39297..977fc11 100644
--- a/app/webrtc/peerconnection_unittest.cc
+++ b/app/webrtc/peerconnection_unittest.cc
@@ -41,19 +41,19 @@
#include "talk/app/webrtc/test/fakeaudiocapturemodule.h"
#include "talk/app/webrtc/test/fakeconstraints.h"
#include "talk/app/webrtc/test/fakedtlsidentityservice.h"
-#include "talk/app/webrtc/test/fakevideotrackrenderer.h"
#include "talk/app/webrtc/test/fakeperiodicvideocapturer.h"
+#include "talk/app/webrtc/test/fakevideotrackrenderer.h"
#include "talk/app/webrtc/test/mockpeerconnectionobservers.h"
#include "talk/app/webrtc/videosourceinterface.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/thread.h"
#include "talk/media/webrtc/fakewebrtcvideoengine.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/thread.h"
#define MAYBE_SKIP_TEST(feature) \
if (!(feature())) { \
@@ -90,6 +90,7 @@
// warnings.
#if !defined(THREAD_SANITIZER)
static const int kMaxWaitForStatsMs = 3000;
+static const int kMaxWaitForRembMs = 5000;
#endif
static const int kMaxWaitForFramesMs = 10000;
static const int kEndAudioFrameCount = 3;
@@ -154,28 +155,28 @@
}
void AddMediaStream(bool audio, bool video) {
- std::string label = kStreamLabelBase +
- talk_base::ToString<int>(
+ std::string stream_label = kStreamLabelBase +
+ rtc::ToString<int>(
static_cast<int>(peer_connection_->local_streams()->count()));
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream =
- peer_connection_factory_->CreateLocalMediaStream(label);
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
+ peer_connection_factory_->CreateLocalMediaStream(stream_label);
if (audio && can_receive_audio()) {
FakeConstraints constraints;
// Disable highpass filter so that we can get all the test audio frames.
constraints.AddMandatory(
MediaConstraintsInterface::kHighpassFilter, false);
- talk_base::scoped_refptr<webrtc::AudioSourceInterface> source =
+ rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
peer_connection_factory_->CreateAudioSource(&constraints);
// TODO(perkj): Test audio source when it is implemented. Currently audio
// always use the default input.
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
- peer_connection_factory_->CreateAudioTrack(kAudioTrackLabelBase,
- source));
+ std::string label = stream_label + kAudioTrackLabelBase;
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
+ peer_connection_factory_->CreateAudioTrack(label, source));
stream->AddTrack(audio_track);
}
if (video && can_receive_video()) {
- stream->AddTrack(CreateLocalVideoTrack(label));
+ stream->AddTrack(CreateLocalVideoTrack(stream_label));
}
EXPECT_TRUE(peer_connection_->AddStream(stream, NULL));
@@ -236,13 +237,13 @@
}
// Verify the CreateDtmfSender interface
void VerifyDtmf() {
- talk_base::scoped_ptr<DummyDtmfObserver> observer(new DummyDtmfObserver());
- talk_base::scoped_refptr<DtmfSenderInterface> dtmf_sender;
+ rtc::scoped_ptr<DummyDtmfObserver> observer(new DummyDtmfObserver());
+ rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender;
// We can't create a DTMF sender with an invalid audio track or a non local
// track.
EXPECT_TRUE(peer_connection_->CreateDtmfSender(NULL) == NULL);
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> non_localtrack(
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> non_localtrack(
peer_connection_factory_->CreateAudioTrack("dummy_track",
NULL));
EXPECT_TRUE(peer_connection_->CreateDtmfSender(non_localtrack) == NULL);
@@ -333,8 +334,8 @@
}
int GetAudioOutputLevelStats(webrtc::MediaStreamTrackInterface* track) {
- talk_base::scoped_refptr<MockStatsObserver>
- observer(new talk_base::RefCountedObject<MockStatsObserver>());
+ rtc::scoped_refptr<MockStatsObserver>
+ observer(new rtc::RefCountedObject<MockStatsObserver>());
EXPECT_TRUE(peer_connection_->GetStats(
observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
@@ -342,8 +343,8 @@
}
int GetAudioInputLevelStats() {
- talk_base::scoped_refptr<MockStatsObserver>
- observer(new talk_base::RefCountedObject<MockStatsObserver>());
+ rtc::scoped_refptr<MockStatsObserver>
+ observer(new rtc::RefCountedObject<MockStatsObserver>());
EXPECT_TRUE(peer_connection_->GetStats(
observer, NULL, PeerConnectionInterface::kStatsOutputLevelStandard));
EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
@@ -351,8 +352,8 @@
}
int GetBytesReceivedStats(webrtc::MediaStreamTrackInterface* track) {
- talk_base::scoped_refptr<MockStatsObserver>
- observer(new talk_base::RefCountedObject<MockStatsObserver>());
+ rtc::scoped_refptr<MockStatsObserver>
+ observer(new rtc::RefCountedObject<MockStatsObserver>());
EXPECT_TRUE(peer_connection_->GetStats(
observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
@@ -360,14 +361,24 @@
}
int GetBytesSentStats(webrtc::MediaStreamTrackInterface* track) {
- talk_base::scoped_refptr<MockStatsObserver>
- observer(new talk_base::RefCountedObject<MockStatsObserver>());
+ rtc::scoped_refptr<MockStatsObserver>
+ observer(new rtc::RefCountedObject<MockStatsObserver>());
EXPECT_TRUE(peer_connection_->GetStats(
observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
return observer->BytesSent();
}
+ int GetAvailableReceivedBandwidthStats() {
+ rtc::scoped_refptr<MockStatsObserver>
+ observer(new rtc::RefCountedObject<MockStatsObserver>());
+ EXPECT_TRUE(peer_connection_->GetStats(
+ observer, NULL, PeerConnectionInterface::kStatsOutputLevelStandard));
+ EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
+ int bw = observer->AvailableReceiveBandwidth();
+ return bw;
+ }
+
int rendered_width() {
EXPECT_FALSE(fake_video_renderers_.empty());
return fake_video_renderers_.empty() ? 1 :
@@ -447,6 +458,12 @@
webrtc::PeerConnectionInterface* pc() {
return peer_connection_.get();
}
+ void StopVideoCapturers() {
+ for (std::vector<cricket::VideoCapturer*>::iterator it =
+ video_capturers_.begin(); it != video_capturers_.end(); ++it) {
+ (*it)->Stop();
+ }
+ }
protected:
explicit PeerConnectionTestClientBase(const std::string& id)
@@ -464,9 +481,8 @@
if (!allocator_factory_) {
return false;
}
- audio_thread_.Start();
fake_audio_capture_module_ = FakeAudioCaptureModule::Create(
- &audio_thread_);
+ rtc::Thread::Current());
if (fake_audio_capture_module_ == NULL) {
return false;
@@ -474,7 +490,7 @@
fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
- talk_base::Thread::Current(), talk_base::Thread::Current(),
+ rtc::Thread::Current(), rtc::Thread::Current(),
fake_audio_capture_module_, fake_video_encoder_factory_,
fake_video_decoder_factory_);
if (!peer_connection_factory_) {
@@ -484,7 +500,7 @@
constraints);
return peer_connection_.get() != NULL;
}
- virtual talk_base::scoped_refptr<webrtc::PeerConnectionInterface>
+ virtual rtc::scoped_refptr<webrtc::PeerConnectionInterface>
CreatePeerConnection(webrtc::PortAllocatorFactoryInterface* factory,
const MediaConstraintsInterface* constraints) = 0;
MessageReceiver* signaling_message_receiver() {
@@ -523,32 +539,28 @@
std::vector<std::string> tones_;
};
- talk_base::scoped_refptr<webrtc::VideoTrackInterface>
+ rtc::scoped_refptr<webrtc::VideoTrackInterface>
CreateLocalVideoTrack(const std::string stream_label) {
// Set max frame rate to 10fps to reduce the risk of the tests to be flaky.
FakeConstraints source_constraints = video_constraints_;
source_constraints.SetMandatoryMaxFrameRate(10);
- talk_base::scoped_refptr<webrtc::VideoSourceInterface> source =
+ cricket::FakeVideoCapturer* fake_capturer =
+ new webrtc::FakePeriodicVideoCapturer();
+ video_capturers_.push_back(fake_capturer);
+ rtc::scoped_refptr<webrtc::VideoSourceInterface> source =
peer_connection_factory_->CreateVideoSource(
- new webrtc::FakePeriodicVideoCapturer(),
- &source_constraints);
+ fake_capturer, &source_constraints);
std::string label = stream_label + kVideoTrackLabelBase;
return peer_connection_factory_->CreateVideoTrack(label, source);
}
std::string id_;
- // Separate thread for executing |fake_audio_capture_module_| tasks. Audio
- // processing must not be performed on the same thread as signaling due to
- // signaling time constraints and relative complexity of the audio pipeline.
- // This is consistent with the video pipeline that us a a separate thread for
- // encoding and decoding.
- talk_base::Thread audio_thread_;
- talk_base::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
+ rtc::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
allocator_factory_;
- talk_base::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
- talk_base::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
+ rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
peer_connection_factory_;
typedef std::pair<std::string, std::string> IceUfragPwdPair;
@@ -556,7 +568,7 @@
bool expect_ice_restart_;
// Needed to keep track of number of frames send.
- talk_base::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
+ rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
// Needed to keep track of number of frames received.
typedef std::map<std::string, webrtc::FakeVideoTrackRenderer*> RenderMap;
RenderMap fake_video_renderers_;
@@ -569,6 +581,10 @@
// For remote peer communication.
MessageReceiver* signaling_message_receiver_;
+
+ // Store references to the video capturers we've created, so that we can stop
+ // them, if required.
+ std::vector<cricket::VideoCapturer*> video_capturers_;
};
class JsepTestClient
@@ -590,8 +606,8 @@
Negotiate(true, true);
}
virtual void Negotiate(bool audio, bool video) {
- talk_base::scoped_ptr<SessionDescriptionInterface> offer;
- EXPECT_TRUE(DoCreateOffer(offer.use()));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer;
+ ASSERT_TRUE(DoCreateOffer(offer.use()));
if (offer->description()->GetContentByName("audio")) {
offer->description()->GetContentByName("audio")->rejected = !audio;
@@ -621,7 +637,7 @@
int sdp_mline_index,
const std::string& msg) {
LOG(INFO) << id() << "ReceiveIceMessage";
- talk_base::scoped_ptr<webrtc::IceCandidateInterface> candidate(
+ rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(
webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, NULL));
EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
}
@@ -723,7 +739,7 @@
remove_sdes_(false) {
}
- virtual talk_base::scoped_refptr<webrtc::PeerConnectionInterface>
+ virtual rtc::scoped_refptr<webrtc::PeerConnectionInterface>
CreatePeerConnection(webrtc::PortAllocatorFactoryInterface* factory,
const MediaConstraintsInterface* constraints) {
// CreatePeerConnection with IceServers.
@@ -733,7 +749,7 @@
ice_servers.push_back(ice_server);
FakeIdentityService* dtls_service =
- talk_base::SSLStreamAdapter::HaveDtlsSrtp() ?
+ rtc::SSLStreamAdapter::HaveDtlsSrtp() ?
new FakeIdentityService() : NULL;
return peer_connection_factory()->CreatePeerConnection(
ice_servers, constraints, factory, dtls_service, this);
@@ -745,10 +761,10 @@
// If we are not sending any streams ourselves it is time to add some.
AddMediaStream(true, true);
}
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription("offer", msg, NULL));
EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
- talk_base::scoped_ptr<SessionDescriptionInterface> answer;
+ rtc::scoped_ptr<SessionDescriptionInterface> answer;
EXPECT_TRUE(DoCreateAnswer(answer.use()));
std::string sdp;
EXPECT_TRUE(answer->ToString(&sdp));
@@ -761,15 +777,15 @@
void HandleIncomingAnswer(const std::string& msg) {
LOG(INFO) << id() << "HandleIncomingAnswer";
- talk_base::scoped_ptr<SessionDescriptionInterface> desc(
+ rtc::scoped_ptr<SessionDescriptionInterface> desc(
webrtc::CreateSessionDescription("answer", msg, NULL));
EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
}
bool DoCreateOfferAnswer(SessionDescriptionInterface** desc,
bool offer) {
- talk_base::scoped_refptr<MockCreateSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<MockCreateSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
MockCreateSessionDescriptionObserver>());
if (offer) {
pc()->CreateOffer(observer, &session_description_constraints_);
@@ -793,8 +809,8 @@
}
bool DoSetLocalDescription(SessionDescriptionInterface* desc) {
- talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<MockSetSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
MockSetSessionDescriptionObserver>());
LOG(INFO) << id() << "SetLocalDescription ";
pc()->SetLocalDescription(observer, desc);
@@ -802,7 +818,7 @@
// EXPECT_TRUE_WAIT, local ice candidates might be sent to the remote peer
// before the offer which is an error.
// The reason is that EXPECT_TRUE_WAIT uses
- // talk_base::Thread::Current()->ProcessMessages(1);
+ // rtc::Thread::Current()->ProcessMessages(1);
// ProcessMessages waits at least 1ms but processes all messages before
// returning. Since this test is synchronous and send messages to the remote
// peer whenever a callback is invoked, this can lead to messages being
@@ -814,8 +830,8 @@
}
bool DoSetRemoteDescription(SessionDescriptionInterface* desc) {
- talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<MockSetSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
MockSetSessionDescriptionObserver>());
LOG(INFO) << id() << "SetRemoteDescription ";
pc()->SetRemoteDescription(observer, desc);
@@ -847,8 +863,8 @@
bool remove_bundle_; // True if bundle should be removed in received SDP.
bool remove_sdes_; // True if a=crypto should be removed in received SDP.
- talk_base::scoped_refptr<DataChannelInterface> data_channel_;
- talk_base::scoped_ptr<MockDataChannelObserver> data_observer_;
+ rtc::scoped_refptr<DataChannelInterface> data_channel_;
+ rtc::scoped_ptr<MockDataChannelObserver> data_observer_;
};
template <typename SignalingClass>
@@ -904,7 +920,7 @@
}
P2PTestConductor() {
- talk_base::InitializeSSL(NULL);
+ rtc::InitializeSSL(NULL);
}
~P2PTestConductor() {
if (initiating_client_) {
@@ -913,7 +929,7 @@
if (receiving_client_) {
receiving_client_->set_signaling_message_receiver(NULL);
}
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
bool CreateTestClients() {
@@ -1019,12 +1035,36 @@
}
}
+ // Wait until 'size' bytes of audio has been seen by the receiver, on the
+ // first audio stream.
+ void WaitForAudioData(int size) {
+ const int kMaxWaitForAudioDataMs = 10000;
+
+ StreamCollectionInterface* local_streams =
+ initializing_client()->local_streams();
+ ASSERT_GT(local_streams->count(), 0u);
+ ASSERT_GT(local_streams->at(0)->GetAudioTracks().size(), 0u);
+ MediaStreamTrackInterface* local_audio_track =
+ local_streams->at(0)->GetAudioTracks()[0];
+
+ // Wait until *any* audio has been received.
+ EXPECT_TRUE_WAIT(
+ receiving_client()->GetBytesReceivedStats(local_audio_track) > 0,
+ kMaxWaitForAudioDataMs);
+
+ // Wait until 'size' number of bytes have been received.
+ size += receiving_client()->GetBytesReceivedStats(local_audio_track);
+ EXPECT_TRUE_WAIT(
+ receiving_client()->GetBytesReceivedStats(local_audio_track) > size,
+ kMaxWaitForAudioDataMs);
+ }
+
SignalingClass* initializing_client() { return initiating_client_.get(); }
SignalingClass* receiving_client() { return receiving_client_.get(); }
private:
- talk_base::scoped_ptr<SignalingClass> initiating_client_;
- talk_base::scoped_ptr<SignalingClass> receiving_client_;
+ rtc::scoped_ptr<SignalingClass> initiating_client_;
+ rtc::scoped_ptr<SignalingClass> receiving_client_;
};
typedef P2PTestConductor<JsepTestClient> JsepPeerConnectionP2PTestClient;
@@ -1081,7 +1121,7 @@
// This test sets up a call between two endpoints that are configured to use
// DTLS key agreement. As a result, DTLS is negotiated and used for transport.
TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtls) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
FakeConstraints setup_constraints;
setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
true);
@@ -1093,7 +1133,7 @@
// This test sets up a audio call initially and then upgrades to audio/video,
// using DTLS.
TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtlsRenegotiate) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
FakeConstraints setup_constraints;
setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
true);
@@ -1108,7 +1148,7 @@
// DTLS key agreement. The offerer don't support SDES. As a result, DTLS is
// negotiated and used for transport.
TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestOfferDtlsButNotSdes) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
FakeConstraints setup_constraints;
setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
true);
@@ -1320,7 +1360,7 @@
// Wait a while to allow the sent data to arrive before an observer is
// registered..
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
MockDataChannelObserver new_observer(receiving_client()->data_channel());
EXPECT_EQ_WAIT(data, new_observer.last_message(), kMaxWaitMs);
@@ -1367,7 +1407,7 @@
// negotiation is completed without error.
#ifdef HAVE_SCTP
TEST_F(JsepPeerConnectionP2PTestClient, CreateOfferWithSctpDataChannel) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
FakeConstraints constraints;
constraints.SetMandatory(
MediaConstraintsInterface::kEnableDtlsSrtp, true);
@@ -1438,4 +1478,69 @@
EnableVideoDecoderFactory();
LocalP2PTest();
}
+
+// Test receive bandwidth stats with only audio enabled at receiver.
+TEST_F(JsepPeerConnectionP2PTestClient, ReceivedBweStatsAudio) {
+ ASSERT_TRUE(CreateTestClients());
+ receiving_client()->SetReceiveAudioVideo(true, false);
+ LocalP2PTest();
+
+ // Wait until we have received some audio data. Following REMB shoud be zero.
+ WaitForAudioData(10000);
+ EXPECT_EQ_WAIT(
+ receiving_client()->GetAvailableReceivedBandwidthStats(), 0,
+ kMaxWaitForRembMs);
+}
+
+// Test receive bandwidth stats with combined BWE.
+TEST_F(JsepPeerConnectionP2PTestClient, ReceivedBweStatsCombined) {
+ FakeConstraints setup_constraints;
+ setup_constraints.AddOptional(
+ MediaConstraintsInterface::kCombinedAudioVideoBwe, true);
+ ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
+ initializing_client()->AddMediaStream(true, true);
+ initializing_client()->AddMediaStream(false, true);
+ initializing_client()->AddMediaStream(false, true);
+ initializing_client()->AddMediaStream(false, true);
+ LocalP2PTest();
+
+ // Run until a non-zero bw is reported.
+ EXPECT_TRUE_WAIT(receiving_client()->GetAvailableReceivedBandwidthStats() > 0,
+ kMaxWaitForRembMs);
+
+ // Halt video capturers, then run until we have gotten some audio. Following
+ // REMB should be non-zero.
+ initializing_client()->StopVideoCapturers();
+ WaitForAudioData(10000);
+ EXPECT_TRUE_WAIT(
+ receiving_client()->GetAvailableReceivedBandwidthStats() > 0,
+ kMaxWaitForRembMs);
+}
+
+// Test receive bandwidth stats with 1 video, 3 audio streams but no combined
+// BWE.
+TEST_F(JsepPeerConnectionP2PTestClient, ReceivedBweStatsNotCombined) {
+ FakeConstraints setup_constraints;
+ setup_constraints.AddOptional(
+ MediaConstraintsInterface::kCombinedAudioVideoBwe, false);
+ ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
+ initializing_client()->AddMediaStream(true, true);
+ initializing_client()->AddMediaStream(false, true);
+ initializing_client()->AddMediaStream(false, true);
+ initializing_client()->AddMediaStream(false, true);
+ LocalP2PTest();
+
+ // Run until a non-zero bw is reported.
+ EXPECT_TRUE_WAIT(receiving_client()->GetAvailableReceivedBandwidthStats() > 0,
+ kMaxWaitForRembMs);
+
+ // Halt video capturers, then run until we have gotten some audio. Following
+ // REMB should be zero.
+ initializing_client()->StopVideoCapturers();
+ WaitForAudioData(10000);
+ EXPECT_EQ_WAIT(
+ receiving_client()->GetAvailableReceivedBandwidthStats(), 0,
+ kMaxWaitForRembMs);
+}
+
#endif // if !defined(THREAD_SANITIZER)
diff --git a/app/webrtc/peerconnectionendtoend_unittest.cc b/app/webrtc/peerconnectionendtoend_unittest.cc
index f701e06..8984781 100644
--- a/app/webrtc/peerconnectionendtoend_unittest.cc
+++ b/app/webrtc/peerconnectionendtoend_unittest.cc
@@ -27,12 +27,12 @@
#include "talk/app/webrtc/test/peerconnectiontestwrapper.h"
#include "talk/app/webrtc/test/mockpeerconnectionobservers.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
#define MAYBE_SKIP_TEST(feature) \
if (!(feature())) { \
@@ -68,14 +68,14 @@
const std::string& newlines,
std::string* message) {
const std::string tmp = line + newlines;
- talk_base::replace_substrs(line.c_str(), line.length(),
+ rtc::replace_substrs(line.c_str(), line.length(),
tmp.c_str(), tmp.length(), message);
}
void Replace(const std::string& line,
const std::string& newlines,
std::string* message) {
- talk_base::replace_substrs(line.c_str(), line.length(),
+ rtc::replace_substrs(line.c_str(), line.length(),
newlines.c_str(), newlines.length(), message);
}
@@ -126,15 +126,15 @@
: public sigslot::has_slots<>,
public testing::Test {
public:
- typedef std::vector<talk_base::scoped_refptr<DataChannelInterface> >
+ typedef std::vector<rtc::scoped_refptr<DataChannelInterface> >
DataChannelList;
PeerConnectionEndToEndTest()
- : caller_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>(
+ : caller_(new rtc::RefCountedObject<PeerConnectionTestWrapper>(
"caller")),
- callee_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>(
+ callee_(new rtc::RefCountedObject<PeerConnectionTestWrapper>(
"callee")) {
- talk_base::InitializeSSL(NULL);
+ rtc::InitializeSSL(NULL);
}
void CreatePcs() {
@@ -222,10 +222,10 @@
// Tests that |dc1| and |dc2| can send to and receive from each other.
void TestDataChannelSendAndReceive(
DataChannelInterface* dc1, DataChannelInterface* dc2) {
- talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc1_observer(
+ rtc::scoped_ptr<webrtc::MockDataChannelObserver> dc1_observer(
new webrtc::MockDataChannelObserver(dc1));
- talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc2_observer(
+ rtc::scoped_ptr<webrtc::MockDataChannelObserver> dc2_observer(
new webrtc::MockDataChannelObserver(dc2));
static const std::string kDummyData = "abcdefg";
@@ -263,12 +263,12 @@
}
~PeerConnectionEndToEndTest() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
protected:
- talk_base::scoped_refptr<PeerConnectionTestWrapper> caller_;
- talk_base::scoped_refptr<PeerConnectionTestWrapper> callee_;
+ rtc::scoped_refptr<PeerConnectionTestWrapper> caller_;
+ rtc::scoped_refptr<PeerConnectionTestWrapper> callee_;
DataChannelList caller_signaled_data_channels_;
DataChannelList callee_signaled_data_channels_;
};
@@ -300,14 +300,14 @@
// Verifies that a DataChannel created before the negotiation can transition to
// "OPEN" and transfer data.
TEST_F(PeerConnectionEndToEndTest, CreateDataChannelBeforeNegotiate) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
CreatePcs();
webrtc::DataChannelInit init;
- talk_base::scoped_refptr<DataChannelInterface> caller_dc(
+ rtc::scoped_refptr<DataChannelInterface> caller_dc(
caller_->CreateDataChannel("data", init));
- talk_base::scoped_refptr<DataChannelInterface> callee_dc(
+ rtc::scoped_refptr<DataChannelInterface> callee_dc(
callee_->CreateDataChannel("data", init));
Negotiate();
@@ -326,22 +326,22 @@
// Verifies that a DataChannel created after the negotiation can transition to
// "OPEN" and transfer data.
TEST_F(PeerConnectionEndToEndTest, CreateDataChannelAfterNegotiate) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
CreatePcs();
webrtc::DataChannelInit init;
// This DataChannel is for creating the data content in the negotiation.
- talk_base::scoped_refptr<DataChannelInterface> dummy(
+ rtc::scoped_refptr<DataChannelInterface> dummy(
caller_->CreateDataChannel("data", init));
Negotiate();
WaitForConnection();
// Creates new DataChannels after the negotiation and verifies their states.
- talk_base::scoped_refptr<DataChannelInterface> caller_dc(
+ rtc::scoped_refptr<DataChannelInterface> caller_dc(
caller_->CreateDataChannel("hello", init));
- talk_base::scoped_refptr<DataChannelInterface> callee_dc(
+ rtc::scoped_refptr<DataChannelInterface> callee_dc(
callee_->CreateDataChannel("hello", init));
WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 1);
@@ -356,14 +356,14 @@
// Verifies that DataChannel IDs are even/odd based on the DTLS roles.
TEST_F(PeerConnectionEndToEndTest, DataChannelIdAssignment) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
CreatePcs();
webrtc::DataChannelInit init;
- talk_base::scoped_refptr<DataChannelInterface> caller_dc_1(
+ rtc::scoped_refptr<DataChannelInterface> caller_dc_1(
caller_->CreateDataChannel("data", init));
- talk_base::scoped_refptr<DataChannelInterface> callee_dc_1(
+ rtc::scoped_refptr<DataChannelInterface> callee_dc_1(
callee_->CreateDataChannel("data", init));
Negotiate();
@@ -372,9 +372,9 @@
EXPECT_EQ(1U, caller_dc_1->id() % 2);
EXPECT_EQ(0U, callee_dc_1->id() % 2);
- talk_base::scoped_refptr<DataChannelInterface> caller_dc_2(
+ rtc::scoped_refptr<DataChannelInterface> caller_dc_2(
caller_->CreateDataChannel("data", init));
- talk_base::scoped_refptr<DataChannelInterface> callee_dc_2(
+ rtc::scoped_refptr<DataChannelInterface> callee_dc_2(
callee_->CreateDataChannel("data", init));
EXPECT_EQ(1U, caller_dc_2->id() % 2);
@@ -385,15 +385,15 @@
// there are multiple DataChannels.
TEST_F(PeerConnectionEndToEndTest,
MessageTransferBetweenTwoPairsOfDataChannels) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
CreatePcs();
webrtc::DataChannelInit init;
- talk_base::scoped_refptr<DataChannelInterface> caller_dc_1(
+ rtc::scoped_refptr<DataChannelInterface> caller_dc_1(
caller_->CreateDataChannel("data", init));
- talk_base::scoped_refptr<DataChannelInterface> caller_dc_2(
+ rtc::scoped_refptr<DataChannelInterface> caller_dc_2(
caller_->CreateDataChannel("data", init));
Negotiate();
@@ -401,10 +401,10 @@
WaitForDataChannelsToOpen(caller_dc_1, callee_signaled_data_channels_, 0);
WaitForDataChannelsToOpen(caller_dc_2, callee_signaled_data_channels_, 1);
- talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc_1_observer(
+ rtc::scoped_ptr<webrtc::MockDataChannelObserver> dc_1_observer(
new webrtc::MockDataChannelObserver(callee_signaled_data_channels_[0]));
- talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc_2_observer(
+ rtc::scoped_ptr<webrtc::MockDataChannelObserver> dc_2_observer(
new webrtc::MockDataChannelObserver(callee_signaled_data_channels_[1]));
const std::string message_1 = "hello 1";
diff --git a/app/webrtc/peerconnectionfactory.cc b/app/webrtc/peerconnectionfactory.cc
index 3628c59..862ceda 100644
--- a/app/webrtc/peerconnectionfactory.cc
+++ b/app/webrtc/peerconnectionfactory.cc
@@ -41,15 +41,16 @@
#include "talk/media/webrtc/webrtcmediaengine.h"
#include "talk/media/webrtc/webrtcvideodecoderfactory.h"
#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
+#include "webrtc/base/bind.h"
#include "webrtc/modules/audio_device/include/audio_device.h"
-using talk_base::scoped_refptr;
+using rtc::scoped_refptr;
namespace {
-typedef talk_base::TypedMessageData<bool> InitMessageData;
+typedef rtc::TypedMessageData<bool> InitMessageData;
-struct CreatePeerConnectionParams : public talk_base::MessageData {
+struct CreatePeerConnectionParams : public rtc::MessageData {
CreatePeerConnectionParams(
const webrtc::PeerConnectionInterface::RTCConfiguration& configuration,
const webrtc::MediaConstraintsInterface* constraints,
@@ -70,7 +71,7 @@
webrtc::PeerConnectionObserver* observer;
};
-struct CreateAudioSourceParams : public talk_base::MessageData {
+struct CreateAudioSourceParams : public rtc::MessageData {
explicit CreateAudioSourceParams(
const webrtc::MediaConstraintsInterface* constraints)
: constraints(constraints) {
@@ -79,7 +80,7 @@
scoped_refptr<webrtc::AudioSourceInterface> source;
};
-struct CreateVideoSourceParams : public talk_base::MessageData {
+struct CreateVideoSourceParams : public rtc::MessageData {
CreateVideoSourceParams(cricket::VideoCapturer* capturer,
const webrtc::MediaConstraintsInterface* constraints)
: capturer(capturer),
@@ -90,11 +91,11 @@
scoped_refptr<webrtc::VideoSourceInterface> source;
};
-struct StartAecDumpParams : public talk_base::MessageData {
- explicit StartAecDumpParams(talk_base::PlatformFile aec_dump_file)
+struct StartAecDumpParams : public rtc::MessageData {
+ explicit StartAecDumpParams(rtc::PlatformFile aec_dump_file)
: aec_dump_file(aec_dump_file) {
}
- talk_base::PlatformFile aec_dump_file;
+ rtc::PlatformFile aec_dump_file;
bool result;
};
@@ -111,10 +112,10 @@
namespace webrtc {
-talk_base::scoped_refptr<PeerConnectionFactoryInterface>
+rtc::scoped_refptr<PeerConnectionFactoryInterface>
CreatePeerConnectionFactory() {
- talk_base::scoped_refptr<PeerConnectionFactory> pc_factory(
- new talk_base::RefCountedObject<PeerConnectionFactory>());
+ rtc::scoped_refptr<PeerConnectionFactory> pc_factory(
+ new rtc::RefCountedObject<PeerConnectionFactory>());
if (!pc_factory->Initialize()) {
return NULL;
@@ -122,15 +123,15 @@
return pc_factory;
}
-talk_base::scoped_refptr<PeerConnectionFactoryInterface>
+rtc::scoped_refptr<PeerConnectionFactoryInterface>
CreatePeerConnectionFactory(
- talk_base::Thread* worker_thread,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
+ rtc::Thread* signaling_thread,
AudioDeviceModule* default_adm,
cricket::WebRtcVideoEncoderFactory* encoder_factory,
cricket::WebRtcVideoDecoderFactory* decoder_factory) {
- talk_base::scoped_refptr<PeerConnectionFactory> pc_factory(
- new talk_base::RefCountedObject<PeerConnectionFactory>(worker_thread,
+ rtc::scoped_refptr<PeerConnectionFactory> pc_factory(
+ new rtc::RefCountedObject<PeerConnectionFactory>(worker_thread,
signaling_thread,
default_adm,
encoder_factory,
@@ -143,8 +144,8 @@
PeerConnectionFactory::PeerConnectionFactory()
: owns_ptrs_(true),
- signaling_thread_(new talk_base::Thread),
- worker_thread_(new talk_base::Thread) {
+ signaling_thread_(new rtc::Thread),
+ worker_thread_(new rtc::Thread) {
bool result = signaling_thread_->Start();
ASSERT(result);
result = worker_thread_->Start();
@@ -152,8 +153,8 @@
}
PeerConnectionFactory::PeerConnectionFactory(
- talk_base::Thread* worker_thread,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
+ rtc::Thread* signaling_thread,
AudioDeviceModule* default_adm,
cricket::WebRtcVideoEncoderFactory* video_encoder_factory,
cricket::WebRtcVideoDecoderFactory* video_decoder_factory)
@@ -185,7 +186,7 @@
return result.data();
}
-void PeerConnectionFactory::OnMessage(talk_base::Message* msg) {
+void PeerConnectionFactory::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_INIT_FACTORY: {
InitMessageData* pdata = static_cast<InitMessageData*>(msg->pdata);
@@ -229,7 +230,7 @@
}
bool PeerConnectionFactory::Initialize_s() {
- talk_base::InitRandom(talk_base::Time());
+ rtc::InitRandom(rtc::Time());
allocator_factory_ = PortAllocatorFactory::Create(worker_thread_);
if (!allocator_factory_)
@@ -239,14 +240,14 @@
new cricket::DummyDeviceManager());
// TODO: Need to make sure only one VoE is created inside
// WebRtcMediaEngine.
- cricket::WebRtcMediaEngine* webrtc_media_engine(
- new cricket::WebRtcMediaEngine(default_adm_.get(),
- NULL, // No secondary adm.
- video_encoder_factory_.get(),
- video_decoder_factory_.get()));
+ cricket::MediaEngineInterface* media_engine(
+ cricket::WebRtcMediaEngineFactory::Create(default_adm_.get(),
+ NULL, // No secondary adm.
+ video_encoder_factory_.get(),
+ video_decoder_factory_.get()));
channel_manager_.reset(new cricket::ChannelManager(
- webrtc_media_engine, device_manager, worker_thread_));
+ media_engine, device_manager, worker_thread_));
channel_manager_->SetVideoRtxEnabled(true);
if (!channel_manager_->Init()) {
return false;
@@ -260,28 +261,28 @@
allocator_factory_ = NULL;
}
-talk_base::scoped_refptr<AudioSourceInterface>
+rtc::scoped_refptr<AudioSourceInterface>
PeerConnectionFactory::CreateAudioSource_s(
const MediaConstraintsInterface* constraints) {
- talk_base::scoped_refptr<LocalAudioSource> source(
+ rtc::scoped_refptr<LocalAudioSource> source(
LocalAudioSource::Create(options_, constraints));
return source;
}
-talk_base::scoped_refptr<VideoSourceInterface>
+rtc::scoped_refptr<VideoSourceInterface>
PeerConnectionFactory::CreateVideoSource_s(
cricket::VideoCapturer* capturer,
const MediaConstraintsInterface* constraints) {
- talk_base::scoped_refptr<VideoSource> source(
+ rtc::scoped_refptr<VideoSource> source(
VideoSource::Create(channel_manager_.get(), capturer, constraints));
return VideoSourceProxy::Create(signaling_thread_, source);
}
-bool PeerConnectionFactory::StartAecDump_s(talk_base::PlatformFile file) {
+bool PeerConnectionFactory::StartAecDump_s(rtc::PlatformFile file) {
return channel_manager_->StartAecDump(file);
}
-talk_base::scoped_refptr<PeerConnectionInterface>
+rtc::scoped_refptr<PeerConnectionInterface>
PeerConnectionFactory::CreatePeerConnection(
const PeerConnectionInterface::RTCConfiguration& configuration,
const MediaConstraintsInterface* constraints,
@@ -296,7 +297,7 @@
return params.peerconnection;
}
-talk_base::scoped_refptr<PeerConnectionInterface>
+rtc::scoped_refptr<PeerConnectionInterface>
PeerConnectionFactory::CreatePeerConnection_s(
const PeerConnectionInterface::RTCConfiguration& configuration,
const MediaConstraintsInterface* constraints,
@@ -304,8 +305,8 @@
DTLSIdentityServiceInterface* dtls_identity_service,
PeerConnectionObserver* observer) {
ASSERT(allocator_factory || allocator_factory_);
- talk_base::scoped_refptr<PeerConnection> pc(
- new talk_base::RefCountedObject<PeerConnection>(this));
+ rtc::scoped_refptr<PeerConnection> pc(
+ new rtc::RefCountedObject<PeerConnection>(this));
if (!pc->Initialize(
configuration,
constraints,
@@ -317,13 +318,13 @@
return PeerConnectionProxy::Create(signaling_thread(), pc);
}
-talk_base::scoped_refptr<MediaStreamInterface>
+rtc::scoped_refptr<MediaStreamInterface>
PeerConnectionFactory::CreateLocalMediaStream(const std::string& label) {
return MediaStreamProxy::Create(signaling_thread_,
MediaStream::Create(label));
}
-talk_base::scoped_refptr<AudioSourceInterface>
+rtc::scoped_refptr<AudioSourceInterface>
PeerConnectionFactory::CreateAudioSource(
const MediaConstraintsInterface* constraints) {
CreateAudioSourceParams params(constraints);
@@ -331,7 +332,7 @@
return params.source;
}
-talk_base::scoped_refptr<VideoSourceInterface>
+rtc::scoped_refptr<VideoSourceInterface>
PeerConnectionFactory::CreateVideoSource(
cricket::VideoCapturer* capturer,
const MediaConstraintsInterface* constraints) {
@@ -342,24 +343,24 @@
return params.source;
}
-talk_base::scoped_refptr<VideoTrackInterface>
+rtc::scoped_refptr<VideoTrackInterface>
PeerConnectionFactory::CreateVideoTrack(
const std::string& id,
VideoSourceInterface* source) {
- talk_base::scoped_refptr<VideoTrackInterface> track(
+ rtc::scoped_refptr<VideoTrackInterface> track(
VideoTrack::Create(id, source));
return VideoTrackProxy::Create(signaling_thread_, track);
}
-talk_base::scoped_refptr<AudioTrackInterface>
+rtc::scoped_refptr<AudioTrackInterface>
PeerConnectionFactory::CreateAudioTrack(const std::string& id,
AudioSourceInterface* source) {
- talk_base::scoped_refptr<AudioTrackInterface> track(
+ rtc::scoped_refptr<AudioTrackInterface> track(
AudioTrack::Create(id, source));
return AudioTrackProxy::Create(signaling_thread_, track);
}
-bool PeerConnectionFactory::StartAecDump(talk_base::PlatformFile file) {
+bool PeerConnectionFactory::StartAecDump(rtc::PlatformFile file) {
StartAecDumpParams params(file);
signaling_thread_->Send(this, MSG_START_AEC_DUMP, ¶ms);
return params.result;
@@ -369,11 +370,11 @@
return channel_manager_.get();
}
-talk_base::Thread* PeerConnectionFactory::signaling_thread() {
+rtc::Thread* PeerConnectionFactory::signaling_thread() {
return signaling_thread_;
}
-talk_base::Thread* PeerConnectionFactory::worker_thread() {
+rtc::Thread* PeerConnectionFactory::worker_thread() {
return worker_thread_;
}
diff --git a/app/webrtc/peerconnectionfactory.h b/app/webrtc/peerconnectionfactory.h
index 633d281..119b7cd 100644
--- a/app/webrtc/peerconnectionfactory.h
+++ b/app/webrtc/peerconnectionfactory.h
@@ -31,20 +31,20 @@
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
#include "talk/session/media/channelmanager.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
class PeerConnectionFactory : public PeerConnectionFactoryInterface,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
virtual void SetOptions(const Options& options) {
options_ = options;
}
- virtual talk_base::scoped_refptr<PeerConnectionInterface>
+ virtual rtc::scoped_refptr<PeerConnectionInterface>
CreatePeerConnection(
const PeerConnectionInterface::RTCConfiguration& configuration,
const MediaConstraintsInterface* constraints,
@@ -54,36 +54,36 @@
bool Initialize();
- virtual talk_base::scoped_refptr<MediaStreamInterface>
+ virtual rtc::scoped_refptr<MediaStreamInterface>
CreateLocalMediaStream(const std::string& label);
- virtual talk_base::scoped_refptr<AudioSourceInterface> CreateAudioSource(
+ virtual rtc::scoped_refptr<AudioSourceInterface> CreateAudioSource(
const MediaConstraintsInterface* constraints);
- virtual talk_base::scoped_refptr<VideoSourceInterface> CreateVideoSource(
+ virtual rtc::scoped_refptr<VideoSourceInterface> CreateVideoSource(
cricket::VideoCapturer* capturer,
const MediaConstraintsInterface* constraints);
- virtual talk_base::scoped_refptr<VideoTrackInterface>
+ virtual rtc::scoped_refptr<VideoTrackInterface>
CreateVideoTrack(const std::string& id,
VideoSourceInterface* video_source);
- virtual talk_base::scoped_refptr<AudioTrackInterface>
+ virtual rtc::scoped_refptr<AudioTrackInterface>
CreateAudioTrack(const std::string& id,
AudioSourceInterface* audio_source);
- virtual bool StartAecDump(talk_base::PlatformFile file);
+ virtual bool StartAecDump(rtc::PlatformFile file);
virtual cricket::ChannelManager* channel_manager();
- virtual talk_base::Thread* signaling_thread();
- virtual talk_base::Thread* worker_thread();
+ virtual rtc::Thread* signaling_thread();
+ virtual rtc::Thread* worker_thread();
const Options& options() const { return options_; }
protected:
PeerConnectionFactory();
PeerConnectionFactory(
- talk_base::Thread* worker_thread,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
+ rtc::Thread* signaling_thread,
AudioDeviceModule* default_adm,
cricket::WebRtcVideoEncoderFactory* video_encoder_factory,
cricket::WebRtcVideoDecoderFactory* video_decoder_factory);
@@ -92,39 +92,39 @@
private:
bool Initialize_s();
void Terminate_s();
- talk_base::scoped_refptr<AudioSourceInterface> CreateAudioSource_s(
+ rtc::scoped_refptr<AudioSourceInterface> CreateAudioSource_s(
const MediaConstraintsInterface* constraints);
- talk_base::scoped_refptr<VideoSourceInterface> CreateVideoSource_s(
+ rtc::scoped_refptr<VideoSourceInterface> CreateVideoSource_s(
cricket::VideoCapturer* capturer,
const MediaConstraintsInterface* constraints);
- talk_base::scoped_refptr<PeerConnectionInterface> CreatePeerConnection_s(
+ rtc::scoped_refptr<PeerConnectionInterface> CreatePeerConnection_s(
const PeerConnectionInterface::RTCConfiguration& configuration,
const MediaConstraintsInterface* constraints,
PortAllocatorFactoryInterface* allocator_factory,
DTLSIdentityServiceInterface* dtls_identity_service,
PeerConnectionObserver* observer);
- bool StartAecDump_s(talk_base::PlatformFile file);
+ bool StartAecDump_s(rtc::PlatformFile file);
- // Implements talk_base::MessageHandler.
- void OnMessage(talk_base::Message* msg);
+ // Implements rtc::MessageHandler.
+ void OnMessage(rtc::Message* msg);
bool owns_ptrs_;
- talk_base::Thread* signaling_thread_;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* signaling_thread_;
+ rtc::Thread* worker_thread_;
Options options_;
- talk_base::scoped_refptr<PortAllocatorFactoryInterface> allocator_factory_;
+ rtc::scoped_refptr<PortAllocatorFactoryInterface> allocator_factory_;
// External Audio device used for audio playback.
- talk_base::scoped_refptr<AudioDeviceModule> default_adm_;
- talk_base::scoped_ptr<cricket::ChannelManager> channel_manager_;
+ rtc::scoped_refptr<AudioDeviceModule> default_adm_;
+ rtc::scoped_ptr<cricket::ChannelManager> channel_manager_;
// External Video encoder factory. This can be NULL if the client has not
// injected any. In that case, video engine will use the internal SW encoder.
- talk_base::scoped_ptr<cricket::WebRtcVideoEncoderFactory>
+ rtc::scoped_ptr<cricket::WebRtcVideoEncoderFactory>
video_encoder_factory_;
// External Video decoder factory. This can be NULL if the client has not
// injected any. In that case, video engine will use the internal SW decoder.
- talk_base::scoped_ptr<cricket::WebRtcVideoDecoderFactory>
+ rtc::scoped_ptr<cricket::WebRtcVideoDecoderFactory>
video_decoder_factory_;
};
diff --git a/app/webrtc/peerconnectionfactory_unittest.cc b/app/webrtc/peerconnectionfactory_unittest.cc
index 01f35d9..5995c46 100644
--- a/app/webrtc/peerconnectionfactory_unittest.cc
+++ b/app/webrtc/peerconnectionfactory_unittest.cc
@@ -30,14 +30,14 @@
#include "talk/app/webrtc/fakeportallocatorfactory.h"
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/peerconnectionfactory.h"
-#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/app/webrtc/test/fakevideotrackrenderer.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
+#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/webrtc/webrtccommon.h"
#include "talk/media/webrtc/webrtcvoe.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread.h"
using webrtc::FakeVideoTrackRenderer;
using webrtc::MediaStreamInterface;
@@ -102,8 +102,8 @@
class PeerConnectionFactoryTest : public testing::Test {
void SetUp() {
- factory_ = webrtc::CreatePeerConnectionFactory(talk_base::Thread::Current(),
- talk_base::Thread::Current(),
+ factory_ = webrtc::CreatePeerConnectionFactory(rtc::Thread::Current(),
+ rtc::Thread::Current(),
NULL,
NULL,
NULL);
@@ -141,21 +141,21 @@
}
}
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory_;
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory_;
NullPeerConnectionObserver observer_;
- talk_base::scoped_refptr<PortAllocatorFactoryInterface> allocator_factory_;
+ rtc::scoped_refptr<PortAllocatorFactoryInterface> allocator_factory_;
};
// Verify creation of PeerConnection using internal ADM, video factory and
// internal libjingle threads.
TEST(PeerConnectionFactoryTestInternal, CreatePCUsingInternalModules) {
- talk_base::scoped_refptr<PeerConnectionFactoryInterface> factory(
+ rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
webrtc::CreatePeerConnectionFactory());
NullPeerConnectionObserver observer;
webrtc::PeerConnectionInterface::IceServers servers;
- talk_base::scoped_refptr<PeerConnectionInterface> pc(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(
factory->CreatePeerConnection(servers, NULL, NULL, NULL, &observer));
EXPECT_TRUE(pc.get() != NULL);
@@ -174,7 +174,7 @@
ice_server.uri = kTurnIceServerWithTransport;
ice_server.password = kTurnPassword;
config.servers.push_back(ice_server);
- talk_base::scoped_refptr<PeerConnectionInterface> pc(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(
factory_->CreatePeerConnection(config, NULL,
allocator_factory_.get(),
NULL,
@@ -210,7 +210,7 @@
ice_server.uri = kTurnIceServerWithTransport;
ice_server.password = kTurnPassword;
ice_servers.push_back(ice_server);
- talk_base::scoped_refptr<PeerConnectionInterface> pc(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(
factory_->CreatePeerConnection(ice_servers, NULL,
allocator_factory_.get(),
NULL,
@@ -240,7 +240,7 @@
ice_server.username = kTurnUsername;
ice_server.password = kTurnPassword;
config.servers.push_back(ice_server);
- talk_base::scoped_refptr<PeerConnectionInterface> pc(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(
factory_->CreatePeerConnection(config, NULL,
allocator_factory_.get(),
NULL,
@@ -261,7 +261,7 @@
ice_server.uri = kTurnIceServerWithTransport;
ice_server.password = kTurnPassword;
config.servers.push_back(ice_server);
- talk_base::scoped_refptr<PeerConnectionInterface> pc(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(
factory_->CreatePeerConnection(config, NULL,
allocator_factory_.get(),
NULL,
@@ -286,7 +286,7 @@
ice_server.uri = kSecureTurnIceServerWithoutTransportAndPortParam;
ice_server.password = kTurnPassword;
config.servers.push_back(ice_server);
- talk_base::scoped_refptr<PeerConnectionInterface> pc(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(
factory_->CreatePeerConnection(config, NULL,
allocator_factory_.get(),
NULL,
@@ -323,7 +323,7 @@
ice_server.uri = kTurnIceServerWithIPv6Address;
ice_server.password = kTurnPassword;
config.servers.push_back(ice_server);
- talk_base::scoped_refptr<PeerConnectionInterface> pc(
+ rtc::scoped_refptr<PeerConnectionInterface> pc(
factory_->CreatePeerConnection(config, NULL,
allocator_factory_.get(),
NULL,
@@ -356,10 +356,10 @@
TEST_F(PeerConnectionFactoryTest, LocalRendering) {
cricket::FakeVideoCapturer* capturer = new cricket::FakeVideoCapturer();
// The source take ownership of |capturer|.
- talk_base::scoped_refptr<VideoSourceInterface> source(
+ rtc::scoped_refptr<VideoSourceInterface> source(
factory_->CreateVideoSource(capturer, NULL));
ASSERT_TRUE(source.get() != NULL);
- talk_base::scoped_refptr<VideoTrackInterface> track(
+ rtc::scoped_refptr<VideoTrackInterface> track(
factory_->CreateVideoTrack("testlabel", source));
ASSERT_TRUE(track.get() != NULL);
FakeVideoTrackRenderer local_renderer(track);
diff --git a/app/webrtc/peerconnectioninterface.h b/app/webrtc/peerconnectioninterface.h
index ed4033c..6ef4847 100644
--- a/app/webrtc/peerconnectioninterface.h
+++ b/app/webrtc/peerconnectioninterface.h
@@ -77,10 +77,10 @@
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/statstypes.h"
#include "talk/app/webrtc/umametrics.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/socketaddress.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/socketaddress.h"
-namespace talk_base {
+namespace rtc {
class Thread;
}
@@ -95,7 +95,7 @@
class MediaConstraintsInterface;
// MediaStream container interface.
-class StreamCollectionInterface : public talk_base::RefCountInterface {
+class StreamCollectionInterface : public rtc::RefCountInterface {
public:
// TODO(ronghuawu): Update the function names to c++ style, e.g. find -> Find.
virtual size_t count() = 0;
@@ -111,15 +111,26 @@
~StreamCollectionInterface() {}
};
-class StatsObserver : public talk_base::RefCountInterface {
+class StatsObserver : public rtc::RefCountInterface {
public:
- virtual void OnComplete(const std::vector<StatsReport>& reports) = 0;
+ // TODO(tommi): Remove.
+ virtual void OnComplete(const std::vector<StatsReport>& reports) {}
+
+ // TODO(tommi): Make pure virtual and remove implementation.
+ virtual void OnComplete(const StatsReports& reports) {
+ std::vector<StatsReportCopyable> report_copies;
+ for (size_t i = 0; i < reports.size(); ++i)
+ report_copies.push_back(StatsReportCopyable(*reports[i]));
+ std::vector<StatsReport>* r =
+ reinterpret_cast<std::vector<StatsReport>*>(&report_copies);
+ OnComplete(*r);
+ }
protected:
virtual ~StatsObserver() {}
};
-class UMAObserver : public talk_base::RefCountInterface {
+class UMAObserver : public rtc::RefCountInterface {
public:
virtual void IncrementCounter(PeerConnectionUMAMetricsCounter type) = 0;
virtual void AddHistogramSample(PeerConnectionUMAMetricsName type,
@@ -129,7 +140,7 @@
virtual ~UMAObserver() {}
};
-class PeerConnectionInterface : public talk_base::RefCountInterface {
+class PeerConnectionInterface : public rtc::RefCountInterface {
public:
// See http://dev.w3.org/2011/webrtc/editor/webrtc.html#state-definitions .
enum SignalingState {
@@ -192,6 +203,38 @@
explicit RTCConfiguration(IceTransportsType type) : type(type) {}
};
+ struct RTCOfferAnswerOptions {
+ static const int kUndefined = -1;
+ static const int kMaxOfferToReceiveMedia = 1;
+
+ // The default value for constraint offerToReceiveX:true.
+ static const int kOfferToReceiveMediaTrue = 1;
+
+ int offer_to_receive_video;
+ int offer_to_receive_audio;
+ bool voice_activity_detection;
+ bool ice_restart;
+ bool use_rtp_mux;
+
+ RTCOfferAnswerOptions()
+ : offer_to_receive_video(kUndefined),
+ offer_to_receive_audio(kUndefined),
+ voice_activity_detection(true),
+ ice_restart(false),
+ use_rtp_mux(true) {}
+
+ RTCOfferAnswerOptions(int offer_to_receive_video,
+ int offer_to_receive_audio,
+ bool voice_activity_detection,
+ bool ice_restart,
+ bool use_rtp_mux)
+ : offer_to_receive_video(offer_to_receive_video),
+ offer_to_receive_audio(offer_to_receive_audio),
+ voice_activity_detection(voice_activity_detection),
+ ice_restart(ice_restart),
+ use_rtp_mux(use_rtp_mux) {}
+ };
+
// Used by GetStats to decide which stats to include in the stats reports.
// |kStatsOutputLevelStandard| includes the standard stats for Javascript API;
// |kStatsOutputLevelDebug| includes both the standard stats and additional
@@ -202,11 +245,11 @@
};
// Accessor methods to active local streams.
- virtual talk_base::scoped_refptr<StreamCollectionInterface>
+ virtual rtc::scoped_refptr<StreamCollectionInterface>
local_streams() = 0;
// Accessor methods to remote streams.
- virtual talk_base::scoped_refptr<StreamCollectionInterface>
+ virtual rtc::scoped_refptr<StreamCollectionInterface>
remote_streams() = 0;
// Add a new MediaStream to be sent on this PeerConnection.
@@ -222,14 +265,14 @@
// Returns pointer to the created DtmfSender on success.
// Otherwise returns NULL.
- virtual talk_base::scoped_refptr<DtmfSenderInterface> CreateDtmfSender(
+ virtual rtc::scoped_refptr<DtmfSenderInterface> CreateDtmfSender(
AudioTrackInterface* track) = 0;
virtual bool GetStats(StatsObserver* observer,
MediaStreamTrackInterface* track,
StatsOutputLevel level) = 0;
- virtual talk_base::scoped_refptr<DataChannelInterface> CreateDataChannel(
+ virtual rtc::scoped_refptr<DataChannelInterface> CreateDataChannel(
const std::string& label,
const DataChannelInit* config) = 0;
@@ -239,7 +282,13 @@
// Create a new offer.
// The CreateSessionDescriptionObserver callback will be called when done.
virtual void CreateOffer(CreateSessionDescriptionObserver* observer,
- const MediaConstraintsInterface* constraints) = 0;
+ const MediaConstraintsInterface* constraints) {}
+
+ // TODO(jiayl): remove the default impl and the old interface when chromium
+ // code is updated.
+ virtual void CreateOffer(CreateSessionDescriptionObserver* observer,
+ const RTCOfferAnswerOptions& options) {}
+
// Create an answer to an offer.
// The CreateSessionDescriptionObserver callback will be called when done.
virtual void CreateAnswer(CreateSessionDescriptionObserver* observer,
@@ -340,13 +389,13 @@
// Factory class used for creating cricket::PortAllocator that is used
// for ICE negotiation.
-class PortAllocatorFactoryInterface : public talk_base::RefCountInterface {
+class PortAllocatorFactoryInterface : public rtc::RefCountInterface {
public:
struct StunConfiguration {
StunConfiguration(const std::string& address, int port)
: server(address, port) {}
// STUN server address and port.
- talk_base::SocketAddress server;
+ rtc::SocketAddress server;
};
struct TurnConfiguration {
@@ -361,7 +410,7 @@
password(password),
transport_type(transport_type),
secure(secure) {}
- talk_base::SocketAddress server;
+ rtc::SocketAddress server;
std::string username;
std::string password;
std::string transport_type;
@@ -378,7 +427,7 @@
};
// Used to receive callbacks of DTLS identity requests.
-class DTLSIdentityRequestObserver : public talk_base::RefCountInterface {
+class DTLSIdentityRequestObserver : public rtc::RefCountInterface {
public:
virtual void OnFailure(int error) = 0;
virtual void OnSuccess(const std::string& der_cert,
@@ -427,7 +476,7 @@
// CreatePeerConnectionFactory method which accepts threads as input and use the
// CreatePeerConnection version that takes a PortAllocatorFactoryInterface as
// argument.
-class PeerConnectionFactoryInterface : public talk_base::RefCountInterface {
+class PeerConnectionFactoryInterface : public rtc::RefCountInterface {
public:
class Options {
public:
@@ -441,7 +490,7 @@
virtual void SetOptions(const Options& options) = 0;
- virtual talk_base::scoped_refptr<PeerConnectionInterface>
+ virtual rtc::scoped_refptr<PeerConnectionInterface>
CreatePeerConnection(
const PeerConnectionInterface::RTCConfiguration& configuration,
const MediaConstraintsInterface* constraints,
@@ -455,7 +504,7 @@
// and not IceServers. RTCConfiguration is made up of ice servers and
// ice transport type.
// http://dev.w3.org/2011/webrtc/editor/webrtc.html
- inline talk_base::scoped_refptr<PeerConnectionInterface>
+ inline rtc::scoped_refptr<PeerConnectionInterface>
CreatePeerConnection(
const PeerConnectionInterface::IceServers& configuration,
const MediaConstraintsInterface* constraints,
@@ -468,29 +517,29 @@
dtls_identity_service, observer);
}
- virtual talk_base::scoped_refptr<MediaStreamInterface>
+ virtual rtc::scoped_refptr<MediaStreamInterface>
CreateLocalMediaStream(const std::string& label) = 0;
// Creates a AudioSourceInterface.
// |constraints| decides audio processing settings but can be NULL.
- virtual talk_base::scoped_refptr<AudioSourceInterface> CreateAudioSource(
+ virtual rtc::scoped_refptr<AudioSourceInterface> CreateAudioSource(
const MediaConstraintsInterface* constraints) = 0;
// Creates a VideoSourceInterface. The new source take ownership of
// |capturer|. |constraints| decides video resolution and frame rate but can
// be NULL.
- virtual talk_base::scoped_refptr<VideoSourceInterface> CreateVideoSource(
+ virtual rtc::scoped_refptr<VideoSourceInterface> CreateVideoSource(
cricket::VideoCapturer* capturer,
const MediaConstraintsInterface* constraints) = 0;
// Creates a new local VideoTrack. The same |source| can be used in several
// tracks.
- virtual talk_base::scoped_refptr<VideoTrackInterface>
+ virtual rtc::scoped_refptr<VideoTrackInterface>
CreateVideoTrack(const std::string& label,
VideoSourceInterface* source) = 0;
// Creates an new AudioTrack. At the moment |source| can be NULL.
- virtual talk_base::scoped_refptr<AudioTrackInterface>
+ virtual rtc::scoped_refptr<AudioTrackInterface>
CreateAudioTrack(const std::string& label,
AudioSourceInterface* source) = 0;
@@ -499,7 +548,7 @@
// the ownerhip. If the operation fails, the file will be closed.
// TODO(grunell): Remove when Chromium has started to use AEC in each source.
// http://crbug.com/264611.
- virtual bool StartAecDump(talk_base::PlatformFile file) = 0;
+ virtual bool StartAecDump(rtc::PlatformFile file) = 0;
protected:
// Dtor and ctor protected as objects shouldn't be created or deleted via
@@ -509,16 +558,16 @@
};
// Create a new instance of PeerConnectionFactoryInterface.
-talk_base::scoped_refptr<PeerConnectionFactoryInterface>
+rtc::scoped_refptr<PeerConnectionFactoryInterface>
CreatePeerConnectionFactory();
// Create a new instance of PeerConnectionFactoryInterface.
// Ownership of |factory|, |default_adm|, and optionally |encoder_factory| and
// |decoder_factory| transferred to the returned factory.
-talk_base::scoped_refptr<PeerConnectionFactoryInterface>
+rtc::scoped_refptr<PeerConnectionFactoryInterface>
CreatePeerConnectionFactory(
- talk_base::Thread* worker_thread,
- talk_base::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
+ rtc::Thread* signaling_thread,
AudioDeviceModule* default_adm,
cricket::WebRtcVideoEncoderFactory* encoder_factory,
cricket::WebRtcVideoDecoderFactory* decoder_factory);
diff --git a/app/webrtc/peerconnectioninterface_unittest.cc b/app/webrtc/peerconnectioninterface_unittest.cc
index 5c9b826..e957b21 100644
--- a/app/webrtc/peerconnectioninterface_unittest.cc
+++ b/app/webrtc/peerconnectioninterface_unittest.cc
@@ -36,15 +36,15 @@
#include "talk/app/webrtc/test/mockpeerconnectionobservers.h"
#include "talk/app/webrtc/test/testsdpstrings.h"
#include "talk/app/webrtc/videosource.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/sctp/sctpdataengine.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
static const char kStreamLabel1[] = "local_stream_1";
static const char kStreamLabel2[] = "local_stream_2";
@@ -66,8 +66,8 @@
return; \
}
-using talk_base::scoped_ptr;
-using talk_base::scoped_refptr;
+using rtc::scoped_ptr;
+using rtc::scoped_refptr;
using webrtc::AudioSourceInterface;
using webrtc::AudioTrackInterface;
using webrtc::DataBuffer;
@@ -229,15 +229,15 @@
class PeerConnectionInterfaceTest : public testing::Test {
protected:
virtual void SetUp() {
- talk_base::InitializeSSL(NULL);
+ rtc::InitializeSSL(NULL);
pc_factory_ = webrtc::CreatePeerConnectionFactory(
- talk_base::Thread::Current(), talk_base::Thread::Current(), NULL, NULL,
+ rtc::Thread::Current(), rtc::Thread::Current(), NULL, NULL,
NULL);
ASSERT_TRUE(pc_factory_.get() != NULL);
}
virtual void TearDown() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
void CreatePeerConnection() {
@@ -361,8 +361,8 @@
}
bool DoCreateOfferAnswer(SessionDescriptionInterface** desc, bool offer) {
- talk_base::scoped_refptr<MockCreateSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<MockCreateSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
MockCreateSessionDescriptionObserver>());
if (offer) {
pc_->CreateOffer(observer, NULL);
@@ -383,8 +383,8 @@
}
bool DoSetSessionDescription(SessionDescriptionInterface* desc, bool local) {
- talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<MockSetSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
MockSetSessionDescriptionObserver>());
if (local) {
pc_->SetLocalDescription(observer, desc);
@@ -407,8 +407,8 @@
// It does not verify the values in the StatReports since a RTCP packet might
// be required.
bool DoGetStats(MediaStreamTrackInterface* track) {
- talk_base::scoped_refptr<MockStatsObserver> observer(
- new talk_base::RefCountedObject<MockStatsObserver>());
+ rtc::scoped_refptr<MockStatsObserver> observer(
+ new rtc::RefCountedObject<MockStatsObserver>());
if (!pc_->GetStats(
observer, track, PeerConnectionInterface::kStatsOutputLevelStandard))
return false;
@@ -438,7 +438,7 @@
}
void CreateOfferAsRemoteDescription() {
- talk_base::scoped_ptr<SessionDescriptionInterface> offer;
+ rtc::scoped_ptr<SessionDescriptionInterface> offer;
EXPECT_TRUE(DoCreateOffer(offer.use()));
std::string sdp;
EXPECT_TRUE(offer->ToString(&sdp));
@@ -490,7 +490,7 @@
}
void CreateOfferAsLocalDescription() {
- talk_base::scoped_ptr<SessionDescriptionInterface> offer;
+ rtc::scoped_ptr<SessionDescriptionInterface> offer;
ASSERT_TRUE(DoCreateOffer(offer.use()));
// TODO(perkj): Currently SetLocalDescription fails if any parameters in an
// audio codec change, even if the parameter has nothing to do with
@@ -772,7 +772,10 @@
}
// Test that we don't get statistics for an invalid track.
-TEST_F(PeerConnectionInterfaceTest, GetStatsForInvalidTrack) {
+// TODO(tommi): Fix this test. DoGetStats will return true
+// for the unknown track (since GetStats is async), but no
+// data is returned for the track.
+TEST_F(PeerConnectionInterfaceTest, DISABLED_GetStatsForInvalidTrack) {
InitiateCall();
scoped_refptr<AudioTrackInterface> unknown_audio_track(
pc_factory_->CreateAudioTrack("unknown track", NULL));
@@ -789,9 +792,9 @@
scoped_refptr<DataChannelInterface> data2 =
pc_->CreateDataChannel("test2", NULL);
ASSERT_TRUE(data1 != NULL);
- talk_base::scoped_ptr<MockDataChannelObserver> observer1(
+ rtc::scoped_ptr<MockDataChannelObserver> observer1(
new MockDataChannelObserver(data1));
- talk_base::scoped_ptr<MockDataChannelObserver> observer2(
+ rtc::scoped_ptr<MockDataChannelObserver> observer2(
new MockDataChannelObserver(data2));
EXPECT_EQ(DataChannelInterface::kConnecting, data1->state());
@@ -836,9 +839,9 @@
scoped_refptr<DataChannelInterface> data2 =
pc_->CreateDataChannel("test2", NULL);
ASSERT_TRUE(data1 != NULL);
- talk_base::scoped_ptr<MockDataChannelObserver> observer1(
+ rtc::scoped_ptr<MockDataChannelObserver> observer1(
new MockDataChannelObserver(data1));
- talk_base::scoped_ptr<MockDataChannelObserver> observer2(
+ rtc::scoped_ptr<MockDataChannelObserver> observer2(
new MockDataChannelObserver(data2));
EXPECT_EQ(DataChannelInterface::kConnecting, data1->state());
@@ -851,7 +854,7 @@
EXPECT_EQ(DataChannelInterface::kOpen, data1->state());
EXPECT_EQ(DataChannelInterface::kOpen, data2->state());
- talk_base::Buffer buffer("test", 4);
+ rtc::Buffer buffer("test", 4);
EXPECT_FALSE(data1->Send(DataBuffer(buffer, true)));
}
@@ -863,7 +866,7 @@
CreatePeerConnection(&constraints);
scoped_refptr<DataChannelInterface> data1 =
pc_->CreateDataChannel("test1", NULL);
- talk_base::scoped_ptr<MockDataChannelObserver> observer1(
+ rtc::scoped_ptr<MockDataChannelObserver> observer1(
new MockDataChannelObserver(data1));
CreateOfferReceiveAnswerWithoutSsrc();
@@ -894,7 +897,7 @@
std::string receive_label = "answer_channel";
std::string sdp;
EXPECT_TRUE(pc_->local_description()->ToString(&sdp));
- talk_base::replace_substrs(offer_label.c_str(), offer_label.length(),
+ rtc::replace_substrs(offer_label.c_str(), offer_label.length(),
receive_label.c_str(), receive_label.length(),
&sdp);
CreateAnswerAsRemoteDescription(sdp);
@@ -1045,9 +1048,9 @@
scoped_refptr<DataChannelInterface> data2 =
pc_->CreateDataChannel("test2", NULL);
ASSERT_TRUE(data1 != NULL);
- talk_base::scoped_ptr<MockDataChannelObserver> observer1(
+ rtc::scoped_ptr<MockDataChannelObserver> observer1(
new MockDataChannelObserver(data1));
- talk_base::scoped_ptr<MockDataChannelObserver> observer2(
+ rtc::scoped_ptr<MockDataChannelObserver> observer2(
new MockDataChannelObserver(data2));
CreateOfferReceiveAnswer();
@@ -1088,7 +1091,7 @@
// FireFox, use it as a remote session description, generate an answer and use
// the answer as a local description.
TEST_F(PeerConnectionInterfaceTest, ReceiveFireFoxOffer) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
FakeConstraints constraints;
constraints.AddMandatory(webrtc::MediaConstraintsInterface::kEnableDtlsSrtp,
true);
@@ -1185,7 +1188,7 @@
EXPECT_FALSE(pc_->AddStream(local_stream, NULL));
ASSERT_FALSE(local_stream->GetAudioTracks().empty());
- talk_base::scoped_refptr<webrtc::DtmfSenderInterface> dtmf_sender(
+ rtc::scoped_refptr<webrtc::DtmfSenderInterface> dtmf_sender(
pc_->CreateDtmfSender(local_stream->GetAudioTracks()[0]));
EXPECT_TRUE(NULL == dtmf_sender); // local stream has been removed.
@@ -1194,9 +1197,9 @@
EXPECT_TRUE(pc_->local_description() != NULL);
EXPECT_TRUE(pc_->remote_description() != NULL);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer;
+ rtc::scoped_ptr<SessionDescriptionInterface> offer;
EXPECT_TRUE(DoCreateOffer(offer.use()));
- talk_base::scoped_ptr<SessionDescriptionInterface> answer;
+ rtc::scoped_ptr<SessionDescriptionInterface> answer;
EXPECT_TRUE(DoCreateAnswer(answer.use()));
std::string sdp;
diff --git a/app/webrtc/peerconnectionproxy.h b/app/webrtc/peerconnectionproxy.h
index 74e5012..ed26eb8 100644
--- a/app/webrtc/peerconnectionproxy.h
+++ b/app/webrtc/peerconnectionproxy.h
@@ -35,19 +35,19 @@
// Define proxy for PeerConnectionInterface.
BEGIN_PROXY_MAP(PeerConnection)
- PROXY_METHOD0(talk_base::scoped_refptr<StreamCollectionInterface>,
+ PROXY_METHOD0(rtc::scoped_refptr<StreamCollectionInterface>,
local_streams)
- PROXY_METHOD0(talk_base::scoped_refptr<StreamCollectionInterface>,
+ PROXY_METHOD0(rtc::scoped_refptr<StreamCollectionInterface>,
remote_streams)
PROXY_METHOD2(bool, AddStream, MediaStreamInterface*,
const MediaConstraintsInterface*)
PROXY_METHOD1(void, RemoveStream, MediaStreamInterface*)
- PROXY_METHOD1(talk_base::scoped_refptr<DtmfSenderInterface>,
+ PROXY_METHOD1(rtc::scoped_refptr<DtmfSenderInterface>,
CreateDtmfSender, AudioTrackInterface*)
PROXY_METHOD3(bool, GetStats, StatsObserver*,
MediaStreamTrackInterface*,
StatsOutputLevel)
- PROXY_METHOD2(talk_base::scoped_refptr<DataChannelInterface>,
+ PROXY_METHOD2(rtc::scoped_refptr<DataChannelInterface>,
CreateDataChannel, const std::string&, const DataChannelInit*)
PROXY_CONSTMETHOD0(const SessionDescriptionInterface*, local_description)
PROXY_CONSTMETHOD0(const SessionDescriptionInterface*, remote_description)
diff --git a/app/webrtc/portallocatorfactory.cc b/app/webrtc/portallocatorfactory.cc
index decd33c..946f8ad 100644
--- a/app/webrtc/portallocatorfactory.cc
+++ b/app/webrtc/portallocatorfactory.cc
@@ -27,27 +27,27 @@
#include "talk/app/webrtc/portallocatorfactory.h"
-#include "talk/base/logging.h"
-#include "talk/base/network.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/client/basicportallocator.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
-using talk_base::scoped_ptr;
+using rtc::scoped_ptr;
-talk_base::scoped_refptr<PortAllocatorFactoryInterface>
+rtc::scoped_refptr<PortAllocatorFactoryInterface>
PortAllocatorFactory::Create(
- talk_base::Thread* worker_thread) {
- talk_base::RefCountedObject<PortAllocatorFactory>* allocator =
- new talk_base::RefCountedObject<PortAllocatorFactory>(worker_thread);
+ rtc::Thread* worker_thread) {
+ rtc::RefCountedObject<PortAllocatorFactory>* allocator =
+ new rtc::RefCountedObject<PortAllocatorFactory>(worker_thread);
return allocator;
}
-PortAllocatorFactory::PortAllocatorFactory(talk_base::Thread* worker_thread)
- : network_manager_(new talk_base::BasicNetworkManager()),
- socket_factory_(new talk_base::BasicPacketSocketFactory(worker_thread)) {
+PortAllocatorFactory::PortAllocatorFactory(rtc::Thread* worker_thread)
+ : network_manager_(new rtc::BasicNetworkManager()),
+ socket_factory_(new rtc::BasicPacketSocketFactory(worker_thread)) {
}
PortAllocatorFactory::~PortAllocatorFactory() {}
@@ -55,19 +55,15 @@
cricket::PortAllocator* PortAllocatorFactory::CreatePortAllocator(
const std::vector<StunConfiguration>& stun,
const std::vector<TurnConfiguration>& turn) {
- std::vector<talk_base::SocketAddress> stun_hosts;
+ cricket::ServerAddresses stun_hosts;
typedef std::vector<StunConfiguration>::const_iterator StunIt;
for (StunIt stun_it = stun.begin(); stun_it != stun.end(); ++stun_it) {
- stun_hosts.push_back(stun_it->server);
+ stun_hosts.insert(stun_it->server);
}
- talk_base::SocketAddress stun_addr;
- if (!stun_hosts.empty()) {
- stun_addr = stun_hosts.front();
- }
scoped_ptr<cricket::BasicPortAllocator> allocator(
new cricket::BasicPortAllocator(
- network_manager_.get(), socket_factory_.get(), stun_addr));
+ network_manager_.get(), socket_factory_.get(), stun_hosts));
for (size_t i = 0; i < turn.size(); ++i) {
cricket::RelayCredentials credentials(turn[i].username, turn[i].password);
@@ -77,6 +73,8 @@
relay_server.ports.push_back(cricket::ProtocolAddress(
turn[i].server, protocol, turn[i].secure));
relay_server.credentials = credentials;
+ // First in the list gets highest priority.
+ relay_server.priority = static_cast<int>(turn.size() - i - 1);
allocator->AddRelay(relay_server);
} else {
LOG(LS_WARNING) << "Ignoring TURN server " << turn[i].server << ". "
diff --git a/app/webrtc/portallocatorfactory.h b/app/webrtc/portallocatorfactory.h
index e30024c..c8890ae 100644
--- a/app/webrtc/portallocatorfactory.h
+++ b/app/webrtc/portallocatorfactory.h
@@ -34,13 +34,13 @@
#define TALK_APP_WEBRTC_PORTALLOCATORFACTORY_H_
#include "talk/app/webrtc/peerconnectioninterface.h"
-#include "talk/base/scoped_ptr.h"
+#include "webrtc/base/scoped_ptr.h"
namespace cricket {
class PortAllocator;
}
-namespace talk_base {
+namespace rtc {
class BasicNetworkManager;
class BasicPacketSocketFactory;
}
@@ -49,20 +49,20 @@
class PortAllocatorFactory : public PortAllocatorFactoryInterface {
public:
- static talk_base::scoped_refptr<PortAllocatorFactoryInterface> Create(
- talk_base::Thread* worker_thread);
+ static rtc::scoped_refptr<PortAllocatorFactoryInterface> Create(
+ rtc::Thread* worker_thread);
virtual cricket::PortAllocator* CreatePortAllocator(
const std::vector<StunConfiguration>& stun,
const std::vector<TurnConfiguration>& turn);
protected:
- explicit PortAllocatorFactory(talk_base::Thread* worker_thread);
+ explicit PortAllocatorFactory(rtc::Thread* worker_thread);
~PortAllocatorFactory();
private:
- talk_base::scoped_ptr<talk_base::BasicNetworkManager> network_manager_;
- talk_base::scoped_ptr<talk_base::BasicPacketSocketFactory> socket_factory_;
+ rtc::scoped_ptr<rtc::BasicNetworkManager> network_manager_;
+ rtc::scoped_ptr<rtc::BasicPacketSocketFactory> socket_factory_;
};
} // namespace webrtc
diff --git a/app/webrtc/proxy.h b/app/webrtc/proxy.h
index 4db4bef..0c21ef9 100644
--- a/app/webrtc/proxy.h
+++ b/app/webrtc/proxy.h
@@ -31,7 +31,7 @@
//
// Example usage:
//
-// class TestInterface : public talk_base::RefCountInterface {
+// class TestInterface : public rtc::RefCountInterface {
// public:
// std::string FooA() = 0;
// std::string FooB(bool arg1) const = 0;
@@ -55,7 +55,7 @@
#ifndef TALK_APP_WEBRTC_PROXY_H_
#define TALK_APP_WEBRTC_PROXY_H_
-#include "talk/base/thread.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
@@ -93,19 +93,19 @@
};
template <typename C, typename R>
-class MethodCall0 : public talk_base::Message,
- public talk_base::MessageHandler {
+class MethodCall0 : public rtc::Message,
+ public rtc::MessageHandler {
public:
typedef R (C::*Method)();
MethodCall0(C* c, Method m) : c_(c), m_(m) {}
- R Marshal(talk_base::Thread* t) {
+ R Marshal(rtc::Thread* t) {
t->Send(this, 0);
return r_.value();
}
private:
- void OnMessage(talk_base::Message*) { r_.Invoke(c_, m_);}
+ void OnMessage(rtc::Message*) { r_.Invoke(c_, m_);}
C* c_;
Method m_;
@@ -113,19 +113,19 @@
};
template <typename C, typename R>
-class ConstMethodCall0 : public talk_base::Message,
- public talk_base::MessageHandler {
+class ConstMethodCall0 : public rtc::Message,
+ public rtc::MessageHandler {
public:
typedef R (C::*Method)() const;
ConstMethodCall0(C* c, Method m) : c_(c), m_(m) {}
- R Marshal(talk_base::Thread* t) {
+ R Marshal(rtc::Thread* t) {
t->Send(this, 0);
return r_.value();
}
private:
- void OnMessage(talk_base::Message*) { r_.Invoke(c_, m_); }
+ void OnMessage(rtc::Message*) { r_.Invoke(c_, m_); }
C* c_;
Method m_;
@@ -133,19 +133,19 @@
};
template <typename C, typename R, typename T1>
-class MethodCall1 : public talk_base::Message,
- public talk_base::MessageHandler {
+class MethodCall1 : public rtc::Message,
+ public rtc::MessageHandler {
public:
typedef R (C::*Method)(T1 a1);
MethodCall1(C* c, Method m, T1 a1) : c_(c), m_(m), a1_(a1) {}
- R Marshal(talk_base::Thread* t) {
+ R Marshal(rtc::Thread* t) {
t->Send(this, 0);
return r_.value();
}
private:
- void OnMessage(talk_base::Message*) { r_.Invoke(c_, m_, a1_); }
+ void OnMessage(rtc::Message*) { r_.Invoke(c_, m_, a1_); }
C* c_;
Method m_;
@@ -154,19 +154,19 @@
};
template <typename C, typename R, typename T1>
-class ConstMethodCall1 : public talk_base::Message,
- public talk_base::MessageHandler {
+class ConstMethodCall1 : public rtc::Message,
+ public rtc::MessageHandler {
public:
typedef R (C::*Method)(T1 a1) const;
ConstMethodCall1(C* c, Method m, T1 a1) : c_(c), m_(m), a1_(a1) {}
- R Marshal(talk_base::Thread* t) {
+ R Marshal(rtc::Thread* t) {
t->Send(this, 0);
return r_.value();
}
private:
- void OnMessage(talk_base::Message*) { r_.Invoke(c_, m_, a1_); }
+ void OnMessage(rtc::Message*) { r_.Invoke(c_, m_, a1_); }
C* c_;
Method m_;
@@ -175,19 +175,19 @@
};
template <typename C, typename R, typename T1, typename T2>
-class MethodCall2 : public talk_base::Message,
- public talk_base::MessageHandler {
+class MethodCall2 : public rtc::Message,
+ public rtc::MessageHandler {
public:
typedef R (C::*Method)(T1 a1, T2 a2);
MethodCall2(C* c, Method m, T1 a1, T2 a2) : c_(c), m_(m), a1_(a1), a2_(a2) {}
- R Marshal(talk_base::Thread* t) {
+ R Marshal(rtc::Thread* t) {
t->Send(this, 0);
return r_.value();
}
private:
- void OnMessage(talk_base::Message*) { r_.Invoke(c_, m_, a1_, a2_); }
+ void OnMessage(rtc::Message*) { r_.Invoke(c_, m_, a1_, a2_); }
C* c_;
Method m_;
@@ -197,20 +197,20 @@
};
template <typename C, typename R, typename T1, typename T2, typename T3>
-class MethodCall3 : public talk_base::Message,
- public talk_base::MessageHandler {
+class MethodCall3 : public rtc::Message,
+ public rtc::MessageHandler {
public:
typedef R (C::*Method)(T1 a1, T2 a2, T3 a3);
MethodCall3(C* c, Method m, T1 a1, T2 a2, T3 a3)
: c_(c), m_(m), a1_(a1), a2_(a2), a3_(a3) {}
- R Marshal(talk_base::Thread* t) {
+ R Marshal(rtc::Thread* t) {
t->Send(this, 0);
return r_.value();
}
private:
- void OnMessage(talk_base::Message*) { r_.Invoke(c_, m_, a1_, a2_, a3_); }
+ void OnMessage(rtc::Message*) { r_.Invoke(c_, m_, a1_, a2_, a3_); }
C* c_;
Method m_;
@@ -224,7 +224,7 @@
class c##Proxy : public c##Interface {\
protected:\
typedef c##Interface C;\
- c##Proxy(talk_base::Thread* thread, C* c)\
+ c##Proxy(rtc::Thread* thread, C* c)\
: owner_thread_(thread), \
c_(c) {}\
~c##Proxy() {\
@@ -232,9 +232,9 @@
call.Marshal(owner_thread_);\
}\
public:\
- static talk_base::scoped_refptr<C> Create(talk_base::Thread* thread, \
+ static rtc::scoped_refptr<C> Create(rtc::Thread* thread, \
C* c) {\
- return new talk_base::RefCountedObject<c##Proxy>(thread, c);\
+ return new rtc::RefCountedObject<c##Proxy>(thread, c);\
}\
#define PROXY_METHOD0(r, method)\
@@ -278,8 +278,8 @@
void Release_s() {\
c_ = NULL;\
}\
- mutable talk_base::Thread* owner_thread_;\
- talk_base::scoped_refptr<C> c_;\
+ mutable rtc::Thread* owner_thread_;\
+ rtc::scoped_refptr<C> c_;\
};\
} // namespace webrtc
diff --git a/app/webrtc/proxy_unittest.cc b/app/webrtc/proxy_unittest.cc
index 71a583c..9173f06 100644
--- a/app/webrtc/proxy_unittest.cc
+++ b/app/webrtc/proxy_unittest.cc
@@ -29,11 +29,11 @@
#include <string>
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
-#include "talk/base/gunit.h"
#include "testing/base/public/gmock.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/refcount.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread.h"
using ::testing::_;
using ::testing::DoAll;
@@ -44,7 +44,7 @@
namespace webrtc {
// Interface used for testing here.
-class FakeInterface : public talk_base::RefCountInterface {
+class FakeInterface : public rtc::RefCountInterface {
public:
virtual void VoidMethod0() = 0;
virtual std::string Method0() = 0;
@@ -70,8 +70,8 @@
// Implementation of the test interface.
class Fake : public FakeInterface {
public:
- static talk_base::scoped_refptr<Fake> Create() {
- return new talk_base::RefCountedObject<Fake>();
+ static rtc::scoped_refptr<Fake> Create() {
+ return new rtc::RefCountedObject<Fake>();
}
MOCK_METHOD0(VoidMethod0, void());
@@ -92,21 +92,21 @@
public:
// Checks that the functions is called on the |signaling_thread_|.
void CheckThread() {
- EXPECT_EQ(talk_base::Thread::Current(), signaling_thread_.get());
+ EXPECT_EQ(rtc::Thread::Current(), signaling_thread_.get());
}
protected:
virtual void SetUp() {
- signaling_thread_.reset(new talk_base::Thread());
+ signaling_thread_.reset(new rtc::Thread());
ASSERT_TRUE(signaling_thread_->Start());
fake_ = Fake::Create();
fake_proxy_ = FakeProxy::Create(signaling_thread_.get(), fake_.get());
}
protected:
- talk_base::scoped_ptr<talk_base::Thread> signaling_thread_;
- talk_base::scoped_refptr<FakeInterface> fake_proxy_;
- talk_base::scoped_refptr<Fake> fake_;
+ rtc::scoped_ptr<rtc::Thread> signaling_thread_;
+ rtc::scoped_refptr<FakeInterface> fake_proxy_;
+ rtc::scoped_refptr<Fake> fake_;
};
TEST_F(ProxyTest, VoidMethod0) {
diff --git a/app/webrtc/remoteaudiosource.cc b/app/webrtc/remoteaudiosource.cc
index 1c275c7..955dff0 100644
--- a/app/webrtc/remoteaudiosource.cc
+++ b/app/webrtc/remoteaudiosource.cc
@@ -30,12 +30,12 @@
#include <algorithm>
#include <functional>
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
namespace webrtc {
-talk_base::scoped_refptr<RemoteAudioSource> RemoteAudioSource::Create() {
- return new talk_base::RefCountedObject<RemoteAudioSource>();
+rtc::scoped_refptr<RemoteAudioSource> RemoteAudioSource::Create() {
+ return new rtc::RefCountedObject<RemoteAudioSource>();
}
RemoteAudioSource::RemoteAudioSource() {
diff --git a/app/webrtc/remoteaudiosource.h b/app/webrtc/remoteaudiosource.h
index ed24214..e805af6 100644
--- a/app/webrtc/remoteaudiosource.h
+++ b/app/webrtc/remoteaudiosource.h
@@ -41,7 +41,7 @@
class RemoteAudioSource : public Notifier<AudioSourceInterface> {
public:
// Creates an instance of RemoteAudioSource.
- static talk_base::scoped_refptr<RemoteAudioSource> Create();
+ static rtc::scoped_refptr<RemoteAudioSource> Create();
protected:
RemoteAudioSource();
diff --git a/app/webrtc/remotevideocapturer.cc b/app/webrtc/remotevideocapturer.cc
index 072c8d8..263d6e8 100644
--- a/app/webrtc/remotevideocapturer.cc
+++ b/app/webrtc/remotevideocapturer.cc
@@ -27,8 +27,8 @@
#include "talk/app/webrtc/remotevideocapturer.h"
-#include "talk/base/logging.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/logging.h"
namespace webrtc {
diff --git a/app/webrtc/remotevideocapturer_unittest.cc b/app/webrtc/remotevideocapturer_unittest.cc
index 6813550..396ef29 100644
--- a/app/webrtc/remotevideocapturer_unittest.cc
+++ b/app/webrtc/remotevideocapturer_unittest.cc
@@ -28,8 +28,8 @@
#include <string>
#include "talk/app/webrtc/remotevideocapturer.h"
-#include "talk/base/gunit.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
+#include "webrtc/base/gunit.h"
using cricket::CaptureState;
using cricket::VideoCapturer;
diff --git a/app/webrtc/sctputils.cc b/app/webrtc/sctputils.cc
index dcc6ba6..988f468 100644
--- a/app/webrtc/sctputils.cc
+++ b/app/webrtc/sctputils.cc
@@ -27,9 +27,9 @@
#include "talk/app/webrtc/sctputils.h"
-#include "talk/base/buffer.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/logging.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/logging.h"
namespace webrtc {
@@ -48,13 +48,13 @@
DCOMCT_UNORDERED_PARTIAL_TIME = 0x82,
};
-bool ParseDataChannelOpenMessage(const talk_base::Buffer& payload,
+bool ParseDataChannelOpenMessage(const rtc::Buffer& payload,
std::string* label,
DataChannelInit* config) {
// Format defined at
// http://tools.ietf.org/html/draft-jesup-rtcweb-data-protocol-04
- talk_base::ByteBuffer buffer(payload.data(), payload.length());
+ rtc::ByteBuffer buffer(payload.data(), payload.length());
uint8 message_type;
if (!buffer.ReadUInt8(&message_type)) {
@@ -125,8 +125,8 @@
return true;
}
-bool ParseDataChannelOpenAckMessage(const talk_base::Buffer& payload) {
- talk_base::ByteBuffer buffer(payload.data(), payload.length());
+bool ParseDataChannelOpenAckMessage(const rtc::Buffer& payload) {
+ rtc::ByteBuffer buffer(payload.data(), payload.length());
uint8 message_type;
if (!buffer.ReadUInt8(&message_type)) {
@@ -143,7 +143,7 @@
bool WriteDataChannelOpenMessage(const std::string& label,
const DataChannelInit& config,
- talk_base::Buffer* payload) {
+ rtc::Buffer* payload) {
// Format defined at
// http://tools.ietf.org/html/draft-ietf-rtcweb-data-protocol-00#section-6.1
uint8 channel_type = 0;
@@ -171,9 +171,9 @@
}
}
- talk_base::ByteBuffer buffer(
+ rtc::ByteBuffer buffer(
NULL, 20 + label.length() + config.protocol.length(),
- talk_base::ByteBuffer::ORDER_NETWORK);
+ rtc::ByteBuffer::ORDER_NETWORK);
buffer.WriteUInt8(DATA_CHANNEL_OPEN_MESSAGE_TYPE);
buffer.WriteUInt8(channel_type);
buffer.WriteUInt16(priority);
@@ -186,8 +186,8 @@
return true;
}
-void WriteDataChannelOpenAckMessage(talk_base::Buffer* payload) {
- talk_base::ByteBuffer buffer(talk_base::ByteBuffer::ORDER_NETWORK);
+void WriteDataChannelOpenAckMessage(rtc::Buffer* payload) {
+ rtc::ByteBuffer buffer(rtc::ByteBuffer::ORDER_NETWORK);
buffer.WriteUInt8(DATA_CHANNEL_OPEN_ACK_MESSAGE_TYPE);
payload->SetData(buffer.Data(), buffer.Length());
}
diff --git a/app/webrtc/sctputils.h b/app/webrtc/sctputils.h
index d0b4e9c..ab1818b 100644
--- a/app/webrtc/sctputils.h
+++ b/app/webrtc/sctputils.h
@@ -32,24 +32,24 @@
#include "talk/app/webrtc/datachannelinterface.h"
-namespace talk_base {
+namespace rtc {
class Buffer;
-} // namespace talk_base
+} // namespace rtc
namespace webrtc {
struct DataChannelInit;
-bool ParseDataChannelOpenMessage(const talk_base::Buffer& payload,
+bool ParseDataChannelOpenMessage(const rtc::Buffer& payload,
std::string* label,
DataChannelInit* config);
-bool ParseDataChannelOpenAckMessage(const talk_base::Buffer& payload);
+bool ParseDataChannelOpenAckMessage(const rtc::Buffer& payload);
bool WriteDataChannelOpenMessage(const std::string& label,
const DataChannelInit& config,
- talk_base::Buffer* payload);
+ rtc::Buffer* payload);
-void WriteDataChannelOpenAckMessage(talk_base::Buffer* payload);
+void WriteDataChannelOpenAckMessage(rtc::Buffer* payload);
} // namespace webrtc
#endif // TALK_APP_WEBRTC_SCTPUTILS_H_
diff --git a/app/webrtc/sctputils_unittest.cc b/app/webrtc/sctputils_unittest.cc
index 6a139a0..164f6dd 100644
--- a/app/webrtc/sctputils_unittest.cc
+++ b/app/webrtc/sctputils_unittest.cc
@@ -25,13 +25,13 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/bytebuffer.h"
-#include "talk/base/gunit.h"
#include "talk/app/webrtc/sctputils.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/gunit.h"
class SctpUtilsTest : public testing::Test {
public:
- void VerifyOpenMessageFormat(const talk_base::Buffer& packet,
+ void VerifyOpenMessageFormat(const rtc::Buffer& packet,
const std::string& label,
const webrtc::DataChannelInit& config) {
uint8 message_type;
@@ -41,7 +41,7 @@
uint16 label_length;
uint16 protocol_length;
- talk_base::ByteBuffer buffer(packet.data(), packet.length());
+ rtc::ByteBuffer buffer(packet.data(), packet.length());
ASSERT_TRUE(buffer.ReadUInt8(&message_type));
EXPECT_EQ(0x03, message_type);
@@ -84,7 +84,7 @@
std::string label = "abc";
config.protocol = "y";
- talk_base::Buffer packet;
+ rtc::Buffer packet;
ASSERT_TRUE(webrtc::WriteDataChannelOpenMessage(label, config, &packet));
VerifyOpenMessageFormat(packet, label, config);
@@ -108,7 +108,7 @@
config.maxRetransmitTime = 10;
config.protocol = "y";
- talk_base::Buffer packet;
+ rtc::Buffer packet;
ASSERT_TRUE(webrtc::WriteDataChannelOpenMessage(label, config, &packet));
VerifyOpenMessageFormat(packet, label, config);
@@ -131,7 +131,7 @@
config.maxRetransmits = 10;
config.protocol = "y";
- talk_base::Buffer packet;
+ rtc::Buffer packet;
ASSERT_TRUE(webrtc::WriteDataChannelOpenMessage(label, config, &packet));
VerifyOpenMessageFormat(packet, label, config);
@@ -149,11 +149,11 @@
}
TEST_F(SctpUtilsTest, WriteParseAckMessage) {
- talk_base::Buffer packet;
+ rtc::Buffer packet;
webrtc::WriteDataChannelOpenAckMessage(&packet);
uint8 message_type;
- talk_base::ByteBuffer buffer(packet.data(), packet.length());
+ rtc::ByteBuffer buffer(packet.data(), packet.length());
ASSERT_TRUE(buffer.ReadUInt8(&message_type));
EXPECT_EQ(0x02, message_type);
diff --git a/app/webrtc/statscollector.cc b/app/webrtc/statscollector.cc
index 67d64fb..5271827 100644
--- a/app/webrtc/statscollector.cc
+++ b/app/webrtc/statscollector.cc
@@ -30,9 +30,10 @@
#include <utility>
#include <vector>
-#include "talk/base/base64.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/session/media/channel.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/timing.h"
namespace webrtc {
@@ -137,6 +138,8 @@
"googLocalCandidateType";
const char StatsReport::kStatsValueNameLocalCertificateId[] =
"googLocalCertificateId";
+const char StatsReport::kStatsValueNameAdaptationChanges[] =
+ "googAdaptationChanges";
const char StatsReport::kStatsValueNameNacksReceived[] = "googNacksReceived";
const char StatsReport::kStatsValueNameNacksSent[] = "googNacksSent";
const char StatsReport::kStatsValueNamePlisReceived[] = "googPlisReceived";
@@ -190,24 +193,22 @@
const char StatsReport::kStatsReportVideoBweId[] = "bweforvideo";
// Implementations of functions in statstypes.h
-void StatsReport::AddValue(const std::string& name, const std::string& value) {
- Value temp;
- temp.name = name;
- temp.value = value;
- values.push_back(temp);
+void StatsReport::AddValue(StatsReport::StatsValueName name,
+ const std::string& value) {
+ values.push_back(Value(name, value));
}
-void StatsReport::AddValue(const std::string& name, int64 value) {
- AddValue(name, talk_base::ToString<int64>(value));
+void StatsReport::AddValue(StatsReport::StatsValueName name, int64 value) {
+ AddValue(name, rtc::ToString<int64>(value));
}
template <typename T>
-void StatsReport::AddValue(const std::string& name,
+void StatsReport::AddValue(StatsReport::StatsValueName name,
const std::vector<T>& value) {
std::ostringstream oss;
oss << "[";
for (size_t i = 0; i < value.size(); ++i) {
- oss << talk_base::ToString<T>(value[i]);
+ oss << rtc::ToString<T>(value[i]);
if (i != value.size() - 1)
oss << ", ";
}
@@ -215,11 +216,11 @@
AddValue(name, oss.str());
}
-void StatsReport::AddBoolean(const std::string& name, bool value) {
+void StatsReport::AddBoolean(StatsReport::StatsValueName name, bool value) {
AddValue(name, value ? "true" : "false");
}
-void StatsReport::ReplaceValue(const std::string& name,
+void StatsReport::ReplaceValue(StatsReport::StatsValueName name,
const std::string& value) {
for (Values::iterator it = values.begin(); it != values.end(); ++it) {
if ((*it).name == name) {
@@ -233,7 +234,32 @@
}
namespace {
-typedef std::map<std::string, StatsReport> StatsMap;
+
+double GetTimeNow() {
+ return rtc::Timing::WallTimeNow() * rtc::kNumMillisecsPerSec;
+}
+
+bool GetTransportIdFromProxy(const cricket::ProxyTransportMap& map,
+ const std::string& proxy,
+ std::string* transport) {
+ // TODO(hta): Remove handling of empty proxy name once tests do not use it.
+ if (proxy.empty()) {
+ transport->clear();
+ return true;
+ }
+
+ cricket::ProxyTransportMap::const_iterator found = map.find(proxy);
+ if (found == map.end()) {
+ LOG(LS_ERROR) << "No transport ID mapping for " << proxy;
+ return false;
+ }
+
+ std::ostringstream ost;
+ // Component 1 is always used for RTP.
+ ost << "Channel-" << found->second << "-1";
+ *transport = ost.str();
+ return true;
+}
std::string StatsId(const std::string& type, const std::string& id) {
return type + "_" + id;
@@ -255,7 +281,7 @@
bool ExtractValueFromReport(
const StatsReport& report,
- const std::string& name,
+ StatsReport::StatsValueName name,
std::string* value) {
StatsReport::Values::const_iterator it = report.values.begin();
for (; it != report.values.end(); ++it) {
@@ -267,17 +293,19 @@
return false;
}
+void AddTrackReport(StatsSet* reports, const std::string& track_id) {
+ // Adds an empty track report.
+ StatsReport* report = reports->ReplaceOrAddNew(
+ StatsId(StatsReport::kStatsReportTypeTrack, track_id));
+ report->type = StatsReport::kStatsReportTypeTrack;
+ report->AddValue(StatsReport::kStatsValueNameTrackId, track_id);
+}
+
template <class TrackVector>
-void CreateTrackReports(const TrackVector& tracks, StatsMap* reports) {
+void CreateTrackReports(const TrackVector& tracks, StatsSet* reports) {
for (size_t j = 0; j < tracks.size(); ++j) {
webrtc::MediaStreamTrackInterface* track = tracks[j];
- // Adds an empty track report.
- StatsReport report;
- report.type = StatsReport::kStatsReportTypeTrack;
- report.id = StatsId(StatsReport::kStatsReportTypeTrack, track->id());
- report.AddValue(StatsReport::kStatsValueNameTrackId,
- track->id());
- (*reports)[report.id] = report;
+ AddTrackReport(reports, track->id());
}
}
@@ -295,7 +323,7 @@
report->AddValue(StatsReport::kStatsValueNameCurrentDelayMs,
info.delay_estimate_ms);
report->AddValue(StatsReport::kStatsValueNameExpandRate,
- talk_base::ToString<float>(info.expand_rate));
+ rtc::ToString<float>(info.expand_rate));
report->AddValue(StatsReport::kStatsValueNamePacketsReceived,
info.packets_rcvd);
report->AddValue(StatsReport::kStatsValueNamePacketsLost,
@@ -330,7 +358,7 @@
info.jitter_ms);
report->AddValue(StatsReport::kStatsValueNameRtt, info.rtt_ms);
report->AddValue(StatsReport::kStatsValueNameEchoCancellationQualityMin,
- talk_base::ToString<float>(info.aec_quality_min));
+ rtc::ToString<float>(info.aec_quality_min));
report->AddValue(StatsReport::kStatsValueNameEchoDelayMedian,
info.echo_delay_median_ms);
report->AddValue(StatsReport::kStatsValueNameEchoDelayStdDev,
@@ -422,6 +450,8 @@
(info.adapt_reason & 0x2) > 0);
report->AddBoolean(StatsReport::kStatsValueNameViewLimitedResolution,
(info.adapt_reason & 0x4) > 0);
+ report->AddValue(StatsReport::kStatsValueNameAdaptationChanges,
+ info.adapt_changes);
report->AddValue(StatsReport::kStatsValueNameAvgEncodeMs, info.avg_encode_ms);
report->AddValue(StatsReport::kStatsValueNameCaptureJitterMs,
info.capture_jitter_ms);
@@ -437,7 +467,7 @@
double stats_gathering_started,
PeerConnectionInterface::StatsOutputLevel level,
StatsReport* report) {
- report->id = StatsReport::kStatsReportVideoBweId;
+ ASSERT(report->id == StatsReport::kStatsReportVideoBweId);
report->type = StatsReport::kStatsReportTypeBwe;
// Clear out stats from previous GatherStats calls if any.
@@ -520,8 +550,12 @@
} // namespace
-StatsCollector::StatsCollector()
- : session_(NULL), stats_gathering_started_(0) {
+StatsCollector::StatsCollector(WebRtcSession* session)
+ : session_(session), stats_gathering_started_(0) {
+ ASSERT(session_);
+}
+
+StatsCollector::~StatsCollector() {
}
// Adds a MediaStream with tracks that can be used as a |selector| in a call
@@ -538,13 +572,19 @@
void StatsCollector::AddLocalAudioTrack(AudioTrackInterface* audio_track,
uint32 ssrc) {
ASSERT(audio_track != NULL);
-#ifdef _DEBUG
for (LocalAudioTrackVector::iterator it = local_audio_tracks_.begin();
it != local_audio_tracks_.end(); ++it) {
ASSERT(it->first != audio_track || it->second != ssrc);
}
-#endif
+
local_audio_tracks_.push_back(std::make_pair(audio_track, ssrc));
+
+ // Create the kStatsReportTypeTrack report for the new track if there is no
+ // report yet.
+ StatsReport* found = reports_.Find(
+ StatsId(StatsReport::kStatsReportTypeTrack, audio_track->id()));
+ if (!found)
+ AddTrackReport(&reports_, audio_track->id());
}
void StatsCollector::RemoveLocalAudioTrack(AudioTrackInterface* audio_track,
@@ -561,49 +601,46 @@
ASSERT(false);
}
-bool StatsCollector::GetStats(MediaStreamTrackInterface* track,
+void StatsCollector::GetStats(MediaStreamTrackInterface* track,
StatsReports* reports) {
ASSERT(reports != NULL);
- reports->clear();
+ ASSERT(reports->empty());
- StatsMap::iterator it;
if (!track) {
- for (it = reports_.begin(); it != reports_.end(); ++it) {
- reports->push_back(it->second);
- }
- return true;
+ StatsSet::const_iterator it;
+ for (it = reports_.begin(); it != reports_.end(); ++it)
+ reports->push_back(&(*it));
+ return;
}
- it = reports_.find(StatsId(StatsReport::kStatsReportTypeSession,
- session_->id()));
- if (it != reports_.end()) {
- reports->push_back(it->second);
- }
+ StatsReport* report =
+ reports_.Find(StatsId(StatsReport::kStatsReportTypeSession,
+ session_->id()));
+ if (report)
+ reports->push_back(report);
- it = reports_.find(StatsId(StatsReport::kStatsReportTypeTrack, track->id()));
+ report = reports_.Find(
+ StatsId(StatsReport::kStatsReportTypeTrack, track->id()));
- if (it == reports_.end()) {
- LOG(LS_WARNING) << "No StatsReport is available for "<< track->id();
- return false;
- }
+ if (!report)
+ return;
- reports->push_back(it->second);
+ reports->push_back(report);
std::string track_id;
- for (it = reports_.begin(); it != reports_.end(); ++it) {
- if (it->second.type != StatsReport::kStatsReportTypeSsrc) {
+ for (StatsSet::const_iterator it = reports_.begin(); it != reports_.end();
+ ++it) {
+ if (it->type != StatsReport::kStatsReportTypeSsrc)
continue;
- }
- if (ExtractValueFromReport(it->second,
+
+ if (ExtractValueFromReport(*it,
StatsReport::kStatsValueNameTrackId,
&track_id)) {
if (track_id == track->id()) {
- reports->push_back(it->second);
+ reports->push_back(&(*it));
}
}
}
-
- return true;
}
void
@@ -612,7 +649,8 @@
// Calls to UpdateStats() that occur less than kMinGatherStatsPeriod number of
// ms apart will be ignored.
const double kMinGatherStatsPeriod = 50;
- if (stats_gathering_started_ + kMinGatherStatsPeriod > time_now) {
+ if (stats_gathering_started_ != 0 &&
+ stats_gathering_started_ + kMinGatherStatsPeriod > time_now) {
return;
}
stats_gathering_started_ = time_now;
@@ -628,30 +666,36 @@
uint32 ssrc,
const std::string& transport_id,
TrackDirection direction) {
- const std::string ssrc_id = talk_base::ToString<uint32>(ssrc);
- StatsMap::iterator it = reports_.find(StatsId(
- StatsReport::kStatsReportTypeSsrc, ssrc_id, direction));
+ const std::string ssrc_id = rtc::ToString<uint32>(ssrc);
+ StatsReport* report = reports_.Find(
+ StatsId(StatsReport::kStatsReportTypeSsrc, ssrc_id, direction));
+ // Use the ID of the track that is currently mapped to the SSRC, if any.
std::string track_id;
- if (it == reports_.end()) {
- if (!GetTrackIdBySsrc(ssrc, &track_id, direction))
+ if (!GetTrackIdBySsrc(ssrc, &track_id, direction)) {
+ if (!report) {
+ // The ssrc is not used by any track or existing report, return NULL
+ // in such case to indicate no report is prepared for the ssrc.
return NULL;
- } else {
- // Keeps the old track id since we want to report the stats for inactive
- // tracks.
- ExtractValueFromReport(it->second,
+ }
+
+ // The ssrc is not used by any existing track. Keeps the old track id
+ // since we want to report the stats for inactive ssrc.
+ ExtractValueFromReport(*report,
StatsReport::kStatsValueNameTrackId,
&track_id);
}
- StatsReport* report = GetOrCreateReport(StatsReport::kStatsReportTypeSsrc,
- ssrc_id, direction);
+ report = GetOrCreateReport(
+ StatsReport::kStatsReportTypeSsrc, ssrc_id, direction);
// Clear out stats from previous GatherStats calls if any.
- if (report->timestamp != stats_gathering_started_) {
- report->values.clear();
- report->timestamp = stats_gathering_started_;
- }
+ // This is required since the report will be returned for the new values.
+ // Having the old values in the report will lead to multiple values with
+ // the same name.
+ // TODO(xians): Consider changing StatsReport to use map instead of vector.
+ report->values.clear();
+ report->timestamp = stats_gathering_started_;
report->AddValue(StatsReport::kStatsValueNameSsrc, ssrc_id);
report->AddValue(StatsReport::kStatsValueNameTrackId, track_id);
@@ -665,23 +709,27 @@
uint32 ssrc,
const std::string& transport_id,
TrackDirection direction) {
- const std::string ssrc_id = talk_base::ToString<uint32>(ssrc);
- StatsMap::iterator it = reports_.find(StatsId(
- StatsReport::kStatsReportTypeRemoteSsrc, ssrc_id, direction));
+ const std::string ssrc_id = rtc::ToString<uint32>(ssrc);
+ StatsReport* report = reports_.Find(
+ StatsId(StatsReport::kStatsReportTypeRemoteSsrc, ssrc_id, direction));
+ // Use the ID of the track that is currently mapped to the SSRC, if any.
std::string track_id;
- if (it == reports_.end()) {
- if (!GetTrackIdBySsrc(ssrc, &track_id, direction))
+ if (!GetTrackIdBySsrc(ssrc, &track_id, direction)) {
+ if (!report) {
+ // The ssrc is not used by any track or existing report, return NULL
+ // in such case to indicate no report is prepared for the ssrc.
return NULL;
- } else {
- // Keeps the old track id since we want to report the stats for inactive
- // tracks.
- ExtractValueFromReport(it->second,
+ }
+
+ // The ssrc is not used by any existing track. Keeps the old track id
+ // since we want to report the stats for inactive ssrc.
+ ExtractValueFromReport(*report,
StatsReport::kStatsValueNameTrackId,
&track_id);
}
- StatsReport* report = GetOrCreateReport(
+ report = GetOrCreateReport(
StatsReport::kStatsReportTypeRemoteSsrc, ssrc_id, direction);
// Clear out stats from previous GatherStats calls if any.
@@ -698,7 +746,7 @@
}
std::string StatsCollector::AddOneCertificateReport(
- const talk_base::SSLCertificate* cert, const std::string& issuer_id) {
+ const rtc::SSLCertificate* cert, const std::string& issuer_id) {
// TODO(bemasc): Move this computation to a helper class that caches these
// values to reduce CPU use in GetStats. This will require adding a fast
// SSLCertificate::Equals() method to detect certificate changes.
@@ -707,8 +755,8 @@
if (!cert->GetSignatureDigestAlgorithm(&digest_algorithm))
return std::string();
- talk_base::scoped_ptr<talk_base::SSLFingerprint> ssl_fingerprint(
- talk_base::SSLFingerprint::Create(digest_algorithm, cert));
+ rtc::scoped_ptr<rtc::SSLFingerprint> ssl_fingerprint(
+ rtc::SSLFingerprint::Create(digest_algorithm, cert));
// SSLFingerprint::Create can fail if the algorithm returned by
// SSLCertificate::GetSignatureDigestAlgorithm is not supported by the
@@ -719,28 +767,27 @@
std::string fingerprint = ssl_fingerprint->GetRfc4572Fingerprint();
- talk_base::Buffer der_buffer;
+ rtc::Buffer der_buffer;
cert->ToDER(&der_buffer);
std::string der_base64;
- talk_base::Base64::EncodeFromArray(
+ rtc::Base64::EncodeFromArray(
der_buffer.data(), der_buffer.length(), &der_base64);
- StatsReport report;
- report.type = StatsReport::kStatsReportTypeCertificate;
- report.id = StatsId(report.type, fingerprint);
- report.timestamp = stats_gathering_started_;
- report.AddValue(StatsReport::kStatsValueNameFingerprint, fingerprint);
- report.AddValue(StatsReport::kStatsValueNameFingerprintAlgorithm,
- digest_algorithm);
- report.AddValue(StatsReport::kStatsValueNameDer, der_base64);
+ StatsReport* report = reports_.ReplaceOrAddNew(
+ StatsId(StatsReport::kStatsReportTypeCertificate, fingerprint));
+ report->type = StatsReport::kStatsReportTypeCertificate;
+ report->timestamp = stats_gathering_started_;
+ report->AddValue(StatsReport::kStatsValueNameFingerprint, fingerprint);
+ report->AddValue(StatsReport::kStatsValueNameFingerprintAlgorithm,
+ digest_algorithm);
+ report->AddValue(StatsReport::kStatsValueNameDer, der_base64);
if (!issuer_id.empty())
- report.AddValue(StatsReport::kStatsValueNameIssuerId, issuer_id);
- reports_[report.id] = report;
- return report.id;
+ report->AddValue(StatsReport::kStatsValueNameIssuerId, issuer_id);
+ return report->id;
}
std::string StatsCollector::AddCertificateReports(
- const talk_base::SSLCertificate* cert) {
+ const rtc::SSLCertificate* cert) {
// Produces a chain of StatsReports representing this certificate and the rest
// of its chain, and adds those reports to |reports_|. The return value is
// the id of the leaf report. The provided cert must be non-null, so at least
@@ -749,14 +796,14 @@
ASSERT(cert != NULL);
std::string issuer_id;
- talk_base::scoped_ptr<talk_base::SSLCertChain> chain;
+ rtc::scoped_ptr<rtc::SSLCertChain> chain;
if (cert->GetChain(chain.accept())) {
// This loop runs in reverse, i.e. from root to leaf, so that each
// certificate's issuer's report ID is known before the child certificate's
// report is generated. The root certificate does not have an issuer ID
// value.
for (ptrdiff_t i = chain->GetSize() - 1; i >= 0; --i) {
- const talk_base::SSLCertificate& cert_i = chain->Get(i);
+ const rtc::SSLCertificate& cert_i = chain->Get(i);
issuer_id = AddOneCertificateReport(&cert_i, issuer_id);
}
}
@@ -766,15 +813,13 @@
void StatsCollector::ExtractSessionInfo() {
// Extract information from the base session.
- StatsReport report;
- report.id = StatsId(StatsReport::kStatsReportTypeSession, session_->id());
- report.type = StatsReport::kStatsReportTypeSession;
- report.timestamp = stats_gathering_started_;
- report.values.clear();
- report.AddBoolean(StatsReport::kStatsValueNameInitiator,
- session_->initiator());
-
- reports_[report.id] = report;
+ StatsReport* report = reports_.ReplaceOrAddNew(
+ StatsId(StatsReport::kStatsReportTypeSession, session_->id()));
+ report->type = StatsReport::kStatsReportTypeSession;
+ report->timestamp = stats_gathering_started_;
+ report->values.clear();
+ report->AddBoolean(StatsReport::kStatsValueNameInitiator,
+ session_->initiator());
cricket::SessionStats stats;
if (session_->GetStats(&stats)) {
@@ -787,78 +832,83 @@
// Attempt to get a copy of the certificates from the transport and
// expose them in stats reports. All channels in a transport share the
// same local and remote certificates.
+ //
+ // Note that Transport::GetIdentity and Transport::GetRemoteCertificate
+ // invoke method calls on the worker thread and block this thread, but
+ // messages are still processed on this thread, which may blow way the
+ // existing transports. So we cannot reuse |transport| after these calls.
std::string local_cert_report_id, remote_cert_report_id;
+
cricket::Transport* transport =
session_->GetTransport(transport_iter->second.content_name);
- if (transport) {
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity;
- if (transport->GetIdentity(identity.accept()))
- local_cert_report_id = AddCertificateReports(
- &(identity->certificate()));
-
- talk_base::scoped_ptr<talk_base::SSLCertificate> cert;
- if (transport->GetRemoteCertificate(cert.accept()))
- remote_cert_report_id = AddCertificateReports(cert.get());
+ rtc::scoped_ptr<rtc::SSLIdentity> identity;
+ if (transport && transport->GetIdentity(identity.accept())) {
+ local_cert_report_id =
+ AddCertificateReports(&(identity->certificate()));
}
+
+ transport = session_->GetTransport(transport_iter->second.content_name);
+ rtc::scoped_ptr<rtc::SSLCertificate> cert;
+ if (transport && transport->GetRemoteCertificate(cert.accept())) {
+ remote_cert_report_id = AddCertificateReports(cert.get());
+ }
+
for (cricket::TransportChannelStatsList::iterator channel_iter
= transport_iter->second.channel_stats.begin();
channel_iter != transport_iter->second.channel_stats.end();
++channel_iter) {
- StatsReport channel_report;
std::ostringstream ostc;
ostc << "Channel-" << transport_iter->second.content_name
<< "-" << channel_iter->component;
- channel_report.id = ostc.str();
- channel_report.type = StatsReport::kStatsReportTypeComponent;
- channel_report.timestamp = stats_gathering_started_;
- channel_report.AddValue(StatsReport::kStatsValueNameComponent,
- channel_iter->component);
+ StatsReport* channel_report = reports_.ReplaceOrAddNew(ostc.str());
+ channel_report->type = StatsReport::kStatsReportTypeComponent;
+ channel_report->timestamp = stats_gathering_started_;
+ channel_report->AddValue(StatsReport::kStatsValueNameComponent,
+ channel_iter->component);
if (!local_cert_report_id.empty())
- channel_report.AddValue(
+ channel_report->AddValue(
StatsReport::kStatsValueNameLocalCertificateId,
local_cert_report_id);
if (!remote_cert_report_id.empty())
- channel_report.AddValue(
+ channel_report->AddValue(
StatsReport::kStatsValueNameRemoteCertificateId,
remote_cert_report_id);
- reports_[channel_report.id] = channel_report;
for (size_t i = 0;
i < channel_iter->connection_infos.size();
++i) {
- StatsReport report;
- const cricket::ConnectionInfo& info
- = channel_iter->connection_infos[i];
std::ostringstream ost;
ost << "Conn-" << transport_iter->first << "-"
<< channel_iter->component << "-" << i;
- report.id = ost.str();
- report.type = StatsReport::kStatsReportTypeCandidatePair;
- report.timestamp = stats_gathering_started_;
+ StatsReport* report = reports_.ReplaceOrAddNew(ost.str());
+ report->type = StatsReport::kStatsReportTypeCandidatePair;
+ report->timestamp = stats_gathering_started_;
// Link from connection to its containing channel.
- report.AddValue(StatsReport::kStatsValueNameChannelId,
- channel_report.id);
- report.AddValue(StatsReport::kStatsValueNameBytesSent,
- info.sent_total_bytes);
- report.AddValue(StatsReport::kStatsValueNameBytesReceived,
- info.recv_total_bytes);
- report.AddBoolean(StatsReport::kStatsValueNameWritable,
- info.writable);
- report.AddBoolean(StatsReport::kStatsValueNameReadable,
- info.readable);
- report.AddBoolean(StatsReport::kStatsValueNameActiveConnection,
- info.best_connection);
- report.AddValue(StatsReport::kStatsValueNameLocalAddress,
- info.local_candidate.address().ToString());
- report.AddValue(StatsReport::kStatsValueNameRemoteAddress,
- info.remote_candidate.address().ToString());
- report.AddValue(StatsReport::kStatsValueNameRtt, info.rtt);
- report.AddValue(StatsReport::kStatsValueNameTransportType,
- info.local_candidate.protocol());
- report.AddValue(StatsReport::kStatsValueNameLocalCandidateType,
- info.local_candidate.type());
- report.AddValue(StatsReport::kStatsValueNameRemoteCandidateType,
- info.remote_candidate.type());
- reports_[report.id] = report;
+ report->AddValue(StatsReport::kStatsValueNameChannelId,
+ channel_report->id);
+
+ const cricket::ConnectionInfo& info =
+ channel_iter->connection_infos[i];
+ report->AddValue(StatsReport::kStatsValueNameBytesSent,
+ info.sent_total_bytes);
+ report->AddValue(StatsReport::kStatsValueNameBytesReceived,
+ info.recv_total_bytes);
+ report->AddBoolean(StatsReport::kStatsValueNameWritable,
+ info.writable);
+ report->AddBoolean(StatsReport::kStatsValueNameReadable,
+ info.readable);
+ report->AddBoolean(StatsReport::kStatsValueNameActiveConnection,
+ info.best_connection);
+ report->AddValue(StatsReport::kStatsValueNameLocalAddress,
+ info.local_candidate.address().ToString());
+ report->AddValue(StatsReport::kStatsValueNameRemoteAddress,
+ info.remote_candidate.address().ToString());
+ report->AddValue(StatsReport::kStatsValueNameRtt, info.rtt);
+ report->AddValue(StatsReport::kStatsValueNameTransportType,
+ info.local_candidate.protocol());
+ report->AddValue(StatsReport::kStatsValueNameLocalCandidateType,
+ info.local_candidate.type());
+ report->AddValue(StatsReport::kStatsValueNameRemoteCandidateType,
+ info.remote_candidate.type());
}
}
}
@@ -875,7 +925,8 @@
return;
}
std::string transport_id;
- if (!GetTransportIdFromProxy(session_->voice_channel()->content_name(),
+ if (!GetTransportIdFromProxy(proxy_to_transport_,
+ session_->voice_channel()->content_name(),
&transport_id)) {
LOG(LS_ERROR) << "Failed to get transport name for proxy "
<< session_->voice_channel()->content_name();
@@ -902,7 +953,8 @@
return;
}
std::string transport_id;
- if (!GetTransportIdFromProxy(session_->video_channel()->content_name(),
+ if (!GetTransportIdFromProxy(proxy_to_transport_,
+ session_->video_channel()->content_name(),
&transport_id)) {
LOG(LS_ERROR) << "Failed to get transport name for proxy "
<< session_->video_channel()->content_name();
@@ -913,46 +965,19 @@
if (video_info.bw_estimations.size() != 1) {
LOG(LS_ERROR) << "BWEs count: " << video_info.bw_estimations.size();
} else {
- StatsReport* report = &reports_[StatsReport::kStatsReportVideoBweId];
+ StatsReport* report =
+ reports_.FindOrAddNew(StatsReport::kStatsReportVideoBweId);
ExtractStats(
video_info.bw_estimations[0], stats_gathering_started_, level, report);
}
}
-double StatsCollector::GetTimeNow() {
- return timing_.WallTimeNow() * talk_base::kNumMillisecsPerSec;
-}
-
-bool StatsCollector::GetTransportIdFromProxy(const std::string& proxy,
- std::string* transport) {
- // TODO(hta): Remove handling of empty proxy name once tests do not use it.
- if (proxy.empty()) {
- transport->clear();
- return true;
- }
- if (proxy_to_transport_.find(proxy) == proxy_to_transport_.end()) {
- LOG(LS_ERROR) << "No transport ID mapping for " << proxy;
- return false;
- }
- std::ostringstream ost;
- // Component 1 is always used for RTP.
- ost << "Channel-" << proxy_to_transport_[proxy] << "-1";
- *transport = ost.str();
- return true;
-}
-
StatsReport* StatsCollector::GetReport(const std::string& type,
const std::string& id,
TrackDirection direction) {
ASSERT(type == StatsReport::kStatsReportTypeSsrc ||
type == StatsReport::kStatsReportTypeRemoteSsrc);
- std::string statsid = StatsId(type, id, direction);
- StatsReport* report = NULL;
- std::map<std::string, StatsReport>::iterator it = reports_.find(statsid);
- if (it != reports_.end())
- report = &(it->second);
-
- return report;
+ return reports_.Find(StatsId(type, id, direction));
}
StatsReport* StatsCollector::GetOrCreateReport(const std::string& type,
@@ -963,8 +988,8 @@
StatsReport* report = GetReport(type, id, direction);
if (report == NULL) {
std::string statsid = StatsId(type, id, direction);
- report = &reports_[statsid]; // Create new element.
- report->id = statsid;
+ report = reports_.FindOrAddNew(statsid);
+ ASSERT(report->id == statsid);
report->type = type;
}
@@ -977,7 +1002,7 @@
it != local_audio_tracks_.end(); ++it) {
AudioTrackInterface* track = it->first;
uint32 ssrc = it->second;
- std::string ssrc_id = talk_base::ToString<uint32>(ssrc);
+ std::string ssrc_id = rtc::ToString<uint32>(ssrc);
StatsReport* report = GetReport(StatsReport::kStatsReportTypeSsrc,
ssrc_id,
kSending);
@@ -1010,10 +1035,10 @@
int signal_level = 0;
if (track->GetSignalLevel(&signal_level)) {
report->ReplaceValue(StatsReport::kStatsValueNameAudioInputLevel,
- talk_base::ToString<int>(signal_level));
+ rtc::ToString<int>(signal_level));
}
- talk_base::scoped_refptr<AudioProcessorInterface> audio_processor(
+ rtc::scoped_refptr<AudioProcessorInterface> audio_processor(
track->GetAudioProcessor());
if (audio_processor.get() == NULL)
return;
@@ -1023,29 +1048,29 @@
report->ReplaceValue(StatsReport::kStatsValueNameTypingNoiseState,
stats.typing_noise_detected ? "true" : "false");
report->ReplaceValue(StatsReport::kStatsValueNameEchoReturnLoss,
- talk_base::ToString<int>(stats.echo_return_loss));
+ rtc::ToString<int>(stats.echo_return_loss));
report->ReplaceValue(
StatsReport::kStatsValueNameEchoReturnLossEnhancement,
- talk_base::ToString<int>(stats.echo_return_loss_enhancement));
+ rtc::ToString<int>(stats.echo_return_loss_enhancement));
report->ReplaceValue(StatsReport::kStatsValueNameEchoDelayMedian,
- talk_base::ToString<int>(stats.echo_delay_median_ms));
+ rtc::ToString<int>(stats.echo_delay_median_ms));
report->ReplaceValue(StatsReport::kStatsValueNameEchoCancellationQualityMin,
- talk_base::ToString<float>(stats.aec_quality_min));
+ rtc::ToString<float>(stats.aec_quality_min));
report->ReplaceValue(StatsReport::kStatsValueNameEchoDelayStdDev,
- talk_base::ToString<int>(stats.echo_delay_std_ms));
+ rtc::ToString<int>(stats.echo_delay_std_ms));
}
bool StatsCollector::GetTrackIdBySsrc(uint32 ssrc, std::string* track_id,
TrackDirection direction) {
if (direction == kSending) {
- if (!session()->GetLocalTrackIdBySsrc(ssrc, track_id)) {
+ if (!session_->GetLocalTrackIdBySsrc(ssrc, track_id)) {
LOG(LS_WARNING) << "The SSRC " << ssrc
<< " is not associated with a sending track";
return false;
}
} else {
ASSERT(direction == kReceiving);
- if (!session()->GetRemoteTrackIdBySsrc(ssrc, track_id)) {
+ if (!session_->GetRemoteTrackIdBySsrc(ssrc, track_id)) {
LOG(LS_WARNING) << "The SSRC " << ssrc
<< " is not associated with a receiving track";
return false;
@@ -1055,4 +1080,8 @@
return true;
}
+void StatsCollector::ClearUpdateStatsCache() {
+ stats_gathering_started_ = 0;
+}
+
} // namespace webrtc
diff --git a/app/webrtc/statscollector.h b/app/webrtc/statscollector.h
index 77a1ba0..db2d788 100644
--- a/app/webrtc/statscollector.h
+++ b/app/webrtc/statscollector.h
@@ -40,8 +40,6 @@
#include "talk/app/webrtc/statstypes.h"
#include "talk/app/webrtc/webrtcsession.h"
-#include "talk/base/timing.h"
-
namespace webrtc {
class StatsCollector {
@@ -51,13 +49,10 @@
kReceiving,
};
- StatsCollector();
-
- // Register the session Stats should operate on.
- // Set to NULL if the session has ended.
- void set_session(WebRtcSession* session) {
- session_ = session;
- }
+ // The caller is responsible for ensuring that the session outlives the
+ // StatsCollector instance.
+ explicit StatsCollector(WebRtcSession* session);
+ virtual ~StatsCollector();
// Adds a MediaStream with tracks that can be used as a |selector| in a call
// to GetStats.
@@ -77,7 +72,11 @@
// be called before this function to get the most recent stats. |selector| is
// a track label or empty string. The most recent reports are stored in
// |reports|.
- bool GetStats(MediaStreamTrackInterface* track,
+ // TODO(tommi): Change this contract to accept a callback object instead
+ // of filling in |reports|. As is, there's a requirement that the caller
+ // uses |reports| immediately without allowing any async activity on
+ // the thread (message handling etc) and then discard the results.
+ void GetStats(MediaStreamTrackInterface* track,
StatsReports* reports);
// Prepare an SSRC report for the given ssrc. Used internally
@@ -87,27 +86,27 @@
// Prepare an SSRC report for the given remote ssrc. Used internally.
StatsReport* PrepareRemoteReport(uint32 ssrc, const std::string& transport,
TrackDirection direction);
- // Extracts the ID of a Transport belonging to an SSRC. Used internally.
- bool GetTransportIdFromProxy(const std::string& proxy,
- std::string* transport_id);
+
+ // Method used by the unittest to force a update of stats since UpdateStats()
+ // that occur less than kMinGatherStatsPeriod number of ms apart will be
+ // ignored.
+ void ClearUpdateStatsCache();
private:
bool CopySelectedReports(const std::string& selector, StatsReports* reports);
// Helper method for AddCertificateReports.
std::string AddOneCertificateReport(
- const talk_base::SSLCertificate* cert, const std::string& issuer_id);
+ const rtc::SSLCertificate* cert, const std::string& issuer_id);
// Adds a report for this certificate and every certificate in its chain, and
// returns the leaf certificate's report's ID.
- std::string AddCertificateReports(const talk_base::SSLCertificate* cert);
+ std::string AddCertificateReports(const rtc::SSLCertificate* cert);
void ExtractSessionInfo();
void ExtractVoiceInfo();
void ExtractVideoInfo(PeerConnectionInterface::StatsOutputLevel level);
- double GetTimeNow();
void BuildSsrcToTransportId();
- WebRtcSession* session() { return session_; }
webrtc::StatsReport* GetOrCreateReport(const std::string& type,
const std::string& id,
TrackDirection direction);
@@ -126,11 +125,10 @@
TrackDirection direction);
// A map from the report id to the report.
- std::map<std::string, StatsReport> reports_;
+ StatsSet reports_;
// Raw pointer to the session the statistics are gathered from.
- WebRtcSession* session_;
+ WebRtcSession* const session_;
double stats_gathering_started_;
- talk_base::Timing timing_;
cricket::ProxyTransportMap proxy_to_transport_;
typedef std::vector<std::pair<AudioTrackInterface*, uint32> >
diff --git a/app/webrtc/statscollector_unittest.cc b/app/webrtc/statscollector_unittest.cc
index 2cd716e..2f4c130 100644
--- a/app/webrtc/statscollector_unittest.cc
+++ b/app/webrtc/statscollector_unittest.cc
@@ -33,15 +33,15 @@
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/mediastreamtrack.h"
#include "talk/app/webrtc/videotrack.h"
-#include "talk/base/base64.h"
-#include "talk/base/fakesslidentity.h"
-#include "talk/base/gunit.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/devices/fakedevicemanager.h"
#include "talk/p2p/base/fakesession.h"
#include "talk/session/media/channelmanager.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/fakesslidentity.h"
+#include "webrtc/base/gunit.h"
using cricket::StatsOptions;
using testing::_;
@@ -75,8 +75,8 @@
class MockWebRtcSession : public webrtc::WebRtcSession {
public:
explicit MockWebRtcSession(cricket::ChannelManager* channel_manager)
- : WebRtcSession(channel_manager, talk_base::Thread::Current(),
- talk_base::Thread::Current(), NULL, NULL) {
+ : WebRtcSession(channel_manager, rtc::Thread::Current(),
+ rtc::Thread::Current(), NULL, NULL) {
}
MOCK_METHOD0(voice_channel, cricket::VoiceChannel*());
MOCK_METHOD0(video_channel, cricket::VideoChannel*());
@@ -126,7 +126,7 @@
public:
explicit FakeAudioTrack(const std::string& id)
: webrtc::MediaStreamTrack<webrtc::AudioTrackInterface>(id),
- processor_(new talk_base::RefCountedObject<FakeAudioProcessor>()) {}
+ processor_(new rtc::RefCountedObject<FakeAudioProcessor>()) {}
std::string kind() const OVERRIDE {
return "audio";
}
@@ -139,17 +139,17 @@
*level = 1;
return true;
}
- virtual talk_base::scoped_refptr<webrtc::AudioProcessorInterface>
+ virtual rtc::scoped_refptr<webrtc::AudioProcessorInterface>
GetAudioProcessor() OVERRIDE {
return processor_;
}
private:
- talk_base::scoped_refptr<FakeAudioProcessor> processor_;
+ rtc::scoped_refptr<FakeAudioProcessor> processor_;
};
bool GetValue(const StatsReport* report,
- const std::string& name,
+ StatsReport::StatsValueName name,
std::string* value) {
StatsReport::Values::const_iterator it = report->values.begin();
for (; it != report->values.end(); ++it) {
@@ -163,15 +163,15 @@
std::string ExtractStatsValue(const std::string& type,
const StatsReports& reports,
- const std::string name) {
+ StatsReport::StatsValueName name) {
if (reports.empty()) {
return kNoReports;
}
for (size_t i = 0; i < reports.size(); ++i) {
- if (reports[i].type != type)
+ if (reports[i]->type != type)
continue;
std::string ret;
- if (GetValue(&reports[i], name, &ret)) {
+ if (GetValue(reports[i], name, &ret)) {
return ret;
}
}
@@ -184,10 +184,10 @@
const StatsReport* FindNthReportByType(
const StatsReports& reports, const std::string& type, int n) {
for (size_t i = 0; i < reports.size(); ++i) {
- if (reports[i].type == type) {
+ if (reports[i]->type == type) {
n--;
if (n == 0)
- return &reports[i];
+ return reports[i];
}
}
return NULL;
@@ -196,28 +196,28 @@
const StatsReport* FindReportById(const StatsReports& reports,
const std::string& id) {
for (size_t i = 0; i < reports.size(); ++i) {
- if (reports[i].id == id) {
- return &reports[i];
+ if (reports[i]->id == id) {
+ return reports[i];
}
}
return NULL;
}
std::string ExtractSsrcStatsValue(StatsReports reports,
- const std::string& name) {
+ StatsReport::StatsValueName name) {
return ExtractStatsValue(
StatsReport::kStatsReportTypeSsrc, reports, name);
}
std::string ExtractBweStatsValue(StatsReports reports,
- const std::string& name) {
+ StatsReport::StatsValueName name) {
return ExtractStatsValue(
StatsReport::kStatsReportTypeBwe, reports, name);
}
std::string DerToPem(const std::string& der) {
- return talk_base::SSLIdentity::DerToPem(
- talk_base::kPemTypeCertificate,
+ return rtc::SSLIdentity::DerToPem(
+ rtc::kPemTypeCertificate,
reinterpret_cast<const unsigned char*>(der.c_str()),
der.length());
}
@@ -241,8 +241,8 @@
std::string der_base64;
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameDer, &der_base64));
- std::string der = talk_base::Base64::Decode(der_base64,
- talk_base::Base64::DO_STRICT);
+ std::string der = rtc::Base64::Decode(der_base64,
+ rtc::Base64::DO_STRICT);
EXPECT_EQ(ders[i], der);
std::string fingerprint_algorithm;
@@ -251,7 +251,7 @@
StatsReport::kStatsValueNameFingerprintAlgorithm,
&fingerprint_algorithm));
// The digest algorithm for a FakeSSLCertificate is always SHA-1.
- std::string sha_1_str = talk_base::DIGEST_SHA_1;
+ std::string sha_1_str = rtc::DIGEST_SHA_1;
EXPECT_EQ(sha_1_str, fingerprint_algorithm);
std::string dummy_fingerprint; // Value is not checked.
@@ -274,50 +274,50 @@
std::string value_in_report;
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameAudioOutputLevel, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.audio_level), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.audio_level), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameBytesReceived, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int64>(info.bytes_rcvd), value_in_report);
+ EXPECT_EQ(rtc::ToString<int64>(info.bytes_rcvd), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameJitterReceived, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.jitter_ms), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.jitter_ms), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameJitterBufferMs, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.jitter_buffer_ms), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.jitter_buffer_ms), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNamePreferredJitterBufferMs,
&value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.jitter_buffer_preferred_ms),
+ EXPECT_EQ(rtc::ToString<int>(info.jitter_buffer_preferred_ms),
value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameCurrentDelayMs, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.delay_estimate_ms), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.delay_estimate_ms), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameExpandRate, &value_in_report));
- EXPECT_EQ(talk_base::ToString<float>(info.expand_rate), value_in_report);
+ EXPECT_EQ(rtc::ToString<float>(info.expand_rate), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNamePacketsReceived, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.packets_rcvd), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.packets_rcvd), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameDecodingCTSG, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.decoding_calls_to_silence_generator),
+ EXPECT_EQ(rtc::ToString<int>(info.decoding_calls_to_silence_generator),
value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameDecodingCTN, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.decoding_calls_to_neteq),
+ EXPECT_EQ(rtc::ToString<int>(info.decoding_calls_to_neteq),
value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameDecodingNormal, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.decoding_normal), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.decoding_normal), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameDecodingPLC, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.decoding_plc), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.decoding_plc), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameDecodingCNG, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.decoding_cng), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.decoding_cng), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameDecodingPLCCNG, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(info.decoding_plc_cng), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(info.decoding_plc_cng), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameCodecName, &value_in_report));
}
@@ -331,46 +331,46 @@
EXPECT_EQ(sinfo.codec_name, value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameBytesSent, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int64>(sinfo.bytes_sent), value_in_report);
+ EXPECT_EQ(rtc::ToString<int64>(sinfo.bytes_sent), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNamePacketsSent, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.packets_sent), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(sinfo.packets_sent), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNamePacketsLost, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.packets_lost), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(sinfo.packets_lost), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameRtt, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.rtt_ms), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(sinfo.rtt_ms), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameRtt, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.rtt_ms), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(sinfo.rtt_ms), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameJitterReceived, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.jitter_ms), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(sinfo.jitter_ms), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameEchoCancellationQualityMin,
&value_in_report));
- EXPECT_EQ(talk_base::ToString<float>(sinfo.aec_quality_min), value_in_report);
+ EXPECT_EQ(rtc::ToString<float>(sinfo.aec_quality_min), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameEchoDelayMedian, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.echo_delay_median_ms),
+ EXPECT_EQ(rtc::ToString<int>(sinfo.echo_delay_median_ms),
value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameEchoDelayStdDev, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.echo_delay_std_ms),
+ EXPECT_EQ(rtc::ToString<int>(sinfo.echo_delay_std_ms),
value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameEchoReturnLoss, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.echo_return_loss),
+ EXPECT_EQ(rtc::ToString<int>(sinfo.echo_return_loss),
value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameEchoReturnLossEnhancement,
&value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.echo_return_loss_enhancement),
+ EXPECT_EQ(rtc::ToString<int>(sinfo.echo_return_loss_enhancement),
value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameAudioInputLevel, &value_in_report));
- EXPECT_EQ(talk_base::ToString<int>(sinfo.audio_level), value_in_report);
+ EXPECT_EQ(rtc::ToString<int>(sinfo.audio_level), value_in_report);
EXPECT_TRUE(GetValue(
report, StatsReport::kStatsValueNameTypingNoiseState, &value_in_report));
std::string typing_detected = sinfo.typing_noise_detected ? "true" : "false";
@@ -433,20 +433,22 @@
class StatsCollectorTest : public testing::Test {
protected:
StatsCollectorTest()
- : media_engine_(new cricket::FakeMediaEngine),
+ : media_engine_(new cricket::FakeMediaEngine()),
channel_manager_(
new cricket::ChannelManager(media_engine_,
new cricket::FakeDeviceManager(),
- talk_base::Thread::Current())),
+ rtc::Thread::Current())),
session_(channel_manager_.get()) {
// By default, we ignore session GetStats calls.
EXPECT_CALL(session_, GetStats(_)).WillRepeatedly(Return(false));
}
+ ~StatsCollectorTest() {}
+
// This creates a standard setup with a transport called "trspname"
// having one transport channel
// and the specified virtual connection name.
- void InitSessionStats(const std::string vc_name) {
+ void InitSessionStats(const std::string& vc_name) {
const std::string kTransportName("trspname");
cricket::TransportStats transport_stats;
cricket::TransportChannelStats channel_stats;
@@ -465,8 +467,6 @@
stream_->AddTrack(track_);
EXPECT_CALL(session_, GetLocalTrackIdBySsrc(kSsrcOfTrack, _))
.WillRepeatedly(DoAll(SetArgPointee<1>(kLocalTrackId), Return(true)));
- EXPECT_CALL(session_, GetRemoteTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(Return(false));
}
// Adds a incoming video track with a given SSRC into the stats.
@@ -474,11 +474,8 @@
stream_ = webrtc::MediaStream::Create("streamlabel");
track_= webrtc::VideoTrack::Create(kRemoteTrackId, NULL);
stream_->AddTrack(track_);
- EXPECT_CALL(session_, GetLocalTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(Return(false));
EXPECT_CALL(session_, GetRemoteTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(DoAll(SetArgPointee<1>(kRemoteTrackId),
- Return(true)));
+ .WillRepeatedly(DoAll(SetArgPointee<1>(kRemoteTrackId), Return(true)));
}
// Adds a outgoing audio track with a given SSRC into the stats.
@@ -486,14 +483,11 @@
if (stream_ == NULL)
stream_ = webrtc::MediaStream::Create("streamlabel");
- audio_track_ = new talk_base::RefCountedObject<FakeAudioTrack>(
+ audio_track_ = new rtc::RefCountedObject<FakeAudioTrack>(
kLocalTrackId);
stream_->AddTrack(audio_track_);
EXPECT_CALL(session_, GetLocalTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(DoAll(SetArgPointee<1>(kLocalTrackId),
- Return(true)));
- EXPECT_CALL(session_, GetRemoteTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(Return(false));
+ .WillOnce(DoAll(SetArgPointee<1>(kLocalTrackId), Return(true)));
}
// Adds a incoming audio track with a given SSRC into the stats.
@@ -501,22 +495,94 @@
if (stream_ == NULL)
stream_ = webrtc::MediaStream::Create("streamlabel");
- audio_track_ = new talk_base::RefCountedObject<FakeAudioTrack>(
+ audio_track_ = new rtc::RefCountedObject<FakeAudioTrack>(
kRemoteTrackId);
stream_->AddTrack(audio_track_);
- EXPECT_CALL(session_, GetLocalTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(Return(false));
EXPECT_CALL(session_, GetRemoteTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(DoAll(SetArgPointee<1>(kRemoteTrackId), Return(true)));
+ .WillOnce(DoAll(SetArgPointee<1>(kRemoteTrackId), Return(true)));
}
- void TestCertificateReports(const talk_base::FakeSSLCertificate& local_cert,
+ void SetupAndVerifyAudioTrackStats(
+ FakeAudioTrack* audio_track,
+ webrtc::MediaStream* stream,
+ webrtc::StatsCollector* stats,
+ cricket::VoiceChannel* voice_channel,
+ const std::string& vc_name,
+ MockVoiceMediaChannel* media_channel,
+ cricket::VoiceSenderInfo* voice_sender_info,
+ cricket::VoiceReceiverInfo* voice_receiver_info,
+ cricket::VoiceMediaInfo* stats_read,
+ StatsReports* reports) {
+ // A track can't have both sender report and recv report at the same time
+ // for now, this might change in the future though.
+ ASSERT((voice_sender_info == NULL) ^ (voice_receiver_info == NULL));
+
+ // Instruct the session to return stats containing the transport channel.
+ InitSessionStats(vc_name);
+ EXPECT_CALL(session_, GetStats(_))
+ .WillRepeatedly(DoAll(SetArgPointee<0>(session_stats_),
+ Return(true)));
+
+ // Constructs an ssrc stats update.
+ if (voice_sender_info)
+ stats_read->senders.push_back(*voice_sender_info);
+ if (voice_receiver_info)
+ stats_read->receivers.push_back(*voice_receiver_info);
+
+ EXPECT_CALL(session_, voice_channel()).WillRepeatedly(
+ Return(voice_channel));
+ EXPECT_CALL(session_, video_channel()).WillRepeatedly(ReturnNull());
+ EXPECT_CALL(*media_channel, GetStats(_))
+ .WillOnce(DoAll(SetArgPointee<0>(*stats_read), Return(true)));
+
+ stats->UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
+ stats->ClearUpdateStatsCache();
+ stats->GetStats(NULL, reports);
+
+ // Verify the existence of the track report.
+ const StatsReport* report = FindNthReportByType(
+ *reports, StatsReport::kStatsReportTypeSsrc, 1);
+ EXPECT_FALSE(report == NULL);
+ std::string track_id = ExtractSsrcStatsValue(
+ *reports, StatsReport::kStatsValueNameTrackId);
+ EXPECT_EQ(audio_track->id(), track_id);
+ std::string ssrc_id = ExtractSsrcStatsValue(
+ *reports, StatsReport::kStatsValueNameSsrc);
+ EXPECT_EQ(rtc::ToString<uint32>(kSsrcOfTrack), ssrc_id);
+
+ // Verifies the values in the track report.
+ if (voice_sender_info) {
+ UpdateVoiceSenderInfoFromAudioTrack(audio_track, voice_sender_info);
+ VerifyVoiceSenderInfoReport(report, *voice_sender_info);
+ }
+ if (voice_receiver_info) {
+ VerifyVoiceReceiverInfoReport(report, *voice_receiver_info);
+ }
+
+ // Verify we get the same result by passing a track to GetStats().
+ StatsReports track_reports; // returned values.
+ stats->GetStats(audio_track, &track_reports);
+ const StatsReport* track_report = FindNthReportByType(
+ track_reports, StatsReport::kStatsReportTypeSsrc, 1);
+ EXPECT_TRUE(track_report);
+ track_id = ExtractSsrcStatsValue(track_reports,
+ StatsReport::kStatsValueNameTrackId);
+ EXPECT_EQ(audio_track->id(), track_id);
+ ssrc_id = ExtractSsrcStatsValue(track_reports,
+ StatsReport::kStatsValueNameSsrc);
+ EXPECT_EQ(rtc::ToString<uint32>(kSsrcOfTrack), ssrc_id);
+ if (voice_sender_info)
+ VerifyVoiceSenderInfoReport(track_report, *voice_sender_info);
+ if (voice_receiver_info)
+ VerifyVoiceReceiverInfoReport(track_report, *voice_receiver_info);
+ }
+
+ void TestCertificateReports(const rtc::FakeSSLCertificate& local_cert,
const std::vector<std::string>& local_ders,
- const talk_base::FakeSSLCertificate& remote_cert,
+ const rtc::FakeSSLCertificate& remote_cert,
const std::vector<std::string>& remote_ders) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
StatsReports reports; // returned values.
- stats.set_session(&session_);
// Fake stats to process.
cricket::TransportChannelStats channel_stats;
@@ -531,12 +597,12 @@
transport_stats;
// Fake certificates to report.
- talk_base::FakeSSLIdentity local_identity(local_cert);
- talk_base::scoped_ptr<talk_base::FakeSSLCertificate> remote_cert_copy(
+ rtc::FakeSSLIdentity local_identity(local_cert);
+ rtc::scoped_ptr<rtc::FakeSSLCertificate> remote_cert_copy(
remote_cert.GetReference());
// Fake transport object.
- talk_base::scoped_ptr<cricket::FakeTransport> transport(
+ rtc::scoped_ptr<cricket::FakeTransport> transport(
new cricket::FakeTransport(
session_.signaling_thread(),
session_.worker_thread(),
@@ -550,7 +616,7 @@
// Configure MockWebRtcSession
EXPECT_CALL(session_, GetTransport(transport_stats.content_name))
- .WillOnce(Return(transport.get()));
+ .WillRepeatedly(Return(transport.get()));
EXPECT_CALL(session_, GetStats(_))
.WillOnce(DoAll(SetArgPointee<0>(session_stats),
Return(true)));
@@ -591,19 +657,19 @@
}
cricket::FakeMediaEngine* media_engine_;
- talk_base::scoped_ptr<cricket::ChannelManager> channel_manager_;
+ rtc::scoped_ptr<cricket::ChannelManager> channel_manager_;
MockWebRtcSession session_;
cricket::SessionStats session_stats_;
- talk_base::scoped_refptr<webrtc::MediaStream> stream_;
- talk_base::scoped_refptr<webrtc::VideoTrack> track_;
- talk_base::scoped_refptr<FakeAudioTrack> audio_track_;
+ rtc::scoped_refptr<webrtc::MediaStream> stream_;
+ rtc::scoped_refptr<webrtc::VideoTrack> track_;
+ rtc::scoped_refptr<FakeAudioTrack> audio_track_;
};
// This test verifies that 64-bit counters are passed successfully.
TEST_F(StatsCollectorTest, BytesCounterHandles64Bits) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, "", false, NULL);
StatsReports reports; // returned values.
cricket::VideoSenderInfo video_sender_info;
@@ -612,7 +678,6 @@
const int64 kBytesSent = 12345678901234LL;
const std::string kBytesSentString("12345678901234");
- stats.set_session(&session_);
AddOutgoingVideoTrackStats();
stats.AddStream(stream_);
@@ -624,19 +689,20 @@
EXPECT_CALL(session_, video_channel()).WillRepeatedly(Return(&video_channel));
EXPECT_CALL(session_, voice_channel()).WillRepeatedly(ReturnNull());
EXPECT_CALL(*media_channel, GetStats(_, _))
- .WillOnce(DoAll(SetArgPointee<1>(stats_read),
- Return(true)));
+ .WillOnce(DoAll(SetArgPointee<1>(stats_read),
+ Return(true)));
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
stats.GetStats(NULL, &reports);
- std::string result = ExtractSsrcStatsValue(reports, "bytesSent");
+ std::string result = ExtractSsrcStatsValue(reports,
+ StatsReport::kStatsValueNameBytesSent);
EXPECT_EQ(kBytesSentString, result);
}
// Test that BWE information is reported via stats.
TEST_F(StatsCollectorTest, BandwidthEstimationInfoIsReported) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, "", false, NULL);
StatsReports reports; // returned values.
cricket::VideoSenderInfo video_sender_info;
@@ -646,7 +712,6 @@
const int64 kBytesSent = 12345678901234LL;
const std::string kBytesSentString("12345678901234");
- stats.set_session(&session_);
AddOutgoingVideoTrackStats();
stats.AddStream(stream_);
@@ -668,18 +733,19 @@
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
stats.GetStats(NULL, &reports);
- std::string result = ExtractSsrcStatsValue(reports, "bytesSent");
+ std::string result = ExtractSsrcStatsValue(reports,
+ StatsReport::kStatsValueNameBytesSent);
EXPECT_EQ(kBytesSentString, result);
- result = ExtractBweStatsValue(reports, "googTargetEncBitrate");
+ result = ExtractBweStatsValue(reports,
+ StatsReport::kStatsValueNameTargetEncBitrate);
EXPECT_EQ(kTargetEncBitrateString, result);
}
// This test verifies that an object of type "googSession" always
// exists in the returned stats.
TEST_F(StatsCollectorTest, SessionObjectExists) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
StatsReports reports; // returned values.
- stats.set_session(&session_);
EXPECT_CALL(session_, video_channel()).WillRepeatedly(ReturnNull());
EXPECT_CALL(session_, voice_channel()).WillRepeatedly(ReturnNull());
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
@@ -692,9 +758,8 @@
// This test verifies that only one object of type "googSession" exists
// in the returned stats.
TEST_F(StatsCollectorTest, OnlyOneSessionObjectExists) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
StatsReports reports; // returned values.
- stats.set_session(&session_);
EXPECT_CALL(session_, video_channel()).WillRepeatedly(ReturnNull());
EXPECT_CALL(session_, voice_channel()).WillRepeatedly(ReturnNull());
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
@@ -711,22 +776,19 @@
// This test verifies that the empty track report exists in the returned stats
// without calling StatsCollector::UpdateStats.
TEST_F(StatsCollectorTest, TrackObjectExistsWithoutUpdateStats) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, "", false, NULL);
AddOutgoingVideoTrackStats();
stats.AddStream(stream_);
- stats.set_session(&session_);
-
- StatsReports reports;
-
// Verfies the existence of the track report.
+ StatsReports reports;
stats.GetStats(NULL, &reports);
EXPECT_EQ((size_t)1, reports.size());
EXPECT_EQ(std::string(StatsReport::kStatsReportTypeTrack),
- reports[0].type);
+ reports[0]->type);
std::string trackValue =
ExtractStatsValue(StatsReport::kStatsReportTypeTrack,
@@ -738,17 +800,13 @@
// This test verifies that the empty track report exists in the returned stats
// when StatsCollector::UpdateStats is called with ssrc stats.
TEST_F(StatsCollectorTest, TrackAndSsrcObjectExistAfterUpdateSsrcStats) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, "", false, NULL);
AddOutgoingVideoTrackStats();
stats.AddStream(stream_);
- stats.set_session(&session_);
-
- StatsReports reports;
-
// Constructs an ssrc stats update.
cricket::VideoSenderInfo video_sender_info;
cricket::VideoMediaInfo stats_read;
@@ -766,6 +824,7 @@
Return(true)));
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
+ StatsReports reports;
stats.GetStats(NULL, &reports);
// |reports| should contain at least one session report, one track report,
// and one ssrc report.
@@ -775,6 +834,7 @@
EXPECT_TRUE(track_report);
// Get report for the specific |track|.
+ reports.clear();
stats.GetStats(track_, &reports);
// |reports| should contain at least one session report, one track report,
// and one ssrc report.
@@ -785,7 +845,7 @@
std::string ssrc_id = ExtractSsrcStatsValue(
reports, StatsReport::kStatsValueNameSsrc);
- EXPECT_EQ(talk_base::ToString<uint32>(kSsrcOfTrack), ssrc_id);
+ EXPECT_EQ(rtc::ToString<uint32>(kSsrcOfTrack), ssrc_id);
std::string track_id = ExtractSsrcStatsValue(
reports, StatsReport::kStatsValueNameTrackId);
@@ -795,19 +855,18 @@
// This test verifies that an SSRC object has the identifier of a Transport
// stats object, and that this transport stats object exists in stats.
TEST_F(StatsCollectorTest, TransportObjectLinkedFromSsrcObject) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
+ // Ignore unused callback (logspam).
+ EXPECT_CALL(session_, GetTransport(_))
+ .WillRepeatedly(Return(static_cast<cricket::Transport*>(NULL)));
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
// The content_name known by the video channel.
const std::string kVcName("vcname");
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, kVcName, false, NULL);
AddOutgoingVideoTrackStats();
stats.AddStream(stream_);
- stats.set_session(&session_);
-
- StatsReports reports;
-
// Constructs an ssrc stats update.
cricket::VideoSenderInfo video_sender_info;
cricket::VideoMediaInfo stats_read;
@@ -830,6 +889,7 @@
Return(true)));
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
+ StatsReports reports;
stats.GetStats(NULL, &reports);
std::string transport_id = ExtractStatsValue(
StatsReport::kStatsReportTypeSsrc,
@@ -844,17 +904,15 @@
// This test verifies that a remote stats object will not be created for
// an outgoing SSRC where remote stats are not returned.
TEST_F(StatsCollectorTest, RemoteSsrcInfoIsAbsent) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
// The content_name known by the video channel.
const std::string kVcName("vcname");
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, kVcName, false, NULL);
AddOutgoingVideoTrackStats();
stats.AddStream(stream_);
- stats.set_session(&session_);
-
EXPECT_CALL(session_, video_channel()).WillRepeatedly(ReturnNull());
EXPECT_CALL(session_, voice_channel()).WillRepeatedly(ReturnNull());
@@ -869,19 +927,18 @@
// This test verifies that a remote stats object will be created for
// an outgoing SSRC where stats are returned.
TEST_F(StatsCollectorTest, RemoteSsrcInfoIsPresent) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
+ // Ignore unused callback (logspam).
+ EXPECT_CALL(session_, GetTransport(_))
+ .WillRepeatedly(Return(static_cast<cricket::Transport*>(NULL)));
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
// The content_name known by the video channel.
const std::string kVcName("vcname");
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, kVcName, false, NULL);
AddOutgoingVideoTrackStats();
stats.AddStream(stream_);
- stats.set_session(&session_);
-
- StatsReports reports;
-
// Instruct the session to return stats containing the transport channel.
InitSessionStats(kVcName);
EXPECT_CALL(session_, GetStats(_))
@@ -906,6 +963,7 @@
Return(true)));
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
+ StatsReports reports;
stats.GetStats(NULL, &reports);
const StatsReport* remote_report = FindNthReportByType(reports,
@@ -917,17 +975,13 @@
// This test verifies that the empty track report exists in the returned stats
// when StatsCollector::UpdateStats is called with ssrc stats.
TEST_F(StatsCollectorTest, ReportsFromRemoteTrack) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, "", false, NULL);
AddIncomingVideoTrackStats();
stats.AddStream(stream_);
- stats.set_session(&session_);
-
- StatsReports reports;
-
// Constructs an ssrc stats update.
cricket::VideoReceiverInfo video_receiver_info;
cricket::VideoMediaInfo stats_read;
@@ -945,6 +999,7 @@
Return(true)));
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
+ StatsReports reports;
stats.GetStats(NULL, &reports);
// |reports| should contain at least one session report, one track report,
// and one ssrc report.
@@ -955,7 +1010,7 @@
std::string ssrc_id = ExtractSsrcStatsValue(
reports, StatsReport::kStatsValueNameSsrc);
- EXPECT_EQ(talk_base::ToString<uint32>(kSsrcOfTrack), ssrc_id);
+ EXPECT_EQ(rtc::ToString<uint32>(kSsrcOfTrack), ssrc_id);
std::string track_id = ExtractSsrcStatsValue(
reports, StatsReport::kStatsValueNameTrackId);
@@ -972,7 +1027,7 @@
local_ders[2] = "some";
local_ders[3] = "der";
local_ders[4] = "values";
- talk_base::FakeSSLCertificate local_cert(DersToPems(local_ders));
+ rtc::FakeSSLCertificate local_cert(DersToPems(local_ders));
// Build remote certificate chain
std::vector<std::string> remote_ders(4);
@@ -980,7 +1035,7 @@
remote_ders[1] = "non-";
remote_ders[2] = "intersecting";
remote_ders[3] = "set";
- talk_base::FakeSSLCertificate remote_cert(DersToPems(remote_ders));
+ rtc::FakeSSLCertificate remote_cert(DersToPems(remote_ders));
TestCertificateReports(local_cert, local_ders, remote_cert, remote_ders);
}
@@ -990,11 +1045,11 @@
TEST_F(StatsCollectorTest, ChainlessCertificateReportsCreated) {
// Build local certificate.
std::string local_der = "This is the local der.";
- talk_base::FakeSSLCertificate local_cert(DerToPem(local_der));
+ rtc::FakeSSLCertificate local_cert(DerToPem(local_der));
// Build remote certificate.
std::string remote_der = "This is somebody else's der.";
- talk_base::FakeSSLCertificate remote_cert(DerToPem(remote_der));
+ rtc::FakeSSLCertificate remote_cert(DerToPem(remote_der));
TestCertificateReports(local_cert, std::vector<std::string>(1, local_der),
remote_cert, std::vector<std::string>(1, remote_der));
@@ -1003,9 +1058,8 @@
// This test verifies that the stats are generated correctly when no
// transport is present.
TEST_F(StatsCollectorTest, NoTransport) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
StatsReports reports; // returned values.
- stats.set_session(&session_);
// Fake stats to process.
cricket::TransportChannelStats channel_stats;
@@ -1021,7 +1075,7 @@
// Configure MockWebRtcSession
EXPECT_CALL(session_, GetTransport(transport_stats.content_name))
- .WillOnce(ReturnNull());
+ .WillRepeatedly(ReturnNull());
EXPECT_CALL(session_, GetStats(_))
.WillOnce(DoAll(SetArgPointee<0>(session_stats),
Return(true)));
@@ -1050,9 +1104,8 @@
// This test verifies that the stats are generated correctly when the transport
// does not have any certificates.
TEST_F(StatsCollectorTest, NoCertificates) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
StatsReports reports; // returned values.
- stats.set_session(&session_);
// Fake stats to process.
cricket::TransportChannelStats channel_stats;
@@ -1067,7 +1120,7 @@
transport_stats;
// Fake transport object.
- talk_base::scoped_ptr<cricket::FakeTransport> transport(
+ rtc::scoped_ptr<cricket::FakeTransport> transport(
new cricket::FakeTransport(
session_.signaling_thread(),
session_.worker_thread(),
@@ -1075,7 +1128,7 @@
// Configure MockWebRtcSession
EXPECT_CALL(session_, GetTransport(transport_stats.content_name))
- .WillOnce(Return(transport.get()));
+ .WillRepeatedly(Return(transport.get()));
EXPECT_CALL(session_, GetStats(_))
.WillOnce(DoAll(SetArgPointee<0>(session_stats),
Return(true)));
@@ -1105,11 +1158,11 @@
TEST_F(StatsCollectorTest, UnsupportedDigestIgnored) {
// Build a local certificate.
std::string local_der = "This is the local der.";
- talk_base::FakeSSLCertificate local_cert(DerToPem(local_der));
+ rtc::FakeSSLCertificate local_cert(DerToPem(local_der));
// Build a remote certificate with an unsupported digest algorithm.
std::string remote_der = "This is somebody else's der.";
- talk_base::FakeSSLCertificate remote_cert(DerToPem(remote_der));
+ rtc::FakeSSLCertificate remote_cert(DerToPem(remote_der));
remote_cert.set_digest_algorithm("foobar");
TestCertificateReports(local_cert, std::vector<std::string>(1, local_der),
@@ -1119,13 +1172,11 @@
// Verifies the correct optons are passed to the VideoMediaChannel when using
// verbose output level.
TEST_F(StatsCollectorTest, StatsOutputLevelVerbose) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
MockVideoMediaChannel* media_channel = new MockVideoMediaChannel();
- cricket::VideoChannel video_channel(talk_base::Thread::Current(),
+ cricket::VideoChannel video_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, "", false, NULL);
- stats.set_session(&session_);
- StatsReports reports; // returned values.
cricket::VideoMediaInfo stats_read;
cricket::BandwidthEstimationInfo bwe;
bwe.total_received_propagation_delta_ms = 10;
@@ -1148,84 +1199,46 @@
Return(true)));
stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelDebug);
+ StatsReports reports; // returned values.
stats.GetStats(NULL, &reports);
std::string result = ExtractBweStatsValue(
- reports, "googReceivedPacketGroupPropagationDeltaSumDebug");
+ reports,
+ StatsReport::kStatsValueNameRecvPacketGroupPropagationDeltaSumDebug);
EXPECT_EQ("10", result);
result = ExtractBweStatsValue(
- reports, "googReceivedPacketGroupPropagationDeltaDebug");
+ reports,
+ StatsReport::kStatsValueNameRecvPacketGroupPropagationDeltaDebug);
EXPECT_EQ("[100, 200]", result);
result = ExtractBweStatsValue(
- reports, "googReceivedPacketGroupArrivalTimeDebug");
+ reports, StatsReport::kStatsValueNameRecvPacketGroupArrivalTimeDebug);
EXPECT_EQ("[1000, 2000]", result);
}
// This test verifies that a local stats object can get statistics via
// AudioTrackInterface::GetStats() method.
TEST_F(StatsCollectorTest, GetStatsFromLocalAudioTrack) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
+ // Ignore unused callback (logspam).
+ EXPECT_CALL(session_, GetTransport(_))
+ .WillRepeatedly(Return(static_cast<cricket::Transport*>(NULL)));
+
MockVoiceMediaChannel* media_channel = new MockVoiceMediaChannel();
// The content_name known by the voice channel.
const std::string kVcName("vcname");
- cricket::VoiceChannel voice_channel(talk_base::Thread::Current(),
+ cricket::VoiceChannel voice_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, kVcName, false);
AddOutgoingAudioTrackStats();
stats.AddStream(stream_);
- stats.AddLocalAudioTrack(audio_track_.get(), kSsrcOfTrack);
-
- stats.set_session(&session_);
-
- // Instruct the session to return stats containing the transport channel.
- InitSessionStats(kVcName);
- EXPECT_CALL(session_, GetStats(_))
- .WillRepeatedly(DoAll(SetArgPointee<0>(session_stats_),
- Return(true)));
+ stats.AddLocalAudioTrack(audio_track_, kSsrcOfTrack);
cricket::VoiceSenderInfo voice_sender_info;
InitVoiceSenderInfo(&voice_sender_info);
- // Constructs an ssrc stats update.
cricket::VoiceMediaInfo stats_read;
- stats_read.senders.push_back(voice_sender_info);
-
- EXPECT_CALL(session_, voice_channel()).WillRepeatedly(Return(&voice_channel));
- EXPECT_CALL(session_, video_channel()).WillRepeatedly(ReturnNull());
- EXPECT_CALL(*media_channel, GetStats(_))
- .WillRepeatedly(DoAll(SetArgPointee<0>(stats_read),
- Return(true)));
-
StatsReports reports; // returned values.
- stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
- stats.GetStats(NULL, &reports);
-
- // Verfy the existence of the track report.
- const StatsReport* report = FindNthReportByType(
- reports, StatsReport::kStatsReportTypeSsrc, 1);
- EXPECT_FALSE(report == NULL);
- std::string track_id = ExtractSsrcStatsValue(
- reports, StatsReport::kStatsValueNameTrackId);
- EXPECT_EQ(kLocalTrackId, track_id);
- std::string ssrc_id = ExtractSsrcStatsValue(
- reports, StatsReport::kStatsValueNameSsrc);
- EXPECT_EQ(talk_base::ToString<uint32>(kSsrcOfTrack), ssrc_id);
-
- // Verifies the values in the track report.
- UpdateVoiceSenderInfoFromAudioTrack(audio_track_.get(), &voice_sender_info);
- VerifyVoiceSenderInfoReport(report, voice_sender_info);
-
- // Verify we get the same result by passing a track to GetStats().
- StatsReports track_reports; // returned values.
- stats.GetStats(audio_track_.get(), &track_reports);
- const StatsReport* track_report = FindNthReportByType(
- track_reports, StatsReport::kStatsReportTypeSsrc, 1);
- EXPECT_TRUE(track_report);
- track_id = ExtractSsrcStatsValue(track_reports,
- StatsReport::kStatsValueNameTrackId);
- EXPECT_EQ(kLocalTrackId, track_id);
- ssrc_id = ExtractSsrcStatsValue(track_reports,
- StatsReport::kStatsValueNameSsrc);
- EXPECT_EQ(talk_base::ToString<uint32>(kSsrcOfTrack), ssrc_id);
- VerifyVoiceSenderInfoReport(track_report, voice_sender_info);
+ SetupAndVerifyAudioTrackStats(
+ audio_track_.get(), stream_.get(), &stats, &voice_channel, kVcName,
+ media_channel, &voice_sender_info, NULL, &stats_read, &reports);
// Verify that there is no remote report for the local audio track because
// we did not set it up.
@@ -1237,68 +1250,45 @@
// This test verifies that audio receive streams populate stats reports
// correctly.
TEST_F(StatsCollectorTest, GetStatsFromRemoteStream) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
+ // Ignore unused callback (logspam).
+ EXPECT_CALL(session_, GetTransport(_))
+ .WillRepeatedly(Return(static_cast<cricket::Transport*>(NULL)));
MockVoiceMediaChannel* media_channel = new MockVoiceMediaChannel();
// The content_name known by the voice channel.
const std::string kVcName("vcname");
- cricket::VoiceChannel voice_channel(talk_base::Thread::Current(),
+ cricket::VoiceChannel voice_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, kVcName, false);
AddIncomingAudioTrackStats();
stats.AddStream(stream_);
- stats.set_session(&session_);
-
- // Instruct the session to return stats containing the transport channel.
- InitSessionStats(kVcName);
- EXPECT_CALL(session_, GetStats(_))
- .WillRepeatedly(DoAll(SetArgPointee<0>(session_stats_),
- Return(true)));
-
cricket::VoiceReceiverInfo voice_receiver_info;
InitVoiceReceiverInfo(&voice_receiver_info);
voice_receiver_info.codec_name = "fake_codec";
- // Constructs an ssrc stats update.
cricket::VoiceMediaInfo stats_read;
- stats_read.receivers.push_back(voice_receiver_info);
-
- EXPECT_CALL(session_, voice_channel()).WillRepeatedly(Return(&voice_channel));
- EXPECT_CALL(session_, video_channel()).WillRepeatedly(ReturnNull());
- EXPECT_CALL(*media_channel, GetStats(_))
- .WillRepeatedly(DoAll(SetArgPointee<0>(stats_read),
- Return(true)));
-
StatsReports reports; // returned values.
- stats.UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard);
- stats.GetStats(NULL, &reports);
-
- // Verify the track id is |kRemoteTrackId|.
- const std::string track_id = ExtractSsrcStatsValue(
- reports, StatsReport::kStatsValueNameTrackId);
- EXPECT_EQ(kRemoteTrackId, track_id);
-
- // Verify the report for this remote track.
- const StatsReport* report = FindNthReportByType(
- reports, StatsReport::kStatsReportTypeSsrc, 1);
- EXPECT_FALSE(report == NULL);
- VerifyVoiceReceiverInfoReport(report, voice_receiver_info);
+ SetupAndVerifyAudioTrackStats(
+ audio_track_.get(), stream_.get(), &stats, &voice_channel, kVcName,
+ media_channel, NULL, &voice_receiver_info, &stats_read, &reports);
}
// This test verifies that a local stats object won't update its statistics
// after a RemoveLocalAudioTrack() call.
TEST_F(StatsCollectorTest, GetStatsAfterRemoveAudioStream) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
+ // Ignore unused callback (logspam).
+ EXPECT_CALL(session_, GetTransport(_))
+ .WillRepeatedly(Return(static_cast<cricket::Transport*>(NULL)));
MockVoiceMediaChannel* media_channel = new MockVoiceMediaChannel();
// The content_name known by the voice channel.
const std::string kVcName("vcname");
- cricket::VoiceChannel voice_channel(talk_base::Thread::Current(),
+ cricket::VoiceChannel voice_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, kVcName, false);
AddOutgoingAudioTrackStats();
stats.AddStream(stream_);
stats.AddLocalAudioTrack(audio_track_.get(), kSsrcOfTrack);
- stats.set_session(&session_);
-
// Instruct the session to return stats containing the transport channel.
InitSessionStats(kVcName);
EXPECT_CALL(session_, GetStats(_))
@@ -1332,7 +1322,7 @@
EXPECT_EQ(kLocalTrackId, track_id);
std::string ssrc_id = ExtractSsrcStatsValue(
reports, StatsReport::kStatsValueNameSsrc);
- EXPECT_EQ(talk_base::ToString<uint32>(kSsrcOfTrack), ssrc_id);
+ EXPECT_EQ(rtc::ToString<uint32>(kSsrcOfTrack), ssrc_id);
// Verifies the values in the track report, no value will be changed by the
// AudioTrackInterface::GetSignalValue() and
@@ -1343,11 +1333,14 @@
// This test verifies that when ongoing and incoming audio tracks are using
// the same ssrc, they populate stats reports correctly.
TEST_F(StatsCollectorTest, LocalAndRemoteTracksWithSameSsrc) {
- webrtc::StatsCollector stats; // Implementation under test.
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
+ // Ignore unused callback (logspam).
+ EXPECT_CALL(session_, GetTransport(_))
+ .WillRepeatedly(Return(static_cast<cricket::Transport*>(NULL)));
MockVoiceMediaChannel* media_channel = new MockVoiceMediaChannel();
// The content_name known by the voice channel.
const std::string kVcName("vcname");
- cricket::VoiceChannel voice_channel(talk_base::Thread::Current(),
+ cricket::VoiceChannel voice_channel(rtc::Thread::Current(),
media_engine_, media_channel, &session_, kVcName, false);
// Create a local stream with a local audio track and adds it to the stats.
@@ -1356,17 +1349,15 @@
stats.AddLocalAudioTrack(audio_track_.get(), kSsrcOfTrack);
// Create a remote stream with a remote audio track and adds it to the stats.
- talk_base::scoped_refptr<webrtc::MediaStream> remote_stream(
+ rtc::scoped_refptr<webrtc::MediaStream> remote_stream(
webrtc::MediaStream::Create("remotestreamlabel"));
- talk_base::scoped_refptr<FakeAudioTrack> remote_track(
- new talk_base::RefCountedObject<FakeAudioTrack>(kRemoteTrackId));
+ rtc::scoped_refptr<FakeAudioTrack> remote_track(
+ new rtc::RefCountedObject<FakeAudioTrack>(kRemoteTrackId));
EXPECT_CALL(session_, GetRemoteTrackIdBySsrc(kSsrcOfTrack, _))
- .WillRepeatedly(DoAll(SetArgPointee<1>(kRemoteTrackId), Return(true)));
+ .WillOnce(DoAll(SetArgPointee<1>(kRemoteTrackId), Return(true)));
remote_stream->AddTrack(remote_track);
stats.AddStream(remote_stream);
- stats.set_session(&session_);
-
// Instruct the session to return stats containing the transport channel.
InitSessionStats(kVcName);
EXPECT_CALL(session_, GetStats(_))
@@ -1408,6 +1399,7 @@
VerifyVoiceSenderInfoReport(track_report, voice_sender_info);
// Get stats for the remote track.
+ reports.clear();
stats.GetStats(remote_track.get(), &reports);
track_report = FindNthReportByType(reports,
StatsReport::kStatsReportTypeSsrc, 1);
@@ -1418,4 +1410,56 @@
VerifyVoiceReceiverInfoReport(track_report, voice_receiver_info);
}
+// This test verifies that when two outgoing audio tracks are using the same
+// ssrc at different times, they populate stats reports correctly.
+// TODO(xians): Figure out if it is possible to encapsulate the setup and
+// avoid duplication of code in test cases.
+TEST_F(StatsCollectorTest, TwoLocalTracksWithSameSsrc) {
+ webrtc::StatsCollector stats(&session_); // Implementation under test.
+ // Ignore unused callback (logspam).
+ EXPECT_CALL(session_, GetTransport(_))
+ .WillRepeatedly(Return(static_cast<cricket::Transport*>(NULL)));
+ MockVoiceMediaChannel* media_channel = new MockVoiceMediaChannel();
+ // The content_name known by the voice channel.
+ const std::string kVcName("vcname");
+ cricket::VoiceChannel voice_channel(rtc::Thread::Current(),
+ media_engine_, media_channel, &session_, kVcName, false);
+
+ // Create a local stream with a local audio track and adds it to the stats.
+ AddOutgoingAudioTrackStats();
+ stats.AddStream(stream_);
+ stats.AddLocalAudioTrack(audio_track_, kSsrcOfTrack);
+
+ cricket::VoiceSenderInfo voice_sender_info;
+ voice_sender_info.add_ssrc(kSsrcOfTrack);
+
+ cricket::VoiceMediaInfo stats_read;
+ StatsReports reports; // returned values.
+ SetupAndVerifyAudioTrackStats(
+ audio_track_.get(), stream_.get(), &stats, &voice_channel, kVcName,
+ media_channel, &voice_sender_info, NULL, &stats_read, &reports);
+
+ // Remove the previous audio track from the stream.
+ stream_->RemoveTrack(audio_track_.get());
+ stats.RemoveLocalAudioTrack(audio_track_.get(), kSsrcOfTrack);
+
+ // Create a new audio track and adds it to the stream and stats.
+ static const std::string kNewTrackId = "new_track_id";
+ rtc::scoped_refptr<FakeAudioTrack> new_audio_track(
+ new rtc::RefCountedObject<FakeAudioTrack>(kNewTrackId));
+ EXPECT_CALL(session_, GetLocalTrackIdBySsrc(kSsrcOfTrack, _))
+ .WillOnce(DoAll(SetArgPointee<1>(kNewTrackId), Return(true)));
+ stream_->AddTrack(new_audio_track);
+
+ stats.AddLocalAudioTrack(new_audio_track, kSsrcOfTrack);
+ stats.ClearUpdateStatsCache();
+ cricket::VoiceSenderInfo new_voice_sender_info;
+ InitVoiceSenderInfo(&new_voice_sender_info);
+ cricket::VoiceMediaInfo new_stats_read;
+ reports.clear();
+ SetupAndVerifyAudioTrackStats(
+ new_audio_track.get(), stream_.get(), &stats, &voice_channel, kVcName,
+ media_channel, &new_voice_sender_info, NULL, &new_stats_read, &reports);
+}
+
} // namespace
diff --git a/app/webrtc/statstypes.h b/app/webrtc/statstypes.h
index 22e281c..656b83c 100644
--- a/app/webrtc/statstypes.h
+++ b/app/webrtc/statstypes.h
@@ -31,38 +31,104 @@
#ifndef TALK_APP_WEBRTC_STATSTYPES_H_
#define TALK_APP_WEBRTC_STATSTYPES_H_
+#include <set>
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/stringencode.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/stringencode.h"
namespace webrtc {
+// TODO(tommi): Move all the implementation that's in this file and
+// statscollector.cc related to these types, into a new, statstypes.cc file.
+
class StatsReport {
public:
- StatsReport() : timestamp(0) { }
+ // TODO(tommi): Remove this ctor.
+ StatsReport() : timestamp(0) {}
+ // TODO(tommi): Make protected and disallow copy completely once not needed.
+ StatsReport(const StatsReport& src)
+ : id(src.id),
+ type(src.type),
+ timestamp(src.timestamp),
+ values(src.values) {}
+
+ // TODO(tommi): Make this copy constructor protected.
+ StatsReport& operator=(const StatsReport& src) {
+ ASSERT(id == src.id);
+ type = src.type;
+ timestamp = src.timestamp;
+ values = src.values;
+ return *this;
+ }
+
+ // Constructor is protected to force use of StatsSet.
+ // TODO(tommi): Make this ctor protected.
+ explicit StatsReport(const std::string& id) : id(id), timestamp(0) {}
+
+ // Operators provided for STL container/algorithm support.
+ bool operator<(const StatsReport& other) const { return id < other.id; }
+ bool operator==(const StatsReport& other) const { return id == other.id; }
+ // Special support for being able to use std::find on a container
+ // without requiring a new StatsReport instance.
+ bool operator==(const std::string& other_id) const { return id == other_id; }
+
+ // TODO(tommi): Change this to be an enum type that holds all the
+ // kStatsValueName constants.
+ typedef const char* StatsValueName;
+
+ // The unique identifier for this object.
+ // This is used as a key for this report in ordered containers,
+ // so it must never be changed.
+ // TODO(tommi): Make this member variable const.
std::string id; // See below for contents.
std::string type; // See below for contents.
struct Value {
- std::string name;
+ Value() : name(NULL) {}
+ // The copy ctor can't be declared as explicit due to problems with STL.
+ Value(const Value& other) : name(other.name), value(other.value) {}
+ explicit Value(StatsValueName name) : name(name) {}
+ Value(StatsValueName name, const std::string& value)
+ : name(name), value(value) {
+ }
+
+ // TODO(tommi): Remove this operator once we don't need it.
+ // The operator is provided for compatibility with STL containers.
+ // The public |name| member variable is otherwise meant to be read-only.
+ Value& operator=(const Value& other) {
+ const_cast<StatsValueName&>(name) = other.name;
+ value = other.value;
+ return *this;
+ }
+
+ // TODO(tommi): Change implementation to do a simple enum value-to-static-
+ // string conversion when client code has been updated to use this method
+ // instead of the |name| member variable.
+ const char* display_name() const { return name; }
+
+ const StatsValueName name;
+
std::string value;
};
- void AddValue(const std::string& name, const std::string& value);
- void AddValue(const std::string& name, int64 value);
+ void AddValue(StatsValueName name, const std::string& value);
+ void AddValue(StatsValueName name, int64 value);
template <typename T>
- void AddValue(const std::string& name, const std::vector<T>& value);
- void AddBoolean(const std::string& name, bool value);
+ void AddValue(StatsValueName name, const std::vector<T>& value);
+ void AddBoolean(StatsValueName name, bool value);
- void ReplaceValue(const std::string& name, const std::string& value);
+ void ReplaceValue(StatsValueName name, const std::string& value);
double timestamp; // Time since 1970-01-01T00:00:00Z in milliseconds.
typedef std::vector<Value> Values;
Values values;
+ // TODO(tommi): These should all be enum values.
+
// StatsReport types.
// A StatsReport of |type| = "googSession" contains overall information
// about the thing libjingle calls a session (which may contain one
@@ -141,6 +207,7 @@
static const char kStatsValueNameBandwidthLimitedResolution[];
static const char kStatsValueNameCpuLimitedResolution[];
static const char kStatsValueNameViewLimitedResolution[];
+ static const char kStatsValueNameAdaptationChanges[];
static const char kStatsValueNameEchoCancellationQualityMin[];
static const char kStatsValueNameEchoDelayMedian[];
static const char kStatsValueNameEchoDelayStdDev[];
@@ -209,7 +276,70 @@
static const char kStatsValueNameDecodingPLCCNG[];
};
-typedef std::vector<StatsReport> StatsReports;
+// This class is provided for the cases where we need to keep
+// snapshots of reports around. This is an edge case.
+// TODO(tommi): Move into the private section of StatsSet.
+class StatsReportCopyable : public StatsReport {
+ public:
+ StatsReportCopyable(const std::string& id) : StatsReport(id) {}
+ explicit StatsReportCopyable(const StatsReport& src)
+ : StatsReport(src) {}
+
+ using StatsReport::operator=;
+};
+
+// Typedef for an array of const StatsReport pointers.
+// Ownership of the pointers held by this implementation is assumed to lie
+// elsewhere and lifetime guarantees are made by the implementation that uses
+// this type. In the StatsCollector, object ownership lies with the StatsSet
+// class.
+typedef std::vector<const StatsReport*> StatsReports;
+
+// A map from the report id to the report.
+// This class wraps an STL container and provides a limited set of
+// functionality in order to keep things simple.
+// TODO(tommi): Use a thread checker here (currently not in libjingle).
+class StatsSet {
+ public:
+ StatsSet() {}
+ ~StatsSet() {}
+
+ typedef std::set<StatsReportCopyable> Container;
+ typedef Container::iterator iterator;
+ typedef Container::const_iterator const_iterator;
+
+ const_iterator begin() const { return list_.begin(); }
+ const_iterator end() const { return list_.end(); }
+
+ // Creates a new report object with |id| that does not already
+ // exist in the list of reports.
+ StatsReport* InsertNew(const std::string& id) {
+ ASSERT(Find(id) == NULL);
+ const StatsReport* ret = &(*list_.insert(StatsReportCopyable(id)).first);
+ return const_cast<StatsReport*>(ret);
+ }
+
+ StatsReport* FindOrAddNew(const std::string& id) {
+ StatsReport* ret = Find(id);
+ return ret ? ret : InsertNew(id);
+ }
+
+ StatsReport* ReplaceOrAddNew(const std::string& id) {
+ list_.erase(id);
+ return InsertNew(id);
+ }
+
+ // Looks for a report with the given |id|. If one is not found, NULL
+ // will be returned.
+ StatsReport* Find(const std::string& id) {
+ const_iterator it = std::find(begin(), end(), id);
+ return it == end() ? NULL :
+ const_cast<StatsReport*>(static_cast<const StatsReport*>(&(*it)));
+ }
+
+ private:
+ Container list_;
+};
} // namespace webrtc
diff --git a/app/webrtc/streamcollection.h b/app/webrtc/streamcollection.h
index 7796b42..0db59a3 100644
--- a/app/webrtc/streamcollection.h
+++ b/app/webrtc/streamcollection.h
@@ -38,16 +38,16 @@
// Implementation of StreamCollection.
class StreamCollection : public StreamCollectionInterface {
public:
- static talk_base::scoped_refptr<StreamCollection> Create() {
- talk_base::RefCountedObject<StreamCollection>* implementation =
- new talk_base::RefCountedObject<StreamCollection>();
+ static rtc::scoped_refptr<StreamCollection> Create() {
+ rtc::RefCountedObject<StreamCollection>* implementation =
+ new rtc::RefCountedObject<StreamCollection>();
return implementation;
}
- static talk_base::scoped_refptr<StreamCollection> Create(
+ static rtc::scoped_refptr<StreamCollection> Create(
StreamCollection* streams) {
- talk_base::RefCountedObject<StreamCollection>* implementation =
- new talk_base::RefCountedObject<StreamCollection>(streams);
+ rtc::RefCountedObject<StreamCollection>* implementation =
+ new rtc::RefCountedObject<StreamCollection>(streams);
return implementation;
}
@@ -115,7 +115,7 @@
explicit StreamCollection(StreamCollection* original)
: media_streams_(original->media_streams_) {
}
- typedef std::vector<talk_base::scoped_refptr<MediaStreamInterface> >
+ typedef std::vector<rtc::scoped_refptr<MediaStreamInterface> >
StreamVector;
StreamVector media_streams_;
};
diff --git a/app/webrtc/test/fakeaudiocapturemodule.cc b/app/webrtc/test/fakeaudiocapturemodule.cc
index c22ed6f..2ad3f0f 100644
--- a/app/webrtc/test/fakeaudiocapturemodule.cc
+++ b/app/webrtc/test/fakeaudiocapturemodule.cc
@@ -27,10 +27,10 @@
#include "talk/app/webrtc/test/fakeaudiocapturemodule.h"
-#include "talk/base/common.h"
-#include "talk/base/refcount.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/refcount.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timeutils.h"
// Audio sample value that is high enough that it doesn't occur naturally when
// frames are being faked. E.g. NetEq will not generate this large sample value
@@ -58,7 +58,7 @@
};
FakeAudioCaptureModule::FakeAudioCaptureModule(
- talk_base::Thread* process_thread)
+ rtc::Thread* process_thread)
: last_process_time_ms_(0),
audio_callback_(NULL),
recording_(false),
@@ -77,12 +77,12 @@
process_thread_->Send(this, MSG_STOP_PROCESS);
}
-talk_base::scoped_refptr<FakeAudioCaptureModule> FakeAudioCaptureModule::Create(
- talk_base::Thread* process_thread) {
+rtc::scoped_refptr<FakeAudioCaptureModule> FakeAudioCaptureModule::Create(
+ rtc::Thread* process_thread) {
if (process_thread == NULL) return NULL;
- talk_base::scoped_refptr<FakeAudioCaptureModule> capture_module(
- new talk_base::RefCountedObject<FakeAudioCaptureModule>(process_thread));
+ rtc::scoped_refptr<FakeAudioCaptureModule> capture_module(
+ new rtc::RefCountedObject<FakeAudioCaptureModule>(process_thread));
if (!capture_module->Initialize()) {
return NULL;
}
@@ -90,19 +90,12 @@
}
int FakeAudioCaptureModule::frames_received() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return frames_received_;
}
-int32_t FakeAudioCaptureModule::Version(char* /*version*/,
- uint32_t& /*remaining_buffer_in_bytes*/,
- uint32_t& /*position*/) const {
- ASSERT(false);
- return 0;
-}
-
int32_t FakeAudioCaptureModule::TimeUntilNextProcess() {
- const uint32 current_time = talk_base::Time();
+ const uint32 current_time = rtc::Time();
if (current_time < last_process_time_ms_) {
// TODO: wraparound could be handled more gracefully.
return 0;
@@ -115,7 +108,7 @@
}
int32_t FakeAudioCaptureModule::Process() {
- last_process_time_ms_ = talk_base::Time();
+ last_process_time_ms_ = rtc::Time();
return 0;
}
@@ -144,7 +137,7 @@
int32_t FakeAudioCaptureModule::RegisterAudioCallback(
webrtc::AudioTransport* audio_callback) {
- talk_base::CritScope cs(&crit_callback_);
+ rtc::CritScope cs(&crit_callback_);
audio_callback_ = audio_callback;
return 0;
}
@@ -249,7 +242,7 @@
return -1;
}
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
playing_ = true;
}
bool start = true;
@@ -260,7 +253,7 @@
int32_t FakeAudioCaptureModule::StopPlayout() {
bool start = false;
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
playing_ = false;
start = ShouldStartProcessing();
}
@@ -269,7 +262,7 @@
}
bool FakeAudioCaptureModule::Playing() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return playing_;
}
@@ -278,7 +271,7 @@
return -1;
}
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
recording_ = true;
}
bool start = true;
@@ -289,7 +282,7 @@
int32_t FakeAudioCaptureModule::StopRecording() {
bool start = false;
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
recording_ = false;
start = ShouldStartProcessing();
}
@@ -298,7 +291,7 @@
}
bool FakeAudioCaptureModule::Recording() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return recording_;
}
@@ -325,12 +318,6 @@
return 0;
}
-int32_t FakeAudioCaptureModule::SpeakerIsAvailable(bool* available) {
- // No speaker, just dropping audio. Return success.
- *available = true;
- return 0;
-}
-
int32_t FakeAudioCaptureModule::InitSpeaker() {
// No speaker, just playing from file. Return success.
return 0;
@@ -341,12 +328,6 @@
return 0;
}
-int32_t FakeAudioCaptureModule::MicrophoneIsAvailable(bool* available) {
- // No microphone, just playing from file. Return success.
- *available = true;
- return 0;
-}
-
int32_t FakeAudioCaptureModule::InitMicrophone() {
// No microphone, just playing from file. Return success.
return 0;
@@ -397,13 +378,13 @@
}
int32_t FakeAudioCaptureModule::SetMicrophoneVolume(uint32_t volume) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
current_mic_level_ = volume;
return 0;
}
int32_t FakeAudioCaptureModule::MicrophoneVolume(uint32_t* volume) const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
*volume = current_mic_level_;
return 0;
}
@@ -617,7 +598,7 @@
return 0;
}
-void FakeAudioCaptureModule::OnMessage(talk_base::Message* msg) {
+void FakeAudioCaptureModule::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_START_PROCESS:
StartProcessP();
@@ -641,7 +622,7 @@
// sent to it. Note that the audio processing pipeline will likely distort the
// original signal.
SetSendBuffer(kHighSampleValue);
- last_process_time_ms_ = talk_base::Time();
+ last_process_time_ms_ = rtc::Time();
return true;
}
@@ -681,7 +662,7 @@
}
void FakeAudioCaptureModule::StartProcessP() {
- ASSERT(talk_base::Thread::Current() == process_thread_);
+ ASSERT(rtc::Thread::Current() == process_thread_);
if (started_) {
// Already started.
return;
@@ -690,16 +671,16 @@
}
void FakeAudioCaptureModule::ProcessFrameP() {
- ASSERT(talk_base::Thread::Current() == process_thread_);
+ ASSERT(rtc::Thread::Current() == process_thread_);
if (!started_) {
- next_frame_time_ = talk_base::Time();
+ next_frame_time_ = rtc::Time();
started_ = true;
}
bool playing;
bool recording;
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
playing = playing_;
recording = recording_;
}
@@ -713,16 +694,16 @@
}
next_frame_time_ += kTimePerFrameMs;
- const uint32 current_time = talk_base::Time();
+ const uint32 current_time = rtc::Time();
const uint32 wait_time = (next_frame_time_ > current_time) ?
next_frame_time_ - current_time : 0;
process_thread_->PostDelayed(wait_time, this, MSG_RUN_PROCESS);
}
void FakeAudioCaptureModule::ReceiveFrameP() {
- ASSERT(talk_base::Thread::Current() == process_thread_);
+ ASSERT(rtc::Thread::Current() == process_thread_);
{
- talk_base::CritScope cs(&crit_callback_);
+ rtc::CritScope cs(&crit_callback_);
if (!audio_callback_) {
return;
}
@@ -730,20 +711,20 @@
uint32_t nSamplesOut = 0;
#ifdef USE_WEBRTC_DEV_BRANCH
int64_t elapsed_time_ms = 0;
+#else
+ uint32_t rtp_timestamp = 0;
+#endif
int64_t ntp_time_ms = 0;
if (audio_callback_->NeedMorePlayData(kNumberSamples, kNumberBytesPerSample,
kNumberOfChannels, kSamplesPerSecond,
rec_buffer_, nSamplesOut,
+#ifdef USE_WEBRTC_DEV_BRANCH
&elapsed_time_ms, &ntp_time_ms) != 0) {
- ASSERT(false);
- }
#else
- if (audio_callback_->NeedMorePlayData(kNumberSamples, kNumberBytesPerSample,
- kNumberOfChannels, kSamplesPerSecond,
- rec_buffer_, nSamplesOut) != 0) {
+ &rtp_timestamp, &ntp_time_ms) != 0) {
+#endif
ASSERT(false);
}
-#endif
ASSERT(nSamplesOut == kNumberSamples);
}
// The SetBuffer() function ensures that after decoding, the audio buffer
@@ -753,14 +734,14 @@
// has been received from the remote side (i.e. faked frames are not being
// pulled).
if (CheckRecBuffer(kHighSampleValue)) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
++frames_received_;
}
}
void FakeAudioCaptureModule::SendFrameP() {
- ASSERT(talk_base::Thread::Current() == process_thread_);
- talk_base::CritScope cs(&crit_callback_);
+ ASSERT(rtc::Thread::Current() == process_thread_);
+ rtc::CritScope cs(&crit_callback_);
if (!audio_callback_) {
return;
}
@@ -780,7 +761,7 @@
}
void FakeAudioCaptureModule::StopProcessP() {
- ASSERT(talk_base::Thread::Current() == process_thread_);
+ ASSERT(rtc::Thread::Current() == process_thread_);
started_ = false;
process_thread_->Clear(this);
}
diff --git a/app/webrtc/test/fakeaudiocapturemodule.h b/app/webrtc/test/fakeaudiocapturemodule.h
index 2267902..79b72b6 100644
--- a/app/webrtc/test/fakeaudiocapturemodule.h
+++ b/app/webrtc/test/fakeaudiocapturemodule.h
@@ -37,22 +37,22 @@
#ifndef TALK_APP_WEBRTC_TEST_FAKEAUDIOCAPTUREMODULE_H_
#define TALK_APP_WEBRTC_TEST_FAKEAUDIOCAPTUREMODULE_H_
-#include "talk/base/basictypes.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/scoped_ref_ptr.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/scoped_ref_ptr.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/audio_device/include/audio_device.h"
-namespace talk_base {
+namespace rtc {
class Thread;
-} // namespace talk_base
+} // namespace rtc
class FakeAudioCaptureModule
: public webrtc::AudioDeviceModule,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
typedef uint16 Sample;
@@ -64,8 +64,8 @@
// Creates a FakeAudioCaptureModule or returns NULL on failure.
// |process_thread| is used to push and pull audio frames to and from the
// returned instance. Note: ownership of |process_thread| is not handed over.
- static talk_base::scoped_refptr<FakeAudioCaptureModule> Create(
- talk_base::Thread* process_thread);
+ static rtc::scoped_refptr<FakeAudioCaptureModule> Create(
+ rtc::Thread* process_thread);
// Returns the number of frames that have been successfully pulled by the
// instance. Note that correctly detecting success can only be done if the
@@ -76,133 +76,132 @@
// Only functions called by PeerConnection are implemented, the rest do
// nothing and return success. If a function is not expected to be called by
// PeerConnection an assertion is triggered if it is in fact called.
- virtual int32_t Version(char* version,
- uint32_t& remaining_buffer_in_bytes,
- uint32_t& position) const;
- virtual int32_t TimeUntilNextProcess();
- virtual int32_t Process();
- virtual int32_t ChangeUniqueId(const int32_t id);
+ virtual int32_t TimeUntilNextProcess() OVERRIDE;
+ virtual int32_t Process() OVERRIDE;
+ virtual int32_t ChangeUniqueId(const int32_t id) OVERRIDE;
- virtual int32_t ActiveAudioLayer(AudioLayer* audio_layer) const;
+ virtual int32_t ActiveAudioLayer(AudioLayer* audio_layer) const OVERRIDE;
- virtual ErrorCode LastError() const;
+ virtual ErrorCode LastError() const OVERRIDE;
virtual int32_t RegisterEventObserver(
- webrtc::AudioDeviceObserver* event_callback);
+ webrtc::AudioDeviceObserver* event_callback) OVERRIDE;
// Note: Calling this method from a callback may result in deadlock.
- virtual int32_t RegisterAudioCallback(webrtc::AudioTransport* audio_callback);
+ virtual int32_t RegisterAudioCallback(
+ webrtc::AudioTransport* audio_callback) OVERRIDE;
- virtual int32_t Init();
- virtual int32_t Terminate();
- virtual bool Initialized() const;
+ virtual int32_t Init() OVERRIDE;
+ virtual int32_t Terminate() OVERRIDE;
+ virtual bool Initialized() const OVERRIDE;
- virtual int16_t PlayoutDevices();
- virtual int16_t RecordingDevices();
- virtual int32_t PlayoutDeviceName(uint16_t index,
- char name[webrtc::kAdmMaxDeviceNameSize],
- char guid[webrtc::kAdmMaxGuidSize]);
- virtual int32_t RecordingDeviceName(uint16_t index,
- char name[webrtc::kAdmMaxDeviceNameSize],
- char guid[webrtc::kAdmMaxGuidSize]);
+ virtual int16_t PlayoutDevices() OVERRIDE;
+ virtual int16_t RecordingDevices() OVERRIDE;
+ virtual int32_t PlayoutDeviceName(
+ uint16_t index,
+ char name[webrtc::kAdmMaxDeviceNameSize],
+ char guid[webrtc::kAdmMaxGuidSize]) OVERRIDE;
+ virtual int32_t RecordingDeviceName(
+ uint16_t index,
+ char name[webrtc::kAdmMaxDeviceNameSize],
+ char guid[webrtc::kAdmMaxGuidSize]) OVERRIDE;
- virtual int32_t SetPlayoutDevice(uint16_t index);
- virtual int32_t SetPlayoutDevice(WindowsDeviceType device);
- virtual int32_t SetRecordingDevice(uint16_t index);
- virtual int32_t SetRecordingDevice(WindowsDeviceType device);
+ virtual int32_t SetPlayoutDevice(uint16_t index) OVERRIDE;
+ virtual int32_t SetPlayoutDevice(WindowsDeviceType device) OVERRIDE;
+ virtual int32_t SetRecordingDevice(uint16_t index) OVERRIDE;
+ virtual int32_t SetRecordingDevice(WindowsDeviceType device) OVERRIDE;
- virtual int32_t PlayoutIsAvailable(bool* available);
- virtual int32_t InitPlayout();
- virtual bool PlayoutIsInitialized() const;
- virtual int32_t RecordingIsAvailable(bool* available);
- virtual int32_t InitRecording();
- virtual bool RecordingIsInitialized() const;
+ virtual int32_t PlayoutIsAvailable(bool* available) OVERRIDE;
+ virtual int32_t InitPlayout() OVERRIDE;
+ virtual bool PlayoutIsInitialized() const OVERRIDE;
+ virtual int32_t RecordingIsAvailable(bool* available) OVERRIDE;
+ virtual int32_t InitRecording() OVERRIDE;
+ virtual bool RecordingIsInitialized() const OVERRIDE;
- virtual int32_t StartPlayout();
- virtual int32_t StopPlayout();
- virtual bool Playing() const;
- virtual int32_t StartRecording();
- virtual int32_t StopRecording();
- virtual bool Recording() const;
+ virtual int32_t StartPlayout() OVERRIDE;
+ virtual int32_t StopPlayout() OVERRIDE;
+ virtual bool Playing() const OVERRIDE;
+ virtual int32_t StartRecording() OVERRIDE;
+ virtual int32_t StopRecording() OVERRIDE;
+ virtual bool Recording() const OVERRIDE;
- virtual int32_t SetAGC(bool enable);
- virtual bool AGC() const;
+ virtual int32_t SetAGC(bool enable) OVERRIDE;
+ virtual bool AGC() const OVERRIDE;
virtual int32_t SetWaveOutVolume(uint16_t volume_left,
- uint16_t volume_right);
+ uint16_t volume_right) OVERRIDE;
virtual int32_t WaveOutVolume(uint16_t* volume_left,
- uint16_t* volume_right) const;
+ uint16_t* volume_right) const OVERRIDE;
- virtual int32_t SpeakerIsAvailable(bool* available);
- virtual int32_t InitSpeaker();
- virtual bool SpeakerIsInitialized() const;
- virtual int32_t MicrophoneIsAvailable(bool* available);
- virtual int32_t InitMicrophone();
- virtual bool MicrophoneIsInitialized() const;
+ virtual int32_t InitSpeaker() OVERRIDE;
+ virtual bool SpeakerIsInitialized() const OVERRIDE;
+ virtual int32_t InitMicrophone() OVERRIDE;
+ virtual bool MicrophoneIsInitialized() const OVERRIDE;
- virtual int32_t SpeakerVolumeIsAvailable(bool* available);
- virtual int32_t SetSpeakerVolume(uint32_t volume);
- virtual int32_t SpeakerVolume(uint32_t* volume) const;
- virtual int32_t MaxSpeakerVolume(uint32_t* max_volume) const;
- virtual int32_t MinSpeakerVolume(uint32_t* min_volume) const;
- virtual int32_t SpeakerVolumeStepSize(uint16_t* step_size) const;
+ virtual int32_t SpeakerVolumeIsAvailable(bool* available) OVERRIDE;
+ virtual int32_t SetSpeakerVolume(uint32_t volume) OVERRIDE;
+ virtual int32_t SpeakerVolume(uint32_t* volume) const OVERRIDE;
+ virtual int32_t MaxSpeakerVolume(uint32_t* max_volume) const OVERRIDE;
+ virtual int32_t MinSpeakerVolume(uint32_t* min_volume) const OVERRIDE;
+ virtual int32_t SpeakerVolumeStepSize(uint16_t* step_size) const OVERRIDE;
- virtual int32_t MicrophoneVolumeIsAvailable(bool* available);
- virtual int32_t SetMicrophoneVolume(uint32_t volume);
- virtual int32_t MicrophoneVolume(uint32_t* volume) const;
- virtual int32_t MaxMicrophoneVolume(uint32_t* max_volume) const;
+ virtual int32_t MicrophoneVolumeIsAvailable(bool* available) OVERRIDE;
+ virtual int32_t SetMicrophoneVolume(uint32_t volume) OVERRIDE;
+ virtual int32_t MicrophoneVolume(uint32_t* volume) const OVERRIDE;
+ virtual int32_t MaxMicrophoneVolume(uint32_t* max_volume) const OVERRIDE;
- virtual int32_t MinMicrophoneVolume(uint32_t* min_volume) const;
- virtual int32_t MicrophoneVolumeStepSize(uint16_t* step_size) const;
+ virtual int32_t MinMicrophoneVolume(uint32_t* min_volume) const OVERRIDE;
+ virtual int32_t MicrophoneVolumeStepSize(uint16_t* step_size) const OVERRIDE;
- virtual int32_t SpeakerMuteIsAvailable(bool* available);
- virtual int32_t SetSpeakerMute(bool enable);
- virtual int32_t SpeakerMute(bool* enabled) const;
+ virtual int32_t SpeakerMuteIsAvailable(bool* available) OVERRIDE;
+ virtual int32_t SetSpeakerMute(bool enable) OVERRIDE;
+ virtual int32_t SpeakerMute(bool* enabled) const OVERRIDE;
- virtual int32_t MicrophoneMuteIsAvailable(bool* available);
- virtual int32_t SetMicrophoneMute(bool enable);
- virtual int32_t MicrophoneMute(bool* enabled) const;
+ virtual int32_t MicrophoneMuteIsAvailable(bool* available) OVERRIDE;
+ virtual int32_t SetMicrophoneMute(bool enable) OVERRIDE;
+ virtual int32_t MicrophoneMute(bool* enabled) const OVERRIDE;
- virtual int32_t MicrophoneBoostIsAvailable(bool* available);
- virtual int32_t SetMicrophoneBoost(bool enable);
- virtual int32_t MicrophoneBoost(bool* enabled) const;
+ virtual int32_t MicrophoneBoostIsAvailable(bool* available) OVERRIDE;
+ virtual int32_t SetMicrophoneBoost(bool enable) OVERRIDE;
+ virtual int32_t MicrophoneBoost(bool* enabled) const OVERRIDE;
- virtual int32_t StereoPlayoutIsAvailable(bool* available) const;
- virtual int32_t SetStereoPlayout(bool enable);
- virtual int32_t StereoPlayout(bool* enabled) const;
- virtual int32_t StereoRecordingIsAvailable(bool* available) const;
- virtual int32_t SetStereoRecording(bool enable);
- virtual int32_t StereoRecording(bool* enabled) const;
- virtual int32_t SetRecordingChannel(const ChannelType channel);
- virtual int32_t RecordingChannel(ChannelType* channel) const;
+ virtual int32_t StereoPlayoutIsAvailable(bool* available) const OVERRIDE;
+ virtual int32_t SetStereoPlayout(bool enable) OVERRIDE;
+ virtual int32_t StereoPlayout(bool* enabled) const OVERRIDE;
+ virtual int32_t StereoRecordingIsAvailable(bool* available) const OVERRIDE;
+ virtual int32_t SetStereoRecording(bool enable) OVERRIDE;
+ virtual int32_t StereoRecording(bool* enabled) const OVERRIDE;
+ virtual int32_t SetRecordingChannel(const ChannelType channel) OVERRIDE;
+ virtual int32_t RecordingChannel(ChannelType* channel) const OVERRIDE;
virtual int32_t SetPlayoutBuffer(const BufferType type,
- uint16_t size_ms = 0);
+ uint16_t size_ms = 0) OVERRIDE;
virtual int32_t PlayoutBuffer(BufferType* type,
- uint16_t* size_ms) const;
- virtual int32_t PlayoutDelay(uint16_t* delay_ms) const;
- virtual int32_t RecordingDelay(uint16_t* delay_ms) const;
+ uint16_t* size_ms) const OVERRIDE;
+ virtual int32_t PlayoutDelay(uint16_t* delay_ms) const OVERRIDE;
+ virtual int32_t RecordingDelay(uint16_t* delay_ms) const OVERRIDE;
- virtual int32_t CPULoad(uint16_t* load) const;
+ virtual int32_t CPULoad(uint16_t* load) const OVERRIDE;
virtual int32_t StartRawOutputFileRecording(
- const char pcm_file_name_utf8[webrtc::kAdmMaxFileNameSize]);
- virtual int32_t StopRawOutputFileRecording();
+ const char pcm_file_name_utf8[webrtc::kAdmMaxFileNameSize]) OVERRIDE;
+ virtual int32_t StopRawOutputFileRecording() OVERRIDE;
virtual int32_t StartRawInputFileRecording(
- const char pcm_file_name_utf8[webrtc::kAdmMaxFileNameSize]);
- virtual int32_t StopRawInputFileRecording();
+ const char pcm_file_name_utf8[webrtc::kAdmMaxFileNameSize]) OVERRIDE;
+ virtual int32_t StopRawInputFileRecording() OVERRIDE;
- virtual int32_t SetRecordingSampleRate(const uint32_t samples_per_sec);
- virtual int32_t RecordingSampleRate(uint32_t* samples_per_sec) const;
- virtual int32_t SetPlayoutSampleRate(const uint32_t samples_per_sec);
- virtual int32_t PlayoutSampleRate(uint32_t* samples_per_sec) const;
+ virtual int32_t SetRecordingSampleRate(
+ const uint32_t samples_per_sec) OVERRIDE;
+ virtual int32_t RecordingSampleRate(uint32_t* samples_per_sec) const OVERRIDE;
+ virtual int32_t SetPlayoutSampleRate(const uint32_t samples_per_sec) OVERRIDE;
+ virtual int32_t PlayoutSampleRate(uint32_t* samples_per_sec) const OVERRIDE;
- virtual int32_t ResetAudioDevice();
- virtual int32_t SetLoudspeakerStatus(bool enable);
- virtual int32_t GetLoudspeakerStatus(bool* enabled) const;
+ virtual int32_t ResetAudioDevice() OVERRIDE;
+ virtual int32_t SetLoudspeakerStatus(bool enable) OVERRIDE;
+ virtual int32_t GetLoudspeakerStatus(bool* enabled) const OVERRIDE;
// End of functions inherited from webrtc::AudioDeviceModule.
- // The following function is inherited from talk_base::MessageHandler.
- virtual void OnMessage(talk_base::Message* msg);
+ // The following function is inherited from rtc::MessageHandler.
+ virtual void OnMessage(rtc::Message* msg) OVERRIDE;
protected:
// The constructor is protected because the class needs to be created as a
@@ -210,7 +209,7 @@
// exposed in which case the burden of proper instantiation would be put on
// the creator of a FakeAudioCaptureModule instance. To create an instance of
// this class use the Create(..) API.
- explicit FakeAudioCaptureModule(talk_base::Thread* process_thread);
+ explicit FakeAudioCaptureModule(rtc::Thread* process_thread);
// The destructor is protected because it is reference counted and should not
// be deleted directly.
virtual ~FakeAudioCaptureModule();
@@ -271,7 +270,7 @@
uint32 next_frame_time_;
// User provided thread context.
- talk_base::Thread* process_thread_;
+ rtc::Thread* process_thread_;
// Buffer for storing samples received from the webrtc::AudioTransport.
char rec_buffer_[kNumberSamples * kNumberBytesPerSample];
@@ -285,10 +284,10 @@
// Protects variables that are accessed from process_thread_ and
// the main thread.
- mutable talk_base::CriticalSection crit_;
+ mutable rtc::CriticalSection crit_;
// Protects |audio_callback_| that is accessed from process_thread_ and
// the main thread.
- talk_base::CriticalSection crit_callback_;
+ rtc::CriticalSection crit_callback_;
};
#endif // TALK_APP_WEBRTC_TEST_FAKEAUDIOCAPTUREMODULE_H_
diff --git a/app/webrtc/test/fakeaudiocapturemodule_unittest.cc b/app/webrtc/test/fakeaudiocapturemodule_unittest.cc
index ab0db06..ddacc38 100644
--- a/app/webrtc/test/fakeaudiocapturemodule_unittest.cc
+++ b/app/webrtc/test/fakeaudiocapturemodule_unittest.cc
@@ -29,9 +29,9 @@
#include <algorithm>
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ref_ptr.h"
-#include "talk/base/thread.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ref_ptr.h"
+#include "webrtc/base/thread.h"
using std::min;
@@ -49,7 +49,7 @@
virtual void SetUp() {
fake_audio_capture_module_ = FakeAudioCaptureModule::Create(
- talk_base::Thread::Current());
+ rtc::Thread::Current());
EXPECT_TRUE(fake_audio_capture_module_.get() != NULL);
}
@@ -84,13 +84,13 @@
const uint8_t nChannels,
const uint32_t samplesPerSec,
void* audioSamples,
-#ifdef USE_WEBRTC_DEV_BRANCH
uint32_t& nSamplesOut,
+#ifdef USE_WEBRTC_DEV_BRANCH
int64_t* elapsed_time_ms,
- int64_t* ntp_time_ms) {
#else
- uint32_t& nSamplesOut) {
+ uint32_t* rtp_timestamp,
#endif
+ int64_t* ntp_time_ms) {
++pull_iterations_;
const uint32_t audio_buffer_size = nSamples * nBytesPerSample;
const uint32_t bytes_out = RecordedDataReceived() ?
@@ -99,15 +99,17 @@
nSamplesOut = bytes_out / nBytesPerSample;
#ifdef USE_WEBRTC_DEV_BRANCH
*elapsed_time_ms = 0;
- *ntp_time_ms = 0;
+#else
+ *rtp_timestamp = 0;
#endif
+ *ntp_time_ms = 0;
return 0;
}
int push_iterations() const { return push_iterations_; }
int pull_iterations() const { return pull_iterations_; }
- talk_base::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
+ rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
private:
bool RecordedDataReceived() const {
@@ -143,11 +145,6 @@
TEST_F(FakeAdmTest, PlayoutTest) {
EXPECT_EQ(0, fake_audio_capture_module_->RegisterAudioCallback(this));
- bool speaker_available = false;
- EXPECT_EQ(0, fake_audio_capture_module_->SpeakerIsAvailable(
- &speaker_available));
- EXPECT_TRUE(speaker_available);
-
bool stereo_available = false;
EXPECT_EQ(0,
fake_audio_capture_module_->StereoPlayoutIsAvailable(
@@ -180,11 +177,6 @@
TEST_F(FakeAdmTest, RecordTest) {
EXPECT_EQ(0, fake_audio_capture_module_->RegisterAudioCallback(this));
- bool microphone_available = false;
- EXPECT_EQ(0, fake_audio_capture_module_->MicrophoneIsAvailable(
- µphone_available));
- EXPECT_TRUE(microphone_available);
-
bool stereo_available = false;
EXPECT_EQ(0, fake_audio_capture_module_->StereoRecordingIsAvailable(
&stereo_available));
diff --git a/app/webrtc/test/fakeconstraints.h b/app/webrtc/test/fakeconstraints.h
index b23007e..f1b7f77 100644
--- a/app/webrtc/test/fakeconstraints.h
+++ b/app/webrtc/test/fakeconstraints.h
@@ -32,7 +32,7 @@
#include <vector>
#include "talk/app/webrtc/mediaconstraintsinterface.h"
-#include "talk/base/stringencode.h"
+#include "webrtc/base/stringencode.h"
namespace webrtc {
@@ -51,7 +51,7 @@
template <class T>
void AddMandatory(const std::string& key, const T& value) {
- mandatory_.push_back(Constraint(key, talk_base::ToString<T>(value)));
+ mandatory_.push_back(Constraint(key, rtc::ToString<T>(value)));
}
template <class T>
@@ -66,12 +66,12 @@
}
}
}
- mandatory_.push_back(Constraint(key, talk_base::ToString<T>(value)));
+ mandatory_.push_back(Constraint(key, rtc::ToString<T>(value)));
}
template <class T>
void AddOptional(const std::string& key, const T& value) {
- optional_.push_back(Constraint(key, talk_base::ToString<T>(value)));
+ optional_.push_back(Constraint(key, rtc::ToString<T>(value)));
}
void SetMandatoryMinAspectRatio(double ratio) {
diff --git a/app/webrtc/test/fakedatachannelprovider.h b/app/webrtc/test/fakedatachannelprovider.h
index 053b3ac..2e71f94 100644
--- a/app/webrtc/test/fakedatachannelprovider.h
+++ b/app/webrtc/test/fakedatachannelprovider.h
@@ -37,7 +37,7 @@
virtual ~FakeDataChannelProvider() {}
virtual bool SendData(const cricket::SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
cricket::SendDataResult* result) OVERRIDE {
ASSERT(ready_to_send_ && transport_available_);
if (send_blocked_) {
@@ -45,7 +45,7 @@
return false;
}
- if (transport_error_) {
+ if (transport_error_ || payload.length() == 0) {
*result = cricket::SDR_ERROR;
return false;
}
diff --git a/app/webrtc/test/fakedtlsidentityservice.h b/app/webrtc/test/fakedtlsidentityservice.h
index 0c1a2a0..57ffcf6 100644
--- a/app/webrtc/test/fakedtlsidentityservice.h
+++ b/app/webrtc/test/fakedtlsidentityservice.h
@@ -65,7 +65,7 @@
using webrtc::DTLSIdentityRequestObserver;
class FakeIdentityService : public webrtc::DTLSIdentityServiceInterface,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
struct Request {
Request(const std::string& common_name,
@@ -73,9 +73,9 @@
: common_name(common_name), observer(observer) {}
std::string common_name;
- talk_base::scoped_refptr<DTLSIdentityRequestObserver> observer;
+ rtc::scoped_refptr<DTLSIdentityRequestObserver> observer;
};
- typedef talk_base::TypedMessageData<Request> MessageData;
+ typedef rtc::TypedMessageData<Request> MessageData;
FakeIdentityService() : should_fail_(false) {}
@@ -89,9 +89,9 @@
DTLSIdentityRequestObserver* observer) {
MessageData* msg = new MessageData(Request(common_name, observer));
if (should_fail_) {
- talk_base::Thread::Current()->Post(this, MSG_FAILURE, msg);
+ rtc::Thread::Current()->Post(this, MSG_FAILURE, msg);
} else {
- talk_base::Thread::Current()->Post(this, MSG_SUCCESS, msg);
+ rtc::Thread::Current()->Post(this, MSG_SUCCESS, msg);
}
return true;
}
@@ -102,8 +102,8 @@
MSG_FAILURE,
};
- // talk_base::MessageHandler implementation.
- void OnMessage(talk_base::Message* msg) {
+ // rtc::MessageHandler implementation.
+ void OnMessage(rtc::Message* msg) {
FakeIdentityService::MessageData* message_data =
static_cast<FakeIdentityService::MessageData*>(msg->pdata);
DTLSIdentityRequestObserver* observer = message_data->data().observer.get();
@@ -125,8 +125,8 @@
const std::string& common_name,
std::string* der_cert,
std::string* der_key) {
- talk_base::SSLIdentity::PemToDer("CERTIFICATE", kCERT_PEM, der_cert);
- talk_base::SSLIdentity::PemToDer("RSA PRIVATE KEY",
+ rtc::SSLIdentity::PemToDer("CERTIFICATE", kCERT_PEM, der_cert);
+ rtc::SSLIdentity::PemToDer("RSA PRIVATE KEY",
kRSA_PRIVATE_KEY_PEM,
der_key);
}
diff --git a/app/webrtc/test/fakemediastreamsignaling.h b/app/webrtc/test/fakemediastreamsignaling.h
index c7b30aa..bd12549 100644
--- a/app/webrtc/test/fakemediastreamsignaling.h
+++ b/app/webrtc/test/fakemediastreamsignaling.h
@@ -45,7 +45,7 @@
public webrtc::MediaStreamSignalingObserver {
public:
explicit FakeMediaStreamSignaling(cricket::ChannelManager* channel_manager) :
- webrtc::MediaStreamSignaling(talk_base::Thread::Current(), this,
+ webrtc::MediaStreamSignaling(rtc::Thread::Current(), this,
channel_manager) {
}
@@ -133,21 +133,21 @@
}
private:
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> CreateStream(
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> CreateStream(
const std::string& stream_label,
const std::string& audio_track_id,
const std::string& video_track_id) {
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream(
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream(
webrtc::MediaStream::Create(stream_label));
if (!audio_track_id.empty()) {
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
webrtc::AudioTrack::Create(audio_track_id, NULL));
stream->AddTrack(audio_track);
}
if (!video_track_id.empty()) {
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> video_track(
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
webrtc::VideoTrack::Create(video_track_id, NULL));
stream->AddTrack(video_track);
}
diff --git a/app/webrtc/test/fakeperiodicvideocapturer.h b/app/webrtc/test/fakeperiodicvideocapturer.h
index 7f70ae2..7603764 100644
--- a/app/webrtc/test/fakeperiodicvideocapturer.h
+++ b/app/webrtc/test/fakeperiodicvideocapturer.h
@@ -31,8 +31,8 @@
#ifndef TALK_APP_WEBRTC_TEST_FAKEPERIODICVIDEOCAPTURER_H_
#define TALK_APP_WEBRTC_TEST_FAKEPERIODICVIDEOCAPTURER_H_
-#include "talk/base/thread.h"
#include "talk/media/base/fakevideocapturer.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
@@ -56,20 +56,20 @@
virtual cricket::CaptureState Start(const cricket::VideoFormat& format) {
cricket::CaptureState state = FakeVideoCapturer::Start(format);
if (state != cricket::CS_FAILED) {
- talk_base::Thread::Current()->Post(this, MSG_CREATEFRAME);
+ rtc::Thread::Current()->Post(this, MSG_CREATEFRAME);
}
return state;
}
virtual void Stop() {
- talk_base::Thread::Current()->Clear(this);
+ rtc::Thread::Current()->Clear(this);
}
// Inherited from MesageHandler.
- virtual void OnMessage(talk_base::Message* msg) {
+ virtual void OnMessage(rtc::Message* msg) {
if (msg->message_id == MSG_CREATEFRAME) {
if (IsRunning()) {
CaptureFrame();
- talk_base::Thread::Current()->PostDelayed(static_cast<int>(
- GetCaptureFormat()->interval / talk_base::kNumNanosecsPerMillisec),
+ rtc::Thread::Current()->PostDelayed(static_cast<int>(
+ GetCaptureFormat()->interval / rtc::kNumNanosecsPerMillisec),
this, MSG_CREATEFRAME);
}
} else {
diff --git a/app/webrtc/test/fakevideotrackrenderer.h b/app/webrtc/test/fakevideotrackrenderer.h
index 0030a0c..5cb67a3 100644
--- a/app/webrtc/test/fakevideotrackrenderer.h
+++ b/app/webrtc/test/fakevideotrackrenderer.h
@@ -62,7 +62,7 @@
private:
cricket::FakeVideoRenderer fake_renderer_;
- talk_base::scoped_refptr<VideoTrackInterface> video_track_;
+ rtc::scoped_refptr<VideoTrackInterface> video_track_;
};
} // namespace webrtc
diff --git a/app/webrtc/test/mockpeerconnectionobservers.h b/app/webrtc/test/mockpeerconnectionobservers.h
index 3ae2162..0570d40 100644
--- a/app/webrtc/test/mockpeerconnectionobservers.h
+++ b/app/webrtc/test/mockpeerconnectionobservers.h
@@ -61,7 +61,7 @@
private:
bool called_;
bool result_;
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_;
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_;
};
class MockSetSessionDescriptionObserver
@@ -109,7 +109,7 @@
size_t received_message_count() const { return received_message_count_; }
private:
- talk_base::scoped_refptr<webrtc::DataChannelInterface> channel_;
+ rtc::scoped_refptr<webrtc::DataChannelInterface> channel_;
DataChannelInterface::DataState state_;
std::string last_message_;
size_t received_message_count_;
@@ -120,46 +120,56 @@
MockStatsObserver()
: called_(false) {}
virtual ~MockStatsObserver() {}
- virtual void OnComplete(const std::vector<webrtc::StatsReport>& reports) {
+ virtual void OnComplete(const StatsReports& reports) {
called_ = true;
- reports_ = reports;
+ reports_.clear();
+ reports_.reserve(reports.size());
+ StatsReports::const_iterator it;
+ for (it = reports.begin(); it != reports.end(); ++it)
+ reports_.push_back(StatsReportCopyable(*(*it)));
}
bool called() const { return called_; }
size_t number_of_reports() const { return reports_.size(); }
int AudioOutputLevel() {
- return GetSsrcStatsValue(
- webrtc::StatsReport::kStatsValueNameAudioOutputLevel);
+ return GetStatsValue(StatsReport::kStatsReportTypeSsrc,
+ StatsReport::kStatsValueNameAudioOutputLevel);
}
int AudioInputLevel() {
- return GetSsrcStatsValue(
- webrtc::StatsReport::kStatsValueNameAudioInputLevel);
+ return GetStatsValue(StatsReport::kStatsReportTypeSsrc,
+ StatsReport::kStatsValueNameAudioInputLevel);
}
int BytesReceived() {
- return GetSsrcStatsValue(
- webrtc::StatsReport::kStatsValueNameBytesReceived);
+ return GetStatsValue(StatsReport::kStatsReportTypeSsrc,
+ StatsReport::kStatsValueNameBytesReceived);
}
int BytesSent() {
- return GetSsrcStatsValue(webrtc::StatsReport::kStatsValueNameBytesSent);
+ return GetStatsValue(StatsReport::kStatsReportTypeSsrc,
+ StatsReport::kStatsValueNameBytesSent);
+ }
+
+ int AvailableReceiveBandwidth() {
+ return GetStatsValue(StatsReport::kStatsReportTypeBwe,
+ StatsReport::kStatsValueNameAvailableReceiveBandwidth);
}
private:
- int GetSsrcStatsValue(const std::string name) {
+ int GetStatsValue(const std::string& type, StatsReport::StatsValueName name) {
if (reports_.empty()) {
return 0;
}
for (size_t i = 0; i < reports_.size(); ++i) {
- if (reports_[i].type != StatsReport::kStatsReportTypeSsrc)
+ if (reports_[i].type != type)
continue;
webrtc::StatsReport::Values::const_iterator it =
reports_[i].values.begin();
for (; it != reports_[i].values.end(); ++it) {
if (it->name == name) {
- return talk_base::FromString<int>(it->value);
+ return rtc::FromString<int>(it->value);
}
}
}
@@ -167,7 +177,7 @@
}
bool called_;
- std::vector<webrtc::StatsReport> reports_;
+ std::vector<StatsReportCopyable> reports_;
};
} // namespace webrtc
diff --git a/app/webrtc/test/peerconnectiontestwrapper.cc b/app/webrtc/test/peerconnectiontestwrapper.cc
index be70969..24932b8 100644
--- a/app/webrtc/test/peerconnectiontestwrapper.cc
+++ b/app/webrtc/test/peerconnectiontestwrapper.cc
@@ -31,7 +31,7 @@
#include "talk/app/webrtc/test/mockpeerconnectionobservers.h"
#include "talk/app/webrtc/test/peerconnectiontestwrapper.h"
#include "talk/app/webrtc/videosourceinterface.h"
-#include "talk/base/gunit.h"
+#include "webrtc/base/gunit.h"
static const char kStreamLabelBase[] = "stream_label";
static const char kVideoTrackLabelBase[] = "video_track";
@@ -75,15 +75,14 @@
return false;
}
- audio_thread_.Start();
fake_audio_capture_module_ = FakeAudioCaptureModule::Create(
- &audio_thread_);
+ rtc::Thread::Current());
if (fake_audio_capture_module_ == NULL) {
return false;
}
peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
- talk_base::Thread::Current(), talk_base::Thread::Current(),
+ rtc::Thread::Current(), rtc::Thread::Current(),
fake_audio_capture_module_, NULL, NULL);
if (!peer_connection_factory_) {
return false;
@@ -95,7 +94,7 @@
ice_server.uri = "stun:stun.l.google.com:19302";
ice_servers.push_back(ice_server);
FakeIdentityService* dtls_service =
- talk_base::SSLStreamAdapter::HaveDtlsSrtp() ?
+ rtc::SSLStreamAdapter::HaveDtlsSrtp() ?
new FakeIdentityService() : NULL;
peer_connection_ = peer_connection_factory_->CreatePeerConnection(
ice_servers, constraints, allocator_factory_.get(), dtls_service, this);
@@ -103,7 +102,7 @@
return peer_connection_.get() != NULL;
}
-talk_base::scoped_refptr<webrtc::DataChannelInterface>
+rtc::scoped_refptr<webrtc::DataChannelInterface>
PeerConnectionTestWrapper::CreateDataChannel(
const std::string& label,
const webrtc::DataChannelInit& init) {
@@ -136,7 +135,7 @@
void PeerConnectionTestWrapper::OnSuccess(SessionDescriptionInterface* desc) {
// This callback should take the ownership of |desc|.
- talk_base::scoped_ptr<SessionDescriptionInterface> owned_desc(desc);
+ rtc::scoped_ptr<SessionDescriptionInterface> owned_desc(desc);
std::string sdp;
EXPECT_TRUE(desc->ToString(&sdp));
@@ -179,8 +178,8 @@
LOG(LS_INFO) << "PeerConnectionTestWrapper " << name_
<< ": SetLocalDescription " << type << " " << sdp;
- talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<MockSetSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
MockSetSessionDescriptionObserver>());
peer_connection_->SetLocalDescription(
observer, webrtc::CreateSessionDescription(type, sdp, NULL));
@@ -191,8 +190,8 @@
LOG(LS_INFO) << "PeerConnectionTestWrapper " << name_
<< ": SetRemoteDescription " << type << " " << sdp;
- talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
- observer(new talk_base::RefCountedObject<
+ rtc::scoped_refptr<MockSetSessionDescriptionObserver>
+ observer(new rtc::RefCountedObject<
MockSetSessionDescriptionObserver>());
peer_connection_->SetRemoteDescription(
observer, webrtc::CreateSessionDescription(type, sdp, NULL));
@@ -201,7 +200,7 @@
void PeerConnectionTestWrapper::AddIceCandidate(const std::string& sdp_mid,
int sdp_mline_index,
const std::string& candidate) {
- talk_base::scoped_ptr<webrtc::IceCandidateInterface> owned_candidate(
+ rtc::scoped_ptr<webrtc::IceCandidateInterface> owned_candidate(
webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, candidate, NULL));
EXPECT_TRUE(peer_connection_->AddIceCandidate(owned_candidate.get()));
}
@@ -252,19 +251,19 @@
void PeerConnectionTestWrapper::GetAndAddUserMedia(
bool audio, const webrtc::FakeConstraints& audio_constraints,
bool video, const webrtc::FakeConstraints& video_constraints) {
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream =
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
GetUserMedia(audio, audio_constraints, video, video_constraints);
EXPECT_TRUE(peer_connection_->AddStream(stream, NULL));
}
-talk_base::scoped_refptr<webrtc::MediaStreamInterface>
+rtc::scoped_refptr<webrtc::MediaStreamInterface>
PeerConnectionTestWrapper::GetUserMedia(
bool audio, const webrtc::FakeConstraints& audio_constraints,
bool video, const webrtc::FakeConstraints& video_constraints) {
std::string label = kStreamLabelBase +
- talk_base::ToString<int>(
+ rtc::ToString<int>(
static_cast<int>(peer_connection_->local_streams()->count()));
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream =
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
peer_connection_factory_->CreateLocalMediaStream(label);
if (audio) {
@@ -272,9 +271,9 @@
// Disable highpass filter so that we can get all the test audio frames.
constraints.AddMandatory(
MediaConstraintsInterface::kHighpassFilter, false);
- talk_base::scoped_refptr<webrtc::AudioSourceInterface> source =
+ rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
peer_connection_factory_->CreateAudioSource(&constraints);
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
peer_connection_factory_->CreateAudioTrack(kAudioTrackLabelBase,
source));
stream->AddTrack(audio_track);
@@ -285,11 +284,11 @@
FakeConstraints constraints = video_constraints;
constraints.SetMandatoryMaxFrameRate(10);
- talk_base::scoped_refptr<webrtc::VideoSourceInterface> source =
+ rtc::scoped_refptr<webrtc::VideoSourceInterface> source =
peer_connection_factory_->CreateVideoSource(
new webrtc::FakePeriodicVideoCapturer(), &constraints);
std::string videotrack_label = label + kVideoTrackLabelBase;
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> video_track(
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
peer_connection_factory_->CreateVideoTrack(videotrack_label, source));
stream->AddTrack(video_track);
diff --git a/app/webrtc/test/peerconnectiontestwrapper.h b/app/webrtc/test/peerconnectiontestwrapper.h
index 05e9b62..d4a0e4e 100644
--- a/app/webrtc/test/peerconnectiontestwrapper.h
+++ b/app/webrtc/test/peerconnectiontestwrapper.h
@@ -32,8 +32,8 @@
#include "talk/app/webrtc/test/fakeaudiocapturemodule.h"
#include "talk/app/webrtc/test/fakeconstraints.h"
#include "talk/app/webrtc/test/fakevideotrackrenderer.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
namespace webrtc {
class PortAllocatorFactoryInterface;
@@ -52,7 +52,7 @@
bool CreatePc(const webrtc::MediaConstraintsInterface* constraints);
- talk_base::scoped_refptr<webrtc::DataChannelInterface> CreateDataChannel(
+ rtc::scoped_refptr<webrtc::DataChannelInterface> CreateDataChannel(
const std::string& label,
const webrtc::DataChannelInit& init);
@@ -106,19 +106,18 @@
bool CheckForConnection();
bool CheckForAudio();
bool CheckForVideo();
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> GetUserMedia(
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> GetUserMedia(
bool audio, const webrtc::FakeConstraints& audio_constraints,
bool video, const webrtc::FakeConstraints& video_constraints);
std::string name_;
- talk_base::Thread audio_thread_;
- talk_base::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
+ rtc::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
allocator_factory_;
- talk_base::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
- talk_base::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
+ rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
peer_connection_factory_;
- talk_base::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
- talk_base::scoped_ptr<webrtc::FakeVideoTrackRenderer> renderer_;
+ rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
+ rtc::scoped_ptr<webrtc::FakeVideoTrackRenderer> renderer_;
};
#endif // TALK_APP_WEBRTC_TEST_PEERCONNECTIONTESTWRAPPER_H_
diff --git a/app/webrtc/videosource.cc b/app/webrtc/videosource.cc
index eb4ab97..589341d 100644
--- a/app/webrtc/videosource.cc
+++ b/app/webrtc/videosource.cc
@@ -28,6 +28,7 @@
#include "talk/app/webrtc/videosource.h"
#include <vector>
+#include <cstdlib>
#include "talk/app/webrtc/mediaconstraintsinterface.h"
#include "talk/session/media/channelmanager.h"
@@ -93,10 +94,10 @@
const MediaConstraintsInterface::Constraint& constraint,
cricket::VideoFormat* format_upper_limit) {
if (constraint.key == MediaConstraintsInterface::kMaxWidth) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
SetUpperLimit(value, &(format_upper_limit->width));
} else if (constraint.key == MediaConstraintsInterface::kMaxHeight) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
SetUpperLimit(value, &(format_upper_limit->height));
}
}
@@ -131,22 +132,22 @@
*format_out = format_in;
if (constraint.key == MediaConstraintsInterface::kMinWidth) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
return (value <= format_in.width);
} else if (constraint.key == MediaConstraintsInterface::kMaxWidth) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
return (value >= format_in.width);
} else if (constraint.key == MediaConstraintsInterface::kMinHeight) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
return (value <= format_in.height);
} else if (constraint.key == MediaConstraintsInterface::kMaxHeight) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
return (value >= format_in.height);
} else if (constraint.key == MediaConstraintsInterface::kMinFrameRate) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
return (value <= cricket::VideoFormat::IntervalToFps(format_in.interval));
} else if (constraint.key == MediaConstraintsInterface::kMaxFrameRate) {
- int value = talk_base::FromString<int>(constraint.value);
+ int value = rtc::FromString<int>(constraint.value);
if (value == 0) {
if (mandatory) {
// TODO(ronghuawu): Convert the constraint value to float when sub-1fps
@@ -163,7 +164,7 @@
return false;
}
} else if (constraint.key == MediaConstraintsInterface::kMinAspectRatio) {
- double value = talk_base::FromString<double>(constraint.value);
+ double value = rtc::FromString<double>(constraint.value);
// The aspect ratio in |constraint.value| has been converted to a string and
// back to a double, so it may have a rounding error.
// E.g if the value 1/3 is converted to a string, the string will not have
@@ -173,7 +174,7 @@
double ratio = static_cast<double>(format_in.width) / format_in.height;
return (value <= ratio + kRoundingTruncation);
} else if (constraint.key == MediaConstraintsInterface::kMaxAspectRatio) {
- double value = talk_base::FromString<double>(constraint.value);
+ double value = rtc::FromString<double>(constraint.value);
double ratio = static_cast<double>(format_in.width) / format_in.height;
// Subtract 0.0005 to avoid rounding problems. Same as above.
const double kRoundingTruncation = 0.0005;
@@ -254,11 +255,15 @@
std::vector<cricket::VideoFormat>::const_iterator it = formats.begin();
std::vector<cricket::VideoFormat>::const_iterator best_it = formats.begin();
- int best_diff = abs(default_area - it->width* it->height);
+ int best_diff_area = std::abs(default_area - it->width * it->height);
+ int64 best_diff_interval = kDefaultFormat.interval;
for (; it != formats.end(); ++it) {
- int diff = abs(default_area - it->width* it->height);
- if (diff < best_diff) {
- best_diff = diff;
+ int diff_area = std::abs(default_area - it->width * it->height);
+ int64 diff_interval = std::abs(kDefaultFormat.interval - it->interval);
+ if (diff_area < best_diff_area ||
+ (diff_area == best_diff_area && diff_interval < best_diff_interval)) {
+ best_diff_area = diff_area;
+ best_diff_interval = diff_interval;
best_it = it;
}
}
@@ -337,14 +342,14 @@
namespace webrtc {
-talk_base::scoped_refptr<VideoSource> VideoSource::Create(
+rtc::scoped_refptr<VideoSource> VideoSource::Create(
cricket::ChannelManager* channel_manager,
cricket::VideoCapturer* capturer,
const webrtc::MediaConstraintsInterface* constraints) {
ASSERT(channel_manager != NULL);
ASSERT(capturer != NULL);
- talk_base::scoped_refptr<VideoSource> source(
- new talk_base::RefCountedObject<VideoSource>(channel_manager,
+ rtc::scoped_refptr<VideoSource> source(
+ new rtc::RefCountedObject<VideoSource>(channel_manager,
capturer));
source->Initialize(constraints);
return source;
diff --git a/app/webrtc/videosource.h b/app/webrtc/videosource.h
index f58b479..830bdf1 100644
--- a/app/webrtc/videosource.h
+++ b/app/webrtc/videosource.h
@@ -32,10 +32,10 @@
#include "talk/app/webrtc/notifier.h"
#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/app/webrtc/videotrackrenderers.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
// VideoSource implements VideoSourceInterface. It owns a
// cricket::VideoCapturer and make sure the camera is started at a resolution
@@ -61,7 +61,7 @@
// VideoSource take ownership of |capturer|.
// |constraints| can be NULL and in that case the camera is opened using a
// default resolution.
- static talk_base::scoped_refptr<VideoSource> Create(
+ static rtc::scoped_refptr<VideoSource> Create(
cricket::ChannelManager* channel_manager,
cricket::VideoCapturer* capturer,
const webrtc::MediaConstraintsInterface* constraints);
@@ -90,8 +90,8 @@
void SetState(SourceState new_state);
cricket::ChannelManager* channel_manager_;
- talk_base::scoped_ptr<cricket::VideoCapturer> video_capturer_;
- talk_base::scoped_ptr<cricket::VideoRenderer> frame_input_;
+ rtc::scoped_ptr<cricket::VideoCapturer> video_capturer_;
+ rtc::scoped_ptr<cricket::VideoRenderer> frame_input_;
cricket::VideoFormat format_;
cricket::VideoOptions options_;
diff --git a/app/webrtc/videosource_unittest.cc b/app/webrtc/videosource_unittest.cc
index 4381176..d9d8acf 100644
--- a/app/webrtc/videosource_unittest.cc
+++ b/app/webrtc/videosource_unittest.cc
@@ -28,15 +28,15 @@
#include <string>
#include <vector>
-#include "talk/app/webrtc/test/fakeconstraints.h"
#include "talk/app/webrtc/remotevideocapturer.h"
+#include "talk/app/webrtc/test/fakeconstraints.h"
#include "talk/app/webrtc/videosource.h"
-#include "talk/base/gunit.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/fakevideorenderer.h"
#include "talk/media/devices/fakedevicemanager.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
#include "talk/session/media/channelmanager.h"
+#include "webrtc/base/gunit.h"
using webrtc::FakeConstraints;
using webrtc::VideoSource;
@@ -121,7 +121,7 @@
private:
MediaSourceInterface::SourceState state_;
- talk_base::scoped_refptr<VideoSourceInterface> source_;
+ rtc::scoped_refptr<VideoSourceInterface> source_;
};
class VideoSourceTest : public testing::Test {
@@ -131,7 +131,7 @@
capturer_(capturer_cleanup_.get()),
channel_manager_(new cricket::ChannelManager(
new cricket::FakeMediaEngine(),
- new cricket::FakeDeviceManager(), talk_base::Thread::Current())) {
+ new cricket::FakeDeviceManager(), rtc::Thread::Current())) {
}
void SetUp() {
@@ -157,12 +157,12 @@
source_->AddSink(&renderer_);
}
- talk_base::scoped_ptr<TestVideoCapturer> capturer_cleanup_;
+ rtc::scoped_ptr<TestVideoCapturer> capturer_cleanup_;
TestVideoCapturer* capturer_;
cricket::FakeVideoRenderer renderer_;
- talk_base::scoped_ptr<cricket::ChannelManager> channel_manager_;
- talk_base::scoped_ptr<StateObserver> state_observer_;
- talk_base::scoped_refptr<VideoSource> source_;
+ rtc::scoped_ptr<cricket::ChannelManager> channel_manager_;
+ rtc::scoped_ptr<StateObserver> state_observer_;
+ rtc::scoped_refptr<VideoSource> source_;
};
diff --git a/app/webrtc/videotrack.cc b/app/webrtc/videotrack.cc
index 7ab7815..8c244a6 100644
--- a/app/webrtc/videotrack.cc
+++ b/app/webrtc/videotrack.cc
@@ -64,10 +64,10 @@
return MediaStreamTrack<VideoTrackInterface>::set_enabled(enable);
}
-talk_base::scoped_refptr<VideoTrack> VideoTrack::Create(
+rtc::scoped_refptr<VideoTrack> VideoTrack::Create(
const std::string& id, VideoSourceInterface* source) {
- talk_base::RefCountedObject<VideoTrack>* track =
- new talk_base::RefCountedObject<VideoTrack>(id, source);
+ rtc::RefCountedObject<VideoTrack>* track =
+ new rtc::RefCountedObject<VideoTrack>(id, source);
return track;
}
diff --git a/app/webrtc/videotrack.h b/app/webrtc/videotrack.h
index acd1b75..40a38f2 100644
--- a/app/webrtc/videotrack.h
+++ b/app/webrtc/videotrack.h
@@ -33,13 +33,13 @@
#include "talk/app/webrtc/mediastreamtrack.h"
#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/app/webrtc/videotrackrenderers.h"
-#include "talk/base/scoped_ref_ptr.h"
+#include "webrtc/base/scoped_ref_ptr.h"
namespace webrtc {
class VideoTrack : public MediaStreamTrack<VideoTrackInterface> {
public:
- static talk_base::scoped_refptr<VideoTrack> Create(
+ static rtc::scoped_refptr<VideoTrack> Create(
const std::string& label, VideoSourceInterface* source);
virtual void AddRenderer(VideoRendererInterface* renderer);
@@ -56,7 +56,7 @@
private:
VideoTrackRenderers renderers_;
- talk_base::scoped_refptr<VideoSourceInterface> video_source_;
+ rtc::scoped_refptr<VideoSourceInterface> video_source_;
};
} // namespace webrtc
diff --git a/app/webrtc/videotrack_unittest.cc b/app/webrtc/videotrack_unittest.cc
index 4a30293..5fe979f 100644
--- a/app/webrtc/videotrack_unittest.cc
+++ b/app/webrtc/videotrack_unittest.cc
@@ -27,16 +27,16 @@
#include <string>
-#include "talk/app/webrtc/test/fakevideotrackrenderer.h"
#include "talk/app/webrtc/remotevideocapturer.h"
+#include "talk/app/webrtc/test/fakevideotrackrenderer.h"
#include "talk/app/webrtc/videosource.h"
#include "talk/app/webrtc/videotrack.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/devices/fakedevicemanager.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
#include "talk/session/media/channelmanager.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
using webrtc::FakeVideoTrackRenderer;
using webrtc::VideoSource;
@@ -48,19 +48,19 @@
TEST(VideoTrack, RenderVideo) {
static const char kVideoTrackId[] = "track_id";
- talk_base::scoped_ptr<cricket::ChannelManager> channel_manager_;
+ rtc::scoped_ptr<cricket::ChannelManager> channel_manager_;
channel_manager_.reset(
new cricket::ChannelManager(new cricket::FakeMediaEngine(),
new cricket::FakeDeviceManager(),
- talk_base::Thread::Current()));
+ rtc::Thread::Current()));
ASSERT_TRUE(channel_manager_->Init());
- talk_base::scoped_refptr<VideoTrackInterface> video_track(
+ rtc::scoped_refptr<VideoTrackInterface> video_track(
VideoTrack::Create(kVideoTrackId,
VideoSource::Create(channel_manager_.get(),
new webrtc::RemoteVideoCapturer(),
NULL)));
// FakeVideoTrackRenderer register itself to |video_track|
- talk_base::scoped_ptr<FakeVideoTrackRenderer> renderer_1(
+ rtc::scoped_ptr<FakeVideoTrackRenderer> renderer_1(
new FakeVideoTrackRenderer(video_track.get()));
cricket::VideoRenderer* render_input = video_track->GetSource()->FrameInput();
@@ -76,7 +76,7 @@
EXPECT_EQ(123, renderer_1->height());
// FakeVideoTrackRenderer register itself to |video_track|
- talk_base::scoped_ptr<FakeVideoTrackRenderer> renderer_2(
+ rtc::scoped_ptr<FakeVideoTrackRenderer> renderer_2(
new FakeVideoTrackRenderer(video_track.get()));
render_input->RenderFrame(&frame);
diff --git a/app/webrtc/videotrackrenderers.cc b/app/webrtc/videotrackrenderers.cc
index b0e0c1f..75ce2be 100644
--- a/app/webrtc/videotrackrenderers.cc
+++ b/app/webrtc/videotrackrenderers.cc
@@ -38,7 +38,7 @@
}
void VideoTrackRenderers::AddRenderer(VideoRendererInterface* renderer) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
std::vector<RenderObserver>::iterator it = renderers_.begin();
for (; it != renderers_.end(); ++it) {
if (it->renderer_ == renderer)
@@ -48,7 +48,7 @@
}
void VideoTrackRenderers::RemoveRenderer(VideoRendererInterface* renderer) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
std::vector<RenderObserver>::iterator it = renderers_.begin();
for (; it != renderers_.end(); ++it) {
if (it->renderer_ == renderer) {
@@ -59,12 +59,12 @@
}
void VideoTrackRenderers::SetEnabled(bool enable) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
enabled_ = enable;
}
bool VideoTrackRenderers::SetSize(int width, int height, int reserved) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
width_ = width;
height_ = height;
std::vector<RenderObserver>::iterator it = renderers_.begin();
@@ -76,7 +76,7 @@
}
bool VideoTrackRenderers::RenderFrame(const cricket::VideoFrame* frame) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
if (!enabled_) {
return true;
}
diff --git a/app/webrtc/videotrackrenderers.h b/app/webrtc/videotrackrenderers.h
index 4bcf6a3..4fba318 100644
--- a/app/webrtc/videotrackrenderers.h
+++ b/app/webrtc/videotrackrenderers.h
@@ -31,8 +31,8 @@
#include <vector>
#include "talk/app/webrtc/mediastreaminterface.h"
-#include "talk/base/criticalsection.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/criticalsection.h"
namespace webrtc {
@@ -69,7 +69,7 @@
bool enabled_;
std::vector<RenderObserver> renderers_;
- talk_base::CriticalSection critical_section_; // Protects the above variables
+ rtc::CriticalSection critical_section_; // Protects the above variables
};
} // namespace webrtc
diff --git a/app/webrtc/webrtcsdp.cc b/app/webrtc/webrtcsdp.cc
index b2d8a30..5887409 100644
--- a/app/webrtc/webrtcsdp.cc
+++ b/app/webrtc/webrtcsdp.cc
@@ -35,10 +35,6 @@
#include "talk/app/webrtc/jsepicecandidate.h"
#include "talk/app/webrtc/jsepsessiondescription.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/cryptoparams.h"
@@ -48,6 +44,10 @@
#include "talk/p2p/base/port.h"
#include "talk/session/media/mediasession.h"
#include "talk/session/media/mediasessionclient.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/stringutils.h"
using cricket::AudioContentDescription;
using cricket::Candidate;
@@ -71,6 +71,7 @@
using cricket::kCodecParamSctpProtocol;
using cricket::kCodecParamSctpStreams;
using cricket::kCodecParamMaxAverageBitrate;
+using cricket::kCodecParamMaxPlaybackRate;
using cricket::kCodecParamAssociatedPayloadType;
using cricket::kWildcardPayloadType;
using cricket::MediaContentDescription;
@@ -83,7 +84,7 @@
using cricket::TransportDescription;
using cricket::TransportInfo;
using cricket::VideoContentDescription;
-using talk_base::SocketAddress;
+using rtc::SocketAddress;
typedef std::vector<RtpHeaderExtension> RtpHeaderExtensions;
@@ -155,6 +156,9 @@
static const char kAttributeRtcpFb[] = "rtcp-fb";
static const char kAttributeSendRecv[] = "sendrecv";
static const char kAttributeInactive[] = "inactive";
+// draft-ietf-mmusic-sctp-sdp-07
+// a=sctp-port
+static const char kAttributeSctpPort[] = "sctp-port";
// Experimental flags
static const char kAttributeXGoogleFlag[] = "x-google-flag";
@@ -168,6 +172,7 @@
// TODO: How to map the prflx with circket candidate type
// static const char kCandidatePrflx[] = "prflx";
static const char kCandidateRelay[] = "relay";
+static const char kTcpCandidateType[] = "tcptype";
static const char kSdpDelimiterEqual = '=';
static const char kSdpDelimiterSpace = ' ';
@@ -216,7 +221,7 @@
: msid_identifier(kDefaultMsid),
// TODO(ronghuawu): What should we do if the appdata doesn't appear?
// Create random string (which will be used as track label later)?
- msid_appdata(talk_base::CreateRandomString(8)) {
+ msid_appdata(rtc::CreateRandomString(8)) {
}
uint32 ssrc_id;
std::string cname;
@@ -231,15 +236,12 @@
typedef std::vector<SsrcInfo> SsrcInfoVec;
typedef std::vector<SsrcGroup> SsrcGroupVec;
-// Serializes the passed in SessionDescription to a SDP string.
-// desc - The SessionDescription object to be serialized.
-static std::string SdpSerializeSessionDescription(
- const JsepSessionDescription& jdesc);
template <class T>
static void AddFmtpLine(const T& codec, std::string* message);
static void BuildMediaDescription(const ContentInfo* content_info,
const TransportInfo* transport_info,
const MediaType media_type,
+ const std::vector<Candidate>& candidates,
std::string* message);
static void BuildSctpContentAttributes(std::string* message, int sctp_port);
static void BuildRtpContentAttributes(
@@ -317,7 +319,7 @@
RtpHeaderExtension* extmap,
SdpParseError* error);
static bool ParseFingerprintAttribute(const std::string& line,
- talk_base::SSLFingerprint** fingerprint,
+ rtc::SSLFingerprint** fingerprint,
SdpParseError* error);
static bool ParseDtlsSetup(const std::string& line,
cricket::ConnectionRole* role,
@@ -480,16 +482,6 @@
AddLine(os.str(), message);
}
-// Returns the first line of the message without the line breaker.
-static bool GetFirstLine(const std::string& message, std::string* line) {
- size_t pos = 0;
- if (!GetLine(message, &pos, line)) {
- // If GetLine failed, just return the full |message|.
- *line = message;
- }
- return true;
-}
-
static bool IsLineType(const std::string& message,
const char type,
size_t line_start) {
@@ -523,21 +515,6 @@
return (line.compare(kLinePrefixLength, attribute.size(), attribute) == 0);
}
-// Verifies the candiate to be of the format candidate:<blah>
-static bool IsRawCandidate(const std::string& line) {
- // Checking candiadte-attribute is starting with "candidate" str.
- if (line.compare(0, strlen(kAttributeCandidate), kAttributeCandidate) != 0) {
- return false;
- }
- const size_t first_candidate = line.find(kSdpDelimiterColon);
- if (first_candidate == std::string::npos)
- return false;
- // In this format we only expecting one candiate. If any additional
- // candidates present, whole string will be discared.
- const size_t any_other = line.find(kSdpDelimiterColon, first_candidate + 1);
- return (any_other == std::string::npos);
-}
-
static bool AddSsrcLine(uint32 ssrc_id, const std::string& attribute,
const std::string& value, std::string* message) {
// RFC 5576
@@ -594,7 +571,7 @@
const std::string& s,
T* t,
SdpParseError* error) {
- if (!talk_base::FromString(s, t)) {
+ if (!rtc::FromString(s, t)) {
std::ostringstream description;
description << "Invalid value: " << s << ".";
return ParseFailed(line, description.str(), error);
@@ -712,22 +689,21 @@
return true;
}
-// Update the media default destination.
+// Update |mline|'s default destination and append a c line after it.
static void UpdateMediaDefaultDestination(
- const std::vector<Candidate>& candidates, std::string* mline) {
+ const std::vector<Candidate>& candidates,
+ const std::string mline,
+ std::string* message) {
+ std::string new_lines;
+ AddLine(mline, &new_lines);
// RFC 4566
// m=<media> <port> <proto> <fmt> ...
std::vector<std::string> fields;
- talk_base::split(*mline, kSdpDelimiterSpace, &fields);
+ rtc::split(mline, kSdpDelimiterSpace, &fields);
if (fields.size() < 3) {
return;
}
- bool is_rtp =
- fields[2].empty() ||
- talk_base::starts_with(fields[2].data(),
- cricket::kMediaProtocolRtpPrefix);
-
std::ostringstream os;
std::string rtp_port, rtp_ip;
if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTP,
@@ -742,39 +718,43 @@
// Update the port in the m line.
// If this is a m-line with port equal to 0, we don't change it.
if (fields[1] != kMediaPortRejected) {
- mline->replace(fields[0].size() + 1,
- fields[1].size(),
- rtp_port);
+ new_lines.replace(fields[0].size() + 1,
+ fields[1].size(),
+ rtp_port);
}
// Add the c line.
// RFC 4566
// c=<nettype> <addrtype> <connection-address>
InitLine(kLineTypeConnection, kConnectionNettype, &os);
os << " " << kConnectionAddrtype << " " << rtp_ip;
- AddLine(os.str(), mline);
+ AddLine(os.str(), &new_lines);
}
+ message->append(new_lines);
+}
- if (is_rtp) {
- std::string rtcp_port, rtcp_ip;
- if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
- &rtcp_port, &rtcp_ip)) {
- // Found default RTCP candidate.
- // RFC 5245
- // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
- // using the a=rtcp attribute as defined in RFC 3605.
+// Gets "a=rtcp" line if found default RTCP candidate from |candidates|.
+static std::string GetRtcpLine(const std::vector<Candidate>& candidates) {
+ std::string rtcp_line, rtcp_port, rtcp_ip;
+ if (GetDefaultDestination(candidates, ICE_CANDIDATE_COMPONENT_RTCP,
+ &rtcp_port, &rtcp_ip)) {
+ // Found default RTCP candidate.
+ // RFC 5245
+ // If the agent is utilizing RTCP, it MUST encode the RTCP candidate
+ // using the a=rtcp attribute as defined in RFC 3605.
- // RFC 3605
- // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
- // connection-address] CRLF
- InitAttrLine(kAttributeRtcp, &os);
- os << kSdpDelimiterColon
- << rtcp_port << " "
- << kConnectionNettype << " "
- << kConnectionAddrtype << " "
- << rtcp_ip;
- AddLine(os.str(), mline);
- }
+ // RFC 3605
+ // rtcp-attribute = "a=rtcp:" port [nettype space addrtype space
+ // connection-address] CRLF
+ std::ostringstream os;
+ InitAttrLine(kAttributeRtcp, &os);
+ os << kSdpDelimiterColon
+ << rtcp_port << " "
+ << kConnectionNettype << " "
+ << kConnectionAddrtype << " "
+ << rtcp_ip;
+ rtcp_line = os.str();
}
+ return rtcp_line;
}
// Get candidates according to the mline index from SessionDescriptionInterface.
@@ -792,36 +772,6 @@
}
std::string SdpSerialize(const JsepSessionDescription& jdesc) {
- std::string sdp = SdpSerializeSessionDescription(jdesc);
-
- std::string sdp_with_candidates;
- size_t pos = 0;
- std::string line;
- int mline_index = -1;
- while (GetLine(sdp, &pos, &line)) {
- if (IsLineType(line, kLineTypeMedia)) {
- ++mline_index;
- std::vector<Candidate> candidates;
- GetCandidatesByMindex(jdesc, mline_index, &candidates);
- // Media line may append other lines inside the
- // UpdateMediaDefaultDestination call, so add the kLineBreak here first.
- line.append(kLineBreak);
- UpdateMediaDefaultDestination(candidates, &line);
- sdp_with_candidates.append(line);
- // Build the a=candidate lines.
- BuildCandidate(candidates, &sdp_with_candidates);
- } else {
- // Copy old line to new sdp without change.
- AddLine(line, &sdp_with_candidates);
- }
- }
- sdp = sdp_with_candidates;
-
- return sdp;
-}
-
-std::string SdpSerializeSessionDescription(
- const JsepSessionDescription& jdesc) {
const cricket::SessionDescription* desc = jdesc.description();
if (!desc) {
return "";
@@ -868,40 +818,36 @@
// MediaStream semantics
InitAttrLine(kAttributeMsidSemantics, &os);
os << kSdpDelimiterColon << " " << kMediaStreamSemantic;
+
std::set<std::string> media_stream_labels;
const ContentInfo* audio_content = GetFirstAudioContent(desc);
if (audio_content)
GetMediaStreamLabels(audio_content, &media_stream_labels);
+
const ContentInfo* video_content = GetFirstVideoContent(desc);
if (video_content)
GetMediaStreamLabels(video_content, &media_stream_labels);
+
for (std::set<std::string>::const_iterator it =
media_stream_labels.begin(); it != media_stream_labels.end(); ++it) {
os << " " << *it;
}
AddLine(os.str(), &message);
- if (audio_content) {
- BuildMediaDescription(audio_content,
- desc->GetTransportInfoByName(audio_content->name),
- cricket::MEDIA_TYPE_AUDIO, &message);
+ // Preserve the order of the media contents.
+ int mline_index = -1;
+ for (cricket::ContentInfos::const_iterator it = desc->contents().begin();
+ it != desc->contents().end(); ++it) {
+ const MediaContentDescription* mdesc =
+ static_cast<const MediaContentDescription*>(it->description);
+ std::vector<Candidate> candidates;
+ GetCandidatesByMindex(jdesc, ++mline_index, &candidates);
+ BuildMediaDescription(&*it,
+ desc->GetTransportInfoByName(it->name),
+ mdesc->type(),
+ candidates,
+ &message);
}
-
-
- if (video_content) {
- BuildMediaDescription(video_content,
- desc->GetTransportInfoByName(video_content->name),
- cricket::MEDIA_TYPE_VIDEO, &message);
- }
-
- const ContentInfo* data_content = GetFirstDataContent(desc);
- if (data_content) {
- BuildMediaDescription(data_content,
- desc->GetTransportInfoByName(data_content->name),
- cricket::MEDIA_TYPE_DATA, &message);
- }
-
-
return message;
}
@@ -913,6 +859,12 @@
std::vector<cricket::Candidate> candidates;
candidates.push_back(candidate.candidate());
BuildCandidate(candidates, &message);
+ // From WebRTC draft section 4.8.1.1 candidate-attribute will be
+ // just candidate:<candidate> not a=candidate:<blah>CRLF
+ ASSERT(message.find("a=") == 0);
+ message.erase(0, 2);
+ ASSERT(message.find(kLineBreak) == message.size() - 2);
+ message.resize(message.size() - 2);
return message;
}
@@ -976,22 +928,36 @@
ASSERT(candidate != NULL);
// Get the first line from |message|.
- std::string first_line;
- GetFirstLine(message, &first_line);
+ std::string first_line = message;
+ size_t pos = 0;
+ GetLine(message, &pos, &first_line);
- size_t start_pos = kLinePrefixLength; // Starting position to parse.
- if (IsRawCandidate(first_line)) {
- // From WebRTC draft section 4.8.1.1 candidate-attribute will be
- // just candidate:<candidate> not a=candidate:<blah>CRLF
- start_pos = 0;
- } else if (!IsLineType(first_line, kLineTypeAttributes) ||
- !HasAttribute(first_line, kAttributeCandidate)) {
- // Must start with a=candidate line.
- // Expecting to be of the format a=candidate:<blah>CRLF.
+ // Makes sure |message| contains only one line.
+ if (message.size() > first_line.size()) {
+ std::string left, right;
+ if (SplitByDelimiter(message, kNewLine, &left, &right) && !right.empty()) {
+ return ParseFailed(message, 0, "Expect one line only", error);
+ }
+ }
+
+ // From WebRTC draft section 4.8.1.1 candidate-attribute should be
+ // candidate:<candidate> when trickled, but we still support
+ // a=candidate:<blah>CRLF for backward compatibility and for parsing a line
+ // from the SDP.
+ if (IsLineType(first_line, kLineTypeAttributes)) {
+ first_line = first_line.substr(kLinePrefixLength);
+ }
+
+ std::string attribute_candidate;
+ std::string candidate_value;
+
+ // |first_line| must be in the form of "candidate:<value>".
+ if (!SplitByDelimiter(first_line, kSdpDelimiterColon,
+ &attribute_candidate, &candidate_value) ||
+ attribute_candidate != kAttributeCandidate) {
if (is_raw) {
std::ostringstream description;
- description << "Expect line: "
- << kAttributeCandidate
+ description << "Expect line: " << kAttributeCandidate
<< ":" << "<candidate-str>";
return ParseFailed(first_line, 0, description.str(), error);
} else {
@@ -1001,8 +967,8 @@
}
std::vector<std::string> fields;
- talk_base::split(first_line.substr(start_pos),
- kSdpDelimiterSpace, &fields);
+ rtc::split(candidate_value, kSdpDelimiterSpace, &fields);
+
// RFC 5245
// a=candidate:<foundation> <component-id> <transport> <priority>
// <connection-address> <port> typ <candidate-types>
@@ -1013,10 +979,8 @@
(fields[6] != kAttributeCandidateTyp)) {
return ParseFailedExpectMinFieldNum(first_line, expected_min_fields, error);
}
- std::string foundation;
- if (!GetValue(fields[0], kAttributeCandidate, &foundation, error)) {
- return false;
- }
+ std::string foundation = fields[0];
+
int component_id = 0;
if (!GetValueFromString(first_line, fields[1], &component_id, error)) {
return false;
@@ -1070,6 +1034,25 @@
++current_position;
}
+ // If this is a TCP candidate, it has additional extension as defined in
+ // RFC 6544.
+ std::string tcptype;
+ if (fields.size() >= (current_position + 2) &&
+ fields[current_position] == kTcpCandidateType) {
+ tcptype = fields[++current_position];
+ ++current_position;
+
+ if (tcptype != cricket::TCPTYPE_ACTIVE_STR &&
+ tcptype != cricket::TCPTYPE_PASSIVE_STR &&
+ tcptype != cricket::TCPTYPE_SIMOPEN_STR) {
+ return ParseFailed(first_line, "Invalid TCP candidate type.", error);
+ }
+
+ if (protocol != cricket::PROTO_TCP) {
+ return ParseFailed(first_line, "Invalid non-TCP candidate", error);
+ }
+ }
+
// Extension
// Empty string as the candidate username and password.
// Will be updated later with the ice-ufrag and ice-pwd.
@@ -1102,6 +1085,7 @@
address, priority, username, password, candidate_type, network_name,
generation, foundation);
candidate->set_related_address(related_address);
+ candidate->set_tcptype(tcptype);
return true;
}
@@ -1113,19 +1097,39 @@
return false;
}
std::vector<std::string> fields;
- talk_base::split(ice_options, kSdpDelimiterSpace, &fields);
+ rtc::split(ice_options, kSdpDelimiterSpace, &fields);
for (size_t i = 0; i < fields.size(); ++i) {
transport_options->push_back(fields[i]);
}
return true;
}
+bool ParseSctpPort(const std::string& line,
+ int* sctp_port,
+ SdpParseError* error) {
+ // draft-ietf-mmusic-sctp-sdp-07
+ // a=sctp-port
+ std::vector<std::string> fields;
+ rtc::split(line.substr(kLinePrefixLength),
+ kSdpDelimiterSpace, &fields);
+ const size_t expected_min_fields = 2;
+ if (fields.size() < expected_min_fields) {
+ return ParseFailedExpectMinFieldNum(line, expected_min_fields, error);
+ }
+ if (!rtc::FromString(fields[1], sctp_port)) {
+ return ParseFailed(line,
+ "Invalid sctp port value.",
+ error);
+ }
+ return true;
+}
+
bool ParseExtmap(const std::string& line, RtpHeaderExtension* extmap,
SdpParseError* error) {
// RFC 5285
// a=extmap:<value>["/"<direction>] <URI> <extensionattributes>
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
const size_t expected_min_fields = 2;
if (fields.size() < expected_min_fields) {
@@ -1138,7 +1142,7 @@
return false;
}
std::vector<std::string> sub_fields;
- talk_base::split(value_direction, kSdpDelimiterSlash, &sub_fields);
+ rtc::split(value_direction, kSdpDelimiterSlash, &sub_fields);
int value = 0;
if (!GetValueFromString(line, sub_fields[0], &value, error)) {
return false;
@@ -1151,6 +1155,7 @@
void BuildMediaDescription(const ContentInfo* content_info,
const TransportInfo* transport_info,
const MediaType media_type,
+ const std::vector<Candidate>& candidates,
std::string* message) {
ASSERT(message != NULL);
if (content_info == NULL || message == NULL) {
@@ -1190,7 +1195,7 @@
video_desc->codecs().begin();
it != video_desc->codecs().end(); ++it) {
fmt.append(" ");
- fmt.append(talk_base::ToString<int>(it->id));
+ fmt.append(rtc::ToString<int>(it->id));
}
} else if (media_type == cricket::MEDIA_TYPE_AUDIO) {
const AudioContentDescription* audio_desc =
@@ -1199,7 +1204,7 @@
audio_desc->codecs().begin();
it != audio_desc->codecs().end(); ++it) {
fmt.append(" ");
- fmt.append(talk_base::ToString<int>(it->id));
+ fmt.append(rtc::ToString<int>(it->id));
}
} else if (media_type == cricket::MEDIA_TYPE_DATA) {
const DataContentDescription* data_desc =
@@ -1216,13 +1221,13 @@
}
}
- fmt.append(talk_base::ToString<int>(sctp_port));
+ fmt.append(rtc::ToString<int>(sctp_port));
} else {
for (std::vector<cricket::DataCodec>::const_iterator it =
data_desc->codecs().begin();
it != data_desc->codecs().end(); ++it) {
fmt.append(" ");
- fmt.append(talk_base::ToString<int>(it->id));
+ fmt.append(rtc::ToString<int>(it->id));
}
}
}
@@ -1240,12 +1245,46 @@
const std::string port = content_info->rejected ?
kMediaPortRejected : kDefaultPort;
- talk_base::SSLFingerprint* fp = (transport_info) ?
+ rtc::SSLFingerprint* fp = (transport_info) ?
transport_info->description.identity_fingerprint.get() : NULL;
+ // Add the m and c lines.
InitLine(kLineTypeMedia, type, &os);
os << " " << port << " " << media_desc->protocol() << fmt;
- AddLine(os.str(), message);
+ std::string mline = os.str();
+ UpdateMediaDefaultDestination(candidates, mline, message);
+
+ // RFC 4566
+ // b=AS:<bandwidth>
+ // We should always use the default bandwidth for RTP-based data
+ // channels. Don't allow SDP to set the bandwidth, because that
+ // would give JS the opportunity to "break the Internet".
+ // TODO(pthatcher): But we need to temporarily allow the SDP to control
+ // this for backwards-compatibility. Once we don't need that any
+ // more, remove this.
+ bool support_dc_sdp_bandwidth_temporarily = true;
+ if (media_desc->bandwidth() >= 1000 &&
+ (media_type != cricket::MEDIA_TYPE_DATA ||
+ support_dc_sdp_bandwidth_temporarily)) {
+ InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
+ os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
+ AddLine(os.str(), message);
+ }
+
+ // Add the a=rtcp line.
+ bool is_rtp =
+ media_desc->protocol().empty() ||
+ rtc::starts_with(media_desc->protocol().data(),
+ cricket::kMediaProtocolRtpPrefix);
+ if (is_rtp) {
+ std::string rtcp_line = GetRtcpLine(candidates);
+ if (!rtcp_line.empty()) {
+ AddLine(rtcp_line, message);
+ }
+ }
+
+ // Build the a=candidate lines.
+ BuildCandidate(candidates, message);
// Use the transport_info to build the media level ice-ufrag and ice-pwd.
if (transport_info) {
@@ -1357,23 +1396,6 @@
}
AddLine(os.str(), message);
- // RFC 4566
- // b=AS:<bandwidth>
- // We should always use the default bandwidth for RTP-based data
- // channels. Don't allow SDP to set the bandwidth, because that
- // would give JS the opportunity to "break the Internet".
- // TODO(pthatcher): But we need to temporarily allow the SDP to control
- // this for backwards-compatibility. Once we don't need that any
- // more, remove this.
- bool support_dc_sdp_bandwidth_temporarily = true;
- if (media_desc->bandwidth() >= 1000 &&
- (media_type != cricket::MEDIA_TYPE_DATA ||
- support_dc_sdp_bandwidth_temporarily)) {
- InitLine(kLineTypeSessionBandwidth, kApplicationSpecificMaximum, &os);
- os << kSdpDelimiterColon << (media_desc->bandwidth() / 1000);
- AddLine(os.str(), message);
- }
-
// RFC 5761
// a=rtcp-mux
if (media_desc->rtcp_mux()) {
@@ -1430,7 +1452,7 @@
std::vector<uint32>::const_iterator ssrc =
track->ssrc_groups[i].ssrcs.begin();
for (; ssrc != track->ssrc_groups[i].ssrcs.end(); ++ssrc) {
- os << kSdpDelimiterSpace << talk_base::ToString<uint32>(*ssrc);
+ os << kSdpDelimiterSpace << rtc::ToString<uint32>(*ssrc);
}
AddLine(os.str(), message);
}
@@ -1513,7 +1535,8 @@
kCodecParamStereo, kCodecParamUseInbandFec, kCodecParamStartBitrate,
kCodecParamMaxBitrate, kCodecParamMinBitrate, kCodecParamMaxQuantization,
kCodecParamSctpProtocol, kCodecParamSctpStreams,
- kCodecParamMaxAverageBitrate, kCodecParamAssociatedPayloadType
+ kCodecParamMaxAverageBitrate, kCodecParamMaxPlaybackRate,
+ kCodecParamAssociatedPayloadType
};
for (size_t i = 0; i < ARRAY_SIZE(kFmtpParams); ++i) {
if (_stricmp(name.c_str(), kFmtpParams[i]) == 0) {
@@ -1565,6 +1588,24 @@
}
}
+bool AddSctpDataCodec(DataContentDescription* media_desc,
+ int sctp_port) {
+ if (media_desc->HasCodec(cricket::kGoogleSctpDataCodecId)) {
+ return ParseFailed("",
+ "Can't have multiple sctp port attributes.",
+ NULL);
+ }
+ // Add the SCTP Port number as a pseudo-codec "port" parameter
+ cricket::DataCodec codec_port(
+ cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
+ 0);
+ codec_port.SetParam(cricket::kCodecParamPort, sctp_port);
+ LOG(INFO) << "AddSctpDataCodec: Got SCTP Port Number "
+ << sctp_port;
+ media_desc->AddCodec(codec_port);
+ return true;
+}
+
bool GetMinValue(const std::vector<int>& values, int* value) {
if (values.empty()) {
return false;
@@ -1582,7 +1623,7 @@
if (found == params.end()) {
return false;
}
- if (!talk_base::FromString(found->second, value)) {
+ if (!rtc::FromString(found->second, value)) {
return false;
}
return true;
@@ -1704,11 +1745,14 @@
InitAttrLine(kAttributeCandidate, &os);
os << kSdpDelimiterColon
- << it->foundation() << " " << it->component() << " "
- << it->protocol() << " " << it->priority() << " "
+ << it->foundation() << " "
+ << it->component() << " "
+ << it->protocol() << " "
+ << it->priority() << " "
<< it->address().ipaddr().ToString() << " "
<< it->address().PortAsString() << " "
- << kAttributeCandidateTyp << " " << type << " ";
+ << kAttributeCandidateTyp << " "
+ << type << " ";
// Related address
if (!it->related_address().IsNil()) {
@@ -1718,6 +1762,10 @@
<< it->related_address().PortAsString() << " ";
}
+ if (it->protocol() == cricket::TCP_PROTOCOL_NAME) {
+ os << kTcpCandidateType << " " << it->tcptype() << " ";
+ }
+
// Extensions
os << kAttributeCandidateGeneration << " " << it->generation();
@@ -1762,7 +1810,7 @@
std::string(), error);
}
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
const size_t expected_fields = 6;
if (fields.size() != expected_fields) {
@@ -1865,7 +1913,7 @@
"Can't have multiple fingerprint attributes at the same level.",
error);
}
- talk_base::SSLFingerprint* fingerprint = NULL;
+ rtc::SSLFingerprint* fingerprint = NULL;
if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
return false;
}
@@ -1900,7 +1948,7 @@
// RFC 5888 and draft-holmberg-mmusic-sdp-bundle-negotiation-00
// a=group:BUNDLE video voice
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
std::string semantics;
if (!GetValue(fields[0], kAttributeGroup, &semantics, error)) {
@@ -1915,7 +1963,7 @@
}
static bool ParseFingerprintAttribute(const std::string& line,
- talk_base::SSLFingerprint** fingerprint,
+ rtc::SSLFingerprint** fingerprint,
SdpParseError* error) {
if (!IsLineType(line, kLineTypeAttributes) ||
!HasAttribute(line, kAttributeFingerprint)) {
@@ -1924,7 +1972,7 @@
}
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
const size_t expected_fields = 2;
if (fields.size() != expected_fields) {
@@ -1943,7 +1991,7 @@
::tolower);
// The second field is the digest value. De-hexify it.
- *fingerprint = talk_base::SSLFingerprint::CreateFromRfc4572(
+ *fingerprint = rtc::SSLFingerprint::CreateFromRfc4572(
algorithm, fields[1]);
if (!*fingerprint) {
return ParseFailed(line,
@@ -1960,7 +2008,7 @@
// setup-attr = "a=setup:" role
// role = "active" / "passive" / "actpass" / "holdconn"
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
+ rtc::split(line.substr(kLinePrefixLength), kSdpDelimiterColon, &fields);
const size_t expected_fields = 2;
if (fields.size() != expected_fields) {
return ParseFailedExpectFieldNum(line, expected_fields, error);
@@ -2105,7 +2153,7 @@
++mline_index;
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
const size_t expected_min_fields = 4;
if (fields.size() < expected_min_fields) {
@@ -2124,18 +2172,20 @@
// <fmt>
std::vector<int> codec_preference;
- for (size_t j = 3 ; j < fields.size(); ++j) {
- // TODO(wu): Remove when below bug is fixed.
- // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
- if (fields[j] == "" && j == fields.size() - 1) {
- continue;
- }
+ if (!is_sctp) {
+ for (size_t j = 3 ; j < fields.size(); ++j) {
+ // TODO(wu): Remove when below bug is fixed.
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=996329
+ if (fields[j] == "" && j == fields.size() - 1) {
+ continue;
+ }
- int pl = 0;
- if (!GetValueFromString(line, fields[j], &pl, error)) {
- return false;
+ int pl = 0;
+ if (!GetValueFromString(line, fields[j], &pl, error)) {
+ return false;
+ }
+ codec_preference.push_back(pl);
}
- codec_preference.push_back(pl);
}
// Make a temporary TransportDescription based on |session_td|.
@@ -2149,7 +2199,7 @@
session_td.identity_fingerprint.get(),
Candidates());
- talk_base::scoped_ptr<MediaContentDescription> content;
+ rtc::scoped_ptr<MediaContentDescription> content;
std::string content_name;
if (HasAttribute(line, kMediaTypeVideo)) {
content.reset(ParseContentDescription<VideoContentDescription>(
@@ -2162,26 +2212,20 @@
codec_preference, pos, &content_name,
&transport, candidates, error));
} else if (HasAttribute(line, kMediaTypeData)) {
- DataContentDescription* desc =
+ DataContentDescription* data_desc =
ParseContentDescription<DataContentDescription>(
message, cricket::MEDIA_TYPE_DATA, mline_index, protocol,
codec_preference, pos, &content_name,
&transport, candidates, error);
+ content.reset(data_desc);
- if (desc && protocol == cricket::kMediaProtocolDtlsSctp) {
- // Add the SCTP Port number as a pseudo-codec "port" parameter
- cricket::DataCodec codec_port(
- cricket::kGoogleSctpDataCodecId, cricket::kGoogleSctpDataCodecName,
- 0);
- codec_port.SetParam(cricket::kCodecParamPort, fields[3]);
- LOG(INFO) << "ParseMediaDescription: Got SCTP Port Number "
- << fields[3];
- ASSERT(!desc->HasCodec(cricket::kGoogleSctpDataCodecId));
- desc->AddCodec(codec_port);
+ int p;
+ if (data_desc && protocol == cricket::kMediaProtocolDtlsSctp &&
+ rtc::FromString(fields[3], &p)) {
+ if (!AddSctpDataCodec(data_desc, p))
+ return false;
}
- content.reset(desc);
-
// We should always use the default bandwidth for RTP-based data
// channels. Don't allow SDP to set the bandwidth, because that
// would give JS the opportunity to "break the Internet".
@@ -2433,7 +2477,7 @@
bool is_rtp =
protocol.empty() ||
- talk_base::starts_with(protocol.data(),
+ rtc::starts_with(protocol.data(),
cricket::kMediaProtocolRtpPrefix);
// Loop until the next m line
@@ -2503,7 +2547,7 @@
return false;
}
} else if (HasAttribute(line, kAttributeFingerprint)) {
- talk_base::SSLFingerprint* fingerprint = NULL;
+ rtc::SSLFingerprint* fingerprint = NULL;
if (!ParseFingerprintAttribute(line, &fingerprint, error)) {
return false;
@@ -2513,6 +2557,15 @@
if (!ParseDtlsSetup(line, &(transport->connection_role), error)) {
return false;
}
+ } else if (HasAttribute(line, kAttributeSctpPort)) {
+ int sctp_port;
+ if (!ParseSctpPort(line, &sctp_port, error)) {
+ return false;
+ }
+ if (!AddSctpDataCodec(static_cast<DataContentDescription*>(media_desc),
+ sctp_port)) {
+ return false;
+ }
} else if (is_rtp) {
//
// RTP specific attrubtes
@@ -2716,7 +2769,7 @@
// draft-alvestrand-mmusic-msid-00
// "msid:" identifier [ " " appdata ]
std::vector<std::string> fields;
- talk_base::split(value, kSdpDelimiterSpace, &fields);
+ rtc::split(value, kSdpDelimiterSpace, &fields);
if (fields.size() < 1 || fields.size() > 2) {
return ParseFailed(line,
"Expected format \"msid:<identifier>[ <appdata>]\".",
@@ -2745,7 +2798,7 @@
// RFC 5576
// a=ssrc-group:<semantics> <ssrc-id> ...
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
const size_t expected_min_fields = 2;
if (fields.size() < expected_min_fields) {
@@ -2771,7 +2824,7 @@
MediaContentDescription* media_desc,
SdpParseError* error) {
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
// RFC 4568
// a=crypto:<tag> <crypto-suite> <key-params> [<session-params>]
@@ -2838,7 +2891,7 @@
MediaContentDescription* media_desc,
SdpParseError* error) {
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
// RFC 4566
// a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encodingparameters>]
@@ -2867,7 +2920,7 @@
}
const std::string encoder = fields[1];
std::vector<std::string> codec_params;
- talk_base::split(encoder, '/', &codec_params);
+ rtc::split(encoder, '/', &codec_params);
// <encoding name>/<clock rate>[/<encodingparameters>]
// 2 mandatory fields
if (codec_params.size() < 2 || codec_params.size() > 3) {
@@ -2955,7 +3008,7 @@
return true;
}
std::vector<std::string> fields;
- talk_base::split(line.substr(kLinePrefixLength),
+ rtc::split(line.substr(kLinePrefixLength),
kSdpDelimiterSpace, &fields);
// RFC 5576
@@ -3010,7 +3063,7 @@
return true;
}
std::vector<std::string> rtcp_fb_fields;
- talk_base::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
+ rtc::split(line.c_str(), kSdpDelimiterSpace, &rtcp_fb_fields);
if (rtcp_fb_fields.size() < 2) {
return ParseFailedGetValue(line, kAttributeRtcpFb, error);
}
diff --git a/app/webrtc/webrtcsdp_unittest.cc b/app/webrtc/webrtcsdp_unittest.cc
index 64776e2..560d5da 100644
--- a/app/webrtc/webrtcsdp_unittest.cc
+++ b/app/webrtc/webrtcsdp_unittest.cc
@@ -31,16 +31,16 @@
#include "talk/app/webrtc/jsepsessiondescription.h"
#include "talk/app/webrtc/webrtcsdp.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslfingerprint.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/constants.h"
#include "talk/p2p/base/constants.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sslfingerprint.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
using cricket::AudioCodec;
using cricket::AudioContentDescription;
@@ -284,6 +284,16 @@
"a=mid:data_content_name\r\n"
"a=sctpmap:5000 webrtc-datachannel 1024\r\n";
+// draft-ietf-mmusic-sctp-sdp-07
+static const char kSdpSctpDataChannelStringWithSctpPort[] =
+ "m=application 1 DTLS/SCTP webrtc-datachannel\r\n"
+ "a=fmtp:webrtc-datachannel max-message-size=100000\r\n"
+ "a=sctp-port 5000\r\n"
+ "c=IN IP4 0.0.0.0\r\n"
+ "a=ice-ufrag:ufrag_data\r\n"
+ "a=ice-pwd:pwd_data\r\n"
+ "a=mid:data_content_name\r\n";
+
static const char kSdpSctpDataChannelWithCandidatesString[] =
"m=application 2345 DTLS/SCTP 5000\r\n"
"c=IN IP4 74.125.127.126\r\n"
@@ -312,6 +322,39 @@
"c=IN IP4 0.0.0.0\r\n"
"a=x-google-flag:conference\r\n";
+static const char kSdpSessionString[] =
+ "v=0\r\n"
+ "o=- 18446744069414584320 18446462598732840960 IN IP4 127.0.0.1\r\n"
+ "s=-\r\n"
+ "t=0 0\r\n"
+ "a=msid-semantic: WMS local_stream\r\n";
+
+static const char kSdpAudioString[] =
+ "m=audio 1 RTP/SAVPF 111\r\n"
+ "c=IN IP4 0.0.0.0\r\n"
+ "a=rtcp:1 IN IP4 0.0.0.0\r\n"
+ "a=ice-ufrag:ufrag_voice\r\na=ice-pwd:pwd_voice\r\n"
+ "a=mid:audio_content_name\r\n"
+ "a=sendrecv\r\n"
+ "a=rtpmap:111 opus/48000/2\r\n"
+ "a=ssrc:1 cname:stream_1_cname\r\n"
+ "a=ssrc:1 msid:local_stream audio_track_id_1\r\n"
+ "a=ssrc:1 mslabel:local_stream\r\n"
+ "a=ssrc:1 label:audio_track_id_1\r\n";
+
+static const char kSdpVideoString[] =
+ "m=video 1 RTP/SAVPF 120\r\n"
+ "c=IN IP4 0.0.0.0\r\n"
+ "a=rtcp:1 IN IP4 0.0.0.0\r\n"
+ "a=ice-ufrag:ufrag_video\r\na=ice-pwd:pwd_video\r\n"
+ "a=mid:video_content_name\r\n"
+ "a=sendrecv\r\n"
+ "a=rtpmap:120 VP8/90000\r\n"
+ "a=ssrc:2 cname:stream_1_cname\r\n"
+ "a=ssrc:2 msid:local_stream video_track_id_1\r\n"
+ "a=ssrc:2 mslabel:local_stream\r\n"
+ "a=ssrc:2 label:video_track_id_1\r\n";
+
// One candidate reference string as per W3c spec.
// candidate:<blah> not a=candidate:<blah>CRLF
@@ -322,6 +365,24 @@
"a=candidate:a0+B/1 1 udp 2130706432 192.168.1.5 1234 typ host "
"generation 2\r\n";
+static const char kSdpTcpActiveCandidate[] =
+ "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host "
+ "tcptype active generation 2";
+static const char kSdpTcpPassiveCandidate[] =
+ "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host "
+ "tcptype passive generation 2";
+static const char kSdpTcpSOCandidate[] =
+ "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host "
+ "tcptype so generation 2";
+static const char kSdpTcpInvalidCandidate[] =
+ "candidate:a0+B/1 1 tcp 2130706432 192.168.1.5 9 typ host "
+ "tcptype invalid generation 2";
+
+// One candidate reference string with IPV6 address.
+static const char kRawIPV6Candidate[] =
+ "candidate:a0+B/1 1 udp 2130706432 "
+ "abcd::abcd::abcd::abcd::abcd::abcd::abcd::abcd 1234 typ host generation 2";
+
// One candidate reference string.
static const char kSdpOneCandidateOldFormat[] =
"a=candidate:a0+B/1 1 udp 2130706432 192.168.1.5 1234 typ host network_name"
@@ -390,14 +451,14 @@
const std::string& newlines,
std::string* message) {
const std::string tmp = line + newlines;
- talk_base::replace_substrs(line.c_str(), line.length(),
+ rtc::replace_substrs(line.c_str(), line.length(),
tmp.c_str(), tmp.length(), message);
}
static void Replace(const std::string& line,
const std::string& newlines,
std::string* message) {
- talk_base::replace_substrs(line.c_str(), line.length(),
+ rtc::replace_substrs(line.c_str(), line.length(),
newlines.c_str(), newlines.length(), message);
}
@@ -474,7 +535,7 @@
desc_.AddContent(kAudioContentName, NS_JINGLE_RTP, audio_desc_);
// VideoContentDescription
- talk_base::scoped_ptr<VideoContentDescription> video(
+ rtc::scoped_ptr<VideoContentDescription> video(
new VideoContentDescription());
video_desc_ = video.get();
StreamParams video_stream1;
@@ -526,7 +587,7 @@
// v4 host
int port = 1234;
- talk_base::SocketAddress address("192.168.1.5", port++);
+ rtc::SocketAddress address("192.168.1.5", port++);
Candidate candidate1(
"", ICE_CANDIDATE_COMPONENT_RTP, "udp", address, kCandidatePriority,
"", "", LOCAL_PORT_TYPE,
@@ -548,7 +609,7 @@
"", kCandidateGeneration, kCandidateFoundation1);
// v6 host
- talk_base::SocketAddress v6_address("::1", port++);
+ rtc::SocketAddress v6_address("::1", port++);
cricket::Candidate candidate5(
"", cricket::ICE_CANDIDATE_COMPONENT_RTP,
"udp", v6_address, kCandidatePriority,
@@ -575,8 +636,8 @@
// stun
int port_stun = 2345;
- talk_base::SocketAddress address_stun("74.125.127.126", port_stun++);
- talk_base::SocketAddress rel_address_stun("192.168.1.5", port_stun++);
+ rtc::SocketAddress address_stun("74.125.127.126", port_stun++);
+ rtc::SocketAddress rel_address_stun("192.168.1.5", port_stun++);
cricket::Candidate candidate9
("", cricket::ICE_CANDIDATE_COMPONENT_RTP,
"udp", address_stun, kCandidatePriority,
@@ -595,7 +656,7 @@
// relay
int port_relay = 3456;
- talk_base::SocketAddress address_relay("74.125.224.39", port_relay++);
+ rtc::SocketAddress address_relay("74.125.224.39", port_relay++);
cricket::Candidate candidate11(
"", cricket::ICE_CANDIDATE_COMPONENT_RTCP,
"udp", address_relay, kCandidatePriority,
@@ -865,9 +926,9 @@
const char ice_ufragx[] = "a=xice-ufrag";
const char ice_pwd[] = "a=ice-pwd";
const char ice_pwdx[] = "a=xice-pwd";
- talk_base::replace_substrs(ice_ufrag, strlen(ice_ufrag),
+ rtc::replace_substrs(ice_ufrag, strlen(ice_ufrag),
ice_ufragx, strlen(ice_ufragx), sdp);
- talk_base::replace_substrs(ice_pwd, strlen(ice_pwd),
+ rtc::replace_substrs(ice_pwd, strlen(ice_pwd),
ice_pwdx, strlen(ice_pwdx), sdp);
return true;
}
@@ -917,7 +978,7 @@
void AddFingerprint() {
desc_.RemoveTransportInfoByName(kAudioContentName);
desc_.RemoveTransportInfoByName(kVideoContentName);
- talk_base::SSLFingerprint fingerprint(talk_base::DIGEST_SHA_1,
+ rtc::SSLFingerprint fingerprint(rtc::DIGEST_SHA_1,
kIdentityDigest,
sizeof(kIdentityDigest));
EXPECT_TRUE(desc_.AddTransportInfo(
@@ -1001,7 +1062,7 @@
}
void AddSctpDataChannel() {
- talk_base::scoped_ptr<DataContentDescription> data(
+ rtc::scoped_ptr<DataContentDescription> data(
new DataContentDescription());
data_desc_ = data.get();
data_desc_->set_protocol(cricket::kMediaProtocolDtlsSctp);
@@ -1018,7 +1079,7 @@
}
void AddRtpDataChannel() {
- talk_base::scoped_ptr<DataContentDescription> data(
+ rtc::scoped_ptr<DataContentDescription> data(
new DataContentDescription());
data_desc_ = data.get();
@@ -1119,7 +1180,7 @@
const std::string& name, int expected_value) {
cricket::CodecParameterMap::const_iterator found = params.find(name);
ASSERT_TRUE(found != params.end());
- EXPECT_EQ(found->second, talk_base::ToString<int>(expected_value));
+ EXPECT_EQ(found->second, rtc::ToString<int>(expected_value));
}
void TestDeserializeCodecParams(const CodecParams& params,
@@ -1287,7 +1348,7 @@
VideoContentDescription* video_desc_;
DataContentDescription* data_desc_;
Candidates candidates_;
- talk_base::scoped_ptr<IceCandidateInterface> jcandidate_;
+ rtc::scoped_ptr<IceCandidateInterface> jcandidate_;
JsepSessionDescription jdesc_;
};
@@ -1408,10 +1469,10 @@
jdesc_.session_version()));
std::string message = webrtc::SdpSerialize(jdesc_);
std::string sdp_with_bandwidth = kSdpFullString;
- InjectAfter("a=mid:video_content_name\r\na=sendrecv\r\n",
+ InjectAfter("c=IN IP4 74.125.224.39\r\n",
"b=AS:100\r\n",
&sdp_with_bandwidth);
- InjectAfter("a=mid:audio_content_name\r\na=sendrecv\r\n",
+ InjectAfter("c=IN IP4 74.125.127.126\r\n",
"b=AS:50\r\n",
&sdp_with_bandwidth);
EXPECT_EQ(sdp_with_bandwidth, message);
@@ -1509,10 +1570,10 @@
char default_portstr[16];
char new_portstr[16];
- talk_base::sprintfn(default_portstr, sizeof(default_portstr), "%d",
+ rtc::sprintfn(default_portstr, sizeof(default_portstr), "%d",
kDefaultSctpPort);
- talk_base::sprintfn(new_portstr, sizeof(new_portstr), "%d", kNewPort);
- talk_base::replace_substrs(default_portstr, strlen(default_portstr),
+ rtc::sprintfn(new_portstr, sizeof(new_portstr), "%d", kNewPort);
+ rtc::replace_substrs(default_portstr, strlen(default_portstr),
new_portstr, strlen(new_portstr),
&expected_sdp);
@@ -1535,7 +1596,7 @@
// TODO(pthatcher): We need to temporarily allow the SDP to control
// this for backwards-compatibility. Once we don't need that any
// more, remove this.
- InjectAfter("a=mid:data_content_name\r\na=sendrecv\r\n",
+ InjectAfter("m=application 1 RTP/SAVPF 101\r\nc=IN IP4 0.0.0.0\r\n",
"b=AS:100\r\n",
&expected_sdp);
EXPECT_EQ(expected_sdp, message);
@@ -1575,7 +1636,23 @@
TEST_F(WebRtcSdpTest, SerializeCandidates) {
std::string message = webrtc::SdpSerializeCandidate(*jcandidate_);
- EXPECT_EQ(std::string(kSdpOneCandidate), message);
+ EXPECT_EQ(std::string(kRawCandidate), message);
+}
+
+// TODO(mallinath) : Enable this test once WebRTCSdp capable of parsing
+// RFC 6544.
+TEST_F(WebRtcSdpTest, SerializeTcpCandidates) {
+ Candidate candidate(
+ "", ICE_CANDIDATE_COMPONENT_RTP, "tcp",
+ rtc::SocketAddress("192.168.1.5", 9), kCandidatePriority,
+ "", "", LOCAL_PORT_TYPE,
+ "", kCandidateGeneration, kCandidateFoundation1);
+ candidate.set_tcptype(cricket::TCPTYPE_ACTIVE_STR);
+ rtc::scoped_ptr<IceCandidateInterface> jcandidate(
+ new JsepIceCandidate(std::string("audio_content_name"), 0, candidate));
+
+ std::string message = webrtc::SdpSerializeCandidate(*jcandidate);
+ EXPECT_EQ(std::string(kSdpTcpActiveCandidate), message);
}
TEST_F(WebRtcSdpTest, DeserializeSessionDescription) {
@@ -1856,14 +1933,22 @@
expected.set_generation(0);
EXPECT_TRUE(jcandidate.candidate().IsEquivalent(expected));
- // Multiple candidate lines.
- // Only the first line will be deserialized. The rest will be ignored.
- sdp = kSdpOneCandidate;
- sdp.append("a=candidate:1 2 tcp 1234 192.168.1.100 5678 typ host\r\n");
+ sdp = kSdpTcpActiveCandidate;
EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate));
- EXPECT_EQ(kDummyMid, jcandidate.sdp_mid());
- EXPECT_EQ(kDummyIndex, jcandidate.sdp_mline_index());
- EXPECT_TRUE(jcandidate.candidate().IsEquivalent(jcandidate_->candidate()));
+ // Make a cricket::Candidate equivalent to kSdpTcpCandidate string.
+ Candidate candidate(
+ "", ICE_CANDIDATE_COMPONENT_RTP, "tcp",
+ rtc::SocketAddress("192.168.1.5", 9), kCandidatePriority,
+ "", "", LOCAL_PORT_TYPE,
+ "", kCandidateGeneration, kCandidateFoundation1);
+ rtc::scoped_ptr<IceCandidateInterface> jcandidate_template(
+ new JsepIceCandidate(std::string("audio_content_name"), 0, candidate));
+ EXPECT_TRUE(jcandidate.candidate().IsEquivalent(
+ jcandidate_template->candidate()));
+ sdp = kSdpTcpPassiveCandidate;
+ EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate));
+ sdp = kSdpTcpSOCandidate;
+ EXPECT_TRUE(SdpDeserializeCandidate(sdp, &jcandidate));
}
// This test verifies the deserialization of candidate-attribute
@@ -1895,10 +1980,29 @@
Replace("candidate:", "", &candidate_attribute);
EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate));
- // Concatenating additional candidate. Expecting deserialization to fail.
- candidate_attribute = kRawCandidate;
- candidate_attribute.append("candidate:1 2 udp 1234 192.168.1.1 typ host");
+ // Candidate line with IPV6 address.
+ EXPECT_TRUE(SdpDeserializeCandidate(kRawIPV6Candidate, &jcandidate));
+}
+
+// This test verifies that the deserialization of an invalid candidate string
+// fails.
+TEST_F(WebRtcSdpTest, DeserializeInvalidCandidiate) {
+ JsepIceCandidate jcandidate(kDummyMid, kDummyIndex);
+
+ std::string candidate_attribute = kRawCandidate;
+ candidate_attribute.replace(0, 1, "x");
EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate));
+
+ candidate_attribute = kSdpOneCandidate;
+ candidate_attribute.replace(0, 1, "x");
+ EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate));
+
+ candidate_attribute = kRawCandidate;
+ candidate_attribute.append("\r\n");
+ candidate_attribute.append(kRawCandidate);
+ EXPECT_FALSE(SdpDeserializeCandidate(candidate_attribute, &jcandidate));
+
+ EXPECT_FALSE(SdpDeserializeCandidate(kSdpTcpInvalidCandidate, &jcandidate));
}
TEST_F(WebRtcSdpTest, DeserializeSdpWithRtpDataChannels) {
@@ -1929,6 +2033,36 @@
EXPECT_TRUE(CompareSessionDescription(jdesc, jdesc_output));
}
+TEST_F(WebRtcSdpTest, DeserializeSdpWithSctpDataChannelsWithSctpPort) {
+ AddSctpDataChannel();
+ JsepSessionDescription jdesc(kDummyString);
+ ASSERT_TRUE(jdesc.Initialize(desc_.Copy(), kSessionId, kSessionVersion));
+
+ std::string sdp_with_data = kSdpString;
+ sdp_with_data.append(kSdpSctpDataChannelStringWithSctpPort);
+ JsepSessionDescription jdesc_output(kDummyString);
+
+ EXPECT_TRUE(SdpDeserialize(sdp_with_data, &jdesc_output));
+ EXPECT_TRUE(CompareSessionDescription(jdesc, jdesc_output));
+}
+
+// Test to check the behaviour if sctp-port is specified
+// on the m= line and in a=sctp-port.
+TEST_F(WebRtcSdpTest, DeserializeSdpWithMultiSctpPort) {
+ AddSctpDataChannel();
+ JsepSessionDescription jdesc(kDummyString);
+ ASSERT_TRUE(jdesc.Initialize(desc_.Copy(), kSessionId, kSessionVersion));
+
+ std::string sdp_with_data = kSdpString;
+ // Append m= attributes
+ sdp_with_data.append(kSdpSctpDataChannelString);
+ // Append a=sctp-port attribute
+ sdp_with_data.append("a=sctp-port 5000\r\n");
+ JsepSessionDescription jdesc_output(kDummyString);
+
+ EXPECT_FALSE(SdpDeserialize(sdp_with_data, &jdesc_output));
+}
+
// For crbug/344475.
TEST_F(WebRtcSdpTest, DeserializeSdpWithCorruptedSctpDataChannels) {
std::string sdp_with_data = kSdpString;
@@ -1946,9 +2080,9 @@
const uint16 kUnusualSctpPort = 9556;
char default_portstr[16];
char unusual_portstr[16];
- talk_base::sprintfn(default_portstr, sizeof(default_portstr), "%d",
+ rtc::sprintfn(default_portstr, sizeof(default_portstr), "%d",
kDefaultSctpPort);
- talk_base::sprintfn(unusual_portstr, sizeof(unusual_portstr), "%d",
+ rtc::sprintfn(unusual_portstr, sizeof(unusual_portstr), "%d",
kUnusualSctpPort);
// First setup the expected JsepSessionDescription.
@@ -1970,13 +2104,26 @@
// Then get the deserialized JsepSessionDescription.
std::string sdp_with_data = kSdpString;
sdp_with_data.append(kSdpSctpDataChannelString);
- talk_base::replace_substrs(default_portstr, strlen(default_portstr),
+ rtc::replace_substrs(default_portstr, strlen(default_portstr),
unusual_portstr, strlen(unusual_portstr),
&sdp_with_data);
JsepSessionDescription jdesc_output(kDummyString);
EXPECT_TRUE(SdpDeserialize(sdp_with_data, &jdesc_output));
EXPECT_TRUE(CompareSessionDescription(jdesc, jdesc_output));
+
+ // We need to test the deserialized JsepSessionDescription from
+ // kSdpSctpDataChannelStringWithSctpPort for
+ // draft-ietf-mmusic-sctp-sdp-07
+ // a=sctp-port
+ sdp_with_data = kSdpString;
+ sdp_with_data.append(kSdpSctpDataChannelStringWithSctpPort);
+ rtc::replace_substrs(default_portstr, strlen(default_portstr),
+ unusual_portstr, strlen(unusual_portstr),
+ &sdp_with_data);
+
+ EXPECT_TRUE(SdpDeserialize(sdp_with_data, &jdesc_output));
+ EXPECT_TRUE(CompareSessionDescription(jdesc, jdesc_output));
}
TEST_F(WebRtcSdpTest, DeserializeSdpWithRtpDataChannelsAndBandwidth) {
@@ -2351,3 +2498,48 @@
EXPECT_EQ(cricket::CONNECTIONROLE_ACTPASS,
vtinfo->description.connection_role);
}
+
+// Verifies that the order of the serialized m-lines follows the order of the
+// ContentInfo in SessionDescription, and vise versa for deserialization.
+TEST_F(WebRtcSdpTest, MediaContentOrderMaintainedRoundTrip) {
+ JsepSessionDescription jdesc(kDummyString);
+ const std::string media_content_sdps[3] = {
+ kSdpAudioString,
+ kSdpVideoString,
+ kSdpSctpDataChannelString
+ };
+ const cricket::MediaType media_types[3] = {
+ cricket::MEDIA_TYPE_AUDIO,
+ cricket::MEDIA_TYPE_VIDEO,
+ cricket::MEDIA_TYPE_DATA
+ };
+
+ // Verifies all 6 permutations.
+ for (size_t i = 0; i < 6; ++i) {
+ size_t media_content_in_sdp[3];
+ // The index of the first media content.
+ media_content_in_sdp[0] = i / 2;
+ // The index of the second media content.
+ media_content_in_sdp[1] = (media_content_in_sdp[0] + i % 2 + 1) % 3;
+ // The index of the third media content.
+ media_content_in_sdp[2] = (media_content_in_sdp[0] + (i + 1) % 2 + 1) % 3;
+
+ std::string sdp_string = kSdpSessionString;
+ for (size_t i = 0; i < 3; ++i)
+ sdp_string += media_content_sdps[media_content_in_sdp[i]];
+
+ EXPECT_TRUE(SdpDeserialize(sdp_string, &jdesc));
+ cricket::SessionDescription* desc = jdesc.description();
+ EXPECT_EQ(3u, desc->contents().size());
+
+ for (size_t i = 0; i < 3; ++i) {
+ const cricket::MediaContentDescription* mdesc =
+ static_cast<const cricket::MediaContentDescription*>(
+ desc->contents()[i].description);
+ EXPECT_EQ(media_types[media_content_in_sdp[i]], mdesc->type());
+ }
+
+ std::string serialized_sdp = webrtc::SdpSerialize(jdesc);
+ EXPECT_EQ(sdp_string, serialized_sdp);
+ }
+}
diff --git a/app/webrtc/webrtcsession.cc b/app/webrtc/webrtcsession.cc
index 1b1c287..13e2128 100644
--- a/app/webrtc/webrtcsession.cc
+++ b/app/webrtc/webrtcsession.cc
@@ -38,15 +38,16 @@
#include "talk/app/webrtc/mediastreamsignaling.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/webrtcsessiondescriptionfactory.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/videocapturer.h"
#include "talk/session/media/channel.h"
#include "talk/session/media/channelmanager.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
using cricket::ContentInfo;
using cricket::ContentInfos;
@@ -74,6 +75,7 @@
"Called with SDP without ice-ufrag and ice-pwd.";
const char kSessionError[] = "Session error code: ";
const char kSessionErrorDesc[] = "Session error description: ";
+const int kMaxUnsignalledRecvStreams = 20;
// Compares |answer| against |offer|. Comparision is done
// for number of m-lines in answer against offer. If matches true will be
@@ -222,30 +224,28 @@
cricket::StreamParams stream_out;
const cricket::ContentInfo* audio_info =
cricket::GetFirstAudioContent(session_description);
- if (!audio_info) {
- return false;
- }
- const cricket::MediaContentDescription* audio_content =
- static_cast<const cricket::MediaContentDescription*>(
- audio_info->description);
+ if (audio_info) {
+ const cricket::MediaContentDescription* audio_content =
+ static_cast<const cricket::MediaContentDescription*>(
+ audio_info->description);
- if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
- *track_id = stream_out.id;
- return true;
+ if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
+ *track_id = stream_out.id;
+ return true;
+ }
}
const cricket::ContentInfo* video_info =
cricket::GetFirstVideoContent(session_description);
- if (!video_info) {
- return false;
- }
- const cricket::MediaContentDescription* video_content =
- static_cast<const cricket::MediaContentDescription*>(
- video_info->description);
+ if (video_info) {
+ const cricket::MediaContentDescription* video_content =
+ static_cast<const cricket::MediaContentDescription*>(
+ video_info->description);
- if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
- *track_id = stream_out.id;
- return true;
+ if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
+ *track_id = stream_out.id;
+ return true;
+ }
}
return false;
}
@@ -381,12 +381,28 @@
std::string string_value;
T value;
if (constraints->GetOptional().FindFirst(key, &string_value)) {
- if (talk_base::FromString(string_value, &value)) {
+ if (rtc::FromString(string_value, &value)) {
option->Set(value);
}
}
}
+uint32 ConvertIceTransportTypeToCandidateFilter(
+ PeerConnectionInterface::IceTransportsType type) {
+ switch (type) {
+ case PeerConnectionInterface::kNone:
+ return cricket::CF_NONE;
+ case PeerConnectionInterface::kRelay:
+ return cricket::CF_RELAY;
+ case PeerConnectionInterface::kNoHost:
+ return (cricket::CF_ALL & ~cricket::CF_HOST);
+ case PeerConnectionInterface::kAll:
+ return cricket::CF_ALL;
+ default: ASSERT(false);
+ }
+ return cricket::CF_NONE;
+}
+
// Help class used to remember if a a remote peer has requested ice restart by
// by sending a description with new ice ufrag and password.
class IceRestartAnswerLatch {
@@ -430,8 +446,10 @@
// No transport description exist. This is not an ice restart.
continue;
}
- if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
- new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
+ if (cricket::IceCredentialsChanged(old_transport_desc->ice_ufrag,
+ old_transport_desc->ice_pwd,
+ new_transport_desc->ice_ufrag,
+ new_transport_desc->ice_pwd)) {
LOG(LS_INFO) << "Remote peer request ice restart.";
ice_restart_ = true;
break;
@@ -445,12 +463,12 @@
WebRtcSession::WebRtcSession(
cricket::ChannelManager* channel_manager,
- talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
cricket::PortAllocator* port_allocator,
MediaStreamSignaling* mediastream_signaling)
: cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
- talk_base::ToString(talk_base::CreateRandomId64() &
+ rtc::ToString(rtc::CreateRandomId64() &
LLONG_MAX),
cricket::NS_JINGLE_RTP, false),
// RFC 3264: The numeric value of the session id and version in the
@@ -467,14 +485,16 @@
}
WebRtcSession::~WebRtcSession() {
- if (voice_channel_.get()) {
- SignalVoiceChannelDestroyed();
- channel_manager_->DestroyVoiceChannel(voice_channel_.release());
- }
+ // Destroy video_channel_ first since it may have a pointer to the
+ // voice_channel_.
if (video_channel_.get()) {
SignalVideoChannelDestroyed();
channel_manager_->DestroyVideoChannel(video_channel_.release());
}
+ if (voice_channel_.get()) {
+ SignalVoiceChannelDestroyed();
+ channel_manager_->DestroyVoiceChannel(voice_channel_.release());
+ }
if (data_channel_.get()) {
SignalDataChannelDestroyed();
channel_manager_->DestroyDataChannel(data_channel_.release());
@@ -546,14 +566,6 @@
video_options_.suspend_below_min_bitrate.Set(value);
}
- if (FindConstraint(
- constraints,
- MediaConstraintsInterface::kSkipEncodingUnusedStreams,
- &value,
- NULL)) {
- video_options_.skip_encoding_unused_streams.Set(value);
- }
-
SetOptionFromOptionalConstraint(constraints,
MediaConstraintsInterface::kScreencastMinBitrate,
&video_options_.screencast_min_bitrate);
@@ -583,16 +595,15 @@
MediaConstraintsInterface::kPayloadPadding,
&video_options_.use_payload_padding);
- // Find improved wifi bwe constraint.
- if (FindConstraint(
- constraints,
- MediaConstraintsInterface::kImprovedWifiBwe,
- &value,
- NULL)) {
- video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
- } else {
- // Enable by default if the constraint is not set.
- video_options_.use_improved_wifi_bandwidth_estimator.Set(true);
+ SetOptionFromOptionalConstraint(constraints,
+ MediaConstraintsInterface::kNumUnsignalledRecvStreams,
+ &video_options_.unsignalled_recv_stream_limit);
+ if (video_options_.unsignalled_recv_stream_limit.IsSet()) {
+ int stream_limit;
+ video_options_.unsignalled_recv_stream_limit.Get(&stream_limit);
+ stream_limit = rtc::_min(kMaxUnsignalledRecvStreams, stream_limit);
+ stream_limit = rtc::_max(0, stream_limit);
+ video_options_.unsignalled_recv_stream_limit.Set(stream_limit);
}
SetOptionFromOptionalConstraint(constraints,
@@ -616,8 +627,8 @@
}
SetOptionFromOptionalConstraint(constraints,
- MediaConstraintsInterface::kOpusFec,
- &audio_options_.opus_fec);
+ MediaConstraintsInterface::kCombinedAudioVideoBwe,
+ &audio_options_.combined_audio_video_bwe);
const cricket::VideoCodec default_codec(
JsepSessionDescription::kDefaultVideoCodecId,
@@ -645,7 +656,8 @@
if (options.disable_encryption) {
webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
}
-
+ port_allocator()->set_candidate_filter(
+ ConvertIceTransportTypeToCandidateFilter(ice_transport));
return true;
}
@@ -679,7 +691,7 @@
return webrtc_session_desc_factory_->SdesPolicy();
}
-bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
+bool WebRtcSession::GetSslRole(rtc::SSLRole* role) {
if (local_description() == NULL || remote_description() == NULL) {
LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
<< "SSL Role of the session.";
@@ -699,9 +711,10 @@
return false;
}
-void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
- const MediaConstraintsInterface* constraints) {
- webrtc_session_desc_factory_->CreateOffer(observer, constraints);
+void WebRtcSession::CreateOffer(
+ CreateSessionDescriptionObserver* observer,
+ const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
+ webrtc_session_desc_factory_->CreateOffer(observer, options);
}
void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
@@ -712,7 +725,7 @@
bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
std::string* err_desc) {
// Takes the ownership of |desc| regardless of the result.
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
// Validate SDP.
if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
@@ -750,6 +763,7 @@
if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
return false;
}
+
// Kick starting the ice candidates allocation.
StartCandidatesAllocation();
@@ -757,7 +771,7 @@
// local session description.
mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
- talk_base::SSLRole role;
+ rtc::SSLRole role;
if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
}
@@ -770,7 +784,7 @@
bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
std::string* err_desc) {
// Takes the ownership of |desc| regardless of the result.
- talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
+ rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
// Validate SDP.
if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
@@ -813,7 +827,7 @@
desc);
remote_desc_.reset(desc_temp.release());
- talk_base::SSLRole role;
+ rtc::SSLRole role;
if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
}
@@ -890,36 +904,16 @@
return false;
}
- cricket::TransportProxy* transport_proxy = NULL;
- if (remote_description()) {
- size_t mediacontent_index =
- static_cast<size_t>(candidate->sdp_mline_index());
- size_t remote_content_size =
- BaseSession::remote_description()->contents().size();
- if (mediacontent_index >= remote_content_size) {
- LOG(LS_ERROR)
- << "ProcessIceMessage: Invalid candidate media index.";
- return false;
+ bool valid = false;
+ if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
+ if (valid) {
+ LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
+ saved_candidates_.push_back(
+ new JsepIceCandidate(candidate->sdp_mid(),
+ candidate->sdp_mline_index(),
+ candidate->candidate()));
}
-
- cricket::ContentInfo content =
- BaseSession::remote_description()->contents()[mediacontent_index];
- transport_proxy = GetTransportProxy(content.name);
- }
-
- // We need to check the local/remote description for the Transport instead of
- // the session, because a new Transport added during renegotiation may have
- // them unset while the session has them set from the previou negotiation. Not
- // doing so may trigger the auto generation of transport description and mess
- // up DTLS identity information, ICE credential, etc.
- if (!transport_proxy || !(transport_proxy->local_description_set() &&
- transport_proxy->remote_description_set())) {
- LOG(LS_INFO) << "ProcessIceMessage: Local/Remote description not set "
- << "on the Transport, save the candidate for later use.";
- saved_candidates_.push_back(
- new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
- candidate->candidate()));
- return true;
+ return valid;
}
// Add this candidate to the remote session description.
@@ -931,8 +925,10 @@
return UseCandidate(candidate);
}
-bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
- return false;
+bool WebRtcSession::SetIceTransports(
+ PeerConnectionInterface::IceTransportsType type) {
+ return port_allocator()->set_candidate_filter(
+ ConvertIceTransportTypeToCandidateFilter(type));
}
bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
@@ -1108,7 +1104,7 @@
}
bool WebRtcSession::SendData(const cricket::SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
cricket::SendDataResult* result) {
if (!data_channel_.get()) {
LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
@@ -1163,7 +1159,7 @@
return data_channel_.get() && data_channel_->ready_to_send_data();
}
-talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
+rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
const std::string& label,
const InternalDataChannelInit* config) {
if (state() == STATE_RECEIVEDTERMINATE) {
@@ -1177,7 +1173,7 @@
config ? (*config) : InternalDataChannelInit();
if (data_channel_type_ == cricket::DCT_SCTP) {
if (new_config.id < 0) {
- talk_base::SSLRole role;
+ rtc::SSLRole role;
if (GetSslRole(&role) &&
!mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
@@ -1190,7 +1186,7 @@
}
}
- talk_base::scoped_refptr<DataChannel> channel(DataChannel::Create(
+ rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
this, data_channel_type_, label, new_config));
if (channel && !mediastream_signaling_->AddDataChannel(channel))
return NULL;
@@ -1210,7 +1206,7 @@
ice_restart_latch_->Reset();
}
-void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
+void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
SetIdentity(identity);
}
@@ -1384,10 +1380,24 @@
if (!remote_desc)
return true;
bool ret = true;
+
for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
const IceCandidateCollection* candidates = remote_desc->candidates(m);
for (size_t n = 0; n < candidates->count(); ++n) {
- ret = UseCandidate(candidates->at(n));
+ const IceCandidateInterface* candidate = candidates->at(n);
+ bool valid = false;
+ if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
+ if (valid) {
+ LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
+ saved_candidates_.push_back(
+ new JsepIceCandidate(candidate->sdp_mid(),
+ candidate->sdp_mline_index(),
+ candidate->candidate()));
+ }
+ continue;
+ }
+
+ ret = UseCandidate(candidate);
if (!ret)
break;
}
@@ -1439,16 +1449,8 @@
void WebRtcSession::RemoveUnusedChannelsAndTransports(
const SessionDescription* desc) {
- const cricket::ContentInfo* voice_info =
- cricket::GetFirstAudioContent(desc);
- if ((!voice_info || voice_info->rejected) && voice_channel_) {
- mediastream_signaling_->OnAudioChannelClose();
- SignalVoiceChannelDestroyed();
- const std::string content_name = voice_channel_->content_name();
- channel_manager_->DestroyVoiceChannel(voice_channel_.release());
- DestroyTransportProxy(content_name);
- }
-
+ // Destroy video_channel_ first since it may have a pointer to the
+ // voice_channel_.
const cricket::ContentInfo* video_info =
cricket::GetFirstVideoContent(desc);
if ((!video_info || video_info->rejected) && video_channel_) {
@@ -1459,6 +1461,16 @@
DestroyTransportProxy(content_name);
}
+ const cricket::ContentInfo* voice_info =
+ cricket::GetFirstAudioContent(desc);
+ if ((!voice_info || voice_info->rejected) && voice_channel_) {
+ mediastream_signaling_->OnAudioChannelClose();
+ SignalVoiceChannelDestroyed();
+ const std::string content_name = voice_channel_->content_name();
+ channel_manager_->DestroyVoiceChannel(voice_channel_.release());
+ DestroyTransportProxy(content_name);
+ }
+
const cricket::ContentInfo* data_info =
cricket::GetFirstDataContent(desc);
if ((!data_info || data_info->rejected) && data_channel_) {
@@ -1563,7 +1575,7 @@
void WebRtcSession::OnDataChannelMessageReceived(
cricket::DataChannel* channel,
const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload) {
+ const rtc::Buffer& payload) {
ASSERT(data_channel_type_ == cricket::DCT_SCTP);
if (params.type == cricket::DMT_CONTROL &&
mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
@@ -1694,4 +1706,42 @@
return desc.str();
}
+// We need to check the local/remote description for the Transport instead of
+// the session, because a new Transport added during renegotiation may have
+// them unset while the session has them set from the previous negotiation.
+// Not doing so may trigger the auto generation of transport description and
+// mess up DTLS identity information, ICE credential, etc.
+bool WebRtcSession::ReadyToUseRemoteCandidate(
+ const IceCandidateInterface* candidate,
+ const SessionDescriptionInterface* remote_desc,
+ bool* valid) {
+ *valid = true;;
+ cricket::TransportProxy* transport_proxy = NULL;
+
+ const SessionDescriptionInterface* current_remote_desc =
+ remote_desc ? remote_desc : remote_description();
+
+ if (!current_remote_desc)
+ return false;
+
+ size_t mediacontent_index =
+ static_cast<size_t>(candidate->sdp_mline_index());
+ size_t remote_content_size =
+ current_remote_desc->description()->contents().size();
+ if (mediacontent_index >= remote_content_size) {
+ LOG(LS_ERROR)
+ << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
+
+ *valid = false;
+ return false;
+ }
+
+ cricket::ContentInfo content =
+ current_remote_desc->description()->contents()[mediacontent_index];
+ transport_proxy = GetTransportProxy(content.name);
+
+ return transport_proxy && transport_proxy->local_description_set() &&
+ transport_proxy->remote_description_set();
+}
+
} // namespace webrtc
diff --git a/app/webrtc/webrtcsession.h b/app/webrtc/webrtcsession.h
index 3ffea8f..86ae435 100644
--- a/app/webrtc/webrtcsession.h
+++ b/app/webrtc/webrtcsession.h
@@ -30,16 +30,16 @@
#include <string>
-#include "talk/app/webrtc/peerconnectioninterface.h"
+#include "talk/app/webrtc/datachannel.h"
#include "talk/app/webrtc/dtmfsender.h"
#include "talk/app/webrtc/mediastreamprovider.h"
-#include "talk/app/webrtc/datachannel.h"
+#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/statstypes.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
#include "talk/media/base/mediachannel.h"
#include "talk/p2p/base/session.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -73,6 +73,9 @@
extern const char kSdpWithoutSdesAndDtlsDisabled[];
extern const char kSessionError[];
extern const char kSessionErrorDesc[];
+// Maximum number of received video streams that will be processed by webrtc
+// even if they are not signalled beforehand.
+extern const int kMaxUnsignalledRecvStreams;
// ICE state callback interface.
class IceObserver {
@@ -106,8 +109,8 @@
public DataChannelProviderInterface {
public:
WebRtcSession(cricket::ChannelManager* channel_manager,
- talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
cricket::PortAllocator* port_allocator,
MediaStreamSignaling* mediastream_signaling);
virtual ~WebRtcSession();
@@ -138,14 +141,15 @@
cricket::SecurePolicy SdesPolicy() const;
// Get current ssl role from transport.
- bool GetSslRole(talk_base::SSLRole* role);
+ bool GetSslRole(rtc::SSLRole* role);
// Generic error message callback from WebRtcSession.
// TODO - It may be necessary to supply error code as well.
sigslot::signal0<> SignalError;
- void CreateOffer(CreateSessionDescriptionObserver* observer,
- const MediaConstraintsInterface* constraints);
+ void CreateOffer(
+ CreateSessionDescriptionObserver* observer,
+ const PeerConnectionInterface::RTCOfferAnswerOptions& options);
void CreateAnswer(CreateSessionDescriptionObserver* observer,
const MediaConstraintsInterface* constraints);
// The ownership of |desc| will be transferred after this call.
@@ -156,7 +160,7 @@
std::string* err_desc);
bool ProcessIceMessage(const IceCandidateInterface* ice_candidate);
- bool UpdateIce(PeerConnectionInterface::IceTransportsType type);
+ bool SetIceTransports(PeerConnectionInterface::IceTransportsType type);
const SessionDescriptionInterface* local_description() const {
return local_desc_.get();
@@ -195,7 +199,7 @@
// Implements DataChannelProviderInterface.
virtual bool SendData(const cricket::SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
cricket::SendDataResult* result) OVERRIDE;
virtual bool ConnectDataChannel(DataChannel* webrtc_data_channel) OVERRIDE;
virtual void DisconnectDataChannel(DataChannel* webrtc_data_channel) OVERRIDE;
@@ -204,7 +208,7 @@
virtual bool ReadyToSendData() const OVERRIDE;
// Implements DataChannelFactory.
- talk_base::scoped_refptr<DataChannel> CreateDataChannel(
+ rtc::scoped_refptr<DataChannel> CreateDataChannel(
const std::string& label,
const InternalDataChannelInit* config) OVERRIDE;
@@ -216,7 +220,7 @@
// Called when an SSLIdentity is generated or retrieved by
// WebRTCSessionDescriptionFactory. Should happen before setLocalDescription.
- void OnIdentityReady(talk_base::SSLIdentity* identity);
+ void OnIdentityReady(rtc::SSLIdentity* identity);
// For unit test.
bool waiting_for_identity() const;
@@ -289,7 +293,7 @@
// messages.
void OnDataChannelMessageReceived(cricket::DataChannel* channel,
const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload);
+ const rtc::Buffer& payload);
std::string BadStateErrMsg(State state);
void SetIceConnectionState(PeerConnectionInterface::IceConnectionState state);
@@ -309,17 +313,25 @@
bool ValidateDtlsSetupAttribute(const cricket::SessionDescription* desc,
Action action);
+ // Returns true if we are ready to push down the remote candidate.
+ // |remote_desc| is the new remote description, or NULL if the current remote
+ // description should be used. Output |valid| is true if the candidate media
+ // index is valid.
+ bool ReadyToUseRemoteCandidate(const IceCandidateInterface* candidate,
+ const SessionDescriptionInterface* remote_desc,
+ bool* valid);
+
std::string GetSessionErrorMsg();
- talk_base::scoped_ptr<cricket::VoiceChannel> voice_channel_;
- talk_base::scoped_ptr<cricket::VideoChannel> video_channel_;
- talk_base::scoped_ptr<cricket::DataChannel> data_channel_;
+ rtc::scoped_ptr<cricket::VoiceChannel> voice_channel_;
+ rtc::scoped_ptr<cricket::VideoChannel> video_channel_;
+ rtc::scoped_ptr<cricket::DataChannel> data_channel_;
cricket::ChannelManager* channel_manager_;
MediaStreamSignaling* mediastream_signaling_;
IceObserver* ice_observer_;
PeerConnectionInterface::IceConnectionState ice_connection_state_;
- talk_base::scoped_ptr<SessionDescriptionInterface> local_desc_;
- talk_base::scoped_ptr<SessionDescriptionInterface> remote_desc_;
+ rtc::scoped_ptr<SessionDescriptionInterface> local_desc_;
+ rtc::scoped_ptr<SessionDescriptionInterface> remote_desc_;
// Candidates that arrived before the remote description was set.
std::vector<IceCandidateInterface*> saved_candidates_;
// If the remote peer is using a older version of implementation.
@@ -333,9 +345,9 @@
// 2. If constraint kEnableRtpDataChannels is true, RTP is allowed (DCT_RTP);
// 3. If both 1&2 are false, data channel is not allowed (DCT_NONE).
cricket::DataChannelType data_channel_type_;
- talk_base::scoped_ptr<IceRestartAnswerLatch> ice_restart_latch_;
+ rtc::scoped_ptr<IceRestartAnswerLatch> ice_restart_latch_;
- talk_base::scoped_ptr<WebRtcSessionDescriptionFactory>
+ rtc::scoped_ptr<WebRtcSessionDescriptionFactory>
webrtc_session_desc_factory_;
sigslot::signal0<> SignalVoiceChannelDestroyed;
diff --git a/app/webrtc/webrtcsession_unittest.cc b/app/webrtc/webrtcsession_unittest.cc
index 956f8a6..7aa87fb 100644
--- a/app/webrtc/webrtcsession_unittest.cc
+++ b/app/webrtc/webrtcsession_unittest.cc
@@ -30,23 +30,12 @@
#include "talk/app/webrtc/jsepsessiondescription.h"
#include "talk/app/webrtc/mediastreamsignaling.h"
#include "talk/app/webrtc/streamcollection.h"
-#include "talk/app/webrtc/videotrack.h"
#include "talk/app/webrtc/test/fakeconstraints.h"
#include "talk/app/webrtc/test/fakedtlsidentityservice.h"
#include "talk/app/webrtc/test/fakemediastreamsignaling.h"
+#include "talk/app/webrtc/videotrack.h"
#include "talk/app/webrtc/webrtcsession.h"
#include "talk/app/webrtc/webrtcsessiondescriptionfactory.h"
-#include "talk/base/fakenetwork.h"
-#include "talk/base/firewallsocketserver.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/network.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/fakevideorenderer.h"
#include "talk/media/base/mediachannel.h"
@@ -57,6 +46,17 @@
#include "talk/p2p/client/basicportallocator.h"
#include "talk/session/media/channelmanager.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/fakenetwork.h"
+#include "webrtc/base/firewallsocketserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/virtualsocketserver.h"
#define MAYBE_SKIP_TEST(feature) \
if (!(feature())) { \
@@ -71,9 +71,9 @@
using cricket::NS_GINGLE_P2P;
using cricket::NS_JINGLE_ICE_UDP;
using cricket::TransportInfo;
-using talk_base::SocketAddress;
-using talk_base::scoped_ptr;
-using talk_base::Thread;
+using rtc::SocketAddress;
+using rtc::scoped_ptr;
+using rtc::Thread;
using webrtc::CreateSessionDescription;
using webrtc::CreateSessionDescriptionObserver;
using webrtc::CreateSessionDescriptionRequest;
@@ -98,6 +98,9 @@
using webrtc::kSdpWithoutSdesCrypto;
using webrtc::kSessionError;
using webrtc::kSessionErrorDesc;
+using webrtc::kMaxUnsignalledRecvStreams;
+
+typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
static const int kClientAddrPort = 0;
static const char kClientAddrHost1[] = "11.11.11.11";
@@ -105,6 +108,8 @@
static const char kStunAddrHost[] = "99.99.99.1";
static const SocketAddress kTurnUdpIntAddr("99.99.99.4", 3478);
static const SocketAddress kTurnUdpExtAddr("99.99.99.6", 0);
+static const char kTurnUsername[] = "test";
+static const char kTurnPassword[] = "test";
static const char kSessionVersion[] = "1";
@@ -133,7 +138,7 @@
const std::string& newlines,
std::string* message) {
const std::string tmp = line + newlines;
- talk_base::replace_substrs(line.c_str(), line.length(),
+ rtc::replace_substrs(line.c_str(), line.length(),
tmp.c_str(), tmp.length(), message);
}
@@ -203,8 +208,8 @@
class WebRtcSessionForTest : public webrtc::WebRtcSession {
public:
WebRtcSessionForTest(cricket::ChannelManager* cmgr,
- talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
cricket::PortAllocator* port_allocator,
webrtc::IceObserver* ice_observer,
webrtc::MediaStreamSignaling* mediastream_signaling)
@@ -223,7 +228,7 @@
};
class WebRtcSessionCreateSDPObserverForTest
- : public talk_base::RefCountedObject<CreateSessionDescriptionObserver> {
+ : public rtc::RefCountedObject<CreateSessionDescriptionObserver> {
public:
enum State {
kInit,
@@ -253,7 +258,7 @@
~WebRtcSessionCreateSDPObserverForTest() {}
private:
- talk_base::scoped_ptr<SessionDescriptionInterface> description_;
+ rtc::scoped_ptr<SessionDescriptionInterface> description_;
State state_;
};
@@ -294,24 +299,28 @@
device_manager_(new cricket::FakeDeviceManager()),
channel_manager_(new cricket::ChannelManager(
media_engine_, data_engine_, device_manager_,
- new cricket::CaptureManager(), talk_base::Thread::Current())),
+ new cricket::CaptureManager(), rtc::Thread::Current())),
tdesc_factory_(new cricket::TransportDescriptionFactory()),
desc_factory_(new cricket::MediaSessionDescriptionFactory(
channel_manager_.get(), tdesc_factory_.get())),
- pss_(new talk_base::PhysicalSocketServer),
- vss_(new talk_base::VirtualSocketServer(pss_.get())),
- fss_(new talk_base::FirewallSocketServer(vss_.get())),
+ pss_(new rtc::PhysicalSocketServer),
+ vss_(new rtc::VirtualSocketServer(pss_.get())),
+ fss_(new rtc::FirewallSocketServer(vss_.get())),
ss_scope_(fss_.get()),
- stun_socket_addr_(talk_base::SocketAddress(kStunAddrHost,
+ stun_socket_addr_(rtc::SocketAddress(kStunAddrHost,
cricket::STUN_SERVER_PORT)),
stun_server_(Thread::Current(), stun_socket_addr_),
turn_server_(Thread::Current(), kTurnUdpIntAddr, kTurnUdpExtAddr),
- allocator_(new cricket::BasicPortAllocator(
- &network_manager_, stun_socket_addr_,
- SocketAddress(), SocketAddress(), SocketAddress())),
mediastream_signaling_(channel_manager_.get()),
ice_type_(PeerConnectionInterface::kAll) {
tdesc_factory_->set_protocol(cricket::ICEPROTO_HYBRID);
+
+ cricket::ServerAddresses stun_servers;
+ stun_servers.insert(stun_socket_addr_);
+ allocator_.reset(new cricket::BasicPortAllocator(
+ &network_manager_,
+ stun_servers,
+ SocketAddress(), SocketAddress(), SocketAddress()));
allocator_->set_flags(cricket::PORTALLOCATOR_DISABLE_TCP |
cricket::PORTALLOCATOR_DISABLE_RELAY |
cricket::PORTALLOCATOR_ENABLE_BUNDLE);
@@ -321,11 +330,11 @@
}
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
void AddInterface(const SocketAddress& addr) {
@@ -339,8 +348,8 @@
void Init(DTLSIdentityServiceInterface* identity_service) {
ASSERT_TRUE(session_.get() == NULL);
session_.reset(new WebRtcSessionForTest(
- channel_manager_.get(), talk_base::Thread::Current(),
- talk_base::Thread::Current(), allocator_.get(),
+ channel_manager_.get(), rtc::Thread::Current(),
+ rtc::Thread::Current(), allocator_.get(),
&observer_,
&mediastream_signaling_));
@@ -374,18 +383,26 @@
// Call mediastream_signaling_.UseOptionsWithStreamX() before this function
// to decide which streams to create.
void InitiateCall() {
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
EXPECT_TRUE_WAIT(PeerConnectionInterface::kIceGatheringNew !=
observer_.ice_gathering_state_,
kIceCandidatesTimeout);
}
+ SessionDescriptionInterface* CreateOffer() {
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.offer_to_receive_audio =
+ RTCOfferAnswerOptions::kOfferToReceiveMediaTrue;
+
+ return CreateOffer(options);
+ }
+
SessionDescriptionInterface* CreateOffer(
- const webrtc::MediaConstraintsInterface* constraints) {
- talk_base::scoped_refptr<WebRtcSessionCreateSDPObserverForTest>
+ const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
+ rtc::scoped_refptr<WebRtcSessionCreateSDPObserverForTest>
observer = new WebRtcSessionCreateSDPObserverForTest();
- session_->CreateOffer(observer, constraints);
+ session_->CreateOffer(observer, options);
EXPECT_TRUE_WAIT(
observer->state() != WebRtcSessionCreateSDPObserverForTest::kInit,
2000);
@@ -394,7 +411,7 @@
SessionDescriptionInterface* CreateAnswer(
const webrtc::MediaConstraintsInterface* constraints) {
- talk_base::scoped_refptr<WebRtcSessionCreateSDPObserverForTest> observer
+ rtc::scoped_refptr<WebRtcSessionCreateSDPObserverForTest> observer
= new WebRtcSessionCreateSDPObserverForTest();
session_->CreateAnswer(observer, constraints);
EXPECT_TRUE_WAIT(
@@ -478,8 +495,8 @@
void SetFactoryDtlsSrtp() {
desc_factory_->set_secure(cricket::SEC_DISABLED);
std::string identity_name = "WebRTC" +
- talk_base::ToString(talk_base::CreateRandomId());
- identity_.reset(talk_base::SSLIdentity::Generate(identity_name));
+ rtc::ToString(rtc::CreateRandomId());
+ identity_.reset(rtc::SSLIdentity::Generate(identity_name));
tdesc_factory_->set_identity(identity_.get());
tdesc_factory_->set_secure(cricket::SEC_REQUIRED);
}
@@ -495,7 +512,7 @@
}
void VerifyAnswerFromNonCryptoOffer() {
- // Create a SDP without Crypto.
+ // Create an SDP without Crypto.
cricket::MediaSessionOptions options;
options.has_video = true;
JsepSessionDescription* offer(
@@ -523,6 +540,28 @@
VerifyCryptoParams(answer->description());
}
+ void SetAndVerifyNumUnsignalledRecvStreams(
+ int value_set, int value_expected) {
+ constraints_.reset(new FakeConstraints());
+ constraints_->AddOptional(
+ webrtc::MediaConstraintsInterface::kNumUnsignalledRecvStreams,
+ value_set);
+ session_.reset();
+ Init(NULL);
+ mediastream_signaling_.SendAudioVideoStream1();
+ SessionDescriptionInterface* offer = CreateOffer();
+
+ SetLocalDescriptionWithoutError(offer);
+
+ video_channel_ = media_engine_->GetVideoChannel(0);
+
+ ASSERT_TRUE(video_channel_ != NULL);
+ cricket::VideoOptions video_options;
+ EXPECT_TRUE(video_channel_->GetOptions(&video_options));
+ EXPECT_EQ(value_expected,
+ video_options.unsignalled_recv_stream_limit.GetWithDefaultIfUnset(-1));
+ }
+
void CompareIceUfragAndPassword(const cricket::SessionDescription* desc1,
const cricket::SessionDescription* desc2,
bool expect_equal) {
@@ -567,10 +606,10 @@
+ "\r\n";
std::string pwd_line = "a=ice-pwd:" + transport_desc->ice_pwd
+ "\r\n";
- talk_base::replace_substrs(ufrag_line.c_str(), ufrag_line.length(),
+ rtc::replace_substrs(ufrag_line.c_str(), ufrag_line.length(),
"", 0,
sdp);
- talk_base::replace_substrs(pwd_line.c_str(), pwd_line.length(),
+ rtc::replace_substrs(pwd_line.c_str(), pwd_line.length(),
"", 0,
sdp);
}
@@ -596,10 +635,10 @@
+ "\r\n";
std::string mod_ufrag = "a=ice-ufrag:" + modified_ice_ufrag + "\r\n";
std::string mod_pwd = "a=ice-pwd:" + modified_ice_pwd + "\r\n";
- talk_base::replace_substrs(ufrag_line.c_str(), ufrag_line.length(),
+ rtc::replace_substrs(ufrag_line.c_str(), ufrag_line.length(),
mod_ufrag.c_str(), mod_ufrag.length(),
sdp);
- talk_base::replace_substrs(pwd_line.c_str(), pwd_line.length(),
+ rtc::replace_substrs(pwd_line.c_str(), pwd_line.length(),
mod_pwd.c_str(), mod_pwd.length(),
sdp);
}
@@ -698,7 +737,7 @@
options.has_video = true;
options.bundle_enabled = true;
- talk_base::scoped_ptr<SessionDescriptionInterface> temp_offer(
+ rtc::scoped_ptr<SessionDescriptionInterface> temp_offer(
CreateRemoteOffer(options, cricket::SEC_ENABLED));
*nodtls_answer =
@@ -719,7 +758,7 @@
cricket::SecurePolicy secure_policy,
const std::string& session_version,
const SessionDescriptionInterface* current_desc) {
- std::string session_id = talk_base::ToString(talk_base::CreateRandomId64());
+ std::string session_id = rtc::ToString(rtc::CreateRandomId64());
const cricket::SessionDescription* cricket_desc = NULL;
if (current_desc) {
cricket_desc = current_desc->description();
@@ -769,10 +808,10 @@
// SessionDescription from the mutated string.
const char* default_port_str = "5000";
char new_port_str[16];
- talk_base::sprintfn(new_port_str, sizeof(new_port_str), "%d", new_port);
+ rtc::sprintfn(new_port_str, sizeof(new_port_str), "%d", new_port);
std::string offer_str;
offer_basis->ToString(&offer_str);
- talk_base::replace_substrs(default_port_str, strlen(default_port_str),
+ rtc::replace_substrs(default_port_str, strlen(default_port_str),
new_port_str, strlen(new_port_str),
&offer_str);
JsepSessionDescription* offer = new JsepSessionDescription(
@@ -796,7 +835,7 @@
cricket::SecurePolicy policy) {
desc_factory_->set_secure(policy);
const std::string session_id =
- talk_base::ToString(talk_base::CreateRandomId64());
+ rtc::ToString(rtc::CreateRandomId64());
JsepSessionDescription* answer(
new JsepSessionDescription(JsepSessionDescription::kAnswer));
if (!answer->Initialize(desc_factory_->CreateAnswer(offer->description(),
@@ -826,17 +865,19 @@
}
void TestSessionCandidatesWithBundleRtcpMux(bool bundle, bool rtcp_mux) {
- AddInterface(talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- FakeConstraints constraints;
- constraints.SetMandatoryUseRtpMux(bundle);
- SessionDescriptionInterface* offer = CreateOffer(&constraints);
+
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.use_rtp_mux = bundle;
+
+ SessionDescriptionInterface* offer = CreateOffer(options);
// SetLocalDescription and SetRemoteDescriptions takes ownership of offer
// and answer.
SetLocalDescriptionWithoutError(offer);
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateRemoteAnswer(session_->local_description()));
std::string sdp;
EXPECT_TRUE(answer->ToString(&sdp));
@@ -849,7 +890,7 @@
// Disable rtcp-mux from the answer
const std::string kRtcpMux = "a=rtcp-mux";
const std::string kXRtcpMux = "a=xrtcp-mux";
- talk_base::replace_substrs(kRtcpMux.c_str(), kRtcpMux.length(),
+ rtc::replace_substrs(kRtcpMux.c_str(), kRtcpMux.length(),
kXRtcpMux.c_str(), kXRtcpMux.length(),
&sdp);
}
@@ -898,10 +939,10 @@
// -> Failed.
// The Gathering state should go: New -> Gathering -> Completed.
void TestLoopbackCall() {
- AddInterface(talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
EXPECT_EQ(PeerConnectionInterface::kIceGatheringNew,
observer_.ice_gathering_state_);
@@ -935,9 +976,9 @@
// Adding firewall rule to block ping requests, which should cause
// transport channel failure.
fss_->AddRule(false,
- talk_base::FP_ANY,
- talk_base::FD_ANY,
- talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ rtc::FP_ANY,
+ rtc::FD_ANY,
+ rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
EXPECT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
observer_.ice_connection_state_,
kIceCandidatesTimeout);
@@ -956,9 +997,9 @@
// wait for the Port to timeout.
int port_timeout = 30000;
fss_->AddRule(false,
- talk_base::FP_ANY,
- talk_base::FD_ANY,
- talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ rtc::FP_ANY,
+ rtc::FD_ANY,
+ rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
EXPECT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
observer_.ice_connection_state_,
kIceCandidatesTimeout + port_timeout);
@@ -1001,7 +1042,7 @@
webrtc::InternalDataChannelInit dci;
dci.reliable = false;
session_->CreateDataChannel("datachannel", &dci);
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
}
@@ -1017,13 +1058,14 @@
SetRemoteDescriptionWithoutError(offer.release());
}
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
const int kNumber = 3;
- talk_base::scoped_refptr<WebRtcSessionCreateSDPObserverForTest>
+ rtc::scoped_refptr<WebRtcSessionCreateSDPObserverForTest>
observers[kNumber];
for (int i = 0; i < kNumber; ++i) {
observers[i] = new WebRtcSessionCreateSDPObserverForTest();
if (type == CreateSessionDescriptionRequest::kOffer) {
- session_->CreateOffer(observers[i], NULL);
+ session_->CreateOffer(observers[i], options);
} else {
session_->CreateAnswer(observers[i], NULL);
}
@@ -1043,26 +1085,38 @@
}
}
+ void ConfigureAllocatorWithTurn() {
+ cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
+ cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
+ relay_server.credentials = credentials;
+ relay_server.ports.push_back(cricket::ProtocolAddress(
+ kTurnUdpIntAddr, cricket::PROTO_UDP, false));
+ allocator_->AddRelay(relay_server);
+ allocator_->set_step_delay(cricket::kMinimumStepDelay);
+ allocator_->set_flags(cricket::PORTALLOCATOR_DISABLE_TCP |
+ cricket::PORTALLOCATOR_ENABLE_BUNDLE);
+ }
+
cricket::FakeMediaEngine* media_engine_;
cricket::FakeDataEngine* data_engine_;
cricket::FakeDeviceManager* device_manager_;
- talk_base::scoped_ptr<cricket::ChannelManager> channel_manager_;
- talk_base::scoped_ptr<cricket::TransportDescriptionFactory> tdesc_factory_;
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity_;
- talk_base::scoped_ptr<cricket::MediaSessionDescriptionFactory> desc_factory_;
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> vss_;
- talk_base::scoped_ptr<talk_base::FirewallSocketServer> fss_;
- talk_base::SocketServerScope ss_scope_;
- talk_base::SocketAddress stun_socket_addr_;
+ rtc::scoped_ptr<cricket::ChannelManager> channel_manager_;
+ rtc::scoped_ptr<cricket::TransportDescriptionFactory> tdesc_factory_;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity_;
+ rtc::scoped_ptr<cricket::MediaSessionDescriptionFactory> desc_factory_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> vss_;
+ rtc::scoped_ptr<rtc::FirewallSocketServer> fss_;
+ rtc::SocketServerScope ss_scope_;
+ rtc::SocketAddress stun_socket_addr_;
cricket::TestStunServer stun_server_;
cricket::TestTurnServer turn_server_;
- talk_base::FakeNetworkManager network_manager_;
- talk_base::scoped_ptr<cricket::BasicPortAllocator> allocator_;
+ rtc::FakeNetworkManager network_manager_;
+ rtc::scoped_ptr<cricket::BasicPortAllocator> allocator_;
PeerConnectionFactoryInterface::Options options_;
- talk_base::scoped_ptr<FakeConstraints> constraints_;
+ rtc::scoped_ptr<FakeConstraints> constraints_;
FakeMediaStreamSignaling mediastream_signaling_;
- talk_base::scoped_ptr<WebRtcSessionForTest> session_;
+ rtc::scoped_ptr<WebRtcSessionForTest> session_;
MockIceObserver observer_;
cricket::FakeVideoMediaChannel* video_channel_;
cricket::FakeVoiceMediaChannel* voice_channel_;
@@ -1096,8 +1150,8 @@
}
TEST_F(WebRtcSessionTest, TestMultihomeCandidates) {
- AddInterface(talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
- AddInterface(talk_base::SocketAddress(kClientAddrHost2, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost2, kClientAddrPort));
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
InitiateCall();
@@ -1107,12 +1161,12 @@
}
TEST_F(WebRtcSessionTest, TestStunError) {
- AddInterface(talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
- AddInterface(talk_base::SocketAddress(kClientAddrHost2, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost2, kClientAddrPort));
fss_->AddRule(false,
- talk_base::FP_UDP,
- talk_base::FD_ANY,
- talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ rtc::FP_UDP,
+ rtc::FD_ANY,
+ rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
InitiateCall();
@@ -1122,6 +1176,53 @@
EXPECT_EQ(6u, observer_.mline_1_candidates_.size());
}
+// Test session delivers no candidates gathered when constraint set to "none".
+TEST_F(WebRtcSessionTest, TestIceTransportsNone) {
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ SetIceTransportType(PeerConnectionInterface::kNone);
+ Init(NULL);
+ mediastream_signaling_.SendAudioVideoStream1();
+ InitiateCall();
+ EXPECT_TRUE_WAIT(observer_.oncandidatesready_, kIceCandidatesTimeout);
+ EXPECT_EQ(0u, observer_.mline_0_candidates_.size());
+ EXPECT_EQ(0u, observer_.mline_1_candidates_.size());
+}
+
+// Test session delivers only relay candidates gathered when constaint set to
+// "relay".
+TEST_F(WebRtcSessionTest, TestIceTransportsRelay) {
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ ConfigureAllocatorWithTurn();
+ SetIceTransportType(PeerConnectionInterface::kRelay);
+ Init(NULL);
+ mediastream_signaling_.SendAudioVideoStream1();
+ InitiateCall();
+ EXPECT_TRUE_WAIT(observer_.oncandidatesready_, kIceCandidatesTimeout);
+ EXPECT_EQ(2u, observer_.mline_0_candidates_.size());
+ EXPECT_EQ(2u, observer_.mline_1_candidates_.size());
+ for (size_t i = 0; i < observer_.mline_0_candidates_.size(); ++i) {
+ EXPECT_EQ(cricket::RELAY_PORT_TYPE,
+ observer_.mline_0_candidates_[i].type());
+ }
+ for (size_t i = 0; i < observer_.mline_1_candidates_.size(); ++i) {
+ EXPECT_EQ(cricket::RELAY_PORT_TYPE,
+ observer_.mline_1_candidates_[i].type());
+ }
+}
+
+// Test session delivers all candidates gathered when constaint set to "all".
+TEST_F(WebRtcSessionTest, TestIceTransportsAll) {
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ SetIceTransportType(PeerConnectionInterface::kAll);
+ Init(NULL);
+ mediastream_signaling_.SendAudioVideoStream1();
+ InitiateCall();
+ EXPECT_TRUE_WAIT(observer_.oncandidatesready_, kIceCandidatesTimeout);
+ // Host + STUN. By default allocator is disabled to gather relay candidates.
+ EXPECT_EQ(4u, observer_.mline_0_candidates_.size());
+ EXPECT_EQ(4u, observer_.mline_1_candidates_.size());
+}
+
TEST_F(WebRtcSessionTest, SetSdpFailedOnInvalidSdp) {
Init(NULL);
SessionDescriptionInterface* offer = NULL;
@@ -1136,7 +1237,7 @@
TEST_F(WebRtcSessionTest, TestCreateSdesOfferReceiveSdesAnswer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
const std::string session_id_orig = offer->session_id();
const std::string session_version_orig = offer->session_version();
SetLocalDescriptionWithoutError(offer);
@@ -1162,23 +1263,22 @@
// Create new offer without send streams.
mediastream_signaling_.SendNothing();
- offer = CreateOffer(NULL);
+ offer = CreateOffer();
// Verify the session id is the same and the session version is
// increased.
EXPECT_EQ(session_id_orig, offer->session_id());
- EXPECT_LT(talk_base::FromString<uint64>(session_version_orig),
- talk_base::FromString<uint64>(offer->session_version()));
+ EXPECT_LT(rtc::FromString<uint64>(session_version_orig),
+ rtc::FromString<uint64>(offer->session_version()));
SetLocalDescriptionWithoutError(offer);
+ EXPECT_EQ(0u, video_channel_->send_streams().size());
+ EXPECT_EQ(0u, voice_channel_->send_streams().size());
mediastream_signaling_.SendAudioVideoStream2();
answer = CreateRemoteAnswer(session_->local_description());
SetRemoteDescriptionWithoutError(answer);
- EXPECT_EQ(0u, video_channel_->send_streams().size());
- EXPECT_EQ(0u, voice_channel_->send_streams().size());
-
// Make sure the receive streams have not changed.
ASSERT_EQ(1u, video_channel_->recv_streams().size());
EXPECT_TRUE(kVideoTrack2 == video_channel_->recv_streams()[0].id);
@@ -1191,7 +1291,7 @@
TEST_F(WebRtcSessionTest, TestReceiveSdesOfferCreateSdesAnswer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream2();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
VerifyCryptoParams(offer->description());
SetRemoteDescriptionWithoutError(offer);
@@ -1218,7 +1318,7 @@
EXPECT_TRUE(kAudioTrack1 == voice_channel_->send_streams()[0].id);
mediastream_signaling_.SendAudioVideoStream1And2();
- offer = CreateOffer(NULL);
+ offer = CreateOffer();
SetRemoteDescriptionWithoutError(offer);
// Answer by turning off all send streams.
@@ -1228,8 +1328,8 @@
// Verify the session id is the same and the session version is
// increased.
EXPECT_EQ(session_id_orig, answer->session_id());
- EXPECT_LT(talk_base::FromString<uint64>(session_version_orig),
- talk_base::FromString<uint64>(answer->session_version()));
+ EXPECT_LT(rtc::FromString<uint64>(session_version_orig),
+ rtc::FromString<uint64>(answer->session_version()));
SetLocalDescriptionWithoutError(answer);
ASSERT_EQ(2u, video_channel_->recv_streams().size());
@@ -1248,12 +1348,12 @@
Init(NULL);
media_engine_->set_fail_create_channel(true);
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
ASSERT_TRUE(offer != NULL);
// SetRemoteDescription and SetLocalDescription will take the ownership of
// the offer.
SetRemoteDescriptionOfferExpectError(kCreateChannelFailed, offer);
- offer = CreateOffer(NULL);
+ offer = CreateOffer();
ASSERT_TRUE(offer != NULL);
SetLocalDescriptionOfferExpectError(kCreateChannelFailed, offer);
}
@@ -1335,7 +1435,7 @@
// Test that we accept an offer with a DTLS fingerprint when DTLS is on
// and that we return an answer with a DTLS fingerprint.
TEST_F(WebRtcSessionTest, TestReceiveDtlsOfferCreateDtlsAnswer) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
mediastream_signaling_.SendAudioVideoStream1();
InitWithDtls();
SetFactoryDtlsSrtp();
@@ -1364,13 +1464,13 @@
// Test that we set a local offer with a DTLS fingerprint when DTLS is on
// and then we accept a remote answer with a DTLS fingerprint successfully.
TEST_F(WebRtcSessionTest, TestCreateDtlsOfferReceiveDtlsAnswer) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
mediastream_signaling_.SendAudioVideoStream1();
InitWithDtls();
SetFactoryDtlsSrtp();
// Verify that we get a crypto fingerprint in the answer.
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
ASSERT_TRUE(offer != NULL);
VerifyFingerprintStatus(offer->description(), true);
// Check that we don't have an a=crypto line in the offer.
@@ -1394,7 +1494,7 @@
// Test that if we support DTLS and the other side didn't offer a fingerprint,
// we will fail to set the remote description.
TEST_F(WebRtcSessionTest, TestReceiveNonDtlsOfferWhenDtlsOn) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
cricket::MediaSessionOptions options;
options.has_video = true;
@@ -1418,7 +1518,7 @@
// Test that we return a failure when applying a local answer that doesn't have
// a DTLS fingerprint when DTLS is required.
TEST_F(WebRtcSessionTest, TestSetLocalNonDtlsAnswerWhenDtlsOn) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
SessionDescriptionInterface* offer = NULL;
SessionDescriptionInterface* answer = NULL;
@@ -1434,9 +1534,9 @@
// Test that we return a failure when applying a remote answer that doesn't have
// a DTLS fingerprint when DTLS is required.
TEST_F(WebRtcSessionTest, TestSetRemoteNonDtlsAnswerWhenDtlsOn) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
cricket::MediaSessionOptions options;
options.has_video = true;
JsepSessionDescription* answer =
@@ -1457,7 +1557,7 @@
InitWithDtls();
// Verify that we get a crypto fingerprint in the answer.
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
ASSERT_TRUE(offer != NULL);
VerifyFingerprintStatus(offer->description(), false);
// Check that we don't have an a=crypto line in the offer.
@@ -1510,11 +1610,11 @@
Init(NULL);
mediastream_signaling_.SendNothing();
// SetLocalDescription take ownership of offer.
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
// SetLocalDescription take ownership of offer.
- SessionDescriptionInterface* offer2 = CreateOffer(NULL);
+ SessionDescriptionInterface* offer2 = CreateOffer();
SetLocalDescriptionWithoutError(offer2);
}
@@ -1522,19 +1622,19 @@
Init(NULL);
mediastream_signaling_.SendNothing();
// SetLocalDescription take ownership of offer.
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetRemoteDescriptionWithoutError(offer);
- SessionDescriptionInterface* offer2 = CreateOffer(NULL);
+ SessionDescriptionInterface* offer2 = CreateOffer();
SetRemoteDescriptionWithoutError(offer2);
}
TEST_F(WebRtcSessionTest, TestSetLocalAndRemoteOffer) {
Init(NULL);
mediastream_signaling_.SendNothing();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
- offer = CreateOffer(NULL);
+ offer = CreateOffer();
SetRemoteDescriptionOfferExpectError(
"Called in wrong state: STATE_SENTINITIATE", offer);
}
@@ -1542,9 +1642,9 @@
TEST_F(WebRtcSessionTest, TestSetRemoteAndLocalOffer) {
Init(NULL);
mediastream_signaling_.SendNothing();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetRemoteDescriptionWithoutError(offer);
- offer = CreateOffer(NULL);
+ offer = CreateOffer();
SetLocalDescriptionOfferExpectError(
"Called in wrong state: STATE_RECEIVEDINITIATE", offer);
}
@@ -1575,7 +1675,7 @@
TEST_F(WebRtcSessionTest, TestSetRemotePrAnswer) {
Init(NULL);
mediastream_signaling_.SendNothing();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionExpectState(offer, BaseSession::STATE_SENTINITIATE);
JsepSessionDescription* pranswer =
@@ -1602,8 +1702,8 @@
TEST_F(WebRtcSessionTest, TestSetLocalAnswerWithoutOffer) {
Init(NULL);
mediastream_signaling_.SendNothing();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
SessionDescriptionInterface* answer =
CreateRemoteAnswer(offer.get());
SetLocalDescriptionAnswerExpectError("Called in wrong state: STATE_INIT",
@@ -1613,8 +1713,8 @@
TEST_F(WebRtcSessionTest, TestSetRemoteAnswerWithoutOffer) {
Init(NULL);
mediastream_signaling_.SendNothing();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
SessionDescriptionInterface* answer =
CreateRemoteAnswer(offer.get());
SetRemoteDescriptionAnswerExpectError(
@@ -1632,7 +1732,7 @@
// Fail since we have not set a offer description.
EXPECT_FALSE(session_->ProcessIceMessage(&ice_candidate1));
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
// Candidate should be allowed to add before remote description.
EXPECT_TRUE(session_->ProcessIceMessage(&ice_candidate1));
@@ -1723,7 +1823,7 @@
// Test that local candidates are added to the local session description and
// that they are retained if the local session description is changed.
TEST_F(WebRtcSessionTest, TestLocalCandidatesAddedToSessionDescription) {
- AddInterface(talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
CreateAndSetRemoteOfferAndLocalAnswer();
@@ -1766,7 +1866,7 @@
JsepIceCandidate ice_candidate(kMediaContentName0, kMediaContentIndex0,
candidate1);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
EXPECT_TRUE(offer->AddCandidate(&ice_candidate));
SetRemoteDescriptionWithoutError(offer);
@@ -1787,7 +1887,7 @@
// Test that offers and answers contains ice candidates when Ice candidates have
// been gathered.
TEST_F(WebRtcSessionTest, TestSetLocalAndRemoteDescriptionWithCandidates) {
- AddInterface(talk_base::SocketAddress(kClientAddrHost1, kClientAddrPort));
+ AddInterface(rtc::SocketAddress(kClientAddrHost1, kClientAddrPort));
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
// Ice is started but candidates are not provided until SetLocalDescription
@@ -1801,8 +1901,8 @@
EXPECT_TRUE_WAIT(0u < observer_.mline_1_candidates_.size(),
kIceCandidatesTimeout);
- talk_base::scoped_ptr<SessionDescriptionInterface> local_offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> local_offer(CreateOffer());
+
ASSERT_TRUE(local_offer->candidates(kMediaContentIndex0) != NULL);
EXPECT_LT(0u, local_offer->candidates(kMediaContentIndex0)->count());
ASSERT_TRUE(local_offer->candidates(kMediaContentIndex1) != NULL);
@@ -1823,8 +1923,7 @@
TEST_F(WebRtcSessionTest, TestChannelCreationsWithContentNames) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
// CreateOffer creates session description with the content names "audio" and
// "video". Goal is to modify these content names and verify transport channel
@@ -1838,12 +1937,12 @@
const std::string kVideoMidReplaceStr = "a=mid:video_content_name";
// Replacing |audio| with |audio_content_name|.
- talk_base::replace_substrs(kAudioMid.c_str(), kAudioMid.length(),
+ rtc::replace_substrs(kAudioMid.c_str(), kAudioMid.length(),
kAudioMidReplaceStr.c_str(),
kAudioMidReplaceStr.length(),
&sdp);
// Replacing |video| with |video_content_name|.
- talk_base::replace_substrs(kVideoMid.c_str(), kVideoMid.length(),
+ rtc::replace_substrs(kVideoMid.c_str(), kVideoMid.length(),
kVideoMidReplaceStr.c_str(),
kVideoMidReplaceStr.length(),
&sdp);
@@ -1867,8 +1966,8 @@
// the send streams when no constraints have been set.
TEST_F(WebRtcSessionTest, CreateOfferWithoutConstraintsOrStreams) {
Init(NULL);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
ASSERT_TRUE(offer != NULL);
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(offer->description());
@@ -1883,8 +1982,8 @@
Init(NULL);
// Test Audio only offer.
mediastream_signaling_.UseOptionsAudioOnly();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(offer->description());
EXPECT_TRUE(content != NULL);
@@ -1893,7 +1992,7 @@
// Test Audio / Video offer.
mediastream_signaling_.SendAudioVideoStream1();
- offer.reset(CreateOffer(NULL));
+ offer.reset(CreateOffer());
content = cricket::GetFirstAudioContent(offer->description());
EXPECT_TRUE(content != NULL);
content = cricket::GetFirstVideoContent(offer->description());
@@ -1904,12 +2003,13 @@
// kOfferToReceiveVideo and kOfferToReceiveAudio constraints are set to false.
TEST_F(WebRtcSessionTest, CreateOfferWithConstraintsWithoutStreams) {
Init(NULL);
- webrtc::FakeConstraints constraints_no_receive;
- constraints_no_receive.SetMandatoryReceiveAudio(false);
- constraints_no_receive.SetMandatoryReceiveVideo(false);
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.offer_to_receive_audio = 0;
+ options.offer_to_receive_video = 0;
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(&constraints_no_receive));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(
+ CreateOffer(options));
+
ASSERT_TRUE(offer != NULL);
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(offer->description());
@@ -1922,10 +2022,12 @@
// kOfferToReceiveAudio constraints are set to true.
TEST_F(WebRtcSessionTest, CreateAudioOnlyOfferWithConstraints) {
Init(NULL);
- webrtc::FakeConstraints constraints_audio_only;
- constraints_audio_only.SetMandatoryReceiveAudio(true);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(&constraints_audio_only));
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.offer_to_receive_audio =
+ RTCOfferAnswerOptions::kOfferToReceiveMediaTrue;
+
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(
+ CreateOffer(options));
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(offer->description());
@@ -1939,27 +2041,39 @@
TEST_F(WebRtcSessionTest, CreateOfferWithConstraints) {
Init(NULL);
// Test Audio / Video offer.
- webrtc::FakeConstraints constraints_audio_video;
- constraints_audio_video.SetMandatoryReceiveAudio(true);
- constraints_audio_video.SetMandatoryReceiveVideo(true);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(&constraints_audio_video));
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.offer_to_receive_audio =
+ RTCOfferAnswerOptions::kOfferToReceiveMediaTrue;
+ options.offer_to_receive_video =
+ RTCOfferAnswerOptions::kOfferToReceiveMediaTrue;
+
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(
+ CreateOffer(options));
+
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(offer->description());
-
EXPECT_TRUE(content != NULL);
+
content = cricket::GetFirstVideoContent(offer->description());
EXPECT_TRUE(content != NULL);
- // TODO(perkj): Should the direction be set to SEND_ONLY if
- // The constraints is set to not receive audio or video but a track is added?
+ // Sets constraints to false and verifies that audio/video contents are
+ // removed.
+ options.offer_to_receive_audio = 0;
+ options.offer_to_receive_video = 0;
+ offer.reset(CreateOffer(options));
+
+ content = cricket::GetFirstAudioContent(offer->description());
+ EXPECT_TRUE(content == NULL);
+ content = cricket::GetFirstVideoContent(offer->description());
+ EXPECT_TRUE(content == NULL);
}
// Test that an answer can not be created if the last remote description is not
// an offer.
TEST_F(WebRtcSessionTest, CreateAnswerWithoutAnOffer) {
Init(NULL);
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
SessionDescriptionInterface* answer = CreateRemoteAnswer(offer);
SetRemoteDescriptionWithoutError(answer);
@@ -1971,9 +2085,9 @@
TEST_F(WebRtcSessionTest, CreateAnswerWithoutConstraintsOrStreams) {
Init(NULL);
// Create a remote offer with audio and video content.
- talk_base::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
+ rtc::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
SetRemoteDescriptionWithoutError(offer.release());
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(NULL));
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(answer->description());
@@ -1991,15 +2105,14 @@
Init(NULL);
// Create a remote offer with audio only.
cricket::MediaSessionOptions options;
- options.has_audio = true;
- options.has_video = false;
- talk_base::scoped_ptr<JsepSessionDescription> offer(
+
+ rtc::scoped_ptr<JsepSessionDescription> offer(
CreateRemoteOffer(options));
ASSERT_TRUE(cricket::GetFirstVideoContent(offer->description()) == NULL);
ASSERT_TRUE(cricket::GetFirstAudioContent(offer->description()) != NULL);
SetRemoteDescriptionWithoutError(offer.release());
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(NULL));
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(answer->description());
@@ -2014,11 +2127,11 @@
TEST_F(WebRtcSessionTest, CreateAnswerWithoutConstraints) {
Init(NULL);
// Create a remote offer with audio and video content.
- talk_base::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
+ rtc::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
SetRemoteDescriptionWithoutError(offer.release());
// Test with a stream with tracks.
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(NULL));
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(answer->description());
@@ -2035,14 +2148,14 @@
TEST_F(WebRtcSessionTest, CreateAnswerWithConstraintsWithoutStreams) {
Init(NULL);
// Create a remote offer with audio and video content.
- talk_base::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
+ rtc::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
SetRemoteDescriptionWithoutError(offer.release());
webrtc::FakeConstraints constraints_no_receive;
constraints_no_receive.SetMandatoryReceiveAudio(false);
constraints_no_receive.SetMandatoryReceiveVideo(false);
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(&constraints_no_receive));
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(answer->description());
@@ -2059,7 +2172,7 @@
TEST_F(WebRtcSessionTest, CreateAnswerWithConstraints) {
Init(NULL);
// Create a remote offer with audio and video content.
- talk_base::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
+ rtc::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
SetRemoteDescriptionWithoutError(offer.release());
webrtc::FakeConstraints constraints_no_receive;
@@ -2068,7 +2181,7 @@
// Test with a stream with tracks.
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(&constraints_no_receive));
// TODO(perkj): Should the direction be set to SEND_ONLY?
@@ -2086,10 +2199,14 @@
TEST_F(WebRtcSessionTest, CreateOfferWithoutCNCodecs) {
AddCNCodecs();
Init(NULL);
- webrtc::FakeConstraints constraints;
- constraints.SetOptionalVAD(false);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(&constraints));
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.offer_to_receive_audio =
+ RTCOfferAnswerOptions::kOfferToReceiveMediaTrue;
+ options.voice_activity_detection = false;
+
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(
+ CreateOffer(options));
+
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(offer->description());
EXPECT_TRUE(content != NULL);
@@ -2100,12 +2217,12 @@
AddCNCodecs();
Init(NULL);
// Create a remote offer with audio and video content.
- talk_base::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
+ rtc::scoped_ptr<JsepSessionDescription> offer(CreateRemoteOffer());
SetRemoteDescriptionWithoutError(offer.release());
webrtc::FakeConstraints constraints;
constraints.SetOptionalVAD(false);
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(&constraints));
const cricket::ContentInfo* content =
cricket::GetFirstAudioContent(answer->description());
@@ -2121,10 +2238,9 @@
EXPECT_TRUE(media_engine_->GetVoiceChannel(0) == NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
cricket::MediaSessionOptions options;
- options.has_video = false;
SessionDescriptionInterface* answer = CreateRemoteAnswer(offer, options);
// SetLocalDescription and SetRemoteDescriptions takes ownership of offer
@@ -2178,7 +2294,7 @@
EXPECT_TRUE(media_engine_->GetVideoChannel(0) == NULL);
EXPECT_TRUE(media_engine_->GetVoiceChannel(0) == NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
cricket::MediaSessionOptions options;
options.has_audio = false;
@@ -2229,8 +2345,7 @@
TEST_F(WebRtcSessionTest, VerifyCryptoParamsInSDP) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
VerifyCryptoParams(offer->description());
SetRemoteDescriptionWithoutError(offer.release());
scoped_ptr<SessionDescriptionInterface> answer(CreateAnswer(NULL));
@@ -2241,8 +2356,7 @@
options_.disable_encryption = true;
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
VerifyNoCryptoParams(offer->description(), false);
}
@@ -2261,7 +2375,8 @@
TEST_F(WebRtcSessionTest, TestSetLocalDescriptionWithoutIce) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
std::string sdp;
RemoveIceUfragPwdLines(offer.get(), &sdp);
SessionDescriptionInterface* modified_offer =
@@ -2273,7 +2388,7 @@
// no a=ice-ufrag and a=ice-pwd lines are present in the SDP.
TEST_F(WebRtcSessionTest, TestSetRemoteDescriptionWithoutIce) {
Init(NULL);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateRemoteOffer());
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateRemoteOffer());
std::string sdp;
RemoveIceUfragPwdLines(offer.get(), &sdp);
SessionDescriptionInterface* modified_offer =
@@ -2287,7 +2402,8 @@
Init(NULL);
tdesc_factory_->set_protocol(cricket::ICEPROTO_RFC5245);
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
std::string sdp;
// Modifying ice ufrag and pwd in local offer with strings smaller than the
// recommended values of 4 and 22 bytes respectively.
@@ -2311,7 +2427,7 @@
TEST_F(WebRtcSessionTest, TestSetRemoteDescriptionInvalidIceCredentials) {
Init(NULL);
tdesc_factory_->set_protocol(cricket::ICEPROTO_RFC5245);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateRemoteOffer());
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateRemoteOffer());
std::string sdp;
// Modifying ice ufrag and pwd in remote offer with strings smaller than the
// recommended values of 4 and 22 bytes respectively.
@@ -2336,8 +2452,8 @@
Init(NULL);
EXPECT_TRUE((cricket::PORTALLOCATOR_ENABLE_BUNDLE &
allocator_->flags()) == cricket::PORTALLOCATOR_ENABLE_BUNDLE);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
cricket::SessionDescription* offer_copy =
offer->description()->Copy();
offer_copy->RemoveGroupByName(cricket::GROUP_TYPE_BUNDLE);
@@ -2354,12 +2470,15 @@
mediastream_signaling_.SendAudioVideoStream1();
EXPECT_TRUE((cricket::PORTALLOCATOR_ENABLE_BUNDLE &
allocator_->flags()) == cricket::PORTALLOCATOR_ENABLE_BUNDLE);
- FakeConstraints constraints;
- constraints.SetMandatoryUseRtpMux(true);
- SessionDescriptionInterface* offer = CreateOffer(&constraints);
+
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.use_rtp_mux = true;
+
+ SessionDescriptionInterface* offer = CreateOffer(options);
+
SetLocalDescriptionWithoutError(offer);
mediastream_signaling_.SendAudioVideoStream2();
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateRemoteAnswer(session_->local_description()));
cricket::SessionDescription* answer_copy = answer->description()->Copy();
answer_copy->RemoveGroupByName(cricket::GROUP_TYPE_BUNDLE);
@@ -2392,15 +2511,17 @@
mediastream_signaling_.SendAudioVideoStream1();
EXPECT_TRUE((cricket::PORTALLOCATOR_ENABLE_BUNDLE &
allocator_->flags()) == cricket::PORTALLOCATOR_ENABLE_BUNDLE);
- FakeConstraints constraints;
- constraints.SetMandatoryUseRtpMux(true);
- SessionDescriptionInterface* offer = CreateOffer(&constraints);
+
+ PeerConnectionInterface::RTCOfferAnswerOptions options;
+ options.use_rtp_mux = true;
+
+ SessionDescriptionInterface* offer = CreateOffer(options);
std::string offer_str;
offer->ToString(&offer_str);
// Disable rtcp-mux
const std::string rtcp_mux = "rtcp-mux";
const std::string xrtcp_mux = "xrtcp-mux";
- talk_base::replace_substrs(rtcp_mux.c_str(), rtcp_mux.length(),
+ rtc::replace_substrs(rtcp_mux.c_str(), rtcp_mux.length(),
xrtcp_mux.c_str(), xrtcp_mux.length(),
&offer_str);
JsepSessionDescription *local_offer =
@@ -2427,7 +2548,7 @@
EXPECT_TRUE(channel->GetOutputScaling(receive_ssrc, &left_vol, &right_vol));
EXPECT_EQ(1, left_vol);
EXPECT_EQ(1, right_vol);
- talk_base::scoped_ptr<FakeAudioRenderer> renderer(new FakeAudioRenderer());
+ rtc::scoped_ptr<FakeAudioRenderer> renderer(new FakeAudioRenderer());
session_->SetAudioPlayout(receive_ssrc, false, renderer.get());
EXPECT_TRUE(channel->GetOutputScaling(receive_ssrc, &left_vol, &right_vol));
EXPECT_EQ(0, left_vol);
@@ -2453,7 +2574,7 @@
cricket::AudioOptions options;
options.echo_cancellation.Set(true);
- talk_base::scoped_ptr<FakeAudioRenderer> renderer(new FakeAudioRenderer());
+ rtc::scoped_ptr<FakeAudioRenderer> renderer(new FakeAudioRenderer());
session_->SetAudioSend(send_ssrc, false, options, renderer.get());
EXPECT_TRUE(channel->IsStreamMuted(send_ssrc));
EXPECT_FALSE(channel->options().echo_cancellation.IsSet());
@@ -2479,7 +2600,7 @@
ASSERT_EQ(1u, channel->send_streams().size());
uint32 send_ssrc = channel->send_streams()[0].first_ssrc();
- talk_base::scoped_ptr<FakeAudioRenderer> renderer(new FakeAudioRenderer());
+ rtc::scoped_ptr<FakeAudioRenderer> renderer(new FakeAudioRenderer());
cricket::AudioOptions options;
session_->SetAudioSend(send_ssrc, true, options, renderer.get());
EXPECT_TRUE(renderer->sink() != NULL);
@@ -2564,7 +2685,7 @@
TEST_F(WebRtcSessionTest, TestInitiatorFlagAsOriginator) {
Init(NULL);
EXPECT_FALSE(session_->initiator());
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SessionDescriptionInterface* answer = CreateRemoteAnswer(offer);
SetLocalDescriptionWithoutError(offer);
EXPECT_TRUE(session_->initiator());
@@ -2590,8 +2711,8 @@
TEST_F(WebRtcSessionTest, TestInitiatorGIceInAnswer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ SessionDescriptionInterface* offer = CreateOffer();
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateRemoteAnswer(offer));
SetLocalDescriptionWithoutError(offer);
std::string sdp;
@@ -2612,7 +2733,7 @@
TEST_F(WebRtcSessionTest, TestInitiatorIceInAnswer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SessionDescriptionInterface* answer = CreateRemoteAnswer(offer);
SetLocalDescriptionWithoutError(offer);
@@ -2626,9 +2747,9 @@
TEST_F(WebRtcSessionTest, TestReceiverGIceInOffer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetRemoteDescriptionWithoutError(offer);
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(NULL));
std::string sdp;
EXPECT_TRUE(answer->ToString(&sdp));
@@ -2648,7 +2769,7 @@
TEST_F(WebRtcSessionTest, TestReceiverIceInOffer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetRemoteDescriptionWithoutError(offer);
SessionDescriptionInterface* answer = CreateAnswer(NULL);
SetLocalDescriptionWithoutError(answer);
@@ -2661,14 +2782,14 @@
TEST_F(WebRtcSessionTest, TestIceOfferGIceOnlyAnswer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
std::string offer_str;
offer->ToString(&offer_str);
// Disable google-ice
const std::string gice_option = "google-ice";
const std::string xgoogle_xice = "xgoogle-xice";
- talk_base::replace_substrs(gice_option.c_str(), gice_option.length(),
+ rtc::replace_substrs(gice_option.c_str(), gice_option.length(),
xgoogle_xice.c_str(), xgoogle_xice.length(),
&offer_str);
JsepSessionDescription *ice_only_offer =
@@ -2693,9 +2814,9 @@
TEST_F(WebRtcSessionTest, TestIncorrectMLinesInRemoteAnswer) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateRemoteAnswer(session_->local_description()));
cricket::SessionDescription* answer_copy = answer->description()->Copy();
@@ -2713,7 +2834,7 @@
EXPECT_TRUE(answer->ToString(&sdp));
const std::string kAudioMid = "a=mid:audio";
const std::string kAudioMidReplaceStr = "a=mid:audio_content_name";
- talk_base::replace_substrs(kAudioMid.c_str(), kAudioMid.length(),
+ rtc::replace_substrs(kAudioMid.c_str(), kAudioMid.length(),
kAudioMidReplaceStr.c_str(),
kAudioMidReplaceStr.length(),
&sdp);
@@ -2725,7 +2846,7 @@
EXPECT_TRUE(answer->ToString(&sdp));
const std::string kAudioMline = "m=audio";
const std::string kAudioMlineReplaceStr = "m=video";
- talk_base::replace_substrs(kAudioMline.c_str(), kAudioMline.length(),
+ rtc::replace_substrs(kAudioMline.c_str(), kAudioMline.length(),
kAudioMlineReplaceStr.c_str(),
kAudioMlineReplaceStr.length(),
&sdp);
@@ -2778,7 +2899,7 @@
ASSERT_TRUE(session_->GetTransportProxy("video") != NULL);
// Pump for 1 second and verify that no candidates are generated.
- talk_base::Thread::Current()->ProcessMessages(1000);
+ rtc::Thread::Current()->ProcessMessages(1000);
EXPECT_TRUE(observer_.mline_0_candidates_.empty());
EXPECT_TRUE(observer_.mline_1_candidates_.empty());
@@ -2794,8 +2915,7 @@
TEST_F(WebRtcSessionTest, TestCryptoAfterSetLocalDescription) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
// Making sure SetLocalDescription correctly sets crypto value in
// SessionDescription object after de-serialization of sdp string. The value
@@ -2814,8 +2934,7 @@
options_.disable_encryption = true;
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(
- CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
// Making sure SetLocalDescription correctly sets crypto value in
// SessionDescription object after de-serialization of sdp string. The value
@@ -2834,24 +2953,23 @@
TEST_F(WebRtcSessionTest, TestCreateAnswerWithNewUfragAndPassword) {
Init(NULL);
cricket::MediaSessionOptions options;
- options.has_audio = true;
options.has_video = true;
- talk_base::scoped_ptr<JsepSessionDescription> offer(
+ rtc::scoped_ptr<JsepSessionDescription> offer(
CreateRemoteOffer(options));
SetRemoteDescriptionWithoutError(offer.release());
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(NULL));
SetLocalDescriptionWithoutError(answer.release());
// Receive an offer with new ufrag and password.
options.transport_options.ice_restart = true;
- talk_base::scoped_ptr<JsepSessionDescription> updated_offer1(
+ rtc::scoped_ptr<JsepSessionDescription> updated_offer1(
CreateRemoteOffer(options, session_->remote_description()));
SetRemoteDescriptionWithoutError(updated_offer1.release());
- talk_base::scoped_ptr<SessionDescriptionInterface> updated_answer1(
+ rtc::scoped_ptr<SessionDescriptionInterface> updated_answer1(
CreateAnswer(NULL));
CompareIceUfragAndPassword(updated_answer1->description(),
@@ -2866,24 +2984,23 @@
TEST_F(WebRtcSessionTest, TestCreateAnswerWithOldUfragAndPassword) {
Init(NULL);
cricket::MediaSessionOptions options;
- options.has_audio = true;
options.has_video = true;
- talk_base::scoped_ptr<JsepSessionDescription> offer(
+ rtc::scoped_ptr<JsepSessionDescription> offer(
CreateRemoteOffer(options));
SetRemoteDescriptionWithoutError(offer.release());
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(
CreateAnswer(NULL));
SetLocalDescriptionWithoutError(answer.release());
// Receive an offer without changed ufrag or password.
options.transport_options.ice_restart = false;
- talk_base::scoped_ptr<JsepSessionDescription> updated_offer2(
+ rtc::scoped_ptr<JsepSessionDescription> updated_offer2(
CreateRemoteOffer(options, session_->remote_description()));
SetRemoteDescriptionWithoutError(updated_offer2.release());
- talk_base::scoped_ptr<SessionDescriptionInterface> updated_answer2(
+ rtc::scoped_ptr<SessionDescriptionInterface> updated_answer2(
CreateAnswer(NULL));
CompareIceUfragAndPassword(updated_answer2->description(),
@@ -2896,7 +3013,7 @@
TEST_F(WebRtcSessionTest, TestSessionContentError) {
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
const std::string session_id_orig = offer->session_id();
const std::string session_version_orig = offer->session_version();
SetLocalDescriptionWithoutError(offer);
@@ -2932,7 +3049,6 @@
TEST_F(WebRtcSessionTest, SetSdpFailedOnSessionError) {
Init(NULL);
cricket::MediaSessionOptions options;
- options.has_audio = true;
options.has_video = true;
cricket::BaseSession::Error error_code = cricket::BaseSession::ERROR_CONTENT;
@@ -2963,7 +3079,7 @@
}
TEST_F(WebRtcSessionTest, TestRtpDataChannelConstraintTakesPrecedence) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
constraints_.reset(new FakeConstraints());
constraints_->AddOptional(
@@ -2977,17 +3093,17 @@
}
TEST_F(WebRtcSessionTest, TestCreateOfferWithSctpEnabledWithoutStreams) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
EXPECT_TRUE(offer->description()->GetContentByName("data") == NULL);
EXPECT_TRUE(offer->description()->GetTransportInfoByName("data") == NULL);
}
TEST_F(WebRtcSessionTest, TestCreateAnswerWithSctpInOfferAndNoStreams) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
SetFactoryDtlsSrtp();
InitWithDtls();
@@ -2999,7 +3115,7 @@
SetRemoteDescriptionWithoutError(offer);
// Verifies the answer contains SCTP.
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(CreateAnswer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(CreateAnswer(NULL));
EXPECT_TRUE(answer != NULL);
EXPECT_TRUE(answer->description()->GetContentByName("data") != NULL);
EXPECT_TRUE(answer->description()->GetTransportInfoByName("data") != NULL);
@@ -3016,7 +3132,7 @@
}
TEST_F(WebRtcSessionTest, TestSctpDataChannelWithDtls) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
@@ -3025,7 +3141,7 @@
}
TEST_F(WebRtcSessionTest, TestDisableSctpDataChannels) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
options_.disable_sctp_data_channels = true;
InitWithDtls();
@@ -3034,7 +3150,7 @@
}
TEST_F(WebRtcSessionTest, TestSctpDataChannelSendPortParsing) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
const int new_send_port = 9998;
const int new_recv_port = 7775;
@@ -3064,7 +3180,7 @@
webrtc::InternalDataChannelInit dci;
dci.reliable = true;
EXPECT_EQ(cricket::DCT_SCTP, data_engine_->last_channel_type());
- talk_base::scoped_refptr<webrtc::DataChannel> dc =
+ rtc::scoped_refptr<webrtc::DataChannel> dc =
session_->CreateDataChannel("datachannel", &dci);
cricket::FakeDataMediaChannel* ch = data_engine_->GetChannel(0);
@@ -3090,12 +3206,13 @@
// Verifies that CreateOffer succeeds when CreateOffer is called before async
// identity generation is finished.
TEST_F(WebRtcSessionTest, TestCreateOfferBeforeIdentityRequestReturnSuccess) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
EXPECT_TRUE(session_->waiting_for_identity());
mediastream_signaling_.SendAudioVideoStream1();
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
+
EXPECT_TRUE(offer != NULL);
VerifyNoCryptoParams(offer->description(), true);
VerifyFingerprintStatus(offer->description(), true);
@@ -3104,7 +3221,7 @@
// Verifies that CreateAnswer succeeds when CreateOffer is called before async
// identity generation is finished.
TEST_F(WebRtcSessionTest, TestCreateAnswerBeforeIdentityRequestReturnSuccess) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
SetFactoryDtlsSrtp();
@@ -3115,7 +3232,7 @@
ASSERT_TRUE(offer.get() != NULL);
SetRemoteDescriptionWithoutError(offer.release());
- talk_base::scoped_ptr<SessionDescriptionInterface> answer(CreateAnswer(NULL));
+ rtc::scoped_ptr<SessionDescriptionInterface> answer(CreateAnswer(NULL));
EXPECT_TRUE(answer != NULL);
VerifyNoCryptoParams(answer->description(), true);
VerifyFingerprintStatus(answer->description(), true);
@@ -3124,22 +3241,24 @@
// Verifies that CreateOffer succeeds when CreateOffer is called after async
// identity generation is finished.
TEST_F(WebRtcSessionTest, TestCreateOfferAfterIdentityRequestReturnSuccess) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls();
EXPECT_TRUE_WAIT(!session_->waiting_for_identity(), 1000);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer(NULL));
+
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
EXPECT_TRUE(offer != NULL);
}
// Verifies that CreateOffer fails when CreateOffer is called after async
// identity generation fails.
TEST_F(WebRtcSessionTest, TestCreateOfferAfterIdentityRequestReturnFailure) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
InitWithDtls(true);
EXPECT_TRUE_WAIT(!session_->waiting_for_identity(), 1000);
- talk_base::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer(NULL));
+
+ rtc::scoped_ptr<SessionDescriptionInterface> offer(CreateOffer());
EXPECT_TRUE(offer == NULL);
}
@@ -3147,7 +3266,7 @@
// before async identity generation is finished.
TEST_F(WebRtcSessionTest,
TestMultipleCreateOfferBeforeIdentityRequestReturnSuccess) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
VerifyMultipleAsyncCreateDescription(
true, CreateSessionDescriptionRequest::kOffer);
}
@@ -3156,7 +3275,7 @@
// before async identity generation fails.
TEST_F(WebRtcSessionTest,
TestMultipleCreateOfferBeforeIdentityRequestReturnFailure) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
VerifyMultipleAsyncCreateDescription(
false, CreateSessionDescriptionRequest::kOffer);
}
@@ -3165,7 +3284,7 @@
// before async identity generation is finished.
TEST_F(WebRtcSessionTest,
TestMultipleCreateAnswerBeforeIdentityRequestReturnSuccess) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
VerifyMultipleAsyncCreateDescription(
true, CreateSessionDescriptionRequest::kAnswer);
}
@@ -3174,7 +3293,7 @@
// before async identity generation fails.
TEST_F(WebRtcSessionTest,
TestMultipleCreateAnswerBeforeIdentityRequestReturnFailure) {
- MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
VerifyMultipleAsyncCreateDescription(
false, CreateSessionDescriptionRequest::kAnswer);
}
@@ -3194,8 +3313,8 @@
ASSERT_TRUE(audio != NULL);
ASSERT_TRUE(audio->description.identity_fingerprint.get() == NULL);
audio->description.identity_fingerprint.reset(
- talk_base::SSLFingerprint::CreateFromRfc4572(
- talk_base::DIGEST_SHA_256, kFakeDtlsFingerprint));
+ rtc::SSLFingerprint::CreateFromRfc4572(
+ rtc::DIGEST_SHA_256, kFakeDtlsFingerprint));
SetRemoteDescriptionOfferExpectError(kSdpWithoutSdesCrypto,
offer);
}
@@ -3207,7 +3326,7 @@
webrtc::MediaConstraintsInterface::kEnableDscp, true);
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
@@ -3233,7 +3352,7 @@
true);
Init(NULL);
mediastream_signaling_.SendAudioVideoStream1();
- SessionDescriptionInterface* offer = CreateOffer(NULL);
+ SessionDescriptionInterface* offer = CreateOffer();
SetLocalDescriptionWithoutError(offer);
@@ -3246,6 +3365,95 @@
video_options.suspend_below_min_bitrate.GetWithDefaultIfUnset(false));
}
+TEST_F(WebRtcSessionTest, TestNumUnsignalledRecvStreamsConstraint) {
+ // Number of unsignalled receiving streams should be between 0 and
+ // kMaxUnsignalledRecvStreams.
+ SetAndVerifyNumUnsignalledRecvStreams(10, 10);
+ SetAndVerifyNumUnsignalledRecvStreams(kMaxUnsignalledRecvStreams + 1,
+ kMaxUnsignalledRecvStreams);
+ SetAndVerifyNumUnsignalledRecvStreams(-1, 0);
+}
+
+TEST_F(WebRtcSessionTest, TestCombinedAudioVideoBweConstraint) {
+ constraints_.reset(new FakeConstraints());
+ constraints_->AddOptional(
+ webrtc::MediaConstraintsInterface::kCombinedAudioVideoBwe,
+ true);
+ Init(NULL);
+ mediastream_signaling_.SendAudioVideoStream1();
+ SessionDescriptionInterface* offer = CreateOffer();
+
+ SetLocalDescriptionWithoutError(offer);
+
+ voice_channel_ = media_engine_->GetVoiceChannel(0);
+
+ ASSERT_TRUE(voice_channel_ != NULL);
+ cricket::AudioOptions audio_options;
+ EXPECT_TRUE(voice_channel_->GetOptions(&audio_options));
+ EXPECT_TRUE(
+ audio_options.combined_audio_video_bwe.GetWithDefaultIfUnset(false));
+}
+
+// Tests that we can renegotiate new media content with ICE candidates in the
+// new remote SDP.
+TEST_F(WebRtcSessionTest, TestRenegotiateNewMediaWithCandidatesInSdp) {
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
+ InitWithDtls();
+ SetFactoryDtlsSrtp();
+
+ mediastream_signaling_.UseOptionsAudioOnly();
+ SessionDescriptionInterface* offer = CreateOffer();
+ SetLocalDescriptionWithoutError(offer);
+
+ SessionDescriptionInterface* answer = CreateRemoteAnswer(offer);
+ SetRemoteDescriptionWithoutError(answer);
+
+ cricket::MediaSessionOptions options;
+ options.has_video = true;
+ offer = CreateRemoteOffer(options, cricket::SEC_DISABLED);
+
+ cricket::Candidate candidate1;
+ candidate1.set_address(rtc::SocketAddress("1.1.1.1", 5000));
+ candidate1.set_component(1);
+ JsepIceCandidate ice_candidate(kMediaContentName1, kMediaContentIndex1,
+ candidate1);
+ EXPECT_TRUE(offer->AddCandidate(&ice_candidate));
+ SetRemoteDescriptionWithoutError(offer);
+
+ answer = CreateAnswer(NULL);
+ SetLocalDescriptionWithoutError(answer);
+}
+
+// Tests that we can renegotiate new media content with ICE candidates separated
+// from the remote SDP.
+TEST_F(WebRtcSessionTest, TestRenegotiateNewMediaWithCandidatesSeparated) {
+ MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
+ InitWithDtls();
+ SetFactoryDtlsSrtp();
+
+ mediastream_signaling_.UseOptionsAudioOnly();
+ SessionDescriptionInterface* offer = CreateOffer();
+ SetLocalDescriptionWithoutError(offer);
+
+ SessionDescriptionInterface* answer = CreateRemoteAnswer(offer);
+ SetRemoteDescriptionWithoutError(answer);
+
+ cricket::MediaSessionOptions options;
+ options.has_video = true;
+ offer = CreateRemoteOffer(options, cricket::SEC_DISABLED);
+ SetRemoteDescriptionWithoutError(offer);
+
+ cricket::Candidate candidate1;
+ candidate1.set_address(rtc::SocketAddress("1.1.1.1", 5000));
+ candidate1.set_component(1);
+ JsepIceCandidate ice_candidate(kMediaContentName1, kMediaContentIndex1,
+ candidate1);
+ EXPECT_TRUE(session_->ProcessIceMessage(&ice_candidate));
+
+ answer = CreateAnswer(NULL);
+ SetLocalDescriptionWithoutError(answer);
+}
+
// TODO(bemasc): Add a TestIceStatesBundle with BUNDLE enabled. That test
// currently fails because upon disconnection and reconnection OnIceComplete is
// called more than once without returning to IceGatheringGathering.
diff --git a/app/webrtc/webrtcsessiondescriptionfactory.cc b/app/webrtc/webrtcsessiondescriptionfactory.cc
index 25d8fc9..7930330 100644
--- a/app/webrtc/webrtcsessiondescriptionfactory.cc
+++ b/app/webrtc/webrtcsessiondescriptionfactory.cc
@@ -72,15 +72,15 @@
MSG_GENERATE_IDENTITY,
};
-struct CreateSessionDescriptionMsg : public talk_base::MessageData {
+struct CreateSessionDescriptionMsg : public rtc::MessageData {
explicit CreateSessionDescriptionMsg(
webrtc::CreateSessionDescriptionObserver* observer)
: observer(observer) {
}
- talk_base::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
+ rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
std::string error;
- talk_base::scoped_ptr<webrtc::SessionDescriptionInterface> description;
+ rtc::scoped_ptr<webrtc::SessionDescriptionInterface> description;
};
} // namespace
@@ -104,7 +104,7 @@
}
WebRtcSessionDescriptionFactory::WebRtcSessionDescriptionFactory(
- talk_base::Thread* signaling_thread,
+ rtc::Thread* signaling_thread,
cricket::ChannelManager* channel_manager,
MediaStreamSignaling* mediastream_signaling,
DTLSIdentityServiceInterface* dtls_identity_service,
@@ -136,7 +136,7 @@
if (identity_service_.get()) {
identity_request_observer_ =
- new talk_base::RefCountedObject<WebRtcIdentityRequestObserver>();
+ new rtc::RefCountedObject<WebRtcIdentityRequestObserver>();
identity_request_observer_->SignalRequestFailed.connect(
this, &WebRtcSessionDescriptionFactory::OnIdentityRequestFailed);
@@ -166,8 +166,9 @@
void WebRtcSessionDescriptionFactory::CreateOffer(
CreateSessionDescriptionObserver* observer,
- const MediaConstraintsInterface* constraints) {
- cricket::MediaSessionOptions options;
+ const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
+ cricket::MediaSessionOptions session_options;
+
std::string error = "CreateOffer";
if (identity_request_state_ == IDENTITY_FAILED) {
error += kFailedDueToIdentityFailed;
@@ -176,14 +177,15 @@
return;
}
- if (!mediastream_signaling_->GetOptionsForOffer(constraints, &options)) {
- error += " called with invalid constraints.";
+ if (!mediastream_signaling_->GetOptionsForOffer(options,
+ &session_options)) {
+ error += " called with invalid options.";
LOG(LS_ERROR) << error;
PostCreateSessionDescriptionFailed(observer, error);
return;
}
- if (!ValidStreams(options.streams)) {
+ if (!ValidStreams(session_options.streams)) {
error += " called with invalid media streams.";
LOG(LS_ERROR) << error;
PostCreateSessionDescriptionFailed(observer, error);
@@ -192,11 +194,11 @@
if (data_channel_type_ == cricket::DCT_SCTP &&
mediastream_signaling_->HasDataChannels()) {
- options.data_channel_type = cricket::DCT_SCTP;
+ session_options.data_channel_type = cricket::DCT_SCTP;
}
CreateSessionDescriptionRequest request(
- CreateSessionDescriptionRequest::kOffer, observer, options);
+ CreateSessionDescriptionRequest::kOffer, observer, session_options);
if (identity_request_state_ == IDENTITY_WAITING) {
create_session_description_requests_.push(request);
} else {
@@ -270,7 +272,7 @@
return session_desc_factory_.secure();
}
-void WebRtcSessionDescriptionFactory::OnMessage(talk_base::Message* msg) {
+void WebRtcSessionDescriptionFactory::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_CREATE_SESSIONDESCRIPTION_SUCCESS: {
CreateSessionDescriptionMsg* param =
@@ -288,7 +290,7 @@
}
case MSG_GENERATE_IDENTITY: {
LOG(LS_INFO) << "Generating identity.";
- SetIdentity(talk_base::SSLIdentity::Generate(kWebRTCIdentityName));
+ SetIdentity(rtc::SSLIdentity::Generate(kWebRTCIdentityName));
break;
}
default:
@@ -316,7 +318,7 @@
JsepSessionDescription* offer(new JsepSessionDescription(
JsepSessionDescription::kOffer));
if (!offer->Initialize(desc, session_id_,
- talk_base::ToString(session_version_++))) {
+ rtc::ToString(session_version_++))) {
delete offer;
PostCreateSessionDescriptionFailed(request.observer,
"Failed to initialize the offer.");
@@ -339,10 +341,10 @@
request.options.transport_options.ice_restart = session_->IceRestartPending();
// We should pass current ssl role to the transport description factory, if
// there is already an existing ongoing session.
- talk_base::SSLRole ssl_role;
+ rtc::SSLRole ssl_role;
if (session_->GetSslRole(&ssl_role)) {
request.options.transport_options.prefer_passive_role =
- (talk_base::SSL_SERVER == ssl_role);
+ (rtc::SSL_SERVER == ssl_role);
}
cricket::SessionDescription* desc(session_desc_factory_.CreateAnswer(
@@ -360,7 +362,7 @@
JsepSessionDescription* answer(new JsepSessionDescription(
JsepSessionDescription::kAnswer));
if (!answer->Initialize(desc, session_id_,
- talk_base::ToString(session_version_++))) {
+ rtc::ToString(session_version_++))) {
delete answer;
PostCreateSessionDescriptionFailed(request.observer,
"Failed to initialize the answer.");
@@ -416,22 +418,22 @@
ASSERT(signaling_thread_->IsCurrent());
LOG(LS_VERBOSE) << "Identity is successfully generated.";
- std::string pem_cert = talk_base::SSLIdentity::DerToPem(
- talk_base::kPemTypeCertificate,
+ std::string pem_cert = rtc::SSLIdentity::DerToPem(
+ rtc::kPemTypeCertificate,
reinterpret_cast<const unsigned char*>(der_cert.data()),
der_cert.length());
- std::string pem_key = talk_base::SSLIdentity::DerToPem(
- talk_base::kPemTypeRsaPrivateKey,
+ std::string pem_key = rtc::SSLIdentity::DerToPem(
+ rtc::kPemTypeRsaPrivateKey,
reinterpret_cast<const unsigned char*>(der_private_key.data()),
der_private_key.length());
- talk_base::SSLIdentity* identity =
- talk_base::SSLIdentity::FromPEMStrings(pem_key, pem_cert);
+ rtc::SSLIdentity* identity =
+ rtc::SSLIdentity::FromPEMStrings(pem_key, pem_cert);
SetIdentity(identity);
}
void WebRtcSessionDescriptionFactory::SetIdentity(
- talk_base::SSLIdentity* identity) {
+ rtc::SSLIdentity* identity) {
identity_request_state_ = IDENTITY_SUCCEEDED;
SignalIdentityReady(identity);
diff --git a/app/webrtc/webrtcsessiondescriptionfactory.h b/app/webrtc/webrtcsessiondescriptionfactory.h
index cad0c65..b870856 100644
--- a/app/webrtc/webrtcsessiondescriptionfactory.h
+++ b/app/webrtc/webrtcsessiondescriptionfactory.h
@@ -29,9 +29,9 @@
#define TALK_APP_WEBRTC_WEBRTCSESSIONDESCRIPTIONFACTORY_H_
#include "talk/app/webrtc/peerconnectioninterface.h"
-#include "talk/base/messagehandler.h"
#include "talk/p2p/base/transportdescriptionfactory.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/messagehandler.h"
namespace cricket {
class ChannelManager;
@@ -77,7 +77,7 @@
options(options) {}
Type type;
- talk_base::scoped_refptr<CreateSessionDescriptionObserver> observer;
+ rtc::scoped_refptr<CreateSessionDescriptionObserver> observer;
cricket::MediaSessionOptions options;
};
@@ -86,11 +86,11 @@
// It queues the create offer/answer request until the DTLS identity
// request has completed, i.e. when OnIdentityRequestFailed or OnIdentityReady
// is called.
-class WebRtcSessionDescriptionFactory : public talk_base::MessageHandler,
+class WebRtcSessionDescriptionFactory : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
WebRtcSessionDescriptionFactory(
- talk_base::Thread* signaling_thread,
+ rtc::Thread* signaling_thread,
cricket::ChannelManager* channel_manager,
MediaStreamSignaling* mediastream_signaling,
DTLSIdentityServiceInterface* dtls_identity_service,
@@ -107,7 +107,7 @@
void CreateOffer(
CreateSessionDescriptionObserver* observer,
- const MediaConstraintsInterface* constraints);
+ const PeerConnectionInterface::RTCOfferAnswerOptions& options);
void CreateAnswer(
CreateSessionDescriptionObserver* observer,
const MediaConstraintsInterface* constraints);
@@ -115,7 +115,7 @@
void SetSdesPolicy(cricket::SecurePolicy secure_policy);
cricket::SecurePolicy SdesPolicy() const;
- sigslot::signal1<talk_base::SSLIdentity*> SignalIdentityReady;
+ sigslot::signal1<rtc::SSLIdentity*> SignalIdentityReady;
// For testing.
bool waiting_for_identity() const {
@@ -131,7 +131,7 @@
};
// MessageHandler implementation.
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
void InternalCreateOffer(CreateSessionDescriptionRequest request);
void InternalCreateAnswer(CreateSessionDescriptionRequest request);
@@ -145,17 +145,17 @@
void OnIdentityRequestFailed(int error);
void OnIdentityReady(const std::string& der_cert,
const std::string& der_private_key);
- void SetIdentity(talk_base::SSLIdentity* identity);
+ void SetIdentity(rtc::SSLIdentity* identity);
std::queue<CreateSessionDescriptionRequest>
create_session_description_requests_;
- talk_base::Thread* signaling_thread_;
+ rtc::Thread* signaling_thread_;
MediaStreamSignaling* mediastream_signaling_;
cricket::TransportDescriptionFactory transport_desc_factory_;
cricket::MediaSessionDescriptionFactory session_desc_factory_;
uint64 session_version_;
- talk_base::scoped_ptr<DTLSIdentityServiceInterface> identity_service_;
- talk_base::scoped_refptr<WebRtcIdentityRequestObserver>
+ rtc::scoped_ptr<DTLSIdentityServiceInterface> identity_service_;
+ rtc::scoped_refptr<WebRtcIdentityRequestObserver>
identity_request_observer_;
WebRtcSession* session_;
std::string session_id_;
diff --git a/base/asyncfile.cc b/base/asyncfile.cc
deleted file mode 100644
index 5c6e11d..0000000
--- a/base/asyncfile.cc
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/asyncfile.h"
-
-namespace talk_base {
-
-AsyncFile::AsyncFile() {
-}
-
-AsyncFile::~AsyncFile() {
-}
-
-} // namespace talk_base
diff --git a/base/asyncfile.h b/base/asyncfile.h
deleted file mode 100644
index 8af52be..0000000
--- a/base/asyncfile.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCFILE_H__
-#define TALK_BASE_ASYNCFILE_H__
-
-#include "talk/base/sigslot.h"
-
-namespace talk_base {
-
-// Provides the ability to perform file I/O asynchronously.
-// TODO: Create a common base class with AsyncSocket.
-class AsyncFile {
- public:
- AsyncFile();
- virtual ~AsyncFile();
-
- // Determines whether the file will receive read events.
- virtual bool readable() = 0;
- virtual void set_readable(bool value) = 0;
-
- // Determines whether the file will receive write events.
- virtual bool writable() = 0;
- virtual void set_writable(bool value) = 0;
-
- sigslot::signal1<AsyncFile*> SignalReadEvent;
- sigslot::signal1<AsyncFile*> SignalWriteEvent;
- sigslot::signal2<AsyncFile*, int> SignalCloseEvent;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ASYNCFILE_H__
diff --git a/base/asynchttprequest.cc b/base/asynchttprequest.cc
deleted file mode 100644
index 68f6100..0000000
--- a/base/asynchttprequest.cc
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/asynchttprequest.h"
-
-namespace talk_base {
-
-enum {
- MSG_TIMEOUT = SignalThread::ST_MSG_FIRST_AVAILABLE,
- MSG_LAUNCH_REQUEST
-};
-static const int kDefaultHTTPTimeout = 30 * 1000; // 30 sec
-
-///////////////////////////////////////////////////////////////////////////////
-// AsyncHttpRequest
-///////////////////////////////////////////////////////////////////////////////
-
-AsyncHttpRequest::AsyncHttpRequest(const std::string &user_agent)
- : start_delay_(0),
- firewall_(NULL),
- port_(80),
- secure_(false),
- timeout_(kDefaultHTTPTimeout),
- fail_redirect_(false),
- factory_(Thread::Current()->socketserver(), user_agent),
- pool_(&factory_),
- client_(user_agent.c_str(), &pool_),
- error_(HE_NONE) {
- client_.SignalHttpClientComplete.connect(this,
- &AsyncHttpRequest::OnComplete);
-}
-
-AsyncHttpRequest::~AsyncHttpRequest() {
-}
-
-void AsyncHttpRequest::OnWorkStart() {
- if (start_delay_ <= 0) {
- LaunchRequest();
- } else {
- Thread::Current()->PostDelayed(start_delay_, this, MSG_LAUNCH_REQUEST);
- }
-}
-
-void AsyncHttpRequest::OnWorkStop() {
- // worker is already quitting, no need to explicitly quit
- LOG(LS_INFO) << "HttpRequest cancelled";
-}
-
-void AsyncHttpRequest::OnComplete(HttpClient* client, HttpErrorType error) {
- Thread::Current()->Clear(this, MSG_TIMEOUT);
-
- set_error(error);
- if (!error) {
- LOG(LS_INFO) << "HttpRequest completed successfully";
-
- std::string value;
- if (client_.response().hasHeader(HH_LOCATION, &value)) {
- response_redirect_ = value.c_str();
- }
- } else {
- LOG(LS_INFO) << "HttpRequest completed with error: " << error;
- }
-
- worker()->Quit();
-}
-
-void AsyncHttpRequest::OnMessage(Message* message) {
- switch (message->message_id) {
- case MSG_TIMEOUT:
- LOG(LS_INFO) << "HttpRequest timed out";
- client_.reset();
- worker()->Quit();
- break;
- case MSG_LAUNCH_REQUEST:
- LaunchRequest();
- break;
- default:
- SignalThread::OnMessage(message);
- break;
- }
-}
-
-void AsyncHttpRequest::DoWork() {
- // Do nothing while we wait for the request to finish. We only do this so
- // that we can be a SignalThread; in the future this class should not be
- // a SignalThread, since it does not need to spawn a new thread.
- Thread::Current()->ProcessMessages(kForever);
-}
-
-void AsyncHttpRequest::LaunchRequest() {
- factory_.SetProxy(proxy_);
- if (secure_)
- factory_.UseSSL(host_.c_str());
-
- bool transparent_proxy = (port_ == 80) &&
- ((proxy_.type == PROXY_HTTPS) || (proxy_.type == PROXY_UNKNOWN));
- if (transparent_proxy) {
- client_.set_proxy(proxy_);
- }
- client_.set_fail_redirect(fail_redirect_);
- client_.set_server(SocketAddress(host_, port_));
-
- LOG(LS_INFO) << "HttpRequest start: " << host_ + client_.request().path;
-
- Thread::Current()->PostDelayed(timeout_, this, MSG_TIMEOUT);
- client_.start();
-}
-
-} // namespace talk_base
diff --git a/base/asynchttprequest.h b/base/asynchttprequest.h
deleted file mode 100644
index 13edf61..0000000
--- a/base/asynchttprequest.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCHTTPREQUEST_H_
-#define TALK_BASE_ASYNCHTTPREQUEST_H_
-
-#include <string>
-#include "talk/base/event.h"
-#include "talk/base/httpclient.h"
-#include "talk/base/signalthread.h"
-#include "talk/base/socketpool.h"
-#include "talk/base/sslsocketfactory.h"
-
-namespace talk_base {
-
-class FirewallManager;
-
-///////////////////////////////////////////////////////////////////////////////
-// AsyncHttpRequest
-// Performs an HTTP request on a background thread. Notifies on the foreground
-// thread once the request is done (successfully or unsuccessfully).
-///////////////////////////////////////////////////////////////////////////////
-
-class AsyncHttpRequest : public SignalThread {
- public:
- explicit AsyncHttpRequest(const std::string &user_agent);
- ~AsyncHttpRequest();
-
- // If start_delay is less than or equal to zero, this starts immediately.
- // Start_delay defaults to zero.
- int start_delay() const { return start_delay_; }
- void set_start_delay(int delay) { start_delay_ = delay; }
-
- const ProxyInfo& proxy() const { return proxy_; }
- void set_proxy(const ProxyInfo& proxy) {
- proxy_ = proxy;
- }
- void set_firewall(FirewallManager * firewall) {
- firewall_ = firewall;
- }
-
- // The DNS name of the host to connect to.
- const std::string& host() { return host_; }
- void set_host(const std::string& host) { host_ = host; }
-
- // The port to connect to on the target host.
- int port() { return port_; }
- void set_port(int port) { port_ = port; }
-
- // Whether the request should use SSL.
- bool secure() { return secure_; }
- void set_secure(bool secure) { secure_ = secure; }
-
- // Time to wait on the download, in ms.
- int timeout() { return timeout_; }
- void set_timeout(int timeout) { timeout_ = timeout; }
-
- // Fail redirects to allow analysis of redirect urls, etc.
- bool fail_redirect() const { return fail_redirect_; }
- void set_fail_redirect(bool redirect) { fail_redirect_ = redirect; }
-
- // Returns the redirect when redirection occurs
- const std::string& response_redirect() { return response_redirect_; }
-
- HttpRequestData& request() { return client_.request(); }
- HttpResponseData& response() { return client_.response(); }
- HttpErrorType error() { return error_; }
-
- protected:
- void set_error(HttpErrorType error) { error_ = error; }
- virtual void OnWorkStart();
- virtual void OnWorkStop();
- void OnComplete(HttpClient* client, HttpErrorType error);
- virtual void OnMessage(Message* message);
- virtual void DoWork();
-
- private:
- void LaunchRequest();
-
- int start_delay_;
- ProxyInfo proxy_;
- FirewallManager* firewall_;
- std::string host_;
- int port_;
- bool secure_;
- int timeout_;
- bool fail_redirect_;
- SslSocketFactory factory_;
- ReuseSocketPool pool_;
- HttpClient client_;
- HttpErrorType error_;
- std::string response_redirect_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ASYNCHTTPREQUEST_H_
diff --git a/base/asynchttprequest_unittest.cc b/base/asynchttprequest_unittest.cc
deleted file mode 100644
index 13842da..0000000
--- a/base/asynchttprequest_unittest.cc
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-#include "talk/base/asynchttprequest.h"
-#include "talk/base/gunit.h"
-#include "talk/base/httpserver.h"
-#include "talk/base/socketstream.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-static const SocketAddress kServerAddr("127.0.0.1", 0);
-static const SocketAddress kServerHostnameAddr("localhost", 0);
-static const char kServerGetPath[] = "/get";
-static const char kServerPostPath[] = "/post";
-static const char kServerResponse[] = "This is a test";
-
-class TestHttpServer : public HttpServer, public sigslot::has_slots<> {
- public:
- TestHttpServer(Thread* thread, const SocketAddress& addr) :
- socket_(thread->socketserver()->CreateAsyncSocket(addr.family(),
- SOCK_STREAM)) {
- socket_->Bind(addr);
- socket_->Listen(5);
- socket_->SignalReadEvent.connect(this, &TestHttpServer::OnAccept);
- }
-
- SocketAddress address() const { return socket_->GetLocalAddress(); }
- void Close() const { socket_->Close(); }
-
- private:
- void OnAccept(AsyncSocket* socket) {
- AsyncSocket* new_socket = socket_->Accept(NULL);
- if (new_socket) {
- HandleConnection(new SocketStream(new_socket));
- }
- }
- talk_base::scoped_ptr<AsyncSocket> socket_;
-};
-
-class AsyncHttpRequestTest : public testing::Test,
- public sigslot::has_slots<> {
- public:
- AsyncHttpRequestTest()
- : started_(false),
- done_(false),
- server_(Thread::Current(), kServerAddr) {
- server_.SignalHttpRequest.connect(this, &AsyncHttpRequestTest::OnRequest);
- }
-
- bool started() const { return started_; }
- bool done() const { return done_; }
-
- AsyncHttpRequest* CreateGetRequest(const std::string& host, int port,
- const std::string& path) {
- talk_base::AsyncHttpRequest* request =
- new talk_base::AsyncHttpRequest("unittest");
- request->SignalWorkDone.connect(this,
- &AsyncHttpRequestTest::OnRequestDone);
- request->request().verb = talk_base::HV_GET;
- request->set_host(host);
- request->set_port(port);
- request->request().path = path;
- request->response().document.reset(new MemoryStream());
- return request;
- }
- AsyncHttpRequest* CreatePostRequest(const std::string& host, int port,
- const std::string& path,
- const std::string content_type,
- StreamInterface* content) {
- talk_base::AsyncHttpRequest* request =
- new talk_base::AsyncHttpRequest("unittest");
- request->SignalWorkDone.connect(this,
- &AsyncHttpRequestTest::OnRequestDone);
- request->request().verb = talk_base::HV_POST;
- request->set_host(host);
- request->set_port(port);
- request->request().path = path;
- request->request().setContent(content_type, content);
- request->response().document.reset(new MemoryStream());
- return request;
- }
-
- const TestHttpServer& server() const { return server_; }
-
- protected:
- void OnRequest(HttpServer* server, HttpServerTransaction* t) {
- started_ = true;
-
- if (t->request.path == kServerGetPath) {
- t->response.set_success("text/plain", new MemoryStream(kServerResponse));
- } else if (t->request.path == kServerPostPath) {
- // reverse the data and reply
- size_t size;
- StreamInterface* in = t->request.document.get();
- StreamInterface* out = new MemoryStream();
- in->GetSize(&size);
- for (size_t i = 0; i < size; ++i) {
- char ch;
- in->SetPosition(size - i - 1);
- in->Read(&ch, 1, NULL, NULL);
- out->Write(&ch, 1, NULL, NULL);
- }
- out->Rewind();
- t->response.set_success("text/plain", out);
- } else {
- t->response.set_error(404);
- }
- server_.Respond(t);
- }
- void OnRequestDone(SignalThread* thread) {
- done_ = true;
- }
-
- private:
- bool started_;
- bool done_;
- TestHttpServer server_;
-};
-
-TEST_F(AsyncHttpRequestTest, TestGetSuccess) {
- AsyncHttpRequest* req = CreateGetRequest(
- kServerHostnameAddr.hostname(), server().address().port(),
- kServerGetPath);
- EXPECT_FALSE(started());
- req->Start();
- EXPECT_TRUE_WAIT(started(), 5000); // Should have started by now.
- EXPECT_TRUE_WAIT(done(), 5000);
- std::string response;
- EXPECT_EQ(200U, req->response().scode);
- ASSERT_TRUE(req->response().document);
- req->response().document->Rewind();
- req->response().document->ReadLine(&response);
- EXPECT_EQ(kServerResponse, response);
- req->Release();
-}
-
-TEST_F(AsyncHttpRequestTest, TestGetNotFound) {
- AsyncHttpRequest* req = CreateGetRequest(
- kServerHostnameAddr.hostname(), server().address().port(),
- "/bad");
- req->Start();
- EXPECT_TRUE_WAIT(done(), 5000);
- size_t size;
- EXPECT_EQ(404U, req->response().scode);
- ASSERT_TRUE(req->response().document);
- req->response().document->GetSize(&size);
- EXPECT_EQ(0U, size);
- req->Release();
-}
-
-TEST_F(AsyncHttpRequestTest, TestGetToNonServer) {
- AsyncHttpRequest* req = CreateGetRequest(
- "127.0.0.1", server().address().port(),
- kServerGetPath);
- // Stop the server before we send the request.
- server().Close();
- req->Start();
- EXPECT_TRUE_WAIT(done(), 10000);
- size_t size;
- EXPECT_EQ(500U, req->response().scode);
- ASSERT_TRUE(req->response().document);
- req->response().document->GetSize(&size);
- EXPECT_EQ(0U, size);
- req->Release();
-}
-
-TEST_F(AsyncHttpRequestTest, DISABLED_TestGetToInvalidHostname) {
- AsyncHttpRequest* req = CreateGetRequest(
- "invalid", server().address().port(),
- kServerGetPath);
- req->Start();
- EXPECT_TRUE_WAIT(done(), 5000);
- size_t size;
- EXPECT_EQ(500U, req->response().scode);
- ASSERT_TRUE(req->response().document);
- req->response().document->GetSize(&size);
- EXPECT_EQ(0U, size);
- req->Release();
-}
-
-TEST_F(AsyncHttpRequestTest, TestPostSuccess) {
- AsyncHttpRequest* req = CreatePostRequest(
- kServerHostnameAddr.hostname(), server().address().port(),
- kServerPostPath, "text/plain", new MemoryStream("abcd1234"));
- req->Start();
- EXPECT_TRUE_WAIT(done(), 5000);
- std::string response;
- EXPECT_EQ(200U, req->response().scode);
- ASSERT_TRUE(req->response().document);
- req->response().document->Rewind();
- req->response().document->ReadLine(&response);
- EXPECT_EQ("4321dcba", response);
- req->Release();
-}
-
-// Ensure that we shut down properly even if work is outstanding.
-TEST_F(AsyncHttpRequestTest, TestCancel) {
- AsyncHttpRequest* req = CreateGetRequest(
- kServerHostnameAddr.hostname(), server().address().port(),
- kServerGetPath);
- req->Start();
- req->Destroy(true);
-}
-
-TEST_F(AsyncHttpRequestTest, TestGetSuccessDelay) {
- AsyncHttpRequest* req = CreateGetRequest(
- kServerHostnameAddr.hostname(), server().address().port(),
- kServerGetPath);
- req->set_start_delay(10); // Delay 10ms.
- req->Start();
- Thread::SleepMs(5);
- EXPECT_FALSE(started()); // Should not have started immediately.
- EXPECT_TRUE_WAIT(started(), 5000); // Should have started by now.
- EXPECT_TRUE_WAIT(done(), 5000);
- std::string response;
- EXPECT_EQ(200U, req->response().scode);
- ASSERT_TRUE(req->response().document);
- req->response().document->Rewind();
- req->response().document->ReadLine(&response);
- EXPECT_EQ(kServerResponse, response);
- req->Release();
-}
-
-} // namespace talk_base
diff --git a/base/asyncinvoker-inl.h b/base/asyncinvoker-inl.h
deleted file mode 100644
index b6be175..0000000
--- a/base/asyncinvoker-inl.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCINVOKER_INL_H_
-#define TALK_BASE_ASYNCINVOKER_INL_H_
-
-#include "talk/base/bind.h"
-#include "talk/base/callback.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ref_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-class AsyncInvoker;
-
-// Helper class for AsyncInvoker. Runs a task and triggers a callback
-// on the calling thread if necessary. Instances are ref-counted so their
-// lifetime can be independent of AsyncInvoker.
-class AsyncClosure : public RefCountInterface {
- public:
- virtual ~AsyncClosure() {}
- // Runs the asynchronous task, and triggers a callback to the calling
- // thread if needed. Should be called from the target thread.
- virtual void Execute() = 0;
-};
-
-// Simple closure that doesn't trigger a callback for the calling thread.
-template <class FunctorT>
-class FireAndForgetAsyncClosure : public AsyncClosure {
- public:
- explicit FireAndForgetAsyncClosure(const FunctorT& functor)
- : functor_(functor) {}
- virtual void Execute() {
- functor_();
- }
- private:
- FunctorT functor_;
-};
-
-// Base class for closures that may trigger a callback for the calling thread.
-// Listens for the "destroyed" signals from the calling thread and the invoker,
-// and cancels the callback to the calling thread if either is destroyed.
-class NotifyingAsyncClosureBase : public AsyncClosure,
- public sigslot::has_slots<> {
- public:
- virtual ~NotifyingAsyncClosureBase() { disconnect_all(); }
-
- protected:
- NotifyingAsyncClosureBase(AsyncInvoker* invoker, Thread* calling_thread);
- void TriggerCallback();
- void SetCallback(const Callback0<void>& callback) {
- CritScope cs(&crit_);
- callback_ = callback;
- }
- bool CallbackCanceled() const { return calling_thread_ == NULL; }
-
- private:
- Callback0<void> callback_;
- CriticalSection crit_;
- AsyncInvoker* invoker_;
- Thread* calling_thread_;
-
- void CancelCallback();
-};
-
-// Closures that have a non-void return value and require a callback.
-template <class ReturnT, class FunctorT, class HostT>
-class NotifyingAsyncClosure : public NotifyingAsyncClosureBase {
- public:
- NotifyingAsyncClosure(AsyncInvoker* invoker,
- Thread* calling_thread,
- const FunctorT& functor,
- void (HostT::*callback)(ReturnT),
- HostT* callback_host)
- : NotifyingAsyncClosureBase(invoker, calling_thread),
- functor_(functor),
- callback_(callback),
- callback_host_(callback_host) {}
- virtual void Execute() {
- ReturnT result = functor_();
- if (!CallbackCanceled()) {
- SetCallback(Callback0<void>(Bind(callback_, callback_host_, result)));
- TriggerCallback();
- }
- }
-
- private:
- FunctorT functor_;
- void (HostT::*callback_)(ReturnT);
- HostT* callback_host_;
-};
-
-// Closures that have a void return value and require a callback.
-template <class FunctorT, class HostT>
-class NotifyingAsyncClosure<void, FunctorT, HostT>
- : public NotifyingAsyncClosureBase {
- public:
- NotifyingAsyncClosure(AsyncInvoker* invoker,
- Thread* calling_thread,
- const FunctorT& functor,
- void (HostT::*callback)(),
- HostT* callback_host)
- : NotifyingAsyncClosureBase(invoker, calling_thread),
- functor_(functor) {
- SetCallback(Callback0<void>(Bind(callback, callback_host)));
- }
- virtual void Execute() {
- functor_();
- TriggerCallback();
- }
-
- private:
- FunctorT functor_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ASYNCINVOKER_INL_H_
diff --git a/base/asyncinvoker.cc b/base/asyncinvoker.cc
deleted file mode 100644
index a57eb7b..0000000
--- a/base/asyncinvoker.cc
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/asyncinvoker.h"
-
-namespace talk_base {
-
-AsyncInvoker::AsyncInvoker() : destroying_(false) {}
-
-AsyncInvoker::~AsyncInvoker() {
- destroying_ = true;
- SignalInvokerDestroyed();
- // Messages for this need to be cleared *before* our destructor is complete.
- MessageQueueManager::Clear(this);
-}
-
-void AsyncInvoker::OnMessage(Message* msg) {
- // Get the AsyncClosure shared ptr from this message's data.
- ScopedRefMessageData<AsyncClosure>* data =
- static_cast<ScopedRefMessageData<AsyncClosure>*>(msg->pdata);
- scoped_refptr<AsyncClosure> closure = data->data();
- delete msg->pdata;
- msg->pdata = NULL;
-
- // Execute the closure and trigger the return message if needed.
- closure->Execute();
-}
-
-void AsyncInvoker::Flush(Thread* thread, uint32 id /*= MQID_ANY*/) {
- if (destroying_) return;
-
- // Run this on |thread| to reduce the number of context switches.
- if (Thread::Current() != thread) {
- thread->Invoke<void>(Bind(&AsyncInvoker::Flush, this, thread, id));
- return;
- }
-
- MessageList removed;
- thread->Clear(this, id, &removed);
- for (MessageList::iterator it = removed.begin(); it != removed.end(); ++it) {
- // This message was pending on this thread, so run it now.
- thread->Send(it->phandler,
- it->message_id,
- it->pdata);
- }
-}
-
-void AsyncInvoker::DoInvoke(Thread* thread, AsyncClosure* closure,
- uint32 id) {
- if (destroying_) {
- LOG(LS_WARNING) << "Tried to invoke while destroying the invoker.";
- // Since this call transwers ownership of |closure|, we clean it up here.
- delete closure;
- return;
- }
- thread->Post(this, id, new ScopedRefMessageData<AsyncClosure>(closure));
-}
-
-NotifyingAsyncClosureBase::NotifyingAsyncClosureBase(AsyncInvoker* invoker,
- Thread* calling_thread)
- : invoker_(invoker), calling_thread_(calling_thread) {
- calling_thread->SignalQueueDestroyed.connect(
- this, &NotifyingAsyncClosureBase::CancelCallback);
- invoker->SignalInvokerDestroyed.connect(
- this, &NotifyingAsyncClosureBase::CancelCallback);
-}
-
-void NotifyingAsyncClosureBase::TriggerCallback() {
- CritScope cs(&crit_);
- if (!CallbackCanceled() && !callback_.empty()) {
- invoker_->AsyncInvoke<void>(calling_thread_, callback_);
- }
-}
-
-void NotifyingAsyncClosureBase::CancelCallback() {
- // If the callback is triggering when this is called, block the
- // destructor of the dying object here by waiting until the callback
- // is done triggering.
- CritScope cs(&crit_);
- // calling_thread_ == NULL means do not trigger the callback.
- calling_thread_ = NULL;
-}
-
-} // namespace talk_base
diff --git a/base/asyncinvoker.h b/base/asyncinvoker.h
deleted file mode 100644
index b7dfac9..0000000
--- a/base/asyncinvoker.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCINVOKER_H_
-#define TALK_BASE_ASYNCINVOKER_H_
-
-#include "talk/base/asyncinvoker-inl.h"
-#include "talk/base/bind.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/scopedptrcollection.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-// Invokes function objects (aka functors) asynchronously on a Thread, and
-// owns the lifetime of calls (ie, when this object is destroyed, calls in
-// flight are cancelled). AsyncInvoker can optionally execute a user-specified
-// function when the asynchronous call is complete, or operates in
-// fire-and-forget mode otherwise.
-//
-// AsyncInvoker does not own the thread it calls functors on.
-//
-// A note about async calls and object lifetimes: users should
-// be mindful of object lifetimes when calling functions asynchronously and
-// ensure objects used by the function _cannot_ be deleted between the
-// invocation and execution of the functor. AsyncInvoker is designed to
-// help: any calls in flight will be cancelled when the AsyncInvoker used to
-// make the call is destructed, and any calls executing will be allowed to
-// complete before AsyncInvoker destructs.
-//
-// The easiest way to ensure lifetimes are handled correctly is to create a
-// class that owns the Thread and AsyncInvoker objects, and then call its
-// methods asynchronously as needed.
-//
-// Example:
-// class MyClass {
-// public:
-// void FireAsyncTaskWithResult(Thread* thread, int x) {
-// // Specify a callback to get the result upon completion.
-// invoker_.AsyncInvoke<int>(
-// thread, Bind(&MyClass::AsyncTaskWithResult, this, x),
-// &MyClass::OnTaskComplete, this);
-// }
-// void FireAnotherAsyncTask(Thread* thread) {
-// // No callback specified means fire-and-forget.
-// invoker_.AsyncInvoke<void>(
-// thread, Bind(&MyClass::AnotherAsyncTask, this));
-//
-// private:
-// int AsyncTaskWithResult(int x) {
-// // Some long running process...
-// return x * x;
-// }
-// void AnotherAsyncTask() {
-// // Some other long running process...
-// }
-// void OnTaskComplete(int result) { result_ = result; }
-//
-// AsyncInvoker invoker_;
-// int result_;
-// };
-class AsyncInvoker : public MessageHandler {
- public:
- AsyncInvoker();
- virtual ~AsyncInvoker();
-
- // Call |functor| asynchronously on |thread|, with no callback upon
- // completion. Returns immediately.
- template <class ReturnT, class FunctorT>
- void AsyncInvoke(Thread* thread,
- const FunctorT& functor,
- uint32 id = 0) {
- AsyncClosure* closure =
- new RefCountedObject<FireAndForgetAsyncClosure<FunctorT> >(functor);
- DoInvoke(thread, closure, id);
- }
-
- // Call |functor| asynchronously on |thread|, calling |callback| when done.
- template <class ReturnT, class FunctorT, class HostT>
- void AsyncInvoke(Thread* thread,
- const FunctorT& functor,
- void (HostT::*callback)(ReturnT),
- HostT* callback_host,
- uint32 id = 0) {
- AsyncClosure* closure =
- new RefCountedObject<NotifyingAsyncClosure<ReturnT, FunctorT, HostT> >(
- this, Thread::Current(), functor, callback, callback_host);
- DoInvoke(thread, closure, id);
- }
-
- // Call |functor| asynchronously on |thread|, calling |callback| when done.
- // Overloaded for void return.
- template <class ReturnT, class FunctorT, class HostT>
- void AsyncInvoke(Thread* thread,
- const FunctorT& functor,
- void (HostT::*callback)(),
- HostT* callback_host,
- uint32 id = 0) {
- AsyncClosure* closure =
- new RefCountedObject<NotifyingAsyncClosure<void, FunctorT, HostT> >(
- this, Thread::Current(), functor, callback, callback_host);
- DoInvoke(thread, closure, id);
- }
-
- // Synchronously execute on |thread| all outstanding calls we own
- // that are pending on |thread|, and wait for calls to complete
- // before returning. Optionally filter by message id.
- // The destructor will not wait for outstanding calls, so if that
- // behavior is desired, call Flush() before destroying this object.
- void Flush(Thread* thread, uint32 id = MQID_ANY);
-
- // Signaled when this object is destructed.
- sigslot::signal0<> SignalInvokerDestroyed;
-
- private:
- virtual void OnMessage(Message* msg);
- void DoInvoke(Thread* thread, AsyncClosure* closure, uint32 id);
-
- bool destroying_;
-
- DISALLOW_COPY_AND_ASSIGN(AsyncInvoker);
-};
-
-} // namespace talk_base
-
-
-#endif // TALK_BASE_ASYNCINVOKER_H_
diff --git a/base/asyncpacketsocket.h b/base/asyncpacketsocket.h
deleted file mode 100644
index 091f1d0..0000000
--- a/base/asyncpacketsocket.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCPACKETSOCKET_H_
-#define TALK_BASE_ASYNCPACKETSOCKET_H_
-
-#include "talk/base/dscp.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socket.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-// This structure holds the info needed to update the packet send time header
-// extension, including the information needed to update the authentication tag
-// after changing the value.
-struct PacketTimeUpdateParams {
- PacketTimeUpdateParams()
- : rtp_sendtime_extension_id(-1), srtp_auth_tag_len(-1),
- srtp_packet_index(-1) {
- }
-
- int rtp_sendtime_extension_id; // extension header id present in packet.
- std::vector<char> srtp_auth_key; // Authentication key.
- int srtp_auth_tag_len; // Authentication tag length.
- int64 srtp_packet_index; // Required for Rtp Packet authentication.
-};
-
-// This structure holds meta information for the packet which is about to send
-// over network.
-struct PacketOptions {
- PacketOptions() : dscp(DSCP_NO_CHANGE) {}
- explicit PacketOptions(DiffServCodePoint dscp) : dscp(dscp) {}
-
- DiffServCodePoint dscp;
- PacketTimeUpdateParams packet_time_params;
-};
-
-// This structure will have the information about when packet is actually
-// received by socket.
-struct PacketTime {
- PacketTime() : timestamp(-1), not_before(-1) {}
- PacketTime(int64 timestamp, int64 not_before)
- : timestamp(timestamp), not_before(not_before) {
- }
-
- int64 timestamp; // Receive time after socket delivers the data.
- int64 not_before; // Earliest possible time the data could have arrived,
- // indicating the potential error in the |timestamp| value,
- // in case the system, is busy. For example, the time of
- // the last select() call.
- // If unknown, this value will be set to zero.
-};
-
-inline PacketTime CreatePacketTime(int64 not_before) {
- return PacketTime(TimeMicros(), not_before);
-}
-
-// Provides the ability to receive packets asynchronously. Sends are not
-// buffered since it is acceptable to drop packets under high load.
-class AsyncPacketSocket : public sigslot::has_slots<> {
- public:
- enum State {
- STATE_CLOSED,
- STATE_BINDING,
- STATE_BOUND,
- STATE_CONNECTING,
- STATE_CONNECTED
- };
-
- AsyncPacketSocket() { }
- virtual ~AsyncPacketSocket() { }
-
- // Returns current local address. Address may be set to NULL if the
- // socket is not bound yet (GetState() returns STATE_BINDING).
- virtual SocketAddress GetLocalAddress() const = 0;
-
- // Returns remote address. Returns zeroes if this is not a client TCP socket.
- virtual SocketAddress GetRemoteAddress() const = 0;
-
- // Send a packet.
- virtual int Send(const void *pv, size_t cb, const PacketOptions& options) = 0;
- virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
- const PacketOptions& options) = 0;
-
- // Close the socket.
- virtual int Close() = 0;
-
- // Returns current state of the socket.
- virtual State GetState() const = 0;
-
- // Get/set options.
- virtual int GetOption(Socket::Option opt, int* value) = 0;
- virtual int SetOption(Socket::Option opt, int value) = 0;
-
- // Get/Set current error.
- // TODO: Remove SetError().
- virtual int GetError() const = 0;
- virtual void SetError(int error) = 0;
-
- // Emitted each time a packet is read. Used only for UDP and
- // connected TCP sockets.
- sigslot::signal5<AsyncPacketSocket*, const char*, size_t,
- const SocketAddress&,
- const PacketTime&> SignalReadPacket;
-
- // Emitted when the socket is currently able to send.
- sigslot::signal1<AsyncPacketSocket*> SignalReadyToSend;
-
- // Emitted after address for the socket is allocated, i.e. binding
- // is finished. State of the socket is changed from BINDING to BOUND
- // (for UDP and server TCP sockets) or CONNECTING (for client TCP
- // sockets).
- sigslot::signal2<AsyncPacketSocket*, const SocketAddress&> SignalAddressReady;
-
- // Emitted for client TCP sockets when state is changed from
- // CONNECTING to CONNECTED.
- sigslot::signal1<AsyncPacketSocket*> SignalConnect;
-
- // Emitted for client TCP sockets when state is changed from
- // CONNECTED to CLOSED.
- sigslot::signal2<AsyncPacketSocket*, int> SignalClose;
-
- // Used only for listening TCP sockets.
- sigslot::signal2<AsyncPacketSocket*, AsyncPacketSocket*> SignalNewConnection;
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(AsyncPacketSocket);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ASYNCPACKETSOCKET_H_
diff --git a/base/asyncresolverinterface.h b/base/asyncresolverinterface.h
deleted file mode 100644
index 4d77c4f..0000000
--- a/base/asyncresolverinterface.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * libjingle
- * Copyright 2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCRESOLVERINTERFACE_H_
-#define TALK_BASE_ASYNCRESOLVERINTERFACE_H_
-
-#include "talk/base/sigslot.h"
-#include "talk/base/socketaddress.h"
-
-namespace talk_base {
-
-// This interface defines the methods to resolve the address asynchronously.
-class AsyncResolverInterface {
- public:
- AsyncResolverInterface() {}
- virtual ~AsyncResolverInterface() {}
-
- // Start address resolve process.
- virtual void Start(const SocketAddress& addr) = 0;
- // Returns top most resolved address of |family|
- virtual bool GetResolvedAddress(int family, SocketAddress* addr) const = 0;
- // Returns error from resolver.
- virtual int GetError() const = 0;
- // Delete the resolver.
- virtual void Destroy(bool wait) = 0;
- // Returns top most resolved IPv4 address if address is resolved successfully.
- // Otherwise returns address set in SetAddress.
- SocketAddress address() const {
- SocketAddress addr;
- GetResolvedAddress(AF_INET, &addr);
- return addr;
- }
-
- // This signal is fired when address resolve process is completed.
- sigslot::signal1<AsyncResolverInterface*> SignalDone;
-};
-
-} // namespace talk_base
-
-#endif
diff --git a/base/asyncsocket.cc b/base/asyncsocket.cc
deleted file mode 100644
index d9ed94c..0000000
--- a/base/asyncsocket.cc
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/asyncsocket.h"
-
-namespace talk_base {
-
-AsyncSocket::AsyncSocket() {
-}
-
-AsyncSocket::~AsyncSocket() {
-}
-
-AsyncSocketAdapter::AsyncSocketAdapter(AsyncSocket* socket) : socket_(NULL) {
- Attach(socket);
-}
-
-AsyncSocketAdapter::~AsyncSocketAdapter() {
- delete socket_;
-}
-
-void AsyncSocketAdapter::Attach(AsyncSocket* socket) {
- ASSERT(!socket_);
- socket_ = socket;
- if (socket_) {
- socket_->SignalConnectEvent.connect(this,
- &AsyncSocketAdapter::OnConnectEvent);
- socket_->SignalReadEvent.connect(this,
- &AsyncSocketAdapter::OnReadEvent);
- socket_->SignalWriteEvent.connect(this,
- &AsyncSocketAdapter::OnWriteEvent);
- socket_->SignalCloseEvent.connect(this,
- &AsyncSocketAdapter::OnCloseEvent);
- }
-}
-
-} // namespace talk_base
diff --git a/base/asyncsocket.h b/base/asyncsocket.h
deleted file mode 100644
index 97859a7..0000000
--- a/base/asyncsocket.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCSOCKET_H_
-#define TALK_BASE_ASYNCSOCKET_H_
-
-#include "talk/base/common.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socket.h"
-
-namespace talk_base {
-
-// TODO: Remove Socket and rename AsyncSocket to Socket.
-
-// Provides the ability to perform socket I/O asynchronously.
-class AsyncSocket : public Socket {
- public:
- AsyncSocket();
- virtual ~AsyncSocket();
-
- virtual AsyncSocket* Accept(SocketAddress* paddr) = 0;
-
- // SignalReadEvent and SignalWriteEvent use multi_threaded_local to allow
- // access concurrently from different thread.
- // For example SignalReadEvent::connect will be called in AsyncUDPSocket ctor
- // but at the same time the SocketDispatcher maybe signaling the read event.
- // ready to read
- sigslot::signal1<AsyncSocket*,
- sigslot::multi_threaded_local> SignalReadEvent;
- // ready to write
- sigslot::signal1<AsyncSocket*,
- sigslot::multi_threaded_local> SignalWriteEvent;
- sigslot::signal1<AsyncSocket*> SignalConnectEvent; // connected
- sigslot::signal2<AsyncSocket*, int> SignalCloseEvent; // closed
-};
-
-class AsyncSocketAdapter : public AsyncSocket, public sigslot::has_slots<> {
- public:
- // The adapted socket may explicitly be NULL, and later assigned using Attach.
- // However, subclasses which support detached mode must override any methods
- // that will be called during the detached period (usually GetState()), to
- // avoid dereferencing a null pointer.
- explicit AsyncSocketAdapter(AsyncSocket* socket);
- virtual ~AsyncSocketAdapter();
- void Attach(AsyncSocket* socket);
- virtual SocketAddress GetLocalAddress() const {
- return socket_->GetLocalAddress();
- }
- virtual SocketAddress GetRemoteAddress() const {
- return socket_->GetRemoteAddress();
- }
- virtual int Bind(const SocketAddress& addr) {
- return socket_->Bind(addr);
- }
- virtual int Connect(const SocketAddress& addr) {
- return socket_->Connect(addr);
- }
- virtual int Send(const void* pv, size_t cb) {
- return socket_->Send(pv, cb);
- }
- virtual int SendTo(const void* pv, size_t cb, const SocketAddress& addr) {
- return socket_->SendTo(pv, cb, addr);
- }
- virtual int Recv(void* pv, size_t cb) {
- return socket_->Recv(pv, cb);
- }
- virtual int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) {
- return socket_->RecvFrom(pv, cb, paddr);
- }
- virtual int Listen(int backlog) {
- return socket_->Listen(backlog);
- }
- virtual AsyncSocket* Accept(SocketAddress* paddr) {
- return socket_->Accept(paddr);
- }
- virtual int Close() {
- return socket_->Close();
- }
- virtual int GetError() const {
- return socket_->GetError();
- }
- virtual void SetError(int error) {
- return socket_->SetError(error);
- }
- virtual ConnState GetState() const {
- return socket_->GetState();
- }
- virtual int EstimateMTU(uint16* mtu) {
- return socket_->EstimateMTU(mtu);
- }
- virtual int GetOption(Option opt, int* value) {
- return socket_->GetOption(opt, value);
- }
- virtual int SetOption(Option opt, int value) {
- return socket_->SetOption(opt, value);
- }
-
- protected:
- virtual void OnConnectEvent(AsyncSocket* socket) {
- SignalConnectEvent(this);
- }
- virtual void OnReadEvent(AsyncSocket* socket) {
- SignalReadEvent(this);
- }
- virtual void OnWriteEvent(AsyncSocket* socket) {
- SignalWriteEvent(this);
- }
- virtual void OnCloseEvent(AsyncSocket* socket, int err) {
- SignalCloseEvent(this, err);
- }
-
- AsyncSocket* socket_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ASYNCSOCKET_H_
diff --git a/base/asynctcpsocket.cc b/base/asynctcpsocket.cc
deleted file mode 100644
index 781fb0a..0000000
--- a/base/asynctcpsocket.cc
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/asynctcpsocket.h"
-
-#include <string.h>
-
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-
-#ifdef POSIX
-#include <errno.h>
-#endif // POSIX
-
-namespace talk_base {
-
-static const size_t kMaxPacketSize = 64 * 1024;
-
-typedef uint16 PacketLength;
-static const size_t kPacketLenSize = sizeof(PacketLength);
-
-static const size_t kBufSize = kMaxPacketSize + kPacketLenSize;
-
-static const int kListenBacklog = 5;
-
-// Binds and connects |socket|
-AsyncSocket* AsyncTCPSocketBase::ConnectSocket(
- talk_base::AsyncSocket* socket,
- const talk_base::SocketAddress& bind_address,
- const talk_base::SocketAddress& remote_address) {
- talk_base::scoped_ptr<talk_base::AsyncSocket> owned_socket(socket);
- if (socket->Bind(bind_address) < 0) {
- LOG(LS_ERROR) << "Bind() failed with error " << socket->GetError();
- return NULL;
- }
- if (socket->Connect(remote_address) < 0) {
- LOG(LS_ERROR) << "Connect() failed with error " << socket->GetError();
- return NULL;
- }
- return owned_socket.release();
-}
-
-AsyncTCPSocketBase::AsyncTCPSocketBase(AsyncSocket* socket, bool listen,
- size_t max_packet_size)
- : socket_(socket),
- listen_(listen),
- insize_(max_packet_size),
- inpos_(0),
- outsize_(max_packet_size),
- outpos_(0) {
- inbuf_ = new char[insize_];
- outbuf_ = new char[outsize_];
-
- ASSERT(socket_.get() != NULL);
- socket_->SignalConnectEvent.connect(
- this, &AsyncTCPSocketBase::OnConnectEvent);
- socket_->SignalReadEvent.connect(this, &AsyncTCPSocketBase::OnReadEvent);
- socket_->SignalWriteEvent.connect(this, &AsyncTCPSocketBase::OnWriteEvent);
- socket_->SignalCloseEvent.connect(this, &AsyncTCPSocketBase::OnCloseEvent);
-
- if (listen_) {
- if (socket_->Listen(kListenBacklog) < 0) {
- LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
- }
- }
-}
-
-AsyncTCPSocketBase::~AsyncTCPSocketBase() {
- delete [] inbuf_;
- delete [] outbuf_;
-}
-
-SocketAddress AsyncTCPSocketBase::GetLocalAddress() const {
- return socket_->GetLocalAddress();
-}
-
-SocketAddress AsyncTCPSocketBase::GetRemoteAddress() const {
- return socket_->GetRemoteAddress();
-}
-
-int AsyncTCPSocketBase::Close() {
- return socket_->Close();
-}
-
-AsyncTCPSocket::State AsyncTCPSocketBase::GetState() const {
- switch (socket_->GetState()) {
- case Socket::CS_CLOSED:
- return STATE_CLOSED;
- case Socket::CS_CONNECTING:
- if (listen_) {
- return STATE_BOUND;
- } else {
- return STATE_CONNECTING;
- }
- case Socket::CS_CONNECTED:
- return STATE_CONNECTED;
- default:
- ASSERT(false);
- return STATE_CLOSED;
- }
-}
-
-int AsyncTCPSocketBase::GetOption(Socket::Option opt, int* value) {
- return socket_->GetOption(opt, value);
-}
-
-int AsyncTCPSocketBase::SetOption(Socket::Option opt, int value) {
- return socket_->SetOption(opt, value);
-}
-
-int AsyncTCPSocketBase::GetError() const {
- return socket_->GetError();
-}
-
-void AsyncTCPSocketBase::SetError(int error) {
- return socket_->SetError(error);
-}
-
-int AsyncTCPSocketBase::SendTo(const void *pv, size_t cb,
- const SocketAddress& addr,
- const talk_base::PacketOptions& options) {
- if (addr == GetRemoteAddress())
- return Send(pv, cb, options);
-
- ASSERT(false);
- socket_->SetError(ENOTCONN);
- return -1;
-}
-
-int AsyncTCPSocketBase::SendRaw(const void * pv, size_t cb) {
- if (outpos_ + cb > outsize_) {
- socket_->SetError(EMSGSIZE);
- return -1;
- }
-
- memcpy(outbuf_ + outpos_, pv, cb);
- outpos_ += cb;
-
- return FlushOutBuffer();
-}
-
-int AsyncTCPSocketBase::FlushOutBuffer() {
- int res = socket_->Send(outbuf_, outpos_);
- if (res <= 0) {
- return res;
- }
- if (static_cast<size_t>(res) <= outpos_) {
- outpos_ -= res;
- } else {
- ASSERT(false);
- return -1;
- }
- if (outpos_ > 0) {
- memmove(outbuf_, outbuf_ + res, outpos_);
- }
- return res;
-}
-
-void AsyncTCPSocketBase::AppendToOutBuffer(const void* pv, size_t cb) {
- ASSERT(outpos_ + cb < outsize_);
- memcpy(outbuf_ + outpos_, pv, cb);
- outpos_ += cb;
-}
-
-void AsyncTCPSocketBase::OnConnectEvent(AsyncSocket* socket) {
- SignalConnect(this);
-}
-
-void AsyncTCPSocketBase::OnReadEvent(AsyncSocket* socket) {
- ASSERT(socket_.get() == socket);
-
- if (listen_) {
- talk_base::SocketAddress address;
- talk_base::AsyncSocket* new_socket = socket->Accept(&address);
- if (!new_socket) {
- // TODO: Do something better like forwarding the error
- // to the user.
- LOG(LS_ERROR) << "TCP accept failed with error " << socket_->GetError();
- return;
- }
-
- HandleIncomingConnection(new_socket);
-
- // Prime a read event in case data is waiting.
- new_socket->SignalReadEvent(new_socket);
- } else {
- int len = socket_->Recv(inbuf_ + inpos_, insize_ - inpos_);
- if (len < 0) {
- // TODO: Do something better like forwarding the error to the user.
- if (!socket_->IsBlocking()) {
- LOG(LS_ERROR) << "Recv() returned error: " << socket_->GetError();
- }
- return;
- }
-
- inpos_ += len;
-
- ProcessInput(inbuf_, &inpos_);
-
- if (inpos_ >= insize_) {
- LOG(LS_ERROR) << "input buffer overflow";
- ASSERT(false);
- inpos_ = 0;
- }
- }
-}
-
-void AsyncTCPSocketBase::OnWriteEvent(AsyncSocket* socket) {
- ASSERT(socket_.get() == socket);
-
- if (outpos_ > 0) {
- FlushOutBuffer();
- }
-
- if (outpos_ == 0) {
- SignalReadyToSend(this);
- }
-}
-
-void AsyncTCPSocketBase::OnCloseEvent(AsyncSocket* socket, int error) {
- SignalClose(this, error);
-}
-
-// AsyncTCPSocket
-// Binds and connects |socket| and creates AsyncTCPSocket for
-// it. Takes ownership of |socket|. Returns NULL if bind() or
-// connect() fail (|socket| is destroyed in that case).
-AsyncTCPSocket* AsyncTCPSocket::Create(
- AsyncSocket* socket,
- const SocketAddress& bind_address,
- const SocketAddress& remote_address) {
- return new AsyncTCPSocket(AsyncTCPSocketBase::ConnectSocket(
- socket, bind_address, remote_address), false);
-}
-
-AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket, bool listen)
- : AsyncTCPSocketBase(socket, listen, kBufSize) {
-}
-
-int AsyncTCPSocket::Send(const void *pv, size_t cb,
- const talk_base::PacketOptions& options) {
- if (cb > kBufSize) {
- SetError(EMSGSIZE);
- return -1;
- }
-
- // If we are blocking on send, then silently drop this packet
- if (!IsOutBufferEmpty())
- return static_cast<int>(cb);
-
- PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
- AppendToOutBuffer(&pkt_len, kPacketLenSize);
- AppendToOutBuffer(pv, cb);
-
- int res = FlushOutBuffer();
- if (res <= 0) {
- // drop packet if we made no progress
- ClearOutBuffer();
- return res;
- }
-
- // We claim to have sent the whole thing, even if we only sent partial
- return static_cast<int>(cb);
-}
-
-void AsyncTCPSocket::ProcessInput(char * data, size_t* len) {
- SocketAddress remote_addr(GetRemoteAddress());
-
- while (true) {
- if (*len < kPacketLenSize)
- return;
-
- PacketLength pkt_len = talk_base::GetBE16(data);
- if (*len < kPacketLenSize + pkt_len)
- return;
-
- SignalReadPacket(this, data + kPacketLenSize, pkt_len, remote_addr,
- CreatePacketTime(0));
-
- *len -= kPacketLenSize + pkt_len;
- if (*len > 0) {
- memmove(data, data + kPacketLenSize + pkt_len, *len);
- }
- }
-}
-
-void AsyncTCPSocket::HandleIncomingConnection(AsyncSocket* socket) {
- SignalNewConnection(this, new AsyncTCPSocket(socket, false));
-}
-
-} // namespace talk_base
diff --git a/base/asynctcpsocket.h b/base/asynctcpsocket.h
deleted file mode 100644
index 2b795f6..0000000
--- a/base/asynctcpsocket.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCTCPSOCKET_H_
-#define TALK_BASE_ASYNCTCPSOCKET_H_
-
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketfactory.h"
-
-namespace talk_base {
-
-// Simulates UDP semantics over TCP. Send and Recv packet sizes
-// are preserved, and drops packets silently on Send, rather than
-// buffer them in user space.
-class AsyncTCPSocketBase : public AsyncPacketSocket {
- public:
- AsyncTCPSocketBase(AsyncSocket* socket, bool listen, size_t max_packet_size);
- virtual ~AsyncTCPSocketBase();
-
- // Pure virtual methods to send and recv data.
- virtual int Send(const void *pv, size_t cb,
- const talk_base::PacketOptions& options) = 0;
- virtual void ProcessInput(char* data, size_t* len) = 0;
- // Signals incoming connection.
- virtual void HandleIncomingConnection(AsyncSocket* socket) = 0;
-
- virtual SocketAddress GetLocalAddress() const;
- virtual SocketAddress GetRemoteAddress() const;
- virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
- const talk_base::PacketOptions& options);
- virtual int Close();
-
- virtual State GetState() const;
- virtual int GetOption(Socket::Option opt, int* value);
- virtual int SetOption(Socket::Option opt, int value);
- virtual int GetError() const;
- virtual void SetError(int error);
-
- protected:
- // Binds and connects |socket| and creates AsyncTCPSocket for
- // it. Takes ownership of |socket|. Returns NULL if bind() or
- // connect() fail (|socket| is destroyed in that case).
- static AsyncSocket* ConnectSocket(AsyncSocket* socket,
- const SocketAddress& bind_address,
- const SocketAddress& remote_address);
- virtual int SendRaw(const void* pv, size_t cb);
- int FlushOutBuffer();
- // Add data to |outbuf_|.
- void AppendToOutBuffer(const void* pv, size_t cb);
-
- // Helper methods for |outpos_|.
- bool IsOutBufferEmpty() const { return outpos_ == 0; }
- void ClearOutBuffer() { outpos_ = 0; }
-
- private:
- // Called by the underlying socket
- void OnConnectEvent(AsyncSocket* socket);
- void OnReadEvent(AsyncSocket* socket);
- void OnWriteEvent(AsyncSocket* socket);
- void OnCloseEvent(AsyncSocket* socket, int error);
-
- scoped_ptr<AsyncSocket> socket_;
- bool listen_;
- char* inbuf_, * outbuf_;
- size_t insize_, inpos_, outsize_, outpos_;
-
- DISALLOW_EVIL_CONSTRUCTORS(AsyncTCPSocketBase);
-};
-
-class AsyncTCPSocket : public AsyncTCPSocketBase {
- public:
- // Binds and connects |socket| and creates AsyncTCPSocket for
- // it. Takes ownership of |socket|. Returns NULL if bind() or
- // connect() fail (|socket| is destroyed in that case).
- static AsyncTCPSocket* Create(AsyncSocket* socket,
- const SocketAddress& bind_address,
- const SocketAddress& remote_address);
- AsyncTCPSocket(AsyncSocket* socket, bool listen);
- virtual ~AsyncTCPSocket() {}
-
- virtual int Send(const void* pv, size_t cb,
- const talk_base::PacketOptions& options);
- virtual void ProcessInput(char* data, size_t* len);
- virtual void HandleIncomingConnection(AsyncSocket* socket);
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(AsyncTCPSocket);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ASYNCTCPSOCKET_H_
diff --git a/base/asynctcpsocket_unittest.cc b/base/asynctcpsocket_unittest.cc
deleted file mode 100644
index 4f87dbd..0000000
--- a/base/asynctcpsocket_unittest.cc
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/asynctcpsocket.h"
-#include "talk/base/gunit.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/virtualsocketserver.h"
-
-namespace talk_base {
-
-class AsyncTCPSocketTest
- : public testing::Test,
- public sigslot::has_slots<> {
- public:
- AsyncTCPSocketTest()
- : pss_(new talk_base::PhysicalSocketServer),
- vss_(new talk_base::VirtualSocketServer(pss_.get())),
- socket_(vss_->CreateAsyncSocket(SOCK_STREAM)),
- tcp_socket_(new AsyncTCPSocket(socket_, true)),
- ready_to_send_(false) {
- tcp_socket_->SignalReadyToSend.connect(this,
- &AsyncTCPSocketTest::OnReadyToSend);
- }
-
- void OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
- ready_to_send_ = true;
- }
-
- protected:
- scoped_ptr<PhysicalSocketServer> pss_;
- scoped_ptr<VirtualSocketServer> vss_;
- AsyncSocket* socket_;
- scoped_ptr<AsyncTCPSocket> tcp_socket_;
- bool ready_to_send_;
-};
-
-TEST_F(AsyncTCPSocketTest, OnWriteEvent) {
- EXPECT_FALSE(ready_to_send_);
- socket_->SignalWriteEvent(socket_);
- EXPECT_TRUE(ready_to_send_);
-}
-
-} // namespace talk_base
diff --git a/base/asyncudpsocket.cc b/base/asyncudpsocket.cc
deleted file mode 100644
index 367287f..0000000
--- a/base/asyncudpsocket.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-static const int BUF_SIZE = 64 * 1024;
-
-AsyncUDPSocket* AsyncUDPSocket::Create(
- AsyncSocket* socket,
- const SocketAddress& bind_address) {
- scoped_ptr<AsyncSocket> owned_socket(socket);
- if (socket->Bind(bind_address) < 0) {
- LOG(LS_ERROR) << "Bind() failed with error " << socket->GetError();
- return NULL;
- }
- return new AsyncUDPSocket(owned_socket.release());
-}
-
-AsyncUDPSocket* AsyncUDPSocket::Create(SocketFactory* factory,
- const SocketAddress& bind_address) {
- AsyncSocket* socket =
- factory->CreateAsyncSocket(bind_address.family(), SOCK_DGRAM);
- if (!socket)
- return NULL;
- return Create(socket, bind_address);
-}
-
-AsyncUDPSocket::AsyncUDPSocket(AsyncSocket* socket)
- : socket_(socket) {
- ASSERT(socket_);
- size_ = BUF_SIZE;
- buf_ = new char[size_];
-
- // The socket should start out readable but not writable.
- socket_->SignalReadEvent.connect(this, &AsyncUDPSocket::OnReadEvent);
- socket_->SignalWriteEvent.connect(this, &AsyncUDPSocket::OnWriteEvent);
-}
-
-AsyncUDPSocket::~AsyncUDPSocket() {
- delete [] buf_;
-}
-
-SocketAddress AsyncUDPSocket::GetLocalAddress() const {
- return socket_->GetLocalAddress();
-}
-
-SocketAddress AsyncUDPSocket::GetRemoteAddress() const {
- return socket_->GetRemoteAddress();
-}
-
-int AsyncUDPSocket::Send(const void *pv, size_t cb,
- const talk_base::PacketOptions& options) {
- return socket_->Send(pv, cb);
-}
-
-int AsyncUDPSocket::SendTo(const void *pv, size_t cb,
- const SocketAddress& addr,
- const talk_base::PacketOptions& options) {
- return socket_->SendTo(pv, cb, addr);
-}
-
-int AsyncUDPSocket::Close() {
- return socket_->Close();
-}
-
-AsyncUDPSocket::State AsyncUDPSocket::GetState() const {
- return STATE_BOUND;
-}
-
-int AsyncUDPSocket::GetOption(Socket::Option opt, int* value) {
- return socket_->GetOption(opt, value);
-}
-
-int AsyncUDPSocket::SetOption(Socket::Option opt, int value) {
- return socket_->SetOption(opt, value);
-}
-
-int AsyncUDPSocket::GetError() const {
- return socket_->GetError();
-}
-
-void AsyncUDPSocket::SetError(int error) {
- return socket_->SetError(error);
-}
-
-void AsyncUDPSocket::OnReadEvent(AsyncSocket* socket) {
- ASSERT(socket_.get() == socket);
-
- SocketAddress remote_addr;
- int len = socket_->RecvFrom(buf_, size_, &remote_addr);
- if (len < 0) {
- // An error here typically means we got an ICMP error in response to our
- // send datagram, indicating the remote address was unreachable.
- // When doing ICE, this kind of thing will often happen.
- // TODO: Do something better like forwarding the error to the user.
- SocketAddress local_addr = socket_->GetLocalAddress();
- LOG(LS_INFO) << "AsyncUDPSocket[" << local_addr.ToSensitiveString() << "] "
- << "receive failed with error " << socket_->GetError();
- return;
- }
-
- // TODO: Make sure that we got all of the packet.
- // If we did not, then we should resize our buffer to be large enough.
- SignalReadPacket(this, buf_, static_cast<size_t>(len), remote_addr,
- CreatePacketTime(0));
-}
-
-void AsyncUDPSocket::OnWriteEvent(AsyncSocket* socket) {
- SignalReadyToSend(this);
-}
-
-} // namespace talk_base
diff --git a/base/asyncudpsocket.h b/base/asyncudpsocket.h
deleted file mode 100644
index 17fb043..0000000
--- a/base/asyncudpsocket.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ASYNCUDPSOCKET_H_
-#define TALK_BASE_ASYNCUDPSOCKET_H_
-
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketfactory.h"
-
-namespace talk_base {
-
-// Provides the ability to receive packets asynchronously. Sends are not
-// buffered since it is acceptable to drop packets under high load.
-class AsyncUDPSocket : public AsyncPacketSocket {
- public:
- // Binds |socket| and creates AsyncUDPSocket for it. Takes ownership
- // of |socket|. Returns NULL if bind() fails (|socket| is destroyed
- // in that case).
- static AsyncUDPSocket* Create(AsyncSocket* socket,
- const SocketAddress& bind_address);
- // Creates a new socket for sending asynchronous UDP packets using an
- // asynchronous socket from the given factory.
- static AsyncUDPSocket* Create(SocketFactory* factory,
- const SocketAddress& bind_address);
- explicit AsyncUDPSocket(AsyncSocket* socket);
- virtual ~AsyncUDPSocket();
-
- virtual SocketAddress GetLocalAddress() const;
- virtual SocketAddress GetRemoteAddress() const;
- virtual int Send(const void *pv, size_t cb,
- const talk_base::PacketOptions& options);
- virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
- const talk_base::PacketOptions& options);
- virtual int Close();
-
- virtual State GetState() const;
- virtual int GetOption(Socket::Option opt, int* value);
- virtual int SetOption(Socket::Option opt, int value);
- virtual int GetError() const;
- virtual void SetError(int error);
-
- private:
- // Called when the underlying socket is ready to be read from.
- void OnReadEvent(AsyncSocket* socket);
- // Called when the underlying socket is ready to send.
- void OnWriteEvent(AsyncSocket* socket);
-
- scoped_ptr<AsyncSocket> socket_;
- char* buf_;
- size_t size_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ASYNCUDPSOCKET_H_
diff --git a/base/asyncudpsocket_unittest.cc b/base/asyncudpsocket_unittest.cc
deleted file mode 100644
index 562577a..0000000
--- a/base/asyncudpsocket_unittest.cc
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/gunit.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/virtualsocketserver.h"
-
-namespace talk_base {
-
-class AsyncUdpSocketTest
- : public testing::Test,
- public sigslot::has_slots<> {
- public:
- AsyncUdpSocketTest()
- : pss_(new talk_base::PhysicalSocketServer),
- vss_(new talk_base::VirtualSocketServer(pss_.get())),
- socket_(vss_->CreateAsyncSocket(SOCK_DGRAM)),
- udp_socket_(new AsyncUDPSocket(socket_)),
- ready_to_send_(false) {
- udp_socket_->SignalReadyToSend.connect(this,
- &AsyncUdpSocketTest::OnReadyToSend);
- }
-
- void OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
- ready_to_send_ = true;
- }
-
- protected:
- scoped_ptr<PhysicalSocketServer> pss_;
- scoped_ptr<VirtualSocketServer> vss_;
- AsyncSocket* socket_;
- scoped_ptr<AsyncUDPSocket> udp_socket_;
- bool ready_to_send_;
-};
-
-TEST_F(AsyncUdpSocketTest, OnWriteEvent) {
- EXPECT_FALSE(ready_to_send_);
- socket_->SignalWriteEvent(socket_);
- EXPECT_TRUE(ready_to_send_);
-}
-
-} // namespace talk_base
diff --git a/base/atomicops.h b/base/atomicops.h
deleted file mode 100644
index 068cd5f..0000000
--- a/base/atomicops.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ATOMICOPS_H_
-#define TALK_BASE_ATOMICOPS_H_
-
-#include <string>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-// A single-producer, single-consumer, fixed-size queue.
-// All methods not ending in Unsafe can be safely called without locking,
-// provided that calls to consumer methods (Peek/Pop) or producer methods (Push)
-// only happen on a single thread per method type. If multiple threads need to
-// read simultaneously or write simultaneously, other synchronization is
-// necessary. Synchronization is also required if a call into any Unsafe method
-// could happen at the same time as a call to any other method.
-template <typename T>
-class FixedSizeLockFreeQueue {
- private:
-// Atomic primitives and memory barrier
-#if defined(__arm__)
- typedef uint32 Atomic32;
-
- // Copied from google3/base/atomicops-internals-arm-v6plus.h
- static inline void MemoryBarrier() {
- asm volatile("dmb":::"memory");
- }
-
- // Adapted from google3/base/atomicops-internals-arm-v6plus.h
- static inline void AtomicIncrement(volatile Atomic32* ptr) {
- Atomic32 str_success, value;
- asm volatile (
- "1:\n"
- "ldrex %1, [%2]\n"
- "add %1, %1, #1\n"
- "strex %0, %1, [%2]\n"
- "teq %0, #0\n"
- "bne 1b"
- : "=&r"(str_success), "=&r"(value)
- : "r" (ptr)
- : "cc", "memory");
- }
-#elif !defined(SKIP_ATOMIC_CHECK)
-#error "No atomic operations defined for the given architecture."
-#endif
-
- public:
- // Constructs an empty queue, with capacity 0.
- FixedSizeLockFreeQueue() : pushed_count_(0),
- popped_count_(0),
- capacity_(0),
- data_() {}
- // Constructs an empty queue with the given capacity.
- FixedSizeLockFreeQueue(size_t capacity) : pushed_count_(0),
- popped_count_(0),
- capacity_(capacity),
- data_(new T[capacity]) {}
-
- // Pushes a value onto the queue. Returns true if the value was successfully
- // pushed (there was space in the queue). This method can be safely called at
- // the same time as PeekFront/PopFront.
- bool PushBack(T value) {
- if (capacity_ == 0) {
- LOG(LS_WARNING) << "Queue capacity is 0.";
- return false;
- }
- if (IsFull()) {
- return false;
- }
-
- data_[pushed_count_ % capacity_] = value;
- // Make sure the data is written before the count is incremented, so other
- // threads can't see the value exists before being able to read it.
- MemoryBarrier();
- AtomicIncrement(&pushed_count_);
- return true;
- }
-
- // Retrieves the oldest value pushed onto the queue. Returns true if there was
- // an item to peek (the queue was non-empty). This method can be safely called
- // at the same time as PushBack.
- bool PeekFront(T* value_out) {
- if (capacity_ == 0) {
- LOG(LS_WARNING) << "Queue capacity is 0.";
- return false;
- }
- if (IsEmpty()) {
- return false;
- }
-
- *value_out = data_[popped_count_ % capacity_];
- return true;
- }
-
- // Retrieves the oldest value pushed onto the queue and removes it from the
- // queue. Returns true if there was an item to pop (the queue was non-empty).
- // This method can be safely called at the same time as PushBack.
- bool PopFront(T* value_out) {
- if (PeekFront(value_out)) {
- AtomicIncrement(&popped_count_);
- return true;
- }
- return false;
- }
-
- // Clears the current items in the queue and sets the new (fixed) size. This
- // method cannot be called at the same time as any other method.
- void ClearAndResizeUnsafe(int new_capacity) {
- capacity_ = new_capacity;
- data_.reset(new T[new_capacity]);
- pushed_count_ = 0;
- popped_count_ = 0;
- }
-
- // Returns true if there is no space left in the queue for new elements.
- int IsFull() const { return pushed_count_ == popped_count_ + capacity_; }
- // Returns true if there are no elements in the queue.
- int IsEmpty() const { return pushed_count_ == popped_count_; }
- // Returns the current number of elements in the queue. This is always in the
- // range [0, capacity]
- size_t Size() const { return pushed_count_ - popped_count_; }
-
- // Returns the capacity of the queue (max size).
- size_t capacity() const { return capacity_; }
-
- private:
- volatile Atomic32 pushed_count_;
- volatile Atomic32 popped_count_;
- size_t capacity_;
- talk_base::scoped_ptr<T[]> data_;
- DISALLOW_COPY_AND_ASSIGN(FixedSizeLockFreeQueue);
-};
-
-}
-
-#endif // TALK_BASE_ATOMICOPS_H_
diff --git a/base/atomicops_unittest.cc b/base/atomicops_unittest.cc
deleted file mode 100644
index 24804c6..0000000
--- a/base/atomicops_unittest.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if !defined(__arm__)
-// For testing purposes, define faked versions of the atomic operations
-#include "talk/base/basictypes.h"
-namespace talk_base {
-typedef uint32 Atomic32;
-static inline void MemoryBarrier() { }
-static inline void AtomicIncrement(volatile Atomic32* ptr) {
- *ptr = *ptr + 1;
-}
-}
-#define SKIP_ATOMIC_CHECK
-#endif
-
-#include "talk/base/atomicops.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-
-TEST(FixedSizeLockFreeQueueTest, TestDefaultConstruct) {
- talk_base::FixedSizeLockFreeQueue<int> queue;
- EXPECT_EQ(0u, queue.capacity());
- EXPECT_EQ(0u, queue.Size());
- EXPECT_FALSE(queue.PushBack(1));
- int val;
- EXPECT_FALSE(queue.PopFront(&val));
-}
-
-TEST(FixedSizeLockFreeQueueTest, TestConstruct) {
- talk_base::FixedSizeLockFreeQueue<int> queue(5);
- EXPECT_EQ(5u, queue.capacity());
- EXPECT_EQ(0u, queue.Size());
- int val;
- EXPECT_FALSE(queue.PopFront(&val));
-}
-
-TEST(FixedSizeLockFreeQueueTest, TestPushPop) {
- talk_base::FixedSizeLockFreeQueue<int> queue(2);
- EXPECT_EQ(2u, queue.capacity());
- EXPECT_EQ(0u, queue.Size());
- EXPECT_TRUE(queue.PushBack(1));
- EXPECT_EQ(1u, queue.Size());
- EXPECT_TRUE(queue.PushBack(2));
- EXPECT_EQ(2u, queue.Size());
- EXPECT_FALSE(queue.PushBack(3));
- EXPECT_EQ(2u, queue.Size());
- int val;
- EXPECT_TRUE(queue.PopFront(&val));
- EXPECT_EQ(1, val);
- EXPECT_EQ(1u, queue.Size());
- EXPECT_TRUE(queue.PopFront(&val));
- EXPECT_EQ(2, val);
- EXPECT_EQ(0u, queue.Size());
- EXPECT_FALSE(queue.PopFront(&val));
- EXPECT_EQ(0u, queue.Size());
-}
-
-TEST(FixedSizeLockFreeQueueTest, TestResize) {
- talk_base::FixedSizeLockFreeQueue<int> queue(2);
- EXPECT_EQ(2u, queue.capacity());
- EXPECT_EQ(0u, queue.Size());
- EXPECT_TRUE(queue.PushBack(1));
- EXPECT_EQ(1u, queue.Size());
-
- queue.ClearAndResizeUnsafe(5);
- EXPECT_EQ(5u, queue.capacity());
- EXPECT_EQ(0u, queue.Size());
- int val;
- EXPECT_FALSE(queue.PopFront(&val));
-}
diff --git a/base/autodetectproxy.cc b/base/autodetectproxy.cc
deleted file mode 100644
index a32043c..0000000
--- a/base/autodetectproxy.cc
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/autodetectproxy.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/httpcommon-inl.h"
-#include "talk/base/nethelpers.h"
-
-namespace talk_base {
-
-static const ProxyType TEST_ORDER[] = {
- PROXY_HTTPS, PROXY_SOCKS5, PROXY_UNKNOWN
-};
-
-static const int kSavedStringLimit = 128;
-
-static void SaveStringToStack(char *dst,
- const std::string &src,
- size_t dst_size) {
- strncpy(dst, src.c_str(), dst_size - 1);
- dst[dst_size - 1] = '\0';
-}
-
-AutoDetectProxy::AutoDetectProxy(const std::string& user_agent)
- : agent_(user_agent), resolver_(NULL), socket_(NULL), next_(0) {
-}
-
-AutoDetectProxy::~AutoDetectProxy() {
- if (resolver_) {
- resolver_->Destroy(false);
- }
-}
-
-void AutoDetectProxy::DoWork() {
- // TODO: Try connecting to server_url without proxy first here?
- if (!server_url_.empty()) {
- LOG(LS_INFO) << "GetProxySettingsForUrl(" << server_url_ << ") - start";
- GetProxyForUrl(agent_.c_str(), server_url_.c_str(), &proxy_);
- LOG(LS_INFO) << "GetProxySettingsForUrl - stop";
- }
- Url<char> url(proxy_.address.HostAsURIString());
- if (url.valid()) {
- LOG(LS_WARNING) << "AutoDetectProxy removing http prefix on proxy host";
- proxy_.address.SetIP(url.host());
- }
- LOG(LS_INFO) << "AutoDetectProxy found proxy at " << proxy_.address;
- if (proxy_.type == PROXY_UNKNOWN) {
- LOG(LS_INFO) << "AutoDetectProxy initiating proxy classification";
- Next();
- // Process I/O until Stop()
- Thread::Current()->ProcessMessages(kForever);
- // Clean up the autodetect socket, from the thread that created it
- delete socket_;
- }
- // TODO: If we found a proxy, try to use it to verify that it
- // works by sending a request to server_url. This could either be
- // done here or by the HttpPortAllocator.
-}
-
-void AutoDetectProxy::OnMessage(Message *msg) {
- if (MSG_UNRESOLVABLE == msg->message_id) {
- // If we can't resolve the proxy, skip straight to failure.
- Complete(PROXY_UNKNOWN);
- } else if (MSG_TIMEOUT == msg->message_id) {
- OnCloseEvent(socket_, ETIMEDOUT);
- } else {
- // This must be the ST_MSG_WORKER_DONE message that deletes the
- // AutoDetectProxy object. We have observed crashes within this stack that
- // seem to be highly reproducible for a small subset of users and thus are
- // probably correlated with a specific proxy setting, so copy potentially
- // relevant information onto the stack to make it available in Windows
- // minidumps.
-
- // Save the user agent and the number of auto-detection passes that we
- // needed.
- char agent[kSavedStringLimit];
- SaveStringToStack(agent, agent_, sizeof agent);
-
- int next = next_;
-
- // Now the detected proxy config (minus the password field, which could be
- // sensitive).
- ProxyType type = proxy().type;
-
- char address_hostname[kSavedStringLimit];
- SaveStringToStack(address_hostname,
- proxy().address.hostname(),
- sizeof address_hostname);
-
- IPAddress address_ip = proxy().address.ipaddr();
-
- uint16 address_port = proxy().address.port();
-
- char autoconfig_url[kSavedStringLimit];
- SaveStringToStack(autoconfig_url,
- proxy().autoconfig_url,
- sizeof autoconfig_url);
-
- bool autodetect = proxy().autodetect;
-
- char bypass_list[kSavedStringLimit];
- SaveStringToStack(bypass_list, proxy().bypass_list, sizeof bypass_list);
-
- char username[kSavedStringLimit];
- SaveStringToStack(username, proxy().username, sizeof username);
-
- SignalThread::OnMessage(msg);
-
- // Log the gathered data at a log level that will never actually be enabled
- // so that the compiler is forced to retain the data on the stack.
- LOG(LS_SENSITIVE) << agent << " " << next << " " << type << " "
- << address_hostname << " " << address_ip << " "
- << address_port << " " << autoconfig_url << " "
- << autodetect << " " << bypass_list << " " << username;
- }
-}
-
-void AutoDetectProxy::OnResolveResult(AsyncResolverInterface* resolver) {
- if (resolver != resolver_) {
- return;
- }
- int error = resolver_->GetError();
- if (error == 0) {
- LOG(LS_VERBOSE) << "Resolved " << proxy_.address << " to "
- << resolver_->address();
- proxy_.address = resolver_->address();
- if (!DoConnect()) {
- Thread::Current()->Post(this, MSG_TIMEOUT);
- }
- } else {
- LOG(LS_INFO) << "Failed to resolve " << resolver_->address();
- resolver_->Destroy(false);
- resolver_ = NULL;
- proxy_.address = SocketAddress();
- Thread::Current()->Post(this, MSG_UNRESOLVABLE);
- }
-}
-
-void AutoDetectProxy::Next() {
- if (TEST_ORDER[next_] >= PROXY_UNKNOWN) {
- Complete(PROXY_UNKNOWN);
- return;
- }
-
- LOG(LS_VERBOSE) << "AutoDetectProxy connecting to "
- << proxy_.address.ToSensitiveString();
-
- if (socket_) {
- Thread::Current()->Clear(this, MSG_TIMEOUT);
- Thread::Current()->Clear(this, MSG_UNRESOLVABLE);
- socket_->Close();
- Thread::Current()->Dispose(socket_);
- socket_ = NULL;
- }
- int timeout = 2000;
- if (proxy_.address.IsUnresolvedIP()) {
- // Launch an asyncresolver. This thread will spin waiting for it.
- timeout += 2000;
- if (!resolver_) {
- resolver_ = new AsyncResolver();
- }
- resolver_->SignalDone.connect(this, &AutoDetectProxy::OnResolveResult);
- resolver_->Start(proxy_.address);
- } else {
- if (!DoConnect()) {
- Thread::Current()->Post(this, MSG_TIMEOUT);
- return;
- }
- }
- Thread::Current()->PostDelayed(timeout, this, MSG_TIMEOUT);
-}
-
-bool AutoDetectProxy::DoConnect() {
- if (resolver_) {
- resolver_->Destroy(false);
- resolver_ = NULL;
- }
- socket_ =
- Thread::Current()->socketserver()->CreateAsyncSocket(
- proxy_.address.family(), SOCK_STREAM);
- if (!socket_) {
- LOG(LS_VERBOSE) << "Unable to create socket for " << proxy_.address;
- return false;
- }
- socket_->SignalConnectEvent.connect(this, &AutoDetectProxy::OnConnectEvent);
- socket_->SignalReadEvent.connect(this, &AutoDetectProxy::OnReadEvent);
- socket_->SignalCloseEvent.connect(this, &AutoDetectProxy::OnCloseEvent);
- socket_->Connect(proxy_.address);
- return true;
-}
-
-void AutoDetectProxy::Complete(ProxyType type) {
- Thread::Current()->Clear(this, MSG_TIMEOUT);
- Thread::Current()->Clear(this, MSG_UNRESOLVABLE);
- if (socket_) {
- socket_->Close();
- }
-
- proxy_.type = type;
- LoggingSeverity sev = (proxy_.type == PROXY_UNKNOWN) ? LS_ERROR : LS_INFO;
- LOG_V(sev) << "AutoDetectProxy detected "
- << proxy_.address.ToSensitiveString()
- << " as type " << proxy_.type;
-
- Thread::Current()->Quit();
-}
-
-void AutoDetectProxy::OnConnectEvent(AsyncSocket * socket) {
- std::string probe;
-
- switch (TEST_ORDER[next_]) {
- case PROXY_HTTPS:
- probe.assign("CONNECT www.google.com:443 HTTP/1.0\r\n"
- "User-Agent: ");
- probe.append(agent_);
- probe.append("\r\n"
- "Host: www.google.com\r\n"
- "Content-Length: 0\r\n"
- "Proxy-Connection: Keep-Alive\r\n"
- "\r\n");
- break;
- case PROXY_SOCKS5:
- probe.assign("\005\001\000", 3);
- break;
- default:
- ASSERT(false);
- return;
- }
-
- LOG(LS_VERBOSE) << "AutoDetectProxy probing type " << TEST_ORDER[next_]
- << " sending " << probe.size() << " bytes";
- socket_->Send(probe.data(), probe.size());
-}
-
-void AutoDetectProxy::OnReadEvent(AsyncSocket * socket) {
- char data[257];
- int len = socket_->Recv(data, 256);
- if (len > 0) {
- data[len] = 0;
- LOG(LS_VERBOSE) << "AutoDetectProxy read " << len << " bytes";
- }
-
- switch (TEST_ORDER[next_]) {
- case PROXY_HTTPS:
- if ((len >= 2) && (data[0] == '\x05')) {
- Complete(PROXY_SOCKS5);
- return;
- }
- if ((len >= 5) && (strncmp(data, "HTTP/", 5) == 0)) {
- Complete(PROXY_HTTPS);
- return;
- }
- break;
- case PROXY_SOCKS5:
- if ((len >= 2) && (data[0] == '\x05')) {
- Complete(PROXY_SOCKS5);
- return;
- }
- break;
- default:
- ASSERT(false);
- return;
- }
-
- ++next_;
- Next();
-}
-
-void AutoDetectProxy::OnCloseEvent(AsyncSocket * socket, int error) {
- LOG(LS_VERBOSE) << "AutoDetectProxy closed with error: " << error;
- ++next_;
- Next();
-}
-
-} // namespace talk_base
diff --git a/base/autodetectproxy.h b/base/autodetectproxy.h
deleted file mode 100644
index 2cbeb82..0000000
--- a/base/autodetectproxy.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_AUTODETECTPROXY_H_
-#define TALK_BASE_AUTODETECTPROXY_H_
-
-#include <string>
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/cryptstring.h"
-#include "talk/base/proxydetect.h"
-#include "talk/base/proxyinfo.h"
-#include "talk/base/signalthread.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// AutoDetectProxy
-///////////////////////////////////////////////////////////////////////////////
-
-class AsyncResolverInterface;
-class AsyncSocket;
-
-class AutoDetectProxy : public SignalThread {
- public:
- explicit AutoDetectProxy(const std::string& user_agent);
-
- const ProxyInfo& proxy() const { return proxy_; }
-
- void set_server_url(const std::string& url) {
- server_url_ = url;
- }
- void set_proxy(const SocketAddress& proxy) {
- proxy_.type = PROXY_UNKNOWN;
- proxy_.address = proxy;
- }
- void set_auth_info(bool use_auth, const std::string& username,
- const CryptString& password) {
- if (use_auth) {
- proxy_.username = username;
- proxy_.password = password;
- }
- }
- // Default implementation of GetProxySettingsForUrl. Override for special
- // implementation.
- virtual bool GetProxyForUrl(const char* agent, const char* url,
- talk_base::ProxyInfo* proxy) {
- return GetProxySettingsForUrl(agent, url, proxy, true);
- }
- enum { MSG_TIMEOUT = SignalThread::ST_MSG_FIRST_AVAILABLE,
- MSG_UNRESOLVABLE,
- ADP_MSG_FIRST_AVAILABLE};
-
- protected:
- virtual ~AutoDetectProxy();
-
- // SignalThread Interface
- virtual void DoWork();
- virtual void OnMessage(Message *msg);
-
- void Next();
- void Complete(ProxyType type);
-
- void OnConnectEvent(AsyncSocket * socket);
- void OnReadEvent(AsyncSocket * socket);
- void OnCloseEvent(AsyncSocket * socket, int error);
- void OnResolveResult(AsyncResolverInterface* resolver);
- bool DoConnect();
-
- private:
- std::string agent_;
- std::string server_url_;
- ProxyInfo proxy_;
- AsyncResolverInterface* resolver_;
- AsyncSocket* socket_;
- int next_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(AutoDetectProxy);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_AUTODETECTPROXY_H_
diff --git a/base/autodetectproxy_unittest.cc b/base/autodetectproxy_unittest.cc
deleted file mode 100644
index 18241a3..0000000
--- a/base/autodetectproxy_unittest.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/autodetectproxy.h"
-#include "talk/base/gunit.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/httpcommon-inl.h"
-
-namespace talk_base {
-
-static const char kUserAgent[] = "";
-static const char kPath[] = "/";
-static const char kHost[] = "relay.google.com";
-static const uint16 kPort = 443;
-static const bool kSecure = true;
-// At most, AutoDetectProxy should take ~6 seconds. Each connect step is
-// allotted 2 seconds, with the initial resolution + connect given an
-// extra 2 seconds. The slowest case is:
-// 1) Resolution + HTTPS takes full 4 seconds and fails (but resolution
-// succeeds).
-// 2) SOCKS5 takes the full 2 seconds.
-// Socket creation time seems unbounded, and has been observed to take >1 second
-// on a linux machine under load. As such, we allow for 10 seconds for timeout,
-// though could still end up with some flakiness.
-static const int kTimeoutMs = 10000;
-
-class AutoDetectProxyTest : public testing::Test, public sigslot::has_slots<> {
- public:
- AutoDetectProxyTest() : auto_detect_proxy_(NULL), done_(false) {}
-
- protected:
- bool Create(const std::string &user_agent,
- const std::string &path,
- const std::string &host,
- uint16 port,
- bool secure,
- bool startnow) {
- auto_detect_proxy_ = new AutoDetectProxy(user_agent);
- EXPECT_TRUE(auto_detect_proxy_ != NULL);
- if (!auto_detect_proxy_) {
- return false;
- }
- Url<char> host_url(path, host, port);
- host_url.set_secure(secure);
- auto_detect_proxy_->set_server_url(host_url.url());
- auto_detect_proxy_->SignalWorkDone.connect(
- this,
- &AutoDetectProxyTest::OnWorkDone);
- if (startnow) {
- auto_detect_proxy_->Start();
- }
- return true;
- }
-
- bool Run(int timeout_ms) {
- EXPECT_TRUE_WAIT(done_, timeout_ms);
- return done_;
- }
-
- void SetProxy(const SocketAddress& proxy) {
- auto_detect_proxy_->set_proxy(proxy);
- }
-
- void Start() {
- auto_detect_proxy_->Start();
- }
-
- void TestCopesWithProxy(const SocketAddress& proxy) {
- // Tests that at least autodetect doesn't crash for a given proxy address.
- ASSERT_TRUE(Create(kUserAgent,
- kPath,
- kHost,
- kPort,
- kSecure,
- false));
- SetProxy(proxy);
- Start();
- ASSERT_TRUE(Run(kTimeoutMs));
- }
-
- private:
- void OnWorkDone(talk_base::SignalThread *thread) {
- AutoDetectProxy *auto_detect_proxy =
- static_cast<talk_base::AutoDetectProxy *>(thread);
- EXPECT_TRUE(auto_detect_proxy == auto_detect_proxy_);
- auto_detect_proxy_ = NULL;
- auto_detect_proxy->Release();
- done_ = true;
- }
-
- AutoDetectProxy *auto_detect_proxy_;
- bool done_;
-};
-
-TEST_F(AutoDetectProxyTest, TestDetectUnresolvedProxy) {
- TestCopesWithProxy(talk_base::SocketAddress("localhost", 9999));
-}
-
-TEST_F(AutoDetectProxyTest, TestDetectUnresolvableProxy) {
- TestCopesWithProxy(talk_base::SocketAddress("invalid", 9999));
-}
-
-TEST_F(AutoDetectProxyTest, TestDetectIPv6Proxy) {
- TestCopesWithProxy(talk_base::SocketAddress("::1", 9999));
-}
-
-TEST_F(AutoDetectProxyTest, TestDetectIPv4Proxy) {
- TestCopesWithProxy(talk_base::SocketAddress("127.0.0.1", 9999));
-}
-
-// Test that proxy detection completes successfully. (Does not actually verify
-// the correct detection result since we don't know what proxy to expect on an
-// arbitrary machine.)
-TEST_F(AutoDetectProxyTest, TestProxyDetection) {
- ASSERT_TRUE(Create(kUserAgent,
- kPath,
- kHost,
- kPort,
- kSecure,
- true));
- ASSERT_TRUE(Run(kTimeoutMs));
-}
-
-} // namespace talk_base
diff --git a/base/bandwidthsmoother.cc b/base/bandwidthsmoother.cc
deleted file mode 100644
index edb4eda..0000000
--- a/base/bandwidthsmoother.cc
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/bandwidthsmoother.h"
-
-#include <limits.h>
-
-namespace talk_base {
-
-BandwidthSmoother::BandwidthSmoother(int initial_bandwidth_guess,
- uint32 time_between_increase,
- double percent_increase,
- size_t samples_count_to_average,
- double min_sample_count_percent)
- : time_between_increase_(time_between_increase),
- percent_increase_(talk_base::_max(1.0, percent_increase)),
- time_at_last_change_(0),
- bandwidth_estimation_(initial_bandwidth_guess),
- accumulator_(samples_count_to_average),
- min_sample_count_percent_(
- talk_base::_min(1.0,
- talk_base::_max(0.0, min_sample_count_percent))) {
-}
-
-// Samples a new bandwidth measurement
-// returns true if the bandwidth estimation changed
-bool BandwidthSmoother::Sample(uint32 sample_time, int bandwidth) {
- if (bandwidth < 0) {
- return false;
- }
-
- accumulator_.AddSample(bandwidth);
-
- if (accumulator_.count() < static_cast<size_t>(
- accumulator_.max_count() * min_sample_count_percent_)) {
- // We have not collected enough samples yet.
- return false;
- }
-
- // Replace bandwidth with the mean of sampled bandwidths.
- const int mean_bandwidth = static_cast<int>(accumulator_.ComputeMean());
-
- if (mean_bandwidth < bandwidth_estimation_) {
- time_at_last_change_ = sample_time;
- bandwidth_estimation_ = mean_bandwidth;
- return true;
- }
-
- const int old_bandwidth_estimation = bandwidth_estimation_;
- const double increase_threshold_d = percent_increase_ * bandwidth_estimation_;
- if (increase_threshold_d > INT_MAX) {
- // If bandwidth goes any higher we would overflow.
- return false;
- }
-
- const int increase_threshold = static_cast<int>(increase_threshold_d);
- if (mean_bandwidth < increase_threshold) {
- time_at_last_change_ = sample_time;
- // The value of bandwidth_estimation remains the same if we don't exceed
- // percent_increase_ * bandwidth_estimation_ for at least
- // time_between_increase_ time.
- } else if (sample_time >= time_at_last_change_ + time_between_increase_) {
- time_at_last_change_ = sample_time;
- if (increase_threshold == 0) {
- // Bandwidth_estimation_ must be zero. Assume a jump from zero to a
- // positive bandwidth means we have regained connectivity.
- bandwidth_estimation_ = mean_bandwidth;
- } else {
- bandwidth_estimation_ = increase_threshold;
- }
- }
- // Else don't make a change.
-
- return old_bandwidth_estimation != bandwidth_estimation_;
-}
-
-} // namespace talk_base
diff --git a/base/bandwidthsmoother.h b/base/bandwidthsmoother.h
deleted file mode 100644
index f63a0f5..0000000
--- a/base/bandwidthsmoother.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_BANDWIDTHSMOOTHER_H_
-#define TALK_BASE_BANDWIDTHSMOOTHER_H_
-
-#include "talk/base/rollingaccumulator.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-// The purpose of BandwidthSmoother is to smooth out bandwidth
-// estimations so that 'trstate' messages can be triggered when we
-// are "sure" there is sufficient bandwidth. To avoid frequent fluctuations,
-// we take a slightly pessimistic view of our bandwidth. We only increase
-// our estimation when we have sampled bandwidth measurements of values
-// at least as large as the current estimation * percent_increase
-// for at least time_between_increase time. If a sampled bandwidth
-// is less than our current estimation we immediately decrease our estimation
-// to that sampled value.
-// We retain the initial bandwidth guess as our current bandwidth estimation
-// until we have received (min_sample_count_percent * samples_count_to_average)
-// number of samples. Min_sample_count_percent must be in range [0, 1].
-class BandwidthSmoother {
- public:
- BandwidthSmoother(int initial_bandwidth_guess,
- uint32 time_between_increase,
- double percent_increase,
- size_t samples_count_to_average,
- double min_sample_count_percent);
-
- // Samples a new bandwidth measurement.
- // bandwidth is expected to be non-negative.
- // returns true if the bandwidth estimation changed
- bool Sample(uint32 sample_time, int bandwidth);
-
- int get_bandwidth_estimation() const {
- return bandwidth_estimation_;
- }
-
- private:
- uint32 time_between_increase_;
- double percent_increase_;
- uint32 time_at_last_change_;
- int bandwidth_estimation_;
- RollingAccumulator<int> accumulator_;
- double min_sample_count_percent_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_BANDWIDTHSMOOTHER_H_
diff --git a/base/bandwidthsmoother_unittest.cc b/base/bandwidthsmoother_unittest.cc
deleted file mode 100644
index 3ba846f..0000000
--- a/base/bandwidthsmoother_unittest.cc
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <limits.h>
-
-#include "talk/base/bandwidthsmoother.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-static const int kTimeBetweenIncrease = 10;
-static const double kPercentIncrease = 1.1;
-static const size_t kSamplesCountToAverage = 2;
-static const double kMinSampleCountPercent = 1.0;
-
-TEST(BandwidthSmootherTest, TestSampleIncrease) {
- BandwidthSmoother mon(1000, // initial_bandwidth_guess
- kTimeBetweenIncrease,
- kPercentIncrease,
- kSamplesCountToAverage,
- kMinSampleCountPercent);
-
- int bandwidth_sample = 1000;
- EXPECT_EQ(bandwidth_sample, mon.get_bandwidth_estimation());
- bandwidth_sample =
- static_cast<int>(bandwidth_sample * kPercentIncrease);
- EXPECT_FALSE(mon.Sample(9, bandwidth_sample));
- EXPECT_TRUE(mon.Sample(10, bandwidth_sample));
- EXPECT_EQ(bandwidth_sample, mon.get_bandwidth_estimation());
- int next_expected_est =
- static_cast<int>(bandwidth_sample * kPercentIncrease);
- bandwidth_sample *= 2;
- EXPECT_TRUE(mon.Sample(20, bandwidth_sample));
- EXPECT_EQ(next_expected_est, mon.get_bandwidth_estimation());
-}
-
-TEST(BandwidthSmootherTest, TestSampleIncreaseFromZero) {
- BandwidthSmoother mon(0, // initial_bandwidth_guess
- kTimeBetweenIncrease,
- kPercentIncrease,
- kSamplesCountToAverage,
- kMinSampleCountPercent);
-
- const int kBandwidthSample = 1000;
- EXPECT_EQ(0, mon.get_bandwidth_estimation());
- EXPECT_FALSE(mon.Sample(9, kBandwidthSample));
- EXPECT_TRUE(mon.Sample(10, kBandwidthSample));
- EXPECT_EQ(kBandwidthSample, mon.get_bandwidth_estimation());
-}
-
-TEST(BandwidthSmootherTest, TestSampleDecrease) {
- BandwidthSmoother mon(1000, // initial_bandwidth_guess
- kTimeBetweenIncrease,
- kPercentIncrease,
- kSamplesCountToAverage,
- kMinSampleCountPercent);
-
- const int kBandwidthSample = 999;
- EXPECT_EQ(1000, mon.get_bandwidth_estimation());
- EXPECT_FALSE(mon.Sample(1, kBandwidthSample));
- EXPECT_EQ(1000, mon.get_bandwidth_estimation());
- EXPECT_TRUE(mon.Sample(2, kBandwidthSample));
- EXPECT_EQ(kBandwidthSample, mon.get_bandwidth_estimation());
-}
-
-TEST(BandwidthSmootherTest, TestSampleTooFewSamples) {
- BandwidthSmoother mon(1000, // initial_bandwidth_guess
- kTimeBetweenIncrease,
- kPercentIncrease,
- 10, // 10 samples.
- 0.5); // 5 min samples.
-
- const int kBandwidthSample = 500;
- EXPECT_EQ(1000, mon.get_bandwidth_estimation());
- EXPECT_FALSE(mon.Sample(1, kBandwidthSample));
- EXPECT_FALSE(mon.Sample(2, kBandwidthSample));
- EXPECT_FALSE(mon.Sample(3, kBandwidthSample));
- EXPECT_FALSE(mon.Sample(4, kBandwidthSample));
- EXPECT_EQ(1000, mon.get_bandwidth_estimation());
- EXPECT_TRUE(mon.Sample(5, kBandwidthSample));
- EXPECT_EQ(kBandwidthSample, mon.get_bandwidth_estimation());
-}
-
-TEST(BandwidthSmootherTest, TestSampleRollover) {
- const int kHugeBandwidth = 2000000000; // > INT_MAX/1.1
- BandwidthSmoother mon(kHugeBandwidth,
- kTimeBetweenIncrease,
- kPercentIncrease,
- kSamplesCountToAverage,
- kMinSampleCountPercent);
-
- EXPECT_FALSE(mon.Sample(10, INT_MAX));
- EXPECT_FALSE(mon.Sample(11, INT_MAX));
- EXPECT_EQ(kHugeBandwidth, mon.get_bandwidth_estimation());
-}
-
-TEST(BandwidthSmootherTest, TestSampleNegative) {
- BandwidthSmoother mon(1000, // initial_bandwidth_guess
- kTimeBetweenIncrease,
- kPercentIncrease,
- kSamplesCountToAverage,
- kMinSampleCountPercent);
-
- EXPECT_FALSE(mon.Sample(10, -1));
- EXPECT_FALSE(mon.Sample(11, -1));
- EXPECT_EQ(1000, mon.get_bandwidth_estimation());
-}
-
-} // namespace talk_base
diff --git a/base/base64.cc b/base/base64.cc
deleted file mode 100644
index 79b045e..0000000
--- a/base/base64.cc
+++ /dev/null
@@ -1,260 +0,0 @@
-
-//*********************************************************************
-//* Base64 - a simple base64 encoder and decoder.
-//*
-//* Copyright (c) 1999, Bob Withers - bwit@pobox.com
-//*
-//* This code may be freely used for any purpose, either personal
-//* or commercial, provided the authors copyright notice remains
-//* intact.
-//*
-//* Enhancements by Stanley Yamane:
-//* o reverse lookup table for the decode function
-//* o reserve string buffer space in advance
-//*
-//*********************************************************************
-
-#include "talk/base/base64.h"
-
-#include <string.h>
-
-#include "talk/base/common.h"
-
-using std::vector;
-
-namespace talk_base {
-
-static const char kPad = '=';
-static const unsigned char pd = 0xFD; // Padding
-static const unsigned char sp = 0xFE; // Whitespace
-static const unsigned char il = 0xFF; // Illegal base64 character
-
-const char Base64::Base64Table[] =
-// 0000000000111111111122222222223333333333444444444455555555556666
-// 0123456789012345678901234567890123456789012345678901234567890123
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
-// Decode Table gives the index of any valid base64 character in the
-// Base64 table
-// 65 == A, 97 == a, 48 == 0, 43 == +, 47 == /
-
-const unsigned char Base64::DecodeTable[] = {
-// 0 1 2 3 4 5 6 7 8 9
- il,il,il,il,il,il,il,il,il,sp, // 0 - 9
- sp,sp,sp,sp,il,il,il,il,il,il, // 10 - 19
- il,il,il,il,il,il,il,il,il,il, // 20 - 29
- il,il,sp,il,il,il,il,il,il,il, // 30 - 39
- il,il,il,62,il,il,il,63,52,53, // 40 - 49
- 54,55,56,57,58,59,60,61,il,il, // 50 - 59
- il,pd,il,il,il, 0, 1, 2, 3, 4, // 60 - 69
- 5, 6, 7, 8, 9,10,11,12,13,14, // 70 - 79
- 15,16,17,18,19,20,21,22,23,24, // 80 - 89
- 25,il,il,il,il,il,il,26,27,28, // 90 - 99
- 29,30,31,32,33,34,35,36,37,38, // 100 - 109
- 39,40,41,42,43,44,45,46,47,48, // 110 - 119
- 49,50,51,il,il,il,il,il,il,il, // 120 - 129
- il,il,il,il,il,il,il,il,il,il, // 130 - 139
- il,il,il,il,il,il,il,il,il,il, // 140 - 149
- il,il,il,il,il,il,il,il,il,il, // 150 - 159
- il,il,il,il,il,il,il,il,il,il, // 160 - 169
- il,il,il,il,il,il,il,il,il,il, // 170 - 179
- il,il,il,il,il,il,il,il,il,il, // 180 - 189
- il,il,il,il,il,il,il,il,il,il, // 190 - 199
- il,il,il,il,il,il,il,il,il,il, // 200 - 209
- il,il,il,il,il,il,il,il,il,il, // 210 - 219
- il,il,il,il,il,il,il,il,il,il, // 220 - 229
- il,il,il,il,il,il,il,il,il,il, // 230 - 239
- il,il,il,il,il,il,il,il,il,il, // 240 - 249
- il,il,il,il,il,il // 250 - 255
-};
-
-bool Base64::IsBase64Char(char ch) {
- return (('A' <= ch) && (ch <= 'Z')) ||
- (('a' <= ch) && (ch <= 'z')) ||
- (('0' <= ch) && (ch <= '9')) ||
- (ch == '+') || (ch == '/');
-}
-
-bool Base64::GetNextBase64Char(char ch, char* next_ch) {
- if (next_ch == NULL) {
- return false;
- }
- const char* p = strchr(Base64Table, ch);
- if (!p)
- return false;
- ++p;
- *next_ch = (*p) ? *p : Base64Table[0];
- return true;
-}
-
-bool Base64::IsBase64Encoded(const std::string& str) {
- for (size_t i = 0; i < str.size(); ++i) {
- if (!IsBase64Char(str.at(i)))
- return false;
- }
- return true;
-}
-
-void Base64::EncodeFromArray(const void* data, size_t len,
- std::string* result) {
- ASSERT(NULL != result);
- result->clear();
- result->resize(((len + 2) / 3) * 4);
- const unsigned char* byte_data = static_cast<const unsigned char*>(data);
-
- unsigned char c;
- size_t i = 0;
- size_t dest_ix = 0;
- while (i < len) {
- c = (byte_data[i] >> 2) & 0x3f;
- (*result)[dest_ix++] = Base64Table[c];
-
- c = (byte_data[i] << 4) & 0x3f;
- if (++i < len) {
- c |= (byte_data[i] >> 4) & 0x0f;
- }
- (*result)[dest_ix++] = Base64Table[c];
-
- if (i < len) {
- c = (byte_data[i] << 2) & 0x3f;
- if (++i < len) {
- c |= (byte_data[i] >> 6) & 0x03;
- }
- (*result)[dest_ix++] = Base64Table[c];
- } else {
- (*result)[dest_ix++] = kPad;
- }
-
- if (i < len) {
- c = byte_data[i] & 0x3f;
- (*result)[dest_ix++] = Base64Table[c];
- ++i;
- } else {
- (*result)[dest_ix++] = kPad;
- }
- }
-}
-
-size_t Base64::GetNextQuantum(DecodeFlags parse_flags, bool illegal_pads,
- const char* data, size_t len, size_t* dpos,
- unsigned char qbuf[4], bool* padded)
-{
- size_t byte_len = 0, pad_len = 0, pad_start = 0;
- for (; (byte_len < 4) && (*dpos < len); ++*dpos) {
- qbuf[byte_len] = DecodeTable[static_cast<unsigned char>(data[*dpos])];
- if ((il == qbuf[byte_len]) || (illegal_pads && (pd == qbuf[byte_len]))) {
- if (parse_flags != DO_PARSE_ANY)
- break;
- // Ignore illegal characters
- } else if (sp == qbuf[byte_len]) {
- if (parse_flags == DO_PARSE_STRICT)
- break;
- // Ignore spaces
- } else if (pd == qbuf[byte_len]) {
- if (byte_len < 2) {
- if (parse_flags != DO_PARSE_ANY)
- break;
- // Ignore unexpected padding
- } else if (byte_len + pad_len >= 4) {
- if (parse_flags != DO_PARSE_ANY)
- break;
- // Ignore extra pads
- } else {
- if (1 == ++pad_len) {
- pad_start = *dpos;
- }
- }
- } else {
- if (pad_len > 0) {
- if (parse_flags != DO_PARSE_ANY)
- break;
- // Ignore pads which are followed by data
- pad_len = 0;
- }
- ++byte_len;
- }
- }
- for (size_t i = byte_len; i < 4; ++i) {
- qbuf[i] = 0;
- }
- if (4 == byte_len + pad_len) {
- *padded = true;
- } else {
- *padded = false;
- if (pad_len) {
- // Roll back illegal padding
- *dpos = pad_start;
- }
- }
- return byte_len;
-}
-
-bool Base64::DecodeFromArray(const char* data, size_t len, DecodeFlags flags,
- std::string* result, size_t* data_used) {
- return DecodeFromArrayTemplate<std::string>(
- data, len, flags, result, data_used);
-}
-
-bool Base64::DecodeFromArray(const char* data, size_t len, DecodeFlags flags,
- vector<char>* result, size_t* data_used) {
- return DecodeFromArrayTemplate<vector<char> >(data, len, flags, result,
- data_used);
-}
-
-template<typename T>
-bool Base64::DecodeFromArrayTemplate(const char* data, size_t len,
- DecodeFlags flags, T* result,
- size_t* data_used)
-{
- ASSERT(NULL != result);
- ASSERT(flags <= (DO_PARSE_MASK | DO_PAD_MASK | DO_TERM_MASK));
-
- const DecodeFlags parse_flags = flags & DO_PARSE_MASK;
- const DecodeFlags pad_flags = flags & DO_PAD_MASK;
- const DecodeFlags term_flags = flags & DO_TERM_MASK;
- ASSERT(0 != parse_flags);
- ASSERT(0 != pad_flags);
- ASSERT(0 != term_flags);
-
- result->clear();
- result->reserve(len);
-
- size_t dpos = 0;
- bool success = true, padded;
- unsigned char c, qbuf[4];
- while (dpos < len) {
- size_t qlen = GetNextQuantum(parse_flags, (DO_PAD_NO == pad_flags),
- data, len, &dpos, qbuf, &padded);
- c = (qbuf[0] << 2) | ((qbuf[1] >> 4) & 0x3);
- if (qlen >= 2) {
- result->push_back(c);
- c = ((qbuf[1] << 4) & 0xf0) | ((qbuf[2] >> 2) & 0xf);
- if (qlen >= 3) {
- result->push_back(c);
- c = ((qbuf[2] << 6) & 0xc0) | qbuf[3];
- if (qlen >= 4) {
- result->push_back(c);
- c = 0;
- }
- }
- }
- if (qlen < 4) {
- if ((DO_TERM_ANY != term_flags) && (0 != c)) {
- success = false; // unused bits
- }
- if ((DO_PAD_YES == pad_flags) && !padded) {
- success = false; // expected padding
- }
- break;
- }
- }
- if ((DO_TERM_BUFFER == term_flags) && (dpos != len)) {
- success = false; // unused chars
- }
- if (data_used) {
- *data_used = dpos;
- }
- return success;
-}
-
-} // namespace talk_base
diff --git a/base/base64.h b/base/base64.h
deleted file mode 100644
index a963515..0000000
--- a/base/base64.h
+++ /dev/null
@@ -1,104 +0,0 @@
-
-//*********************************************************************
-//* C_Base64 - a simple base64 encoder and decoder.
-//*
-//* Copyright (c) 1999, Bob Withers - bwit@pobox.com
-//*
-//* This code may be freely used for any purpose, either personal
-//* or commercial, provided the authors copyright notice remains
-//* intact.
-//*********************************************************************
-
-#ifndef TALK_BASE_BASE64_H__
-#define TALK_BASE_BASE64_H__
-
-#include <string>
-#include <vector>
-
-namespace talk_base {
-
-class Base64
-{
-public:
- enum DecodeOption {
- DO_PARSE_STRICT = 1, // Parse only base64 characters
- DO_PARSE_WHITE = 2, // Parse only base64 and whitespace characters
- DO_PARSE_ANY = 3, // Parse all characters
- DO_PARSE_MASK = 3,
-
- DO_PAD_YES = 4, // Padding is required
- DO_PAD_ANY = 8, // Padding is optional
- DO_PAD_NO = 12, // Padding is disallowed
- DO_PAD_MASK = 12,
-
- DO_TERM_BUFFER = 16, // Must termiante at end of buffer
- DO_TERM_CHAR = 32, // May terminate at any character boundary
- DO_TERM_ANY = 48, // May terminate at a sub-character bit offset
- DO_TERM_MASK = 48,
-
- // Strictest interpretation
- DO_STRICT = DO_PARSE_STRICT | DO_PAD_YES | DO_TERM_BUFFER,
-
- DO_LAX = DO_PARSE_ANY | DO_PAD_ANY | DO_TERM_CHAR,
- };
- typedef int DecodeFlags;
-
- static bool IsBase64Char(char ch);
-
- // Get the char next to the |ch| from the Base64Table.
- // If the |ch| is the last one in the Base64Table then returns
- // the first one from the table.
- // Expects the |ch| be a base64 char.
- // The result will be saved in |next_ch|.
- // Returns true on success.
- static bool GetNextBase64Char(char ch, char* next_ch);
-
- // Determines whether the given string consists entirely of valid base64
- // encoded characters.
- static bool IsBase64Encoded(const std::string& str);
-
- static void EncodeFromArray(const void* data, size_t len,
- std::string* result);
- static bool DecodeFromArray(const char* data, size_t len, DecodeFlags flags,
- std::string* result, size_t* data_used);
- static bool DecodeFromArray(const char* data, size_t len, DecodeFlags flags,
- std::vector<char>* result, size_t* data_used);
-
- // Convenience Methods
- static inline std::string Encode(const std::string& data) {
- std::string result;
- EncodeFromArray(data.data(), data.size(), &result);
- return result;
- }
- static inline std::string Decode(const std::string& data, DecodeFlags flags) {
- std::string result;
- DecodeFromArray(data.data(), data.size(), flags, &result, NULL);
- return result;
- }
- static inline bool Decode(const std::string& data, DecodeFlags flags,
- std::string* result, size_t* data_used)
- {
- return DecodeFromArray(data.data(), data.size(), flags, result, data_used);
- }
- static inline bool Decode(const std::string& data, DecodeFlags flags,
- std::vector<char>* result, size_t* data_used)
- {
- return DecodeFromArray(data.data(), data.size(), flags, result, data_used);
- }
-
-private:
- static const char Base64Table[];
- static const unsigned char DecodeTable[];
-
- static size_t GetNextQuantum(DecodeFlags parse_flags, bool illegal_pads,
- const char* data, size_t len, size_t* dpos,
- unsigned char qbuf[4], bool* padded);
- template<typename T>
- static bool DecodeFromArrayTemplate(const char* data, size_t len,
- DecodeFlags flags, T* result,
- size_t* data_used);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_BASE64_H__
diff --git a/base/base64_unittest.cc b/base/base64_unittest.cc
deleted file mode 100644
index 20869e4..0000000
--- a/base/base64_unittest.cc
+++ /dev/null
@@ -1,1018 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/common.h"
-#include "talk/base/base64.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/stream.h"
-
-#include "talk/base/testbase64.h"
-
-using namespace std;
-using namespace talk_base;
-
-static struct {
- size_t plain_length;
- const char* plaintext;
- const char* cyphertext;
-} base64_tests[] = {
-
- // Basic bit patterns;
- // values obtained with "echo -n '...' | uuencode -m test"
-
- { 1, "\000", "AA==" },
- { 1, "\001", "AQ==" },
- { 1, "\002", "Ag==" },
- { 1, "\004", "BA==" },
- { 1, "\010", "CA==" },
- { 1, "\020", "EA==" },
- { 1, "\040", "IA==" },
- { 1, "\100", "QA==" },
- { 1, "\200", "gA==" },
-
- { 1, "\377", "/w==" },
- { 1, "\376", "/g==" },
- { 1, "\375", "/Q==" },
- { 1, "\373", "+w==" },
- { 1, "\367", "9w==" },
- { 1, "\357", "7w==" },
- { 1, "\337", "3w==" },
- { 1, "\277", "vw==" },
- { 1, "\177", "fw==" },
- { 2, "\000\000", "AAA=" },
- { 2, "\000\001", "AAE=" },
- { 2, "\000\002", "AAI=" },
- { 2, "\000\004", "AAQ=" },
- { 2, "\000\010", "AAg=" },
- { 2, "\000\020", "ABA=" },
- { 2, "\000\040", "ACA=" },
- { 2, "\000\100", "AEA=" },
- { 2, "\000\200", "AIA=" },
- { 2, "\001\000", "AQA=" },
- { 2, "\002\000", "AgA=" },
- { 2, "\004\000", "BAA=" },
- { 2, "\010\000", "CAA=" },
- { 2, "\020\000", "EAA=" },
- { 2, "\040\000", "IAA=" },
- { 2, "\100\000", "QAA=" },
- { 2, "\200\000", "gAA=" },
-
- { 2, "\377\377", "//8=" },
- { 2, "\377\376", "//4=" },
- { 2, "\377\375", "//0=" },
- { 2, "\377\373", "//s=" },
- { 2, "\377\367", "//c=" },
- { 2, "\377\357", "/+8=" },
- { 2, "\377\337", "/98=" },
- { 2, "\377\277", "/78=" },
- { 2, "\377\177", "/38=" },
- { 2, "\376\377", "/v8=" },
- { 2, "\375\377", "/f8=" },
- { 2, "\373\377", "+/8=" },
- { 2, "\367\377", "9/8=" },
- { 2, "\357\377", "7/8=" },
- { 2, "\337\377", "3/8=" },
- { 2, "\277\377", "v/8=" },
- { 2, "\177\377", "f/8=" },
-
- { 3, "\000\000\000", "AAAA" },
- { 3, "\000\000\001", "AAAB" },
- { 3, "\000\000\002", "AAAC" },
- { 3, "\000\000\004", "AAAE" },
- { 3, "\000\000\010", "AAAI" },
- { 3, "\000\000\020", "AAAQ" },
- { 3, "\000\000\040", "AAAg" },
- { 3, "\000\000\100", "AABA" },
- { 3, "\000\000\200", "AACA" },
- { 3, "\000\001\000", "AAEA" },
- { 3, "\000\002\000", "AAIA" },
- { 3, "\000\004\000", "AAQA" },
- { 3, "\000\010\000", "AAgA" },
- { 3, "\000\020\000", "ABAA" },
- { 3, "\000\040\000", "ACAA" },
- { 3, "\000\100\000", "AEAA" },
- { 3, "\000\200\000", "AIAA" },
- { 3, "\001\000\000", "AQAA" },
- { 3, "\002\000\000", "AgAA" },
- { 3, "\004\000\000", "BAAA" },
- { 3, "\010\000\000", "CAAA" },
- { 3, "\020\000\000", "EAAA" },
- { 3, "\040\000\000", "IAAA" },
- { 3, "\100\000\000", "QAAA" },
- { 3, "\200\000\000", "gAAA" },
-
- { 3, "\377\377\377", "////" },
- { 3, "\377\377\376", "///+" },
- { 3, "\377\377\375", "///9" },
- { 3, "\377\377\373", "///7" },
- { 3, "\377\377\367", "///3" },
- { 3, "\377\377\357", "///v" },
- { 3, "\377\377\337", "///f" },
- { 3, "\377\377\277", "//+/" },
- { 3, "\377\377\177", "//9/" },
- { 3, "\377\376\377", "//7/" },
- { 3, "\377\375\377", "//3/" },
- { 3, "\377\373\377", "//v/" },
- { 3, "\377\367\377", "//f/" },
- { 3, "\377\357\377", "/+//" },
- { 3, "\377\337\377", "/9//" },
- { 3, "\377\277\377", "/7//" },
- { 3, "\377\177\377", "/3//" },
- { 3, "\376\377\377", "/v//" },
- { 3, "\375\377\377", "/f//" },
- { 3, "\373\377\377", "+///" },
- { 3, "\367\377\377", "9///" },
- { 3, "\357\377\377", "7///" },
- { 3, "\337\377\377", "3///" },
- { 3, "\277\377\377", "v///" },
- { 3, "\177\377\377", "f///" },
-
- // Random numbers: values obtained with
- //
- // #! /bin/bash
- // dd bs=$1 count=1 if=/dev/random of=/tmp/bar.random
- // od -N $1 -t o1 /tmp/bar.random
- // uuencode -m test < /tmp/bar.random
- //
- // where $1 is the number of bytes (2, 3)
-
- { 2, "\243\361", "o/E=" },
- { 2, "\024\167", "FHc=" },
- { 2, "\313\252", "y6o=" },
- { 2, "\046\041", "JiE=" },
- { 2, "\145\236", "ZZ4=" },
- { 2, "\254\325", "rNU=" },
- { 2, "\061\330", "Mdg=" },
- { 2, "\245\032", "pRo=" },
- { 2, "\006\000", "BgA=" },
- { 2, "\375\131", "/Vk=" },
- { 2, "\303\210", "w4g=" },
- { 2, "\040\037", "IB8=" },
- { 2, "\261\372", "sfo=" },
- { 2, "\335\014", "3Qw=" },
- { 2, "\233\217", "m48=" },
- { 2, "\373\056", "+y4=" },
- { 2, "\247\232", "p5o=" },
- { 2, "\107\053", "Rys=" },
- { 2, "\204\077", "hD8=" },
- { 2, "\276\211", "vok=" },
- { 2, "\313\110", "y0g=" },
- { 2, "\363\376", "8/4=" },
- { 2, "\251\234", "qZw=" },
- { 2, "\103\262", "Q7I=" },
- { 2, "\142\312", "Yso=" },
- { 2, "\067\211", "N4k=" },
- { 2, "\220\001", "kAE=" },
- { 2, "\152\240", "aqA=" },
- { 2, "\367\061", "9zE=" },
- { 2, "\133\255", "W60=" },
- { 2, "\176\035", "fh0=" },
- { 2, "\032\231", "Gpk=" },
-
- { 3, "\013\007\144", "Cwdk" },
- { 3, "\030\112\106", "GEpG" },
- { 3, "\047\325\046", "J9Um" },
- { 3, "\310\160\022", "yHAS" },
- { 3, "\131\100\237", "WUCf" },
- { 3, "\064\342\134", "NOJc" },
- { 3, "\010\177\004", "CH8E" },
- { 3, "\345\147\205", "5WeF" },
- { 3, "\300\343\360", "wOPw" },
- { 3, "\061\240\201", "MaCB" },
- { 3, "\225\333\044", "ldsk" },
- { 3, "\215\137\352", "jV/q" },
- { 3, "\371\147\160", "+Wdw" },
- { 3, "\030\320\051", "GNAp" },
- { 3, "\044\174\241", "JHyh" },
- { 3, "\260\127\037", "sFcf" },
- { 3, "\111\045\033", "SSUb" },
- { 3, "\202\114\107", "gkxH" },
- { 3, "\057\371\042", "L/ki" },
- { 3, "\223\247\244", "k6ek" },
- { 3, "\047\216\144", "J45k" },
- { 3, "\203\070\327", "gzjX" },
- { 3, "\247\140\072", "p2A6" },
- { 3, "\124\115\116", "VE1O" },
- { 3, "\157\162\050", "b3Io" },
- { 3, "\357\223\004", "75ME" },
- { 3, "\052\117\156", "Kk9u" },
- { 3, "\347\154\000", "52wA" },
- { 3, "\303\012\142", "wwpi" },
- { 3, "\060\035\362", "MB3y" },
- { 3, "\130\226\361", "WJbx" },
- { 3, "\173\013\071", "ews5" },
- { 3, "\336\004\027", "3gQX" },
- { 3, "\357\366\234", "7/ac" },
- { 3, "\353\304\111", "68RJ" },
- { 3, "\024\264\131", "FLRZ" },
- { 3, "\075\114\251", "PUyp" },
- { 3, "\315\031\225", "zRmV" },
- { 3, "\154\201\276", "bIG+" },
- { 3, "\200\066\072", "gDY6" },
- { 3, "\142\350\267", "Yui3" },
- { 3, "\033\000\166", "GwB2" },
- { 3, "\210\055\077", "iC0/" },
- { 3, "\341\037\124", "4R9U" },
- { 3, "\161\103\152", "cUNq" },
- { 3, "\270\142\131", "uGJZ" },
- { 3, "\337\076\074", "3z48" },
- { 3, "\375\106\362", "/Uby" },
- { 3, "\227\301\127", "l8FX" },
- { 3, "\340\002\234", "4AKc" },
- { 3, "\121\064\033", "UTQb" },
- { 3, "\157\134\143", "b1xj" },
- { 3, "\247\055\327", "py3X" },
- { 3, "\340\142\005", "4GIF" },
- { 3, "\060\260\143", "MLBj" },
- { 3, "\075\203\170", "PYN4" },
- { 3, "\143\160\016", "Y3AO" },
- { 3, "\313\013\063", "ywsz" },
- { 3, "\174\236\135", "fJ5d" },
- { 3, "\103\047\026", "QycW" },
- { 3, "\365\005\343", "9QXj" },
- { 3, "\271\160\223", "uXCT" },
- { 3, "\362\255\172", "8q16" },
- { 3, "\113\012\015", "SwoN" },
-
- // various lengths, generated by this python script:
- //
- // from string import lowercase as lc
- // for i in range(27):
- // print '{ %2d, "%s",%s "%s" },' % (i, lc[:i], ' ' * (26-i),
- // lc[:i].encode('base64').strip())
-
- { 0, "abcdefghijklmnopqrstuvwxyz", "" },
- { 1, "abcdefghijklmnopqrstuvwxyz", "YQ==" },
- { 2, "abcdefghijklmnopqrstuvwxyz", "YWI=" },
- { 3, "abcdefghijklmnopqrstuvwxyz", "YWJj" },
- { 4, "abcdefghijklmnopqrstuvwxyz", "YWJjZA==" },
- { 5, "abcdefghijklmnopqrstuvwxyz", "YWJjZGU=" },
- { 6, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVm" },
- { 7, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZw==" },
- { 8, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2g=" },
- { 9, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hp" },
- { 10, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpag==" },
- { 11, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpams=" },
- { 12, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamts" },
- { 13, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbQ==" },
- { 14, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW4=" },
- { 15, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5v" },
- { 16, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcA==" },
- { 17, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHE=" },
- { 18, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFy" },
- { 19, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFycw==" },
- { 20, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3Q=" },
- { 21, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1" },
- { 22, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dg==" },
- { 23, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnc=" },
- { 24, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4" },
- { 25, "abcdefghijklmnopqrstuvwxy", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eQ==" },
- { 26, "abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=" },
-};
-#if 0
-static struct {
- const char* plaintext;
- const char* cyphertext;
-} base64_strings[] = {
-
- // The first few Google quotes
- // Cyphertext created with "uuencode - GNU sharutils 4.2.1"
- {
- "Everyone! We're teetering on the brink of disaster."
- " - Sergey Brin, 6/24/99, regarding the company's state "
- "after the unleashing of Netscape/Google search",
-
- "RXZlcnlvbmUhICBXZSdyZSB0ZWV0ZXJpbmcgb24gdGhlIGJyaW5rIG9mIGRp"
- "c2FzdGVyLiAtIFNlcmdleSBCcmluLCA2LzI0Lzk5LCByZWdhcmRpbmcgdGhl"
- "IGNvbXBhbnkncyBzdGF0ZSBhZnRlciB0aGUgdW5sZWFzaGluZyBvZiBOZXRz"
- "Y2FwZS9Hb29nbGUgc2VhcmNo" },
-
- {
- "I'm not sure why we're still alive, but we seem to be."
- " - Larry Page, 6/24/99, while hiding in the kitchenette "
- "during the Netscape traffic overflow",
-
- "SSdtIG5vdCBzdXJlIHdoeSB3ZSdyZSBzdGlsbCBhbGl2ZSwgYnV0IHdlIHNl"
- "ZW0gdG8gYmUuIC0gTGFycnkgUGFnZSwgNi8yNC85OSwgd2hpbGUgaGlkaW5n"
- "IGluIHRoZSBraXRjaGVuZXR0ZSBkdXJpbmcgdGhlIE5ldHNjYXBlIHRyYWZm"
- "aWMgb3ZlcmZsb3c" },
-
- {
- "I think kids want porn."
- " - Sergey Brin, 6/99, on why Google shouldn't prioritize a "
- "filtered search for children and families",
-
- "SSB0aGluayBraWRzIHdhbnQgcG9ybi4gLSBTZXJnZXkgQnJpbiwgNi85OSwg"
- "b24gd2h5IEdvb2dsZSBzaG91bGRuJ3QgcHJpb3JpdGl6ZSBhIGZpbHRlcmVk"
- "IHNlYXJjaCBmb3IgY2hpbGRyZW4gYW5kIGZhbWlsaWVz" },
-};
-#endif
-// Compare bytes 0..len-1 of x and y. If not equal, abort with verbose error
-// message showing position and numeric value that differed.
-// Handles embedded nulls just like any other byte.
-// Only added because string.compare() in gcc-3.3.3 seems to misbehave with
-// embedded nulls.
-// TODO: switch back to string.compare() if/when gcc is fixed
-#define EXPECT_EQ_ARRAY(len, x, y, msg) \
- for (size_t j = 0; j < len; ++j) { \
- if (x[j] != y[j]) { \
- LOG(LS_ERROR) << "" # x << " != " # y \
- << " byte " << j << " msg: " << msg; \
- } \
- }
-
-size_t Base64Escape(const unsigned char *src, size_t szsrc, char *dest,
- size_t szdest) {
- std::string escaped;
- Base64::EncodeFromArray((const char *)src, szsrc, &escaped);
- memcpy(dest, escaped.data(), min(escaped.size(), szdest));
- return escaped.size();
-}
-
-size_t Base64Unescape(const char *src, size_t szsrc, char *dest,
- size_t szdest) {
- std::string unescaped;
- EXPECT_TRUE(Base64::DecodeFromArray(src, szsrc, Base64::DO_LAX, &unescaped,
- NULL));
- memcpy(dest, unescaped.data(), min(unescaped.size(), szdest));
- return unescaped.size();
-}
-
-size_t Base64Unescape(const char *src, size_t szsrc, string *s) {
- EXPECT_TRUE(Base64::DecodeFromArray(src, szsrc, Base64::DO_LAX, s, NULL));
- return s->size();
-}
-
-TEST(Base64, EncodeDecodeBattery) {
- LOG(LS_VERBOSE) << "Testing base-64";
-
- size_t i;
-
- // Check the short strings; this tests the math (and boundaries)
- for( i = 0; i < sizeof(base64_tests) / sizeof(base64_tests[0]); ++i ) {
- char encode_buffer[100];
- size_t encode_length;
- char decode_buffer[100];
- size_t decode_length;
- size_t cypher_length;
-
- LOG(LS_VERBOSE) << "B64: " << base64_tests[i].cyphertext;
-
- const unsigned char* unsigned_plaintext =
- reinterpret_cast<const unsigned char*>(base64_tests[i].plaintext);
-
- cypher_length = strlen(base64_tests[i].cyphertext);
-
- // The basic escape function:
- memset(encode_buffer, 0, sizeof(encode_buffer));
- encode_length = Base64Escape(unsigned_plaintext,
- base64_tests[i].plain_length,
- encode_buffer,
- sizeof(encode_buffer));
- // Is it of the expected length?
- EXPECT_EQ(encode_length, cypher_length);
-
- // Is it the expected encoded value?
- EXPECT_STREQ(encode_buffer, base64_tests[i].cyphertext);
-
- // If we encode it into a buffer of exactly the right length...
- memset(encode_buffer, 0, sizeof(encode_buffer));
- encode_length = Base64Escape(unsigned_plaintext,
- base64_tests[i].plain_length,
- encode_buffer,
- cypher_length);
- // Is it still of the expected length?
- EXPECT_EQ(encode_length, cypher_length);
-
- // And is the value still correct? (i.e., not losing the last byte)
- EXPECT_STREQ(encode_buffer, base64_tests[i].cyphertext);
-
- // If we decode it back:
- memset(decode_buffer, 0, sizeof(decode_buffer));
- decode_length = Base64Unescape(encode_buffer,
- cypher_length,
- decode_buffer,
- sizeof(decode_buffer));
-
- // Is it of the expected length?
- EXPECT_EQ(decode_length, base64_tests[i].plain_length);
-
- // Is it the expected decoded value?
- EXPECT_EQ(0, memcmp(decode_buffer, base64_tests[i].plaintext, decode_length));
-
- // Our decoder treats the padding '=' characters at the end as
- // optional. If encode_buffer has any, run some additional
- // tests that fiddle with them.
- char* first_equals = strchr(encode_buffer, '=');
- if (first_equals) {
- // How many equals signs does the string start with?
- int equals = (*(first_equals+1) == '=') ? 2 : 1;
-
- // Try chopping off the equals sign(s) entirely. The decoder
- // should still be okay with this.
- string decoded2("this junk should also be ignored");
- *first_equals = '\0';
- EXPECT_NE(0U, Base64Unescape(encode_buffer, first_equals-encode_buffer,
- &decoded2));
- EXPECT_EQ(decoded2.size(), base64_tests[i].plain_length);
- EXPECT_EQ_ARRAY(decoded2.size(), decoded2.data(), base64_tests[i].plaintext, i);
-
- size_t len;
-
- // try putting some extra stuff after the equals signs, or in between them
- if (equals == 2) {
- sprintfn(first_equals, 6, " = = ");
- len = first_equals - encode_buffer + 5;
- } else {
- sprintfn(first_equals, 6, " = ");
- len = first_equals - encode_buffer + 3;
- }
- decoded2.assign("this junk should be ignored");
- EXPECT_NE(0U, Base64Unescape(encode_buffer, len, &decoded2));
- EXPECT_EQ(decoded2.size(), base64_tests[i].plain_length);
- EXPECT_EQ_ARRAY(decoded2.size(), decoded2, base64_tests[i].plaintext, i);
- }
- }
-}
-
-// here's a weird case: a giant base64 encoded stream which broke our base64
-// decoding. Let's test it explicitly.
-const char SpecificTest[] =
- "/9j/4AAQSkZJRgABAgEASABIAAD/4Q0HRXhpZgAATU0AKgAAAAgADAEOAAIAAAAgAAAAngEPAAI\n"
- "AAAAFAAAAvgEQAAIAAAAJAAAAwwESAAMAAAABAAEAAAEaAAUAAAABAAAAzAEbAAUAAAABAAAA1A\n"
- "EoAAMAAAABAAIAAAExAAIAAAAUAAAA3AEyAAIAAAAUAAAA8AE8AAIAAAAQAAABBAITAAMAAAABA\n"
- "AIAAIdpAAQAAAABAAABFAAAAsQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgAFNPTlkA\n"
- "RFNDLVAyMDAAAAAASAAAAAEAAABIAAAAAUFkb2JlIFBob3Rvc2hvcCA3LjAAMjAwNzowMTozMCA\n"
- "yMzoxMDowNABNYWMgT1MgWCAxMC40LjgAAByCmgAFAAAAAQAAAmqCnQAFAAAAAQAAAnKIIgADAA\n"
- "AAAQACAACIJwADAAAAAQBkAACQAAAHAAAABDAyMjCQAwACAAAAFAAAAnqQBAACAAAAFAAAAo6RA\n"
- "QAHAAAABAECAwCRAgAFAAAAAQAAAqKSBAAKAAAAAQAAAqqSBQAFAAAAAQAAArKSBwADAAAAAQAF\n"
- "AACSCAADAAAAAQAAAACSCQADAAAAAQAPAACSCgAFAAAAAQAAArqgAAAHAAAABDAxMDCgAQADAAA\n"
- "AAf//AACgAgAEAAAAAQAAAGSgAwAEAAAAAQAAAGSjAAAHAAAAAQMAAACjAQAHAAAAAQEAAACkAQ\n"
- "ADAAAAAQAAAACkAgADAAAAAQAAAACkAwADAAAAAQAAAACkBgADAAAAAQAAAACkCAADAAAAAQAAA\n"
- "ACkCQADAAAAAQAAAACkCgADAAAAAQAAAAAAAAAAAAAACgAAAZAAAAAcAAAACjIwMDc6MDE6MjAg\n"
- "MjM6MDU6NTIAMjAwNzowMToyMCAyMzowNTo1MgAAAAAIAAAAAQAAAAAAAAAKAAAAMAAAABAAAAB\n"
- "PAAAACgAAAAYBAwADAAAAAQAGAAABGgAFAAAAAQAAAxIBGwAFAAAAAQAAAxoBKAADAAAAAQACAA\n"
- "ACAQAEAAAAAQAAAyICAgAEAAAAAQAACd0AAAAAAAAASAAAAAEAAABIAAAAAf/Y/+AAEEpGSUYAA\n"
- "QIBAEgASAAA/+0ADEFkb2JlX0NNAAL/7gAOQWRvYmUAZIAAAAAB/9sAhAAMCAgICQgMCQkMEQsK\n"
- "CxEVDwwMDxUYExMVExMYEQwMDAwMDBEMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQ0LCw0\n"
- "ODRAODhAUDg4OFBQODg4OFBEMDAwMDBERDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA\n"
- "wMDAz/wAARCABkAGQDASIAAhEBAxEB/90ABAAH/8QBPwAAAQUBAQEBAQEAAAAAAAAAAwABAgQFB\n"
- "gcICQoLAQABBQEBAQEBAQAAAAAAAAABAAIDBAUGBwgJCgsQAAEEAQMCBAIFBwYIBQMMMwEAAhED\n"
- "BCESMQVBUWETInGBMgYUkaGxQiMkFVLBYjM0coLRQwclklPw4fFjczUWorKDJkSTVGRFwqN0Nhf\n"
- "SVeJl8rOEw9N14/NGJ5SkhbSVxNTk9KW1xdXl9VZmdoaWprbG1ub2N0dXZ3eHl6e3x9fn9xEAAg\n"
- "IBAgQEAwQFBgcHBgU1AQACEQMhMRIEQVFhcSITBTKBkRShsUIjwVLR8DMkYuFygpJDUxVjczTxJ\n"
- "QYWorKDByY1wtJEk1SjF2RFVTZ0ZeLys4TD03Xj80aUpIW0lcTU5PSltcXV5fVWZnaGlqa2xtbm\n"
- "9ic3R1dnd4eXp7fH/9oADAMBAAIRAxEAPwDy7bKNTUXNLz9EaJPDWMjxH4ozhtpYwaACT8ShaaW\n"
- "bW0uEc9/JFfjj0Q4Hk/PRDxwX7y47W9z/AN9Cv4+O3ILK2DcRqT2CaSvEbcl1Jbz37KG1dBldLo\n"
- "qaS4l9xGjG9v6yoDAdYIaIjUk+AREgo4y5sapirb8Yl0NHHdKvBNm4yA1o5Pc+SPEFvCWqB3HZF\n"
- "Hj2SbWQ/afGFP0bHP8ATY0uc4w1o1JPkkimGiS2KvqlnmBkOZQTyydzgPMM9v8A0lp4v1Nx9gF1\n"
- "tpdqJaGtH/S3I0i3lISXW/8AMqnd/O2bfg2eUkqVYf/Q8zuncO4Bj7lZ+n7f5Mj5KsJcY8NUZ4d\n"
- "uEDVo1HkeU0rg3Om4H2rabCWUN7DQuK1n5FWKW4uCwG92gDRJBS6exhxmMboQI+Cv4WFTQ42Bs2\n"
- "fvnkkqEmy2YxoMMbpVzaz6jt+RbpHZs8lzkHqrasKkYOKP0jgDfZ4N/wDM1tNrcWfSPmRyq9uNV\n"
- "DnFg2s97i7UkjxKVrq0eVz3spZsja+ASDzwsh9jnOk/JFzb3XZD3v1c4yT8UACTCniKDUnKz5Nj\n"
- "G33XV1DV73BrT8dF23SejV4zg9g33cOsPb+SxVvqv9ViwNy8vS0iWs/daf8A0Y5dpTi1sADGxCR\n"
- "K1o0YBEmInlXWYbDBcDLdPJXa8f71Yrx2jnUoAqLnfZK5hJaW2vdwEk5a/wD/0fN6Ia/e76IiVf\n"
- "xavUL7CPpnT4LNbYXAVjuQt/AqDmNYO/Kjnoy4hr5J8SwMhrRMaeSvbsxrfUazcOw4UX0Cisem2\n"
- "SBoD4+Kz8nC6llbSLCRrubJA8kwUWbUDa29X1PMa7aQWjuDC0MXMdbDbhI7eazBiUfZ6GOYRe1s\n"
- "WvGgJ8Vbw2+m4Bx9s6JpNHuuGo1FF53r/SHYua61gLse0lzXeBP5rkvqx0o5vVWz7WY49QkiQSP\n"
- "oN/tLoevW/ogxv0HA7tJ0AnhT+pdDGYVl/wCdcTPkGn2NU0JWNWvlgAbHV6fEqdu2gR/r2WlWwt\n"
- "AA5VXAEsLXTqJafArQY5rRr9LiPBJiZsZCI1pJjxCi0j4oncSICSkWwzwkjeaSch//0vO7sP7Lm\n"
- "enO9ogtd5FbPT3Q5pCpZVc4ld3Lmn3O8j9EI2BYdunKjOobMQIyI+rusc2wx4d0eutwGnHh/uQc\n"
- "Ha7ladj6mVANGvcqOgz0Go7HJ12/GEHcwvB/dPY6ImbbaMaASGuIBjkN7qofs9Ubg9g7OI9p/t/\n"
- "RTSmhTHr0v6eSz6UgCPP2/wAVu9Ex2V49dVY2iACB4BZeVXQ/AJ3gzGnnOi2+kACpru8flUsNmt\n"
- "zHRf6xfWCnoeAfTh2ZaQKazx/Ke7+QxcKz61fWA2uuObaC4zGhaPJrXBL64ZFmR124O09ENraPK\n"
- "N3/AH5GqxIrZVUyp2K2vfdkENsDnxuex9m4Ox9n82xSgNd9D+p/XR1npgseR9ppOy4Dx/NfH/CL\n"
- "oQJGunmvMv8AFq3KHVcq3HkYQbD2nuSf0I/rMavSg6TLjLigQhJ7Z58v9QkmlsTOqSCn/9PzL7R\n"
- "d6Qq3n0wZ2zotXpT9xLfFYvkr/S7jXeB8E0jRkhKpC3q8LcJ/kmCrTnkuAPCq4do9Q/ytVbuAeY\n"
- "Gg5lQybQK+82GBqEQUA1kOHPYf3LLsoyN36G5w8iUfHxepbXE2l0cApALgLHzBq9UxhTXU5hMC1\n"
- "ktnSCup6S4Ctk+C5XqVGcaHPfuiuHkeTTuWz0+9zaKiH6CC0/yXBSQ2a/MxojV57634rq+v2PLY\n"
- "be1r2nsYG13/AFKxbfCBMcr0brGAzrGEwCG31ncx0SfBzf7S4+zoHUWWsJq3hz9oLfcBH77R9H+\n"
- "0pA13u/qPgDp/Q6ri39JlfpXkDx+h/msWn1L6wdO6bSbcrIbU2Q0xLnSe21kuVejJspbVS5+4bd\n"
- "ocBAkD/orG+tP1ar67Wy7GtZTm1SCXfRsb+a18fRe38x6SG3/44H1Z3f0y2I+l6DoSXD/8xPrDs\n"
- "3enVu3bdnqN3R+//USSVo//1PLohhce+gRWS0Nsby3lRgFkKxQyW7SgUh3em5Tbq2uB9wWw1wey\n"
- "J1XGV2XYdm5k7e4WzidXY9oMwo5RZ4T6Hd1ixwfp96PWbAJBVTHzK7O6Ky5oJB1HZMqmUEFlkGy\n"
- "xpa4zI1Hkq31dy7bMN9BAc3HeWAnnbyxEycmuup1jiAGglZ31PyrmZ9tQg1WtNj54EHR3/S2qTH\n"
- "1Yc5GgD1FFtzPdWGkd2AyflogZmRmsz6PSrbXbdo+txOrP337f3fzVo15DK2uyrTtqpBOnBKx6b\n"
- "7MjJsz7tHWOAYP3WD6LU6cqGjFCNl1MmvLcxv6YtDTLSAqP27LrdtYHXFnJZI+Tp3MWg68OpDPv\n"
- "UMUM2lkQBoouKQ6swjE9Nml+1sz1PW+z6xt27zuj+skrX2ZvqR5z8kkuOfdPt43/1fMm/grFG6f\n"
- "Lss9JA7JG7tnZs/SfJUrfS3foJ9TvHCopJsV8nWx/t24bJn8Fo/5TjWJXMJIS+i+G36TsZ/7Q9P\n"
- "8ATfzfeOFofVSZv2/zvt+O3X/v65dJPjt/BiyfN1/wn0zre79nVej/ADG8ep4x2/6Srjd6TdviF\n"
- "52ko8m6/Ht9X1KnftEo+POwxzK8mSTF46vrH6T1/OEl5Okkl//Z/+0uHFBob3Rvc2hvcCAzLjAA\n"
- "OEJJTQQEAAAAAAArHAIAAAIAAhwCeAAfICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAA\n"
- "4QklNBCUAAAAAABD7Caa9B0wqNp2P4sxXqayFOEJJTQPqAAAAAB2wPD94bWwgdmVyc2lvbj0iMS\n"
- "4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHBsaXN0IFBVQkxJQyAiLS8vQXBwbGUgQ\n"
- "29tcHV0ZXIvL0RURCBQTElTVCAxLjAvL0VOIiAiaHR0cDovL3d3dy5hcHBsZS5jb20vRFREcy9Q\n"
- "cm9wZXJ0eUxpc3QtMS4wLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo8ZGljdD4KCTxrZXk\n"
- "+Y29tLmFwcGxlLnByaW50LlBhZ2VGb3JtYXQuUE1Ib3Jpem9udGFsUmVzPC9rZXk+Cgk8ZGljdD\n"
- "4KCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuY3JlYXRvcjwva2V5PgoJCTxzdHJpbmc+Y\n"
- "29tLmFwcGxlLnByaW50aW5nbWFuYWdlcjwvc3RyaW5nPgoJCTxrZXk+Y29tLmFwcGxlLnByaW50\n"
- "LnRpY2tldC5pdGVtQXJyYXk8L2tleT4KCQk8YXJyYXk+CgkJCTxkaWN0PgoJCQkJPGtleT5jb20\n"
- "uYXBwbGUucHJpbnQuUGFnZUZvcm1hdC5QTUhvcml6b250YWxSZXM8L2tleT4KCQkJCTxyZWFsPj\n"
- "cyPC9yZWFsPgoJCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNsaWVudDwva2V5PgoJC\n"
- "QkJPHN0cmluZz5jb20uYXBwbGUucHJpbnRpbmdtYW5hZ2VyPC9zdHJpbmc+CgkJCQk8a2V5PmNv\n"
- "bS5hcHBsZS5wcmludC50aWNrZXQubW9kRGF0ZTwva2V5PgoJCQkJPGRhdGU+MjAwNy0wMS0zMFQ\n"
- "yMjowODo0MVo8L2RhdGU+CgkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuc3RhdGVGbG\n"
- "FnPC9rZXk+CgkJCQk8aW50ZWdlcj4wPC9pbnRlZ2VyPgoJCQk8L2RpY3Q+CgkJPC9hcnJheT4KC\n"
- "TwvZGljdD4KCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhZ2VGb3JtYXQuUE1PcmllbnRhdGlvbjwv\n"
- "a2V5PgoJPGRpY3Q+CgkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNyZWF0b3I8L2tleT4\n"
- "KCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGluZ21hbmFnZXI8L3N0cmluZz4KCQk8a2V5PmNvbS\n"
- "5hcHBsZS5wcmludC50aWNrZXQuaXRlbUFycmF5PC9rZXk+CgkJPGFycmF5PgoJCQk8ZGljdD4KC\n"
- "QkJCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhZ2VGb3JtYXQuUE1PcmllbnRhdGlvbjwva2V5PgoJ\n"
- "CQkJPGludGVnZXI+MTwvaW50ZWdlcj4KCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LnRpY2tldC5\n"
- "jbGllbnQ8L2tleT4KCQkJCTxzdHJpbmc+Y29tLmFwcGxlLnByaW50aW5nbWFuYWdlcjwvc3RyaW\n"
- "5nPgoJCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0Lm1vZERhdGU8L2tleT4KCQkJCTxkY\n"
- "XRlPjIwMDctMDEtMzBUMjI6MDg6NDFaPC9kYXRlPgoJCQkJPGtleT5jb20uYXBwbGUucHJpbnQu\n"
- "dGlja2V0LnN0YXRlRmxhZzwva2V5PgoJCQkJPGludGVnZXI+MDwvaW50ZWdlcj4KCQkJPC9kaWN\n"
- "0PgoJCTwvYXJyYXk+Cgk8L2RpY3Q+Cgk8a2V5PmNvbS5hcHBsZS5wcmludC5QYWdlRm9ybWF0Ll\n"
- "BNU2NhbGluZzwva2V5PgoJPGRpY3Q+CgkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNyZ\n"
- "WF0b3I8L2tleT4KCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGluZ21hbmFnZXI8L3N0cmluZz4K\n"
- "CQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuaXRlbUFycmF5PC9rZXk+CgkJPGFycmF5Pgo\n"
- "JCQk8ZGljdD4KCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhZ2VGb3JtYXQuUE1TY2FsaW5nPC\n"
- "9rZXk+CgkJCQk8cmVhbD4xPC9yZWFsPgoJCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0L\n"
- "mNsaWVudDwva2V5PgoJCQkJPHN0cmluZz5jb20uYXBwbGUucHJpbnRpbmdtYW5hZ2VyPC9zdHJp\n"
- "bmc+CgkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQubW9kRGF0ZTwva2V5PgoJCQkJPGR\n"
- "hdGU+MjAwNy0wMS0zMFQyMjowODo0MVo8L2RhdGU+CgkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC\n"
- "50aWNrZXQuc3RhdGVGbGFnPC9rZXk+CgkJCQk8aW50ZWdlcj4wPC9pbnRlZ2VyPgoJCQk8L2RpY\n"
- "3Q+CgkJPC9hcnJheT4KCTwvZGljdD4KCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhZ2VGb3JtYXQu\n"
- "UE1WZXJ0aWNhbFJlczwva2V5PgoJPGRpY3Q+CgkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V\n"
- "0LmNyZWF0b3I8L2tleT4KCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGluZ21hbmFnZXI8L3N0cm\n"
- "luZz4KCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuaXRlbUFycmF5PC9rZXk+CgkJPGFyc\n"
- "mF5PgoJCQk8ZGljdD4KCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhZ2VGb3JtYXQuUE1WZXJ0\n"
- "aWNhbFJlczwva2V5PgoJCQkJPHJlYWw+NzI8L3JlYWw+CgkJCQk8a2V5PmNvbS5hcHBsZS5wcml\n"
- "udC50aWNrZXQuY2xpZW50PC9rZXk+CgkJCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGluZ21hbm\n"
- "FnZXI8L3N0cmluZz4KCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LnRpY2tldC5tb2REYXRlPC9rZ\n"
- "Xk+CgkJCQk8ZGF0ZT4yMDA3LTAxLTMwVDIyOjA4OjQxWjwvZGF0ZT4KCQkJCTxrZXk+Y29tLmFw\n"
- "cGxlLnByaW50LnRpY2tldC5zdGF0ZUZsYWc8L2tleT4KCQkJCTxpbnRlZ2VyPjA8L2ludGVnZXI\n"
- "+CgkJCTwvZGljdD4KCQk8L2FycmF5PgoJPC9kaWN0PgoJPGtleT5jb20uYXBwbGUucHJpbnQuUG\n"
- "FnZUZvcm1hdC5QTVZlcnRpY2FsU2NhbGluZzwva2V5PgoJPGRpY3Q+CgkJPGtleT5jb20uYXBwb\n"
- "GUucHJpbnQudGlja2V0LmNyZWF0b3I8L2tleT4KCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGlu\n"
- "Z21hbmFnZXI8L3N0cmluZz4KCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuaXRlbUFycmF\n"
- "5PC9rZXk+CgkJPGFycmF5PgoJCQk8ZGljdD4KCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhZ2\n"
- "VGb3JtYXQuUE1WZXJ0aWNhbFNjYWxpbmc8L2tleT4KCQkJCTxyZWFsPjE8L3JlYWw+CgkJCQk8a\n"
- "2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuY2xpZW50PC9rZXk+CgkJCQk8c3RyaW5nPmNvbS5h\n"
- "cHBsZS5wcmludGluZ21hbmFnZXI8L3N0cmluZz4KCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LnR\n"
- "pY2tldC5tb2REYXRlPC9rZXk+CgkJCQk8ZGF0ZT4yMDA3LTAxLTMwVDIyOjA4OjQxWjwvZGF0ZT\n"
- "4KCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LnRpY2tldC5zdGF0ZUZsYWc8L2tleT4KCQkJCTxpb\n"
- "nRlZ2VyPjA8L2ludGVnZXI+CgkJCTwvZGljdD4KCQk8L2FycmF5PgoJPC9kaWN0PgoJPGtleT5j\n"
- "b20uYXBwbGUucHJpbnQuc3ViVGlja2V0LnBhcGVyX2luZm9fdGlja2V0PC9rZXk+Cgk8ZGljdD4\n"
- "KCQk8a2V5PmNvbS5hcHBsZS5wcmludC5QYWdlRm9ybWF0LlBNQWRqdXN0ZWRQYWdlUmVjdDwva2\n"
- "V5PgoJCTxkaWN0PgoJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuY3JlYXRvcjwva2V5P\n"
- "goJCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGluZ21hbmFnZXI8L3N0cmluZz4KCQkJPGtleT5j\n"
- "b20uYXBwbGUucHJpbnQudGlja2V0Lml0ZW1BcnJheTwva2V5PgoJCQk8YXJyYXk+CgkJCQk8ZGl\n"
- "jdD4KCQkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC5QYWdlRm9ybWF0LlBNQWRqdXN0ZWRQYWdlUm\n"
- "VjdDwva2V5PgoJCQkJCTxhcnJheT4KCQkJCQkJPHJlYWw+MC4wPC9yZWFsPgoJCQkJCQk8cmVhb\n"
- "D4wLjA8L3JlYWw+CgkJCQkJCTxyZWFsPjczNDwvcmVhbD4KCQkJCQkJPHJlYWw+NTc2PC9yZWFs\n"
- "PgoJCQkJCTwvYXJyYXk+CgkJCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNsaWVudDw\n"
- "va2V5PgoJCQkJCTxzdHJpbmc+Y29tLmFwcGxlLnByaW50aW5nbWFuYWdlcjwvc3RyaW5nPgoJCQ\n"
- "kJCTxrZXk+Y29tLmFwcGxlLnByaW50LnRpY2tldC5tb2REYXRlPC9rZXk+CgkJCQkJPGRhdGU+M\n"
- "jAwNy0wMS0zMFQyMjowODo0MVo8L2RhdGU+CgkJCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlj\n"
- "a2V0LnN0YXRlRmxhZzwva2V5PgoJCQkJCTxpbnRlZ2VyPjA8L2ludGVnZXI+CgkJCQk8L2RpY3Q\n"
- "+CgkJCTwvYXJyYXk+CgkJPC9kaWN0PgoJCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhZ2VGb3JtYX\n"
- "QuUE1BZGp1c3RlZFBhcGVyUmVjdDwva2V5PgoJCTxkaWN0PgoJCQk8a2V5PmNvbS5hcHBsZS5wc\n"
- "mludC50aWNrZXQuY3JlYXRvcjwva2V5PgoJCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGluZ21h\n"
- "bmFnZXI8L3N0cmluZz4KCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0Lml0ZW1BcnJheTw\n"
- "va2V5PgoJCQk8YXJyYXk+CgkJCQk8ZGljdD4KCQkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC5QYW\n"
- "dlRm9ybWF0LlBNQWRqdXN0ZWRQYXBlclJlY3Q8L2tleT4KCQkJCQk8YXJyYXk+CgkJCQkJCTxyZ\n"
- "WFsPi0xODwvcmVhbD4KCQkJCQkJPHJlYWw+LTE4PC9yZWFsPgoJCQkJCQk8cmVhbD43NzQ8L3Jl\n"
- "YWw+CgkJCQkJCTxyZWFsPjU5NDwvcmVhbD4KCQkJCQk8L2FycmF5PgoJCQkJCTxrZXk+Y29tLmF\n"
- "wcGxlLnByaW50LnRpY2tldC5jbGllbnQ8L2tleT4KCQkJCQk8c3RyaW5nPmNvbS5hcHBsZS5wcm\n"
- "ludGluZ21hbmFnZXI8L3N0cmluZz4KCQkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQub\n"
- "W9kRGF0ZTwva2V5PgoJCQkJCTxkYXRlPjIwMDctMDEtMzBUMjI6MDg6NDFaPC9kYXRlPgoJCQkJ\n"
- "CTxrZXk+Y29tLmFwcGxlLnByaW50LnRpY2tldC5zdGF0ZUZsYWc8L2tleT4KCQkJCQk8aW50ZWd\n"
- "lcj4wPC9pbnRlZ2VyPgoJCQkJPC9kaWN0PgoJCQk8L2FycmF5PgoJCTwvZGljdD4KCQk8a2V5Pm\n"
- "NvbS5hcHBsZS5wcmludC5QYXBlckluZm8uUE1QYXBlck5hbWU8L2tleT4KCQk8ZGljdD4KCQkJP\n"
- "GtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNyZWF0b3I8L2tleT4KCQkJPHN0cmluZz5jb20u\n"
- "YXBwbGUucHJpbnQucG0uUG9zdFNjcmlwdDwvc3RyaW5nPgoJCQk8a2V5PmNvbS5hcHBsZS5wcml\n"
- "udC50aWNrZXQuaXRlbUFycmF5PC9rZXk+CgkJCTxhcnJheT4KCQkJCTxkaWN0PgoJCQkJCTxrZX\n"
- "k+Y29tLmFwcGxlLnByaW50LlBhcGVySW5mby5QTVBhcGVyTmFtZTwva2V5PgoJCQkJCTxzdHJpb\n"
- "mc+bmEtbGV0dGVyPC9zdHJpbmc+CgkJCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNs\n"
- "aWVudDwva2V5PgoJCQkJCTxzdHJpbmc+Y29tLmFwcGxlLnByaW50LnBtLlBvc3RTY3JpcHQ8L3N\n"
- "0cmluZz4KCQkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQubW9kRGF0ZTwva2V5PgoJCQ\n"
- "kJCTxkYXRlPjIwMDMtMDctMDFUMTc6NDk6MzZaPC9kYXRlPgoJCQkJCTxrZXk+Y29tLmFwcGxlL\n"
- "nByaW50LnRpY2tldC5zdGF0ZUZsYWc8L2tleT4KCQkJCQk8aW50ZWdlcj4xPC9pbnRlZ2VyPgoJ\n"
- "CQkJPC9kaWN0PgoJCQk8L2FycmF5PgoJCTwvZGljdD4KCQk8a2V5PmNvbS5hcHBsZS5wcmludC5\n"
- "QYXBlckluZm8uUE1VbmFkanVzdGVkUGFnZVJlY3Q8L2tleT4KCQk8ZGljdD4KCQkJPGtleT5jb2\n"
- "0uYXBwbGUucHJpbnQudGlja2V0LmNyZWF0b3I8L2tleT4KCQkJPHN0cmluZz5jb20uYXBwbGUuc\n"
- "HJpbnQucG0uUG9zdFNjcmlwdDwvc3RyaW5nPgoJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNr\n"
- "ZXQuaXRlbUFycmF5PC9rZXk+CgkJCTxhcnJheT4KCQkJCTxkaWN0PgoJCQkJCTxrZXk+Y29tLmF\n"
- "wcGxlLnByaW50LlBhcGVySW5mby5QTVVuYWRqdXN0ZWRQYWdlUmVjdDwva2V5PgoJCQkJCTxhcn\n"
- "JheT4KCQkJCQkJPHJlYWw+MC4wPC9yZWFsPgoJCQkJCQk8cmVhbD4wLjA8L3JlYWw+CgkJCQkJC\n"
- "TxyZWFsPjczNDwvcmVhbD4KCQkJCQkJPHJlYWw+NTc2PC9yZWFsPgoJCQkJCTwvYXJyYXk+CgkJ\n"
- "CQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNsaWVudDwva2V5PgoJCQkJCTxzdHJpbmc\n"
- "+Y29tLmFwcGxlLnByaW50aW5nbWFuYWdlcjwvc3RyaW5nPgoJCQkJCTxrZXk+Y29tLmFwcGxlLn\n"
- "ByaW50LnRpY2tldC5tb2REYXRlPC9rZXk+CgkJCQkJPGRhdGU+MjAwNy0wMS0zMFQyMjowODo0M\n"
- "Vo8L2RhdGU+CgkJCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LnN0YXRlRmxhZzwva2V5\n"
- "PgoJCQkJCTxpbnRlZ2VyPjA8L2ludGVnZXI+CgkJCQk8L2RpY3Q+CgkJCTwvYXJyYXk+CgkJPC9\n"
- "kaWN0PgoJCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhcGVySW5mby5QTVVuYWRqdXN0ZWRQYXBlcl\n"
- "JlY3Q8L2tleT4KCQk8ZGljdD4KCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V0LmNyZWF0b\n"
- "3I8L2tleT4KCQkJPHN0cmluZz5jb20uYXBwbGUucHJpbnQucG0uUG9zdFNjcmlwdDwvc3RyaW5n\n"
- "PgoJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuaXRlbUFycmF5PC9rZXk+CgkJCTxhcnJ\n"
- "heT4KCQkJCTxkaWN0PgoJCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LlBhcGVySW5mby5QTVVuYW\n"
- "RqdXN0ZWRQYXBlclJlY3Q8L2tleT4KCQkJCQk8YXJyYXk+CgkJCQkJCTxyZWFsPi0xODwvcmVhb\n"
- "D4KCQkJCQkJPHJlYWw+LTE4PC9yZWFsPgoJCQkJCQk8cmVhbD43NzQ8L3JlYWw+CgkJCQkJCTxy\n"
- "ZWFsPjU5NDwvcmVhbD4KCQkJCQk8L2FycmF5PgoJCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LnR\n"
- "pY2tldC5jbGllbnQ8L2tleT4KCQkJCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmludGluZ21hbmFnZX\n"
- "I8L3N0cmluZz4KCQkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQubW9kRGF0ZTwva2V5P\n"
- "goJCQkJCTxkYXRlPjIwMDctMDEtMzBUMjI6MDg6NDFaPC9kYXRlPgoJCQkJCTxrZXk+Y29tLmFw\n"
- "cGxlLnByaW50LnRpY2tldC5zdGF0ZUZsYWc8L2tleT4KCQkJCQk8aW50ZWdlcj4wPC9pbnRlZ2V\n"
- "yPgoJCQkJPC9kaWN0PgoJCQk8L2FycmF5PgoJCTwvZGljdD4KCQk8a2V5PmNvbS5hcHBsZS5wcm\n"
- "ludC5QYXBlckluZm8ucHBkLlBNUGFwZXJOYW1lPC9rZXk+CgkJPGRpY3Q+CgkJCTxrZXk+Y29tL\n"
- "mFwcGxlLnByaW50LnRpY2tldC5jcmVhdG9yPC9rZXk+CgkJCTxzdHJpbmc+Y29tLmFwcGxlLnBy\n"
- "aW50LnBtLlBvc3RTY3JpcHQ8L3N0cmluZz4KCQkJPGtleT5jb20uYXBwbGUucHJpbnQudGlja2V\n"
- "0Lml0ZW1BcnJheTwva2V5PgoJCQk8YXJyYXk+CgkJCQk8ZGljdD4KCQkJCQk8a2V5PmNvbS5hcH\n"
- "BsZS5wcmludC5QYXBlckluZm8ucHBkLlBNUGFwZXJOYW1lPC9rZXk+CgkJCQkJPHN0cmluZz5VU\n"
- "yBMZXR0ZXI8L3N0cmluZz4KCQkJCQk8a2V5PmNvbS5hcHBsZS5wcmludC50aWNrZXQuY2xpZW50\n"
- "PC9rZXk+CgkJCQkJPHN0cmluZz5jb20uYXBwbGUucHJpbnQucG0uUG9zdFNjcmlwdDwvc3RyaW5\n"
- "nPgoJCQkJCTxrZXk+Y29tLmFwcGxlLnByaW50LnRpY2tldC5tb2REYXRlPC9rZXk+CgkJCQkJPG\n"
- "RhdGU+MjAwMy0wNy0wMVQxNzo0OTozNlo8L2RhdGU+CgkJCQkJPGtleT5jb20uYXBwbGUucHJpb\n"
- "nQudGlja2V0LnN0YXRlRmxhZzwva2V5PgoJCQkJCTxpbnRlZ2VyPjE8L2ludGVnZXI+CgkJCQk8\n"
- "L2RpY3Q+CgkJCTwvYXJyYXk+CgkJPC9kaWN0PgoJCTxrZXk+Y29tLmFwcGxlLnByaW50LnRpY2t\n"
- "ldC5BUElWZXJzaW9uPC9rZXk+CgkJPHN0cmluZz4wMC4yMDwvc3RyaW5nPgoJCTxrZXk+Y29tLm\n"
- "FwcGxlLnByaW50LnRpY2tldC5wcml2YXRlTG9jazwva2V5PgoJCTxmYWxzZS8+CgkJPGtleT5jb\n"
- "20uYXBwbGUucHJpbnQudGlja2V0LnR5cGU8L2tleT4KCQk8c3RyaW5nPmNvbS5hcHBsZS5wcmlu\n"
- "dC5QYXBlckluZm9UaWNrZXQ8L3N0cmluZz4KCTwvZGljdD4KCTxrZXk+Y29tLmFwcGxlLnByaW5\n"
- "0LnRpY2tldC5BUElWZXJzaW9uPC9rZXk+Cgk8c3RyaW5nPjAwLjIwPC9zdHJpbmc+Cgk8a2V5Pm\n"
- "NvbS5hcHBsZS5wcmludC50aWNrZXQucHJpdmF0ZUxvY2s8L2tleT4KCTxmYWxzZS8+Cgk8a2V5P\n"
- "mNvbS5hcHBsZS5wcmludC50aWNrZXQudHlwZTwva2V5PgoJPHN0cmluZz5jb20uYXBwbGUucHJp\n"
- "bnQuUGFnZUZvcm1hdFRpY2tldDwvc3RyaW5nPgo8L2RpY3Q+CjwvcGxpc3Q+CjhCSU0D6QAAAAA\n"
- "AeAADAAAASABIAAAAAALeAkD/7v/uAwYCUgNnBSgD/AACAAAASABIAAAAAALYAigAAQAAAGQAAA\n"
- "ABAAMDAwAAAAF//wABAAEAAAAAAAAAAAAAAABoCAAZAZAAAAAAACAAAAAAAAAAAAAAAAAAAAAAA\n"
- "AAAAAAAAAAAADhCSU0D7QAAAAAAEABIAAAAAQABAEgAAAABAAE4QklNBCYAAAAAAA4AAAAAAAAA\n"
- "AAAAP4AAADhCSU0EDQAAAAAABAAAAB44QklNBBkAAAAAAAQAAAAeOEJJTQPzAAAAAAAJAAAAAAA\n"
- "AAAABADhCSU0ECgAAAAAAAQAAOEJJTScQAAAAAAAKAAEAAAAAAAAAAThCSU0D9QAAAAAASAAvZm\n"
- "YAAQBsZmYABgAAAAAAAQAvZmYAAQChmZoABgAAAAAAAQAyAAAAAQBaAAAABgAAAAAAAQA1AAAAA\n"
- "QAtAAAABgAAAAAAAThCSU0D+AAAAAAAcAAA/////////////////////////////wPoAAAAAP//\n"
- "//////////////////////////8D6AAAAAD/////////////////////////////A+gAAAAA///\n"
- "//////////////////////////wPoAAA4QklNBAgAAAAAABAAAAABAAACQAAAAkAAAAAAOEJJTQ\n"
- "QeAAAAAAAEAAAAADhCSU0EGgAAAAADRQAAAAYAAAAAAAAAAAAAAGQAAABkAAAACABEAFMAQwAwA\n"
- "DIAMwAyADUAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAGQAAABkAAAAAAAAAAAA\n"
- "AAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAEAAAAAAABudWxsAAAAAgAAAAZib3VuZHN\n"
- "PYmpjAAAAAQAAAAAAAFJjdDEAAAAEAAAAAFRvcCBsb25nAAAAAAAAAABMZWZ0bG9uZwAAAAAAAA\n"
- "AAQnRvbWxvbmcAAABkAAAAAFJnaHRsb25nAAAAZAAAAAZzbGljZXNWbExzAAAAAU9iamMAAAABA\n"
- "AAAAAAFc2xpY2UAAAASAAAAB3NsaWNlSURsb25nAAAAAAAAAAdncm91cElEbG9uZwAAAAAAAAAG\n"
- "b3JpZ2luZW51bQAAAAxFU2xpY2VPcmlnaW4AAAANYXV0b0dlbmVyYXRlZAAAAABUeXBlZW51bQA\n"
- "AAApFU2xpY2VUeXBlAAAAAEltZyAAAAAGYm91bmRzT2JqYwAAAAEAAAAAAABSY3QxAAAABAAAAA\n"
- "BUb3AgbG9uZwAAAAAAAAAATGVmdGxvbmcAAAAAAAAAAEJ0b21sb25nAAAAZAAAAABSZ2h0bG9uZ\n"
- "wAAAGQAAAADdXJsVEVYVAAAAAEAAAAAAABudWxsVEVYVAAAAAEAAAAAAABNc2dlVEVYVAAAAAEA\n"
- "AAAAAAZhbHRUYWdURVhUAAAAAQAAAAAADmNlbGxUZXh0SXNIVE1MYm9vbAEAAAAIY2VsbFRleHR\n"
- "URVhUAAAAAQAAAAAACWhvcnpBbGlnbmVudW0AAAAPRVNsaWNlSG9yekFsaWduAAAAB2RlZmF1bH\n"
- "QAAAAJdmVydEFsaWduZW51bQAAAA9FU2xpY2VWZXJ0QWxpZ24AAAAHZGVmYXVsdAAAAAtiZ0Nvb\n"
- "G9yVHlwZWVudW0AAAARRVNsaWNlQkdDb2xvclR5cGUAAAAATm9uZQAAAAl0b3BPdXRzZXRsb25n\n"
- "AAAAAAAAAApsZWZ0T3V0c2V0bG9uZwAAAAAAAAAMYm90dG9tT3V0c2V0bG9uZwAAAAAAAAALcml\n"
- "naHRPdXRzZXRsb25nAAAAAAA4QklNBBEAAAAAAAEBADhCSU0EFAAAAAAABAAAAAE4QklNBAwAAA\n"
- "AACfkAAAABAAAAZAAAAGQAAAEsAAB1MAAACd0AGAAB/9j/4AAQSkZJRgABAgEASABIAAD/7QAMQ\n"
- "WRvYmVfQ00AAv/uAA5BZG9iZQBkgAAAAAH/2wCEAAwICAgJCAwJCQwRCwoLERUPDAwPFRgTExUT\n"
- "ExgRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBDQsLDQ4NEA4OEBQODg4UFA4\n"
- "ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAGQAZA\n"
- "MBIgACEQEDEQH/3QAEAAf/xAE/AAABBQEBAQEBAQAAAAAAAAADAAECBAUGBwgJCgsBAAEFAQEBA\n"
- "QEBAAAAAAAAAAEAAgMEBQYHCAkKCxAAAQQBAwIEAgUHBggFAwwzAQACEQMEIRIxBUFRYRMicYEy\n"
- "BhSRobFCIyQVUsFiMzRygtFDByWSU/Dh8WNzNRaisoMmRJNUZEXCo3Q2F9JV4mXys4TD03Xj80Y\n"
- "nlKSFtJXE1OT0pbXF1eX1VmZ2hpamtsbW5vY3R1dnd4eXp7fH1+f3EQACAgECBAQDBAUGBwcGBT\n"
- "UBAAIRAyExEgRBUWFxIhMFMoGRFKGxQiPBUtHwMyRi4XKCkkNTFWNzNPElBhaisoMHJjXC0kSTV\n"
- "KMXZEVVNnRl4vKzhMPTdePzRpSkhbSVxNTk9KW1xdXl9VZmdoaWprbG1ub2JzdHV2d3h5ent8f/\n"
- "2gAMAwEAAhEDEQA/APLtso1NRc0vP0Rok8NYyPEfijOG2ljBoAJPxKFppZtbS4Rz38kV+OPRDge\n"
- "T89EPHBfvLjtb3P8A30K/j47cgsrYNxGpPYJpK8RtyXUlvPfsobV0GV0uippLiX3EaMb2/rKgMB\n"
- "1ghoiNST4BESCjjLmxqmKtvxiXQ0cd0q8E2bjIDWjk9z5I8QW8JaoHcdkUePZJtZD9p8YU/Rsc/\n"
- "wBNjS5zjDWjUk+SSKYaJLYq+qWeYGQ5lBPLJ3OA8wz2/wDSWni/U3H2AXW2l2oloa0f9LcjSLeU\n"
- "hJdb/wAyqd387Zt+DZ5SSpVh/9DzO6dw7gGPuVn6ft/kyPkqwlxjw1Rnh24QNWjUeR5TSuDc6bg\n"
- "fatpsJZQ3sNC4rWfkVYpbi4LAb3aANEkFLp7GHGYxuhAj4K/hYVNDjYGzZ++eSSoSbLZjGgwxul\n"
- "XNrPqO35FukdmzyXOQeqtqwqRg4o/SOAN9ng3/AMzW02txZ9I+ZHKr241UOcWDaz3uLtSSPEpWu\n"
- "rR5XPeylmyNr4BIPPCyH2Oc6T8kXNvddkPe/VzjJPxQAJMKeIoNScrPk2MbfddXUNXvcGtPx0Xb\n"
- "dJ6NXjOD2Dfdw6w9v5LFW+q/1WLA3Ly9LSJaz91p/wDRjl2lOLWwAMbEJErWjRgESYieVdZhsMF\n"
- "wMt08ldrx/vVivHaOdSgCoud9krmElpba93ASTlr/AP/R83ohr97voiJV/Fq9QvsI+mdPgs1thc\n"
- "BWO5C38CoOY1g78qOejLiGvknxLAyGtExp5K9uzGt9RrNw7DhRfQKKx6bZIGgPj4rPycLqWVtIs\n"
- "JGu5skDyTBRZtQNrb1fU8xrtpBaO4MLQxcx1sNuEjt5rMGJR9noY5hF7Wxa8aAnxVvDb6bgHH2z\n"
- "omk0e64ajUUXnev9Idi5rrWAux7SXNd4E/muS+rHSjm9VbPtZjj1CSJBI+g3+0uh69b+iDG/QcD\n"
- "u0nQCeFP6l0MZhWX/AJ1xM+QafY1TQlY1a+WABsdXp8Sp27aBH+vZaVbC0ADlVcASwtdOolp8Ct\n"
- "BjmtGv0uI8EmJmxkIjWkmPEKLSPiidxIgJKRbDPCSN5pJyH//S87uw/suZ6c72iC13kVs9PdDmk\n"
- "KllVziV3cuafc7yP0QjYFh26cqM6hsxAjIj6u6xzbDHh3R663AaceH+5BwdruVp2PqZUA0a9yo6\n"
- "DPQajscnXb8YQdzC8H909joiZttoxoBIa4gGOQ3uqh+z1RuD2Ds4j2n+39FNKaFMevS/p5LPpSA\n"
- "I8/b/ABW70THZXj11VjaIAIHgFl5VdD8AneDMaec6Lb6QAKmu7x+VSw2a3MdF/rF9YKeh4B9OHZ\n"
- "lpAprPH8p7v5DFwrPrV9YDa645toLjMaFo8mtcEvrhkWZHXbg7T0Q2to8o3f8AfkarEitlVTKnY\n"
- "ra992QQ2wOfG57H2bg7H2fzbFKA130P6n9dHWemCx5H2mk7LgPH818f8IuhAka6ea8y/wAWrcod\n"
- "VyrceRhBsPae5J/Qj+sxq9KDpMuMuKBCEntnny/1CSaWxM6pIKf/0/MvtF3pCrefTBnbOi1elP3\n"
- "Et8Vi+Sv9LuNd4HwTSNGSEqkLerwtwn+SYKtOeS4A8Krh2j1D/K1Vu4B5gaDmVDJtAr7zYYGoRB\n"
- "QDWQ4c9h/csuyjI3fobnDyJR8fF6ltcTaXRwCkAuAsfMGr1TGFNdTmEwLWS2dIK6npLgK2T4Lle\n"
- "pUZxoc9+6K4eR5NO5bPT73NoqIfoILT/JcFJDZr8zGiNXnvrfiur6/Y8tht7WvaexgbXf8AUrFt\n"
- "8IExyvRusYDOsYTAIbfWdzHRJ8HN/tLj7OgdRZawmreHP2gt9wEfvtH0f7SkDXe7+o+AOn9DquL\n"
- "f0mV+leQPH6H+axafUvrB07ptJtyshtTZDTEudJ7bWS5V6MmyltVLn7ht2hwECQP+isb60/Vqvr\n"
- "tbLsa1lObVIJd9Gxv5rXx9F7fzHpIbf/jgfVnd/TLYj6XoOhJcP/zE+sOzd6dW7dt2eo3dH7/9R\n"
- "JJWj//U8uiGFx76BFZLQ2xvLeVGAWQrFDJbtKBSHd6blNura4H3BbDXB7InVcZXZdh2bmTt7hbO\n"
- "J1dj2gzCjlFnhPod3WLHB+n3o9ZsAkFVMfMrs7orLmgkHUdkyqZQQWWQbLGlrjMjUeSrfV3Ltsw\n"
- "30EBzcd5YCedvLETJya66nWOIAaCVnfU/KuZn21CDVa02PngQdHf9LapMfVhzkaAPUUW3M91YaR\n"
- "3YDJ+WiBmZGazPo9Kttdt2j63E6s/fft/d/NWjXkMra7KtO2qkE6cErHpvsyMmzPu0dY4Bg/dYP\n"
- "otTpyoaMUI2XUya8tzG/pi0NMtICo/bsut21gdcWclkj5OncxaDrw6kM+9QxQzaWRAGii4pDqzC\n"
- "MT02aX7WzPU9b7PrG3bvO6P6yStfZm+pHnPySS4590+3jf/V8yb+CsUbp8uyz0kDskbu2dmz9J8\n"
- "lSt9Ld+gn1O8cKikmxXydbH+3bhsmfwWj/lONYlcwkhL6L4bfpOxn/tD0/wBN/N944Wh9VJm/b/\n"
- "O+347df+/rl0k+O38GLJ83X/CfTOt7v2dV6P8AMbx6njHb/pKuN3pN2+IXnaSjybr8e31fUqd+0\n"
- "Sj487DHMryZJMXjq+sfpPX84SXk6SSX/9kAOEJJTQQhAAAAAABVAAAAAQEAAAAPAEEAZABvAGIA\n"
- "ZQAgAFAAaABvAHQAbwBzAGgAbwBwAAAAEwBBAGQAbwBiAGUAIABQAGgAbwB0AG8AcwBoAG8AcAA\n"
- "gADcALgAwAAAAAQA4QklNBAYAAAAAAAcABQAAAAEBAP/hFWdodHRwOi8vbnMuYWRvYmUuY29tL3\n"
- "hhcC8xLjAvADw/eHBhY2tldCBiZWdpbj0n77u/JyBpZD0nVzVNME1wQ2VoaUh6cmVTek5UY3prY\n"
- "zlkJz8+Cjw/YWRvYmUteGFwLWZpbHRlcnMgZXNjPSJDUiI/Pgo8eDp4YXBtZXRhIHhtbG5zOng9\n"
- "J2Fkb2JlOm5zOm1ldGEvJyB4OnhhcHRrPSdYTVAgdG9vbGtpdCAyLjguMi0zMywgZnJhbWV3b3J\n"
- "rIDEuNSc+CjxyZGY6UkRGIHhtbG5zOnJkZj0naHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi\n"
- "1yZGYtc3ludGF4LW5zIycgeG1sbnM6aVg9J2h0dHA6Ly9ucy5hZG9iZS5jb20vaVgvMS4wLyc+C\n"
- "gogPHJkZjpEZXNjcmlwdGlvbiBhYm91dD0ndXVpZDoyMmQwMmIwYS1iMjQ5LTExZGItOGFmOC05\n"
- "MWQ1NDAzZjkyZjknCiAgeG1sbnM6cGRmPSdodHRwOi8vbnMuYWRvYmUuY29tL3BkZi8xLjMvJz4\n"
- "KICA8IS0tIHBkZjpTdWJqZWN0IGlzIGFsaWFzZWQgLS0+CiA8L3JkZjpEZXNjcmlwdGlvbj4KCi\n"
- "A8cmRmOkRlc2NyaXB0aW9uIGFib3V0PSd1dWlkOjIyZDAyYjBhLWIyNDktMTFkYi04YWY4LTkxZ\n"
- "DU0MDNmOTJmOScKICB4bWxuczpwaG90b3Nob3A9J2h0dHA6Ly9ucy5hZG9iZS5jb20vcGhvdG9z\n"
- "aG9wLzEuMC8nPgogIDwhLS0gcGhvdG9zaG9wOkNhcHRpb24gaXMgYWxpYXNlZCAtLT4KIDwvcmR\n"
- "mOkRlc2NyaXB0aW9uPgoKIDxyZGY6RGVzY3JpcHRpb24gYWJvdXQ9J3V1aWQ6MjJkMDJiMGEtYj\n"
- "I0OS0xMWRiLThhZjgtOTFkNTQwM2Y5MmY5JwogIHhtbG5zOnhhcD0naHR0cDovL25zLmFkb2JlL\n"
- "mNvbS94YXAvMS4wLyc+CiAgPCEtLSB4YXA6RGVzY3JpcHRpb24gaXMgYWxpYXNlZCAtLT4KIDwv\n"
- "cmRmOkRlc2NyaXB0aW9uPgoKIDxyZGY6RGVzY3JpcHRpb24gYWJvdXQ9J3V1aWQ6MjJkMDJiMGE\n"
- "tYjI0OS0xMWRiLThhZjgtOTFkNTQwM2Y5MmY5JwogIHhtbG5zOnhhcE1NPSdodHRwOi8vbnMuYW\n"
- "RvYmUuY29tL3hhcC8xLjAvbW0vJz4KICA8eGFwTU06RG9jdW1lbnRJRD5hZG9iZTpkb2NpZDpwa\n"
- "G90b3Nob3A6MjJkMDJiMDYtYjI0OS0xMWRiLThhZjgtOTFkNTQwM2Y5MmY5PC94YXBNTTpEb2N1\n"
- "bWVudElEPgogPC9yZGY6RGVzY3JpcHRpb24+CgogPHJkZjpEZXNjcmlwdGlvbiBhYm91dD0ndXV\n"
- "pZDoyMmQwMmIwYS1iMjQ5LTExZGItOGFmOC05MWQ1NDAzZjkyZjknCiAgeG1sbnM6ZGM9J2h0dH\n"
- "A6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvJz4KICA8ZGM6ZGVzY3JpcHRpb24+CiAgIDxyZ\n"
- "GY6QWx0PgogICAgPHJkZjpsaSB4bWw6bGFuZz0neC1kZWZhdWx0Jz4gICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgPC9yZGY6bGk+CiAgIDwvcmRmOkFsdD4KICA8L2RjOmRlc2NyaXB0aW9\n"
- "uPgogPC9yZGY6RGVzY3JpcHRpb24+Cgo8L3JkZjpSREY+CjwveDp4YXBtZXRhPgogICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIA\n"
- "ogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg\n"
- "ICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC\n"
- "AgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI\n"
- "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAg\n"
- "ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA\n"
- "gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgIC\n"
- "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0ndyc/P\n"
- "v/uAA5BZG9iZQBkQAAAAAH/2wCEAAQDAwMDAwQDAwQGBAMEBgcFBAQFBwgGBgcGBggKCAkJCQkI\n"
- "CgoMDAwMDAoMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBAUFCAcIDwoKDxQODg4UFA4ODg4UEQwMDAw\n"
- "MEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAGQAZAMBEQACEQEDEQ\n"
- "H/3QAEAA3/xAGiAAAABwEBAQEBAAAAAAAAAAAEBQMCBgEABwgJCgsBAAICAwEBAQEBAAAAAAAAA\n"
- "AEAAgMEBQYHCAkKCxAAAgEDAwIEAgYHAwQCBgJzAQIDEQQABSESMUFRBhNhInGBFDKRoQcVsUIj\n"
- "wVLR4TMWYvAkcoLxJUM0U5KismNzwjVEJ5OjszYXVGR0w9LiCCaDCQoYGYSURUaktFbTVSga8uP\n"
- "zxNTk9GV1hZWltcXV5fVmdoaWprbG1ub2N0dXZ3eHl6e3x9fn9zhIWGh4iJiouMjY6PgpOUlZaX\n"
- "mJmam5ydnp+So6SlpqeoqaqrrK2ur6EQACAgECAwUFBAUGBAgDA20BAAIRAwQhEjFBBVETYSIGc\n"
- "YGRMqGx8BTB0eEjQhVSYnLxMyQ0Q4IWklMlomOywgdz0jXiRIMXVJMICQoYGSY2RRonZHRVN/Kj\n"
- "s8MoKdPj84SUpLTE1OT0ZXWFlaW1xdXl9UZWZnaGlqa2xtbm9kdXZ3eHl6e3x9fn9zhIWGh4iJi\n"
- "ouMjY6Pg5SVlpeYmZqbnJ2en5KjpKWmp6ipqqusra6vr/2gAMAwEAAhEDEQA/APBnplwPAdR+GB\n"
- "KY6dYtNG1w39yh4+xb+zIksgEfFaRSSoIx8f7RPRRkSWQimM+lRmwWVXFWYigHxUUVoMiJM+Fj0\n"
- "tg0RBegLE0Wu+3c+GTBazFCGI7HtSp9slbFYYzyoBsegw2hY1Afl3wqqRqahk+0tDgKpgu4DAUU\n"
- "+HY+GRS2ePiMKtUB3G+KGuONq//Q8OzpFbW5WnxMop4k9crG5ZnZNJkEOn21utVRYw7HxZtz+OR\n"
- "vdsrZ2lRtci4aVxFEQA0neg/ZXxJpTITNNuOFss0vSotYNvZ2qGRkPKSTqiU8Sdqk5SZU5Ix8XJ\n"
- "NNZ8k6bp8TtM73OputUtYq0Unux/hkRkJOzZLCAN2KR+VpbtSkCBaDnIzdlWu59u+XeJTjeASk8\n"
- "+juZOESEAVqx8BvU/PJibScTrTy09560hkWOGFd2YgFnPQKD19zhOSkxw2l8Vm6XAiYb8gg+k5O\n"
- "9mnhoon9H3cs5s7WF5pp29OGGMFndyaAKBuTiEEPQLD8h/NDmNdYlttNkYjlbFjcXCr3LLH8II8\n"
- "C2WUGviZvon/OPWkm3RNSv72SYllMkKxQRV67CQMSKYQAxMkR/wBC56d61P0heel4cYuVOXWvTp\n"
- "h4Qjjf/9Hw5qBYyISaqjBV+QpvkAzKcki4HomnIxck/wBhtlR2bhunvlDywddMUl4zW+kQ9FQ8X\n"
- "nfuSewrtmPkycPvc/DhMhvyegXOrWWhmLQPKlsj6xIAiLCoZkY96nv7npmJvI2XOjQFMl0fyRqM\n"
- "NoxvZvrGt33wlATwiMnVnY1LEdSfuyXF3KIDmUu88w2XlnTl8raAlb2ZFfVL0jdYRtQnxc7BfDC\n"
- "OaJR7nm3me5tdOtjbMvp3ZRXkV6chVQRX79hmVjgZG+jgZ5jHGhzecXF5LPL6jEjstSSaDM51Ka\n"
- "6MZ9S1C0sEBe8uZo4YCBXdjxGw60wEWyEqfUHkT8vLXRJFuLdTcaqfhlvWUErtukZ3ABPUjIXTE\n"
- "m3rGmeV2Tk5UKz/AG/E/wAcgZKya20C3b02kjYtH8AqCygbkUH0nLYlgUb+gbWtPbpXt/n2ybB/\n"
- "/9Lw4oaVxGd+PxH3qBkGaY3KyiSP01IkiUclH8sg+LKydm6INvZvKsFu+kWtvD8LRoFNRup6moO\n"
- "aqd277HsGW+XPLmn6XM17FF6l7vW4fd2Zuu+RFls2tmUNrLJb7TSBertGQGqetDkxE0na0pvtHs\n"
- "QkszWyiGAG5laYlnkeMVHJj8sA5rPk+SvMepTalqlxd3B5zTOXdj/MxqafLpm5xioh5nPK5kpRG\n"
- "pkcKAST0A6k5NpfUP5K/ki1ssHmHzF+71KRQ8Nud/Qibb/kYw6/yjbrXISlSH07YaHbWyxx2kXE\n"
- "KACB2zHJtLI7XSelBRvH2xCpvaaTDHXkOTVBPcUG2479RlsdmJVPRtvV+ylenQ0y62FP/9PxRpo\n"
- "WG5FxKKxKFDA+GVS5NsebLdFsRePc3siVW4f4QR0QVAGYeSXR2unhtZ6s60K6jt+MMSFwtF2+xX\n"
- "wr7eGUGLlRPQMsE2vxQm7itxKg3VCfT2+nb8cDYaCDtfOXmCCcROrQrUhkkCHYn6emRMqZxjbLd\n"
- "F1+W/4xajHzjNCtQKMffETWUdngX5p+QZ9A8xS6hbo0ui37NNDPT7DOalHpsCD08Rmyw5ARTpdV\n"
- "gIPEF35MeRn80ed4S5EdrpKm9kZ15K0iH92hB7Me/tmS60vt/QrCYyekiBdgSTXcjqV9q9MokFD\n"
- "N7S3aFVVR8RoK9zldqndvAY6nffr/AGYQqLhjdpCoIAZW22HavU/LJBUP9WblX0xTw7fOmWsX/9\n"
- "Tw7FdvMqWkQ3Z1qfED+mQIbI77PX/LFis9vBajZm2Y+x65rMh3t30Bsze400aVaIbSLk6r8CMRT\n"
- "l/NmOcllnGDD9Y8uecNfEEiXrMgDGWAyGOOu5WlB+vMrHODTlxZCdjsyFdB006VpVtLasurQxBL\n"
- "64WiLI4/aFT1ANOXemV5piR2b9NiljB4yyHy9CLOVI5GJhB+CvXY9R8xmINzs5HNZ+Z96BZpbxA\n"
- "fVJo39UFefwopYgL4nMiMd2qZoIn/AJx00u3t/Lt7qpp9Yv5GLf5MUTERqfbvmzBeezjd9H+VlL\n"
- "wSQzBqsvOGQD7L12rXsemPNxmXQSxxIPU2nFV4HYqR1xEUWj4ZAxBryr2G+J2VGDZlLrxUH6KZA\n"
- "Fkqb15VFelfwy+2FP8A/9Xxlf6AdA182Yk9eFeLxSjoVfcfSMo4uIOfkweFOnpvlWYrLEwNFAA+\n"
- "nMOYdrhFvQLeSO7coBXiK8iKiv07Zj8Ac4QtNrW1njUcKcT+yAR/xGmR4WcsStLpTuPU9IFaEsV\n"
- "BP3k4m2AgBzSwyQNcIwNTE1aI3wnam9O2Ug7s5Ckk/NDndeVXa2H78MqqV6jmeBp9+ZWKXqDjZ4\n"
- "+gvVvy30qCy0qzsLRBCnBI2VdgUTqPvOZ7y+Q7pz+bn5q6d+VflZxZlJ/NN4ypptk5qtB9qRwDX\n"
- "gn/AAx2y2ItpfKFv+eH5qNeTajJ5ovVaVywSqvEtTUKqupAA6D2y0BNPtv/AJx//M5PzL8mJeXT\n"
- "L+ndPf6rqarSpkAqsnEAAeoN6DpkJRYci9lROSgSUUH9o9K5Tw0ztfSHnXkOtK9q+PHwydq//9b\n"
- "yxrVoZNBtNSA5zRMPXmH8j0CLXuBmHE+qneamHpEuqYeV7pzFVTRgQK5XMNmnlb1vyyY5QA1OwJ\n"
- "+eUF2seTOLu5s7azVIVAkpVn/hhnIALG73Yz5jvb1dICqzpDNIqyFD8SxH7R28cxibZCiWOsdJs\n"
- "PTM6XNstPhnkjIhcHuJBVfvOCiUSn0TfWrTTLjyw8guA/PifTO3xcxxA8a5ZAbimvJP0m3p/kFF\n"
- "WxhmpWQJ9NW3zZPHz5vlb/nIDVbrWfzO1RJhxGnpDaRL/khA1T7ktmSOTAJhZaAUtLawsbayl8v\n"
- "xWi3Gpay0cF3HPcFRJJHJMXVrcJ8UaAFG5LWjF8tAYW9H/wCcOo9bTzxrt/owkTyksZW5gkIKvI\n"
- "7k26nvyReRJHyyBWT7dWQyOWlbnK2526e1O1MqIUFE84uPLkOdK9RXI0E2/wD/1/DA1bURZLY/W\n"
- "ZDZqwb0eXw7dMgIi7bjllVXsz7yNcfWC0Vd3Ip92Y2UOz0cnsPlwyx8xQ/u24sMxCadoJp9LOXk\n"
- "VX/uwRUE0BI8cokbLMyoKouHu2MaKGXw7fLDwgoGSkbHpaNZyLLHRSKcFFQQRvUdMlwUFOQyLzr\n"
- "ztpCaba6fPau4ijv4OURY8AjVFKV7ZZiO+7Vnh6XvXkSWNbW2WTb92KDxIFMzwHlZc3zX+fuizW\n"
- "f5p3ty8XGDU4YLmCQiisyII3+4rvl8UB5ffEghRGvOm7AbnvWvjk1fen/ONPldPKP5aWOpPCfr2\n"
- "uE31y6q2wbaMEn+VAMDSdyzrzj+avlHyTp0l/r2rxWFuHWJuIeacu4qFCRgsajfBwsty89/6Gr/\n"
- "ACa9an+JL/hSnrfoubhXwpXpjwhaL//Q8E1AqtcAZMs8l6i1nqMa1oSVP0VynKLDmaWdSfQXl69\n"
- "jF1Jv8MhDb5rpB3AO7INRRLhhGp4R05FgaGvTMU8200xS70zVDMRp2pTIOvBmB3PgQP15kxIcnD\n"
- "LH/EEz0rRvOJhldr9pQtCqyd6VrShGTqw5d4ARv9jHfOGl+ZJNMluLkyenaFbiRdqFYW5nrWuwO\n"
- "MKB5MdSMRxnhlu9N8p6lLFpti63FUjCtFJTrDKvse2bEDZ4XJ9RZB+YPli2/Mjy5bxoUi1a0YS2\n"
- "85UOwIXiy9jRu+TBppfOF1+V3m22vrdpNPM8cs/oo0VJlUqQPjValR3+IZNNvtLS9Yu9Mi0/TJr\n"
- "kyp6QhWVVCIWRATsKBemwwFrDzT87fybs/wA1bW21PRb+DTvNlgGSRp6iC8i3KJJx+y6n7D0Pwm\n"
- "hxBZXT55/6Fi/Nf0PW+qWXq+t6X1X67F6vD/ftK04V/wBl344U8b//0fBapxheVh9ocV+nviqY2\n"
- "/qQJDew/bioWHiuQ8m0bbvaPKGtQ6jaxSo9JloCK75gZI0Xb4sgkHo8MouoAvP94BsRmGY7uWJU\n"
- "gzbypOQpNOvIdK4Nw2WCE2tXulTkjEEbdafgclxMhFBas93dwyQzsWDghlJFONKHJCZtjOFBJfy\n"
- "j1y9vPL9zpbIs0WkXL2sUjA8hDXlGCRXtt07ZuYvL5KJeo6bfajbkzWkcToR8dqshZ6in2fhNK/\n"
- "PDTUlXmHVvMdr5o0v9H2kdrqGpfu7m0nkY87Uf7tkKAU4/s03ynLkEBbfihx7dGT6va67LbRMNR\n"
- "aKOBuUTKgIBXoK1BOYR1M3aQ0mOt9yxUeZNdtJhFapLqMluSXkg5oxJrUMW5KevQ9MmNXXNqOiH\n"
- "Rr/Hmv8A1r9I/oj95w+r+j9Yf1+NP5+nXtTD+dF8tkfkOlv/0vC3ph7f0/alcVTbS4A8QibuKb5\n"
- "RI05EBYRFpdX3ly79a2qYCavH/EY7TCYyMD5PSdD8+wXUSn1ArDqOhBzFlipz4ZwWbaV5htbsgF\n"
- "qg9crMXKErGyYwajFGzxyHlGSePbbwyqg5UZlCaxrFpaWU95LIqrEjMAT4Dp9OShGy1ZslBhv/A\n"
- "Dj9rd/a+aL+xUK+m38L3d0HrxRo2HFtu5D8c27y8t30raarbWkU+u6g4gsNORn+EcUaSh2Pc0/4\n"
- "lgtAjezzbT9SutY1i782al8Nxdyotqh6xWybIg+jc5q8s+I27bFDgFPQp9RE+nrag70+L6crrZu\n"
- "4jajokdv6LW/Dii1Wo61PXKQN3KPK0L+h4/rnD/K5V78a5LhXxd3/0/DMXXtwxVNtL9Xkaf3f7N\n"
- "etfbKMjdjtkZ9D6ufrlK0+HpX8coF9HJ26sXvfqXrf7i/U+uften/d/wCyrmQL6uOav0pvpP8Ai\n"
- "b1F+rV59+vH6a5XLhcjH4nRmY/xpxHP0/UptWvT6Mx/RbmjxWK+aP8AFf1M/pCv1Kvxen9inavf\n"
- "MrFwXtzcLUeLXq5Mv/I3nz1b0v8AjofuKVry9KrUpTanOlf9jmQ68va/zH9b/COn/o7/AI431mP\n"
- "65SvLh+zWvbl9rMfNfC34K4kmj9T6lD6FKclp/DNYXZx5srsPrHor6nXvkgxTPS/U+rv6dPU5mt\n"
- "fngFN5ulv+l/pL/Lp/scerHo//2Q==\n";
-
-static std::string gCommandLine;
-
-TEST(Base64, LargeSample) {
- LOG(LS_VERBOSE) << "Testing specific base64 file";
-
- char unescaped[64 * 1024];
-
- // unescape that massive blob above
- size_t size = Base64Unescape(SpecificTest,
- sizeof(SpecificTest),
- unescaped,
- sizeof(unescaped));
-
- EXPECT_EQ(size, sizeof(testbase64));
- EXPECT_EQ(0, memcmp(testbase64, unescaped, sizeof(testbase64)));
-}
-
-bool DecodeTest(const char* encoded, size_t expect_unparsed,
- const char* decoded, Base64::DecodeFlags flags)
-{
- std::string result;
- size_t consumed = 0, encoded_len = strlen(encoded);
- bool success = Base64::DecodeFromArray(encoded, encoded_len, flags,
- &result, &consumed);
- size_t unparsed = encoded_len - consumed;
- EXPECT_EQ(expect_unparsed, unparsed) << "\"" << encoded
- << "\" -> \"" << decoded
- << "\"";
- EXPECT_STREQ(decoded, result.c_str());
- return success;
-}
-
-#define Flags(x,y,z) \
- Base64::DO_PARSE_##x | Base64::DO_PAD_##y | Base64::DO_TERM_##z
-
-TEST(Base64, DecodeParseOptions) {
- // Trailing whitespace
- EXPECT_TRUE (DecodeTest("YWJjZA== ", 1, "abcd", Flags(STRICT, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA== ", 0, "abcd", Flags(WHITE, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA== ", 0, "abcd", Flags(ANY, YES, CHAR)));
-
- // Embedded whitespace
- EXPECT_FALSE(DecodeTest("YWJjZA= =", 3, "abcd", Flags(STRICT, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA= =", 0, "abcd", Flags(WHITE, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA= =", 0, "abcd", Flags(ANY, YES, CHAR)));
-
- // Embedded non-base64 characters
- EXPECT_FALSE(DecodeTest("YWJjZA=*=", 3, "abcd", Flags(STRICT, YES, CHAR)));
- EXPECT_FALSE(DecodeTest("YWJjZA=*=", 3, "abcd", Flags(WHITE, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA=*=", 0, "abcd", Flags(ANY, YES, CHAR)));
-
- // Unexpected padding characters
- EXPECT_FALSE(DecodeTest("YW=JjZA==", 7, "a", Flags(STRICT, YES, CHAR)));
- EXPECT_FALSE(DecodeTest("YW=JjZA==", 7, "a", Flags(WHITE, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YW=JjZA==", 0, "abcd", Flags(ANY, YES, CHAR)));
-}
-
-TEST(Base64, DecodePadOptions) {
- // Padding
- EXPECT_TRUE (DecodeTest("YWJjZA==", 0, "abcd", Flags(STRICT, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA==", 0, "abcd", Flags(STRICT, ANY, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA==", 2, "abcd", Flags(STRICT, NO, CHAR)));
-
- // Incomplete padding
- EXPECT_FALSE(DecodeTest("YWJjZA=", 1, "abcd", Flags(STRICT, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA=", 1, "abcd", Flags(STRICT, ANY, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA=", 1, "abcd", Flags(STRICT, NO, CHAR)));
-
- // No padding
- EXPECT_FALSE(DecodeTest("YWJjZA", 0, "abcd", Flags(STRICT, YES, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA", 0, "abcd", Flags(STRICT, ANY, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJjZA", 0, "abcd", Flags(STRICT, NO, CHAR)));
-}
-
-TEST(Base64, DecodeTerminateOptions) {
- // Complete quantum
- EXPECT_TRUE (DecodeTest("YWJj", 0, "abc", Flags(STRICT, NO, BUFFER)));
- EXPECT_TRUE (DecodeTest("YWJj", 0, "abc", Flags(STRICT, NO, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJj", 0, "abc", Flags(STRICT, NO, ANY)));
-
- // Complete quantum with trailing data
- EXPECT_FALSE(DecodeTest("YWJj*", 1, "abc", Flags(STRICT, NO, BUFFER)));
- EXPECT_TRUE (DecodeTest("YWJj*", 1, "abc", Flags(STRICT, NO, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJj*", 1, "abc", Flags(STRICT, NO, ANY)));
-
- // Incomplete quantum
- EXPECT_FALSE(DecodeTest("YWJ", 0, "ab", Flags(STRICT, NO, BUFFER)));
- EXPECT_FALSE(DecodeTest("YWJ", 0, "ab", Flags(STRICT, NO, CHAR)));
- EXPECT_TRUE (DecodeTest("YWJ", 0, "ab", Flags(STRICT, NO, ANY)));
-}
-
-TEST(Base64, GetNextBase64Char) {
- // The table looks like this:
- // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
- char next_char;
- EXPECT_TRUE(Base64::GetNextBase64Char('A', &next_char));
- EXPECT_EQ('B', next_char);
- EXPECT_TRUE(Base64::GetNextBase64Char('Z', &next_char));
- EXPECT_EQ('a', next_char);
- EXPECT_TRUE(Base64::GetNextBase64Char('/', &next_char));
- EXPECT_EQ('A', next_char);
- EXPECT_FALSE(Base64::GetNextBase64Char('&', &next_char));
- EXPECT_FALSE(Base64::GetNextBase64Char('Z', NULL));
-}
diff --git a/base/basicdefs.h b/base/basicdefs.h
deleted file mode 100644
index 7829d45..0000000
--- a/base/basicdefs.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_BASICDEFS_H_
-#define TALK_BASE_BASICDEFS_H_
-
-#if HAVE_CONFIG_H
-#include "config.h" // NOLINT
-#endif
-
-#define ARRAY_SIZE(x) (static_cast<int>(sizeof(x) / sizeof(x[0])))
-
-#endif // TALK_BASE_BASICDEFS_H_
diff --git a/base/basictypes.h b/base/basictypes.h
deleted file mode 100644
index f7f5b66..0000000
--- a/base/basictypes.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_BASICTYPES_H_
-#define TALK_BASE_BASICTYPES_H_
-
-#include <stddef.h> // for NULL, size_t
-
-#if !(defined(_MSC_VER) && (_MSC_VER < 1600))
-#include <stdint.h> // for uintptr_t
-#endif
-
-#ifdef HAVE_CONFIG_H
-#include "config.h" // NOLINT
-#endif
-
-#include "talk/base/constructormagic.h"
-
-#if !defined(INT_TYPES_DEFINED)
-#define INT_TYPES_DEFINED
-#ifdef COMPILER_MSVC
-typedef unsigned __int64 uint64;
-typedef __int64 int64;
-#ifndef INT64_C
-#define INT64_C(x) x ## I64
-#endif
-#ifndef UINT64_C
-#define UINT64_C(x) x ## UI64
-#endif
-#define INT64_F "I64"
-#else // COMPILER_MSVC
-// On Mac OS X, cssmconfig.h defines uint64 as uint64_t
-// TODO(fbarchard): Use long long for compatibility with chromium on BSD/OSX.
-#if defined(OSX)
-typedef uint64_t uint64;
-typedef int64_t int64;
-#ifndef INT64_C
-#define INT64_C(x) x ## LL
-#endif
-#ifndef UINT64_C
-#define UINT64_C(x) x ## ULL
-#endif
-#define INT64_F "l"
-#elif defined(__LP64__)
-typedef unsigned long uint64; // NOLINT
-typedef long int64; // NOLINT
-#ifndef INT64_C
-#define INT64_C(x) x ## L
-#endif
-#ifndef UINT64_C
-#define UINT64_C(x) x ## UL
-#endif
-#define INT64_F "l"
-#else // __LP64__
-typedef unsigned long long uint64; // NOLINT
-typedef long long int64; // NOLINT
-#ifndef INT64_C
-#define INT64_C(x) x ## LL
-#endif
-#ifndef UINT64_C
-#define UINT64_C(x) x ## ULL
-#endif
-#define INT64_F "ll"
-#endif // __LP64__
-#endif // COMPILER_MSVC
-typedef unsigned int uint32;
-typedef int int32;
-typedef unsigned short uint16; // NOLINT
-typedef short int16; // NOLINT
-typedef unsigned char uint8;
-typedef signed char int8;
-#endif // INT_TYPES_DEFINED
-
-// Detect compiler is for x86 or x64.
-#if defined(__x86_64__) || defined(_M_X64) || \
- defined(__i386__) || defined(_M_IX86)
-#define CPU_X86 1
-#endif
-// Detect compiler is for arm.
-#if defined(__arm__) || defined(_M_ARM)
-#define CPU_ARM 1
-#endif
-#if defined(CPU_X86) && defined(CPU_ARM)
-#error CPU_X86 and CPU_ARM both defined.
-#endif
-#if !defined(ARCH_CPU_BIG_ENDIAN) && !defined(ARCH_CPU_LITTLE_ENDIAN)
-// x86, arm or GCC provided __BYTE_ORDER__ macros
-#if CPU_X86 || CPU_ARM || \
- (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
-#define ARCH_CPU_LITTLE_ENDIAN
-#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
-#define ARCH_CPU_BIG_ENDIAN
-#else
-#error ARCH_CPU_BIG_ENDIAN or ARCH_CPU_LITTLE_ENDIAN should be defined.
-#endif
-#endif
-#if defined(ARCH_CPU_BIG_ENDIAN) && defined(ARCH_CPU_LITTLE_ENDIAN)
-#error ARCH_CPU_BIG_ENDIAN and ARCH_CPU_LITTLE_ENDIAN both defined.
-#endif
-
-#ifdef WIN32
-typedef int socklen_t;
-#endif
-
-// The following only works for C++
-#ifdef __cplusplus
-namespace talk_base {
- template<class T> inline T _min(T a, T b) { return (a > b) ? b : a; }
- template<class T> inline T _max(T a, T b) { return (a < b) ? b : a; }
-
- // For wait functions that take a number of milliseconds, kForever indicates
- // unlimited time.
- const int kForever = -1;
-}
-
-#define ALIGNP(p, t) \
- (reinterpret_cast<uint8*>(((reinterpret_cast<uintptr_t>(p) + \
- ((t) - 1)) & ~((t) - 1))))
-#define IS_ALIGNED(p, a) (!((uintptr_t)(p) & ((a) - 1)))
-
-// Note: UNUSED is also defined in common.h
-#ifndef UNUSED
-#define UNUSED(x) Unused(static_cast<const void*>(&x))
-#define UNUSED2(x, y) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y))
-#define UNUSED3(x, y, z) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y)); \
- Unused(static_cast<const void*>(&z))
-#define UNUSED4(x, y, z, a) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y)); \
- Unused(static_cast<const void*>(&z)); \
- Unused(static_cast<const void*>(&a))
-#define UNUSED5(x, y, z, a, b) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y)); \
- Unused(static_cast<const void*>(&z)); \
- Unused(static_cast<const void*>(&a)); \
- Unused(static_cast<const void*>(&b))
-inline void Unused(const void*) {}
-#endif // UNUSED
-
-// Use these to declare and define a static local variable (static T;) so that
-// it is leaked so that its destructors are not called at exit.
-#define LIBJINGLE_DEFINE_STATIC_LOCAL(type, name, arguments) \
- static type& name = *new type arguments
-
-#endif // __cplusplus
-#endif // TALK_BASE_BASICTYPES_H_
diff --git a/base/basictypes_unittest.cc b/base/basictypes_unittest.cc
deleted file mode 100644
index caf1115..0000000
--- a/base/basictypes_unittest.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/basictypes.h"
-
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-TEST(BasicTypesTest, Endian) {
- uint16 v16 = 0x1234u;
- uint8 first_byte = *reinterpret_cast<uint8*>(&v16);
-#if defined(ARCH_CPU_LITTLE_ENDIAN)
- EXPECT_EQ(0x34u, first_byte);
-#elif defined(ARCH_CPU_BIG_ENDIAN)
- EXPECT_EQ(0x12u, first_byte);
-#endif
-}
-
-TEST(BasicTypesTest, SizeOfTypes) {
- int8 i8 = -1;
- uint8 u8 = 1u;
- int16 i16 = -1;
- uint16 u16 = 1u;
- int32 i32 = -1;
- uint32 u32 = 1u;
- int64 i64 = -1;
- uint64 u64 = 1u;
- EXPECT_EQ(1u, sizeof(i8));
- EXPECT_EQ(1u, sizeof(u8));
- EXPECT_EQ(2u, sizeof(i16));
- EXPECT_EQ(2u, sizeof(u16));
- EXPECT_EQ(4u, sizeof(i32));
- EXPECT_EQ(4u, sizeof(u32));
- EXPECT_EQ(8u, sizeof(i64));
- EXPECT_EQ(8u, sizeof(u64));
- EXPECT_GT(0, i8);
- EXPECT_LT(0u, u8);
- EXPECT_GT(0, i16);
- EXPECT_LT(0u, u16);
- EXPECT_GT(0, i32);
- EXPECT_LT(0u, u32);
- EXPECT_GT(0, i64);
- EXPECT_LT(0u, u64);
-}
-
-TEST(BasicTypesTest, SizeOfConstants) {
- EXPECT_EQ(8u, sizeof(INT64_C(0)));
- EXPECT_EQ(8u, sizeof(UINT64_C(0)));
- EXPECT_EQ(8u, sizeof(INT64_C(0x1234567887654321)));
- EXPECT_EQ(8u, sizeof(UINT64_C(0x8765432112345678)));
-}
-
-// Test CPU_ macros
-#if !defined(CPU_ARM) && defined(__arm__)
-#error expected CPU_ARM to be defined.
-#endif
-#if !defined(CPU_X86) && (defined(WIN32) || defined(OSX))
-#error expected CPU_X86 to be defined.
-#endif
-#if !defined(ARCH_CPU_LITTLE_ENDIAN) && \
- (defined(WIN32) || defined(OSX) || defined(CPU_X86))
-#error expected ARCH_CPU_LITTLE_ENDIAN to be defined.
-#endif
-
-// TODO(fbarchard): Test all macros in basictypes.h
-
-} // namespace talk_base
diff --git a/base/bind.h b/base/bind.h
deleted file mode 100644
index 5b4eaac..0000000
--- a/base/bind.h
+++ /dev/null
@@ -1,604 +0,0 @@
-// This file was GENERATED by command:
-// pump.py bind.h.pump
-// DO NOT EDIT BY HAND!!!
-
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// To generate bind.h from bind.h.pump, execute:
-// /home/build/google3/third_party/gtest/scripts/pump.py bind.h.pump
-
-// Bind() is an overloaded function that converts method calls into function
-// objects (aka functors). It captures any arguments to the method by value
-// when Bind is called, producing a stateful, nullary function object. Care
-// should be taken about the lifetime of objects captured by Bind(); the
-// returned functor knows nothing about the lifetime of the method's object or
-// any arguments passed by pointer, and calling the functor with a destroyed
-// object will surely do bad things.
-//
-// Example usage:
-// struct Foo {
-// int Test1() { return 42; }
-// int Test2() const { return 52; }
-// int Test3(int x) { return x*x; }
-// float Test4(int x, float y) { return x + y; }
-// };
-//
-// int main() {
-// Foo foo;
-// cout << talk_base::Bind(&Foo::Test1, &foo)() << endl;
-// cout << talk_base::Bind(&Foo::Test2, &foo)() << endl;
-// cout << talk_base::Bind(&Foo::Test3, &foo, 3)() << endl;
-// cout << talk_base::Bind(&Foo::Test4, &foo, 7, 8.5f)() << endl;
-// }
-
-#ifndef TALK_BASE_BIND_H_
-#define TALK_BASE_BIND_H_
-
-#define NONAME
-
-namespace talk_base {
-namespace detail {
-// This is needed because the template parameters in Bind can't be resolved
-// if they're used both as parameters of the function pointer type and as
-// parameters to Bind itself: the function pointer parameters are exact
-// matches to the function prototype, but the parameters to bind have
-// references stripped. This trick allows the compiler to dictate the Bind
-// parameter types rather than deduce them.
-template <class T> struct identity { typedef T type; };
-} // namespace detail
-
-template <class ObjectT, class MethodT, class R>
-class MethodFunctor0 {
- public:
- MethodFunctor0(MethodT method, ObjectT* object)
- : method_(method), object_(object) {}
- R operator()() const {
- return (object_->*method_)(); }
- private:
- MethodT method_;
- ObjectT* object_;
-};
-
-template <class FunctorT, class R>
-class Functor0 {
- public:
- explicit Functor0(const FunctorT& functor)
- : functor_(functor) {}
- R operator()() const {
- return functor_(); }
- private:
- FunctorT functor_;
-};
-
-
-#define FP_T(x) R (ObjectT::*x)()
-
-template <class ObjectT, class R>
-MethodFunctor0<ObjectT, FP_T(NONAME), R>
-Bind(FP_T(method), ObjectT* object) {
- return MethodFunctor0<ObjectT, FP_T(NONAME), R>(
- method, object);
-}
-
-#undef FP_T
-#define FP_T(x) R (ObjectT::*x)() const
-
-template <class ObjectT, class R>
-MethodFunctor0<const ObjectT, FP_T(NONAME), R>
-Bind(FP_T(method), const ObjectT* object) {
- return MethodFunctor0<const ObjectT, FP_T(NONAME), R>(
- method, object);
-}
-
-#undef FP_T
-#define FP_T(x) R (*x)()
-
-template <class R>
-Functor0<FP_T(NONAME), R>
-Bind(FP_T(function)) {
- return Functor0<FP_T(NONAME), R>(
- function);
-}
-
-#undef FP_T
-
-template <class ObjectT, class MethodT, class R,
- class P1>
-class MethodFunctor1 {
- public:
- MethodFunctor1(MethodT method, ObjectT* object,
- P1 p1)
- : method_(method), object_(object),
- p1_(p1) {}
- R operator()() const {
- return (object_->*method_)(p1_); }
- private:
- MethodT method_;
- ObjectT* object_;
- P1 p1_;
-};
-
-template <class FunctorT, class R,
- class P1>
-class Functor1 {
- public:
- Functor1(const FunctorT& functor, P1 p1)
- : functor_(functor),
- p1_(p1) {}
- R operator()() const {
- return functor_(p1_); }
- private:
- FunctorT functor_;
- P1 p1_;
-};
-
-
-#define FP_T(x) R (ObjectT::*x)(P1)
-
-template <class ObjectT, class R,
- class P1>
-MethodFunctor1<ObjectT, FP_T(NONAME), R, P1>
-Bind(FP_T(method), ObjectT* object,
- typename detail::identity<P1>::type p1) {
- return MethodFunctor1<ObjectT, FP_T(NONAME), R, P1>(
- method, object, p1);
-}
-
-#undef FP_T
-#define FP_T(x) R (ObjectT::*x)(P1) const
-
-template <class ObjectT, class R,
- class P1>
-MethodFunctor1<const ObjectT, FP_T(NONAME), R, P1>
-Bind(FP_T(method), const ObjectT* object,
- typename detail::identity<P1>::type p1) {
- return MethodFunctor1<const ObjectT, FP_T(NONAME), R, P1>(
- method, object, p1);
-}
-
-#undef FP_T
-#define FP_T(x) R (*x)(P1)
-
-template <class R,
- class P1>
-Functor1<FP_T(NONAME), R, P1>
-Bind(FP_T(function),
- typename detail::identity<P1>::type p1) {
- return Functor1<FP_T(NONAME), R, P1>(
- function, p1);
-}
-
-#undef FP_T
-
-template <class ObjectT, class MethodT, class R,
- class P1,
- class P2>
-class MethodFunctor2 {
- public:
- MethodFunctor2(MethodT method, ObjectT* object,
- P1 p1,
- P2 p2)
- : method_(method), object_(object),
- p1_(p1),
- p2_(p2) {}
- R operator()() const {
- return (object_->*method_)(p1_, p2_); }
- private:
- MethodT method_;
- ObjectT* object_;
- P1 p1_;
- P2 p2_;
-};
-
-template <class FunctorT, class R,
- class P1,
- class P2>
-class Functor2 {
- public:
- Functor2(const FunctorT& functor, P1 p1, P2 p2)
- : functor_(functor),
- p1_(p1),
- p2_(p2) {}
- R operator()() const {
- return functor_(p1_, p2_); }
- private:
- FunctorT functor_;
- P1 p1_;
- P2 p2_;
-};
-
-
-#define FP_T(x) R (ObjectT::*x)(P1, P2)
-
-template <class ObjectT, class R,
- class P1,
- class P2>
-MethodFunctor2<ObjectT, FP_T(NONAME), R, P1, P2>
-Bind(FP_T(method), ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2) {
- return MethodFunctor2<ObjectT, FP_T(NONAME), R, P1, P2>(
- method, object, p1, p2);
-}
-
-#undef FP_T
-#define FP_T(x) R (ObjectT::*x)(P1, P2) const
-
-template <class ObjectT, class R,
- class P1,
- class P2>
-MethodFunctor2<const ObjectT, FP_T(NONAME), R, P1, P2>
-Bind(FP_T(method), const ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2) {
- return MethodFunctor2<const ObjectT, FP_T(NONAME), R, P1, P2>(
- method, object, p1, p2);
-}
-
-#undef FP_T
-#define FP_T(x) R (*x)(P1, P2)
-
-template <class R,
- class P1,
- class P2>
-Functor2<FP_T(NONAME), R, P1, P2>
-Bind(FP_T(function),
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2) {
- return Functor2<FP_T(NONAME), R, P1, P2>(
- function, p1, p2);
-}
-
-#undef FP_T
-
-template <class ObjectT, class MethodT, class R,
- class P1,
- class P2,
- class P3>
-class MethodFunctor3 {
- public:
- MethodFunctor3(MethodT method, ObjectT* object,
- P1 p1,
- P2 p2,
- P3 p3)
- : method_(method), object_(object),
- p1_(p1),
- p2_(p2),
- p3_(p3) {}
- R operator()() const {
- return (object_->*method_)(p1_, p2_, p3_); }
- private:
- MethodT method_;
- ObjectT* object_;
- P1 p1_;
- P2 p2_;
- P3 p3_;
-};
-
-template <class FunctorT, class R,
- class P1,
- class P2,
- class P3>
-class Functor3 {
- public:
- Functor3(const FunctorT& functor, P1 p1, P2 p2, P3 p3)
- : functor_(functor),
- p1_(p1),
- p2_(p2),
- p3_(p3) {}
- R operator()() const {
- return functor_(p1_, p2_, p3_); }
- private:
- FunctorT functor_;
- P1 p1_;
- P2 p2_;
- P3 p3_;
-};
-
-
-#define FP_T(x) R (ObjectT::*x)(P1, P2, P3)
-
-template <class ObjectT, class R,
- class P1,
- class P2,
- class P3>
-MethodFunctor3<ObjectT, FP_T(NONAME), R, P1, P2, P3>
-Bind(FP_T(method), ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3) {
- return MethodFunctor3<ObjectT, FP_T(NONAME), R, P1, P2, P3>(
- method, object, p1, p2, p3);
-}
-
-#undef FP_T
-#define FP_T(x) R (ObjectT::*x)(P1, P2, P3) const
-
-template <class ObjectT, class R,
- class P1,
- class P2,
- class P3>
-MethodFunctor3<const ObjectT, FP_T(NONAME), R, P1, P2, P3>
-Bind(FP_T(method), const ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3) {
- return MethodFunctor3<const ObjectT, FP_T(NONAME), R, P1, P2, P3>(
- method, object, p1, p2, p3);
-}
-
-#undef FP_T
-#define FP_T(x) R (*x)(P1, P2, P3)
-
-template <class R,
- class P1,
- class P2,
- class P3>
-Functor3<FP_T(NONAME), R, P1, P2, P3>
-Bind(FP_T(function),
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3) {
- return Functor3<FP_T(NONAME), R, P1, P2, P3>(
- function, p1, p2, p3);
-}
-
-#undef FP_T
-
-template <class ObjectT, class MethodT, class R,
- class P1,
- class P2,
- class P3,
- class P4>
-class MethodFunctor4 {
- public:
- MethodFunctor4(MethodT method, ObjectT* object,
- P1 p1,
- P2 p2,
- P3 p3,
- P4 p4)
- : method_(method), object_(object),
- p1_(p1),
- p2_(p2),
- p3_(p3),
- p4_(p4) {}
- R operator()() const {
- return (object_->*method_)(p1_, p2_, p3_, p4_); }
- private:
- MethodT method_;
- ObjectT* object_;
- P1 p1_;
- P2 p2_;
- P3 p3_;
- P4 p4_;
-};
-
-template <class FunctorT, class R,
- class P1,
- class P2,
- class P3,
- class P4>
-class Functor4 {
- public:
- Functor4(const FunctorT& functor, P1 p1, P2 p2, P3 p3, P4 p4)
- : functor_(functor),
- p1_(p1),
- p2_(p2),
- p3_(p3),
- p4_(p4) {}
- R operator()() const {
- return functor_(p1_, p2_, p3_, p4_); }
- private:
- FunctorT functor_;
- P1 p1_;
- P2 p2_;
- P3 p3_;
- P4 p4_;
-};
-
-
-#define FP_T(x) R (ObjectT::*x)(P1, P2, P3, P4)
-
-template <class ObjectT, class R,
- class P1,
- class P2,
- class P3,
- class P4>
-MethodFunctor4<ObjectT, FP_T(NONAME), R, P1, P2, P3, P4>
-Bind(FP_T(method), ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3,
- typename detail::identity<P4>::type p4) {
- return MethodFunctor4<ObjectT, FP_T(NONAME), R, P1, P2, P3, P4>(
- method, object, p1, p2, p3, p4);
-}
-
-#undef FP_T
-#define FP_T(x) R (ObjectT::*x)(P1, P2, P3, P4) const
-
-template <class ObjectT, class R,
- class P1,
- class P2,
- class P3,
- class P4>
-MethodFunctor4<const ObjectT, FP_T(NONAME), R, P1, P2, P3, P4>
-Bind(FP_T(method), const ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3,
- typename detail::identity<P4>::type p4) {
- return MethodFunctor4<const ObjectT, FP_T(NONAME), R, P1, P2, P3, P4>(
- method, object, p1, p2, p3, p4);
-}
-
-#undef FP_T
-#define FP_T(x) R (*x)(P1, P2, P3, P4)
-
-template <class R,
- class P1,
- class P2,
- class P3,
- class P4>
-Functor4<FP_T(NONAME), R, P1, P2, P3, P4>
-Bind(FP_T(function),
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3,
- typename detail::identity<P4>::type p4) {
- return Functor4<FP_T(NONAME), R, P1, P2, P3, P4>(
- function, p1, p2, p3, p4);
-}
-
-#undef FP_T
-
-template <class ObjectT, class MethodT, class R,
- class P1,
- class P2,
- class P3,
- class P4,
- class P5>
-class MethodFunctor5 {
- public:
- MethodFunctor5(MethodT method, ObjectT* object,
- P1 p1,
- P2 p2,
- P3 p3,
- P4 p4,
- P5 p5)
- : method_(method), object_(object),
- p1_(p1),
- p2_(p2),
- p3_(p3),
- p4_(p4),
- p5_(p5) {}
- R operator()() const {
- return (object_->*method_)(p1_, p2_, p3_, p4_, p5_); }
- private:
- MethodT method_;
- ObjectT* object_;
- P1 p1_;
- P2 p2_;
- P3 p3_;
- P4 p4_;
- P5 p5_;
-};
-
-template <class FunctorT, class R,
- class P1,
- class P2,
- class P3,
- class P4,
- class P5>
-class Functor5 {
- public:
- Functor5(const FunctorT& functor, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
- : functor_(functor),
- p1_(p1),
- p2_(p2),
- p3_(p3),
- p4_(p4),
- p5_(p5) {}
- R operator()() const {
- return functor_(p1_, p2_, p3_, p4_, p5_); }
- private:
- FunctorT functor_;
- P1 p1_;
- P2 p2_;
- P3 p3_;
- P4 p4_;
- P5 p5_;
-};
-
-
-#define FP_T(x) R (ObjectT::*x)(P1, P2, P3, P4, P5)
-
-template <class ObjectT, class R,
- class P1,
- class P2,
- class P3,
- class P4,
- class P5>
-MethodFunctor5<ObjectT, FP_T(NONAME), R, P1, P2, P3, P4, P5>
-Bind(FP_T(method), ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3,
- typename detail::identity<P4>::type p4,
- typename detail::identity<P5>::type p5) {
- return MethodFunctor5<ObjectT, FP_T(NONAME), R, P1, P2, P3, P4, P5>(
- method, object, p1, p2, p3, p4, p5);
-}
-
-#undef FP_T
-#define FP_T(x) R (ObjectT::*x)(P1, P2, P3, P4, P5) const
-
-template <class ObjectT, class R,
- class P1,
- class P2,
- class P3,
- class P4,
- class P5>
-MethodFunctor5<const ObjectT, FP_T(NONAME), R, P1, P2, P3, P4, P5>
-Bind(FP_T(method), const ObjectT* object,
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3,
- typename detail::identity<P4>::type p4,
- typename detail::identity<P5>::type p5) {
- return MethodFunctor5<const ObjectT, FP_T(NONAME), R, P1, P2, P3, P4, P5>(
- method, object, p1, p2, p3, p4, p5);
-}
-
-#undef FP_T
-#define FP_T(x) R (*x)(P1, P2, P3, P4, P5)
-
-template <class R,
- class P1,
- class P2,
- class P3,
- class P4,
- class P5>
-Functor5<FP_T(NONAME), R, P1, P2, P3, P4, P5>
-Bind(FP_T(function),
- typename detail::identity<P1>::type p1,
- typename detail::identity<P2>::type p2,
- typename detail::identity<P3>::type p3,
- typename detail::identity<P4>::type p4,
- typename detail::identity<P5>::type p5) {
- return Functor5<FP_T(NONAME), R, P1, P2, P3, P4, P5>(
- function, p1, p2, p3, p4, p5);
-}
-
-#undef FP_T
-
-} // namespace talk_base
-
-#undef NONAME
-
-#endif // TALK_BASE_BIND_H_
diff --git a/base/bind.h.pump b/base/bind.h.pump
deleted file mode 100644
index 2ebb895..0000000
--- a/base/bind.h.pump
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// To generate bind.h from bind.h.pump, execute:
-// /home/build/google3/third_party/gtest/scripts/pump.py bind.h.pump
-
-// Bind() is an overloaded function that converts method calls into function
-// objects (aka functors). It captures any arguments to the method by value
-// when Bind is called, producing a stateful, nullary function object. Care
-// should be taken about the lifetime of objects captured by Bind(); the
-// returned functor knows nothing about the lifetime of the method's object or
-// any arguments passed by pointer, and calling the functor with a destroyed
-// object will surely do bad things.
-//
-// Example usage:
-// struct Foo {
-// int Test1() { return 42; }
-// int Test2() const { return 52; }
-// int Test3(int x) { return x*x; }
-// float Test4(int x, float y) { return x + y; }
-// };
-//
-// int main() {
-// Foo foo;
-// cout << talk_base::Bind(&Foo::Test1, &foo)() << endl;
-// cout << talk_base::Bind(&Foo::Test2, &foo)() << endl;
-// cout << talk_base::Bind(&Foo::Test3, &foo, 3)() << endl;
-// cout << talk_base::Bind(&Foo::Test4, &foo, 7, 8.5f)() << endl;
-// }
-
-#ifndef TALK_BASE_BIND_H_
-#define TALK_BASE_BIND_H_
-
-#define NONAME
-
-namespace talk_base {
-namespace detail {
-// This is needed because the template parameters in Bind can't be resolved
-// if they're used both as parameters of the function pointer type and as
-// parameters to Bind itself: the function pointer parameters are exact
-// matches to the function prototype, but the parameters to bind have
-// references stripped. This trick allows the compiler to dictate the Bind
-// parameter types rather than deduce them.
-template <class T> struct identity { typedef T type; };
-} // namespace detail
-
-$var n = 5
-$range i 0..n
-$for i [[
-$range j 1..i
-
-template <class ObjectT, class MethodT, class R$for j [[,
- class P$j]]>
-class MethodFunctor$i {
- public:
- MethodFunctor$i(MethodT method, ObjectT* object$for j [[,
- P$j p$j]])
- : method_(method), object_(object)$for j [[,
- p$(j)_(p$j)]] {}
- R operator()() const {
- return (object_->*method_)($for j , [[p$(j)_]]); }
- private:
- MethodT method_;
- ObjectT* object_;$for j [[
-
- P$j p$(j)_;]]
-
-};
-
-template <class FunctorT, class R$for j [[,
- class P$j]]>
-class Functor$i {
- public:
- $if i == 0 [[explicit ]]
-Functor$i(const FunctorT& functor$for j [[, P$j p$j]])
- : functor_(functor)$for j [[,
- p$(j)_(p$j)]] {}
- R operator()() const {
- return functor_($for j , [[p$(j)_]]); }
- private:
- FunctorT functor_;$for j [[
-
- P$j p$(j)_;]]
-
-};
-
-
-#define FP_T(x) R (ObjectT::*x)($for j , [[P$j]])
-
-template <class ObjectT, class R$for j [[,
- class P$j]]>
-MethodFunctor$i<ObjectT, FP_T(NONAME), R$for j [[, P$j]]>
-Bind(FP_T(method), ObjectT* object$for j [[,
- typename detail::identity<P$j>::type p$j]]) {
- return MethodFunctor$i<ObjectT, FP_T(NONAME), R$for j [[, P$j]]>(
- method, object$for j [[, p$j]]);
-}
-
-#undef FP_T
-#define FP_T(x) R (ObjectT::*x)($for j , [[P$j]]) const
-
-template <class ObjectT, class R$for j [[,
- class P$j]]>
-MethodFunctor$i<const ObjectT, FP_T(NONAME), R$for j [[, P$j]]>
-Bind(FP_T(method), const ObjectT* object$for j [[,
- typename detail::identity<P$j>::type p$j]]) {
- return MethodFunctor$i<const ObjectT, FP_T(NONAME), R$for j [[, P$j]]>(
- method, object$for j [[, p$j]]);
-}
-
-#undef FP_T
-#define FP_T(x) R (*x)($for j , [[P$j]])
-
-template <class R$for j [[,
- class P$j]]>
-Functor$i<FP_T(NONAME), R$for j [[, P$j]]>
-Bind(FP_T(function)$for j [[,
- typename detail::identity<P$j>::type p$j]]) {
- return Functor$i<FP_T(NONAME), R$for j [[, P$j]]>(
- function$for j [[, p$j]]);
-}
-
-#undef FP_T
-
-]]
-
-} // namespace talk_base
-
-#undef NONAME
-
-#endif // TALK_BASE_BIND_H_
diff --git a/base/bind_unittest.cc b/base/bind_unittest.cc
deleted file mode 100644
index 78ac278..0000000
--- a/base/bind_unittest.cc
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/bind.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-namespace {
-
-struct MethodBindTester {
- void NullaryVoid() { ++call_count; }
- int NullaryInt() { ++call_count; return 1; }
- int NullaryConst() const { ++call_count; return 2; }
- void UnaryVoid(int dummy) { ++call_count; }
- template <class T> T Identity(T value) { ++call_count; return value; }
- int UnaryByRef(int& value) const { ++call_count; return ++value; } // NOLINT
- int Multiply(int a, int b) const { ++call_count; return a * b; }
- mutable int call_count;
-};
-
-int Return42() { return 42; }
-int Negate(int a) { return -a; }
-int Multiply(int a, int b) { return a * b; }
-
-} // namespace
-
-TEST(BindTest, BindToMethod) {
- MethodBindTester object = {0};
- EXPECT_EQ(0, object.call_count);
- Bind(&MethodBindTester::NullaryVoid, &object)();
- EXPECT_EQ(1, object.call_count);
- EXPECT_EQ(1, Bind(&MethodBindTester::NullaryInt, &object)());
- EXPECT_EQ(2, object.call_count);
- EXPECT_EQ(2, Bind(&MethodBindTester::NullaryConst,
- static_cast<const MethodBindTester*>(&object))());
- EXPECT_EQ(3, object.call_count);
- Bind(&MethodBindTester::UnaryVoid, &object, 5)();
- EXPECT_EQ(4, object.call_count);
- EXPECT_EQ(100, Bind(&MethodBindTester::Identity<int>, &object, 100)());
- EXPECT_EQ(5, object.call_count);
- const std::string string_value("test string");
- EXPECT_EQ(string_value, Bind(&MethodBindTester::Identity<std::string>,
- &object, string_value)());
- EXPECT_EQ(6, object.call_count);
- int value = 11;
- EXPECT_EQ(12, Bind(&MethodBindTester::UnaryByRef, &object, value)());
- EXPECT_EQ(12, value);
- EXPECT_EQ(7, object.call_count);
- EXPECT_EQ(56, Bind(&MethodBindTester::Multiply, &object, 7, 8)());
- EXPECT_EQ(8, object.call_count);
-}
-
-TEST(BindTest, BindToFunction) {
- EXPECT_EQ(42, Bind(&Return42)());
- EXPECT_EQ(3, Bind(&Negate, -3)());
- EXPECT_EQ(56, Bind(&Multiply, 8, 7)());
-}
-
-} // namespace talk_base
diff --git a/base/buffer.h b/base/buffer.h
deleted file mode 100644
index 2d589f2..0000000
--- a/base/buffer.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * libjingle
- * Copyright 2004-2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_BUFFER_H_
-#define TALK_BASE_BUFFER_H_
-
-#include <string.h>
-
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-// Basic buffer class, can be grown and shrunk dynamically.
-// Unlike std::string/vector, does not initialize data when expanding capacity.
-class Buffer {
- public:
- Buffer() {
- Construct(NULL, 0, 0);
- }
- Buffer(const void* data, size_t length) {
- Construct(data, length, length);
- }
- Buffer(const void* data, size_t length, size_t capacity) {
- Construct(data, length, capacity);
- }
- Buffer(const Buffer& buf) {
- Construct(buf.data(), buf.length(), buf.length());
- }
-
- const char* data() const { return data_.get(); }
- char* data() { return data_.get(); }
- // TODO: should this be size(), like STL?
- size_t length() const { return length_; }
- size_t capacity() const { return capacity_; }
-
- Buffer& operator=(const Buffer& buf) {
- if (&buf != this) {
- Construct(buf.data(), buf.length(), buf.length());
- }
- return *this;
- }
- bool operator==(const Buffer& buf) const {
- return (length_ == buf.length() &&
- memcmp(data_.get(), buf.data(), length_) == 0);
- }
- bool operator!=(const Buffer& buf) const {
- return !operator==(buf);
- }
-
- void SetData(const void* data, size_t length) {
- ASSERT(data != NULL || length == 0);
- SetLength(length);
- memcpy(data_.get(), data, length);
- }
- void AppendData(const void* data, size_t length) {
- ASSERT(data != NULL || length == 0);
- size_t old_length = length_;
- SetLength(length_ + length);
- memcpy(data_.get() + old_length, data, length);
- }
- void SetLength(size_t length) {
- SetCapacity(length);
- length_ = length;
- }
- void SetCapacity(size_t capacity) {
- if (capacity > capacity_) {
- talk_base::scoped_ptr<char[]> data(new char[capacity]);
- memcpy(data.get(), data_.get(), length_);
- data_.swap(data);
- capacity_ = capacity;
- }
- }
-
- void TransferTo(Buffer* buf) {
- ASSERT(buf != NULL);
- buf->data_.reset(data_.release());
- buf->length_ = length_;
- buf->capacity_ = capacity_;
- Construct(NULL, 0, 0);
- }
-
- protected:
- void Construct(const void* data, size_t length, size_t capacity) {
- data_.reset(new char[capacity_ = capacity]);
- SetData(data, length);
- }
-
- scoped_ptr<char[]> data_;
- size_t length_;
- size_t capacity_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_BUFFER_H_
diff --git a/base/buffer_unittest.cc b/base/buffer_unittest.cc
deleted file mode 100644
index b0aa243..0000000
--- a/base/buffer_unittest.cc
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/buffer.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-static const char kTestData[] = {
- 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF
-};
-
-TEST(BufferTest, TestConstructDefault) {
- Buffer buf;
- EXPECT_EQ(0U, buf.length());
- EXPECT_EQ(0U, buf.capacity());
- EXPECT_EQ(Buffer(), buf);
-}
-
-TEST(BufferTest, TestConstructEmptyWithCapacity) {
- Buffer buf(NULL, 0, 256U);
- EXPECT_EQ(0U, buf.length());
- EXPECT_EQ(256U, buf.capacity());
- EXPECT_EQ(Buffer(), buf);
-}
-
-TEST(BufferTest, TestConstructData) {
- Buffer buf(kTestData, sizeof(kTestData));
- EXPECT_EQ(sizeof(kTestData), buf.length());
- EXPECT_EQ(sizeof(kTestData), buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
- EXPECT_EQ(Buffer(kTestData, sizeof(kTestData)), buf);
-}
-
-TEST(BufferTest, TestConstructDataWithCapacity) {
- Buffer buf(kTestData, sizeof(kTestData), 256U);
- EXPECT_EQ(sizeof(kTestData), buf.length());
- EXPECT_EQ(256U, buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
- EXPECT_EQ(Buffer(kTestData, sizeof(kTestData)), buf);
-}
-
-TEST(BufferTest, TestConstructCopy) {
- Buffer buf1(kTestData, sizeof(kTestData), 256), buf2(buf1);
- EXPECT_EQ(sizeof(kTestData), buf2.length());
- EXPECT_EQ(sizeof(kTestData), buf2.capacity()); // capacity isn't copied
- EXPECT_EQ(0, memcmp(buf2.data(), kTestData, sizeof(kTestData)));
- EXPECT_EQ(buf1, buf2);
-}
-
-TEST(BufferTest, TestAssign) {
- Buffer buf1, buf2(kTestData, sizeof(kTestData), 256);
- EXPECT_NE(buf1, buf2);
- buf1 = buf2;
- EXPECT_EQ(sizeof(kTestData), buf1.length());
- EXPECT_EQ(sizeof(kTestData), buf1.capacity()); // capacity isn't copied
- EXPECT_EQ(0, memcmp(buf1.data(), kTestData, sizeof(kTestData)));
- EXPECT_EQ(buf1, buf2);
-}
-
-TEST(BufferTest, TestSetData) {
- Buffer buf;
- buf.SetData(kTestData, sizeof(kTestData));
- EXPECT_EQ(sizeof(kTestData), buf.length());
- EXPECT_EQ(sizeof(kTestData), buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
-}
-
-TEST(BufferTest, TestAppendData) {
- Buffer buf(kTestData, sizeof(kTestData));
- buf.AppendData(kTestData, sizeof(kTestData));
- EXPECT_EQ(2 * sizeof(kTestData), buf.length());
- EXPECT_EQ(2 * sizeof(kTestData), buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
- EXPECT_EQ(0, memcmp(buf.data() + sizeof(kTestData),
- kTestData, sizeof(kTestData)));
-}
-
-TEST(BufferTest, TestSetLengthSmaller) {
- Buffer buf;
- buf.SetData(kTestData, sizeof(kTestData));
- buf.SetLength(sizeof(kTestData) / 2);
- EXPECT_EQ(sizeof(kTestData) / 2, buf.length());
- EXPECT_EQ(sizeof(kTestData), buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData) / 2));
-}
-
-TEST(BufferTest, TestSetLengthLarger) {
- Buffer buf;
- buf.SetData(kTestData, sizeof(kTestData));
- buf.SetLength(sizeof(kTestData) * 2);
- EXPECT_EQ(sizeof(kTestData) * 2, buf.length());
- EXPECT_EQ(sizeof(kTestData) * 2, buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
-}
-
-TEST(BufferTest, TestSetCapacitySmaller) {
- Buffer buf;
- buf.SetData(kTestData, sizeof(kTestData));
- buf.SetCapacity(sizeof(kTestData) / 2); // should be ignored
- EXPECT_EQ(sizeof(kTestData), buf.length());
- EXPECT_EQ(sizeof(kTestData), buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
-}
-
-TEST(BufferTest, TestSetCapacityLarger) {
- Buffer buf(kTestData, sizeof(kTestData));
- buf.SetCapacity(sizeof(kTestData) * 2);
- EXPECT_EQ(sizeof(kTestData), buf.length());
- EXPECT_EQ(sizeof(kTestData) * 2, buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
-}
-
-TEST(BufferTest, TestSetCapacityThenSetLength) {
- Buffer buf(kTestData, sizeof(kTestData));
- buf.SetCapacity(sizeof(kTestData) * 4);
- memcpy(buf.data() + sizeof(kTestData), kTestData, sizeof(kTestData));
- buf.SetLength(sizeof(kTestData) * 2);
- EXPECT_EQ(sizeof(kTestData) * 2, buf.length());
- EXPECT_EQ(sizeof(kTestData) * 4, buf.capacity());
- EXPECT_EQ(0, memcmp(buf.data(), kTestData, sizeof(kTestData)));
- EXPECT_EQ(0, memcmp(buf.data() + sizeof(kTestData),
- kTestData, sizeof(kTestData)));
-}
-
-TEST(BufferTest, TestTransfer) {
- Buffer buf1(kTestData, sizeof(kTestData), 256U), buf2;
- buf1.TransferTo(&buf2);
- EXPECT_EQ(0U, buf1.length());
- EXPECT_EQ(0U, buf1.capacity());
- EXPECT_EQ(sizeof(kTestData), buf2.length());
- EXPECT_EQ(256U, buf2.capacity()); // capacity does transfer
- EXPECT_EQ(0, memcmp(buf2.data(), kTestData, sizeof(kTestData)));
-}
-
-} // namespace talk_base
diff --git a/base/bytebuffer.cc b/base/bytebuffer.cc
deleted file mode 100644
index 396a1d3..0000000
--- a/base/bytebuffer.cc
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/bytebuffer.h"
-
-#include <assert.h>
-#include <string.h>
-
-#include <algorithm>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/byteorder.h"
-
-namespace talk_base {
-
-static const int DEFAULT_SIZE = 4096;
-
-ByteBuffer::ByteBuffer() {
- Construct(NULL, DEFAULT_SIZE, ORDER_NETWORK);
-}
-
-ByteBuffer::ByteBuffer(ByteOrder byte_order) {
- Construct(NULL, DEFAULT_SIZE, byte_order);
-}
-
-ByteBuffer::ByteBuffer(const char* bytes, size_t len) {
- Construct(bytes, len, ORDER_NETWORK);
-}
-
-ByteBuffer::ByteBuffer(const char* bytes, size_t len, ByteOrder byte_order) {
- Construct(bytes, len, byte_order);
-}
-
-ByteBuffer::ByteBuffer(const char* bytes) {
- Construct(bytes, strlen(bytes), ORDER_NETWORK);
-}
-
-void ByteBuffer::Construct(const char* bytes, size_t len,
- ByteOrder byte_order) {
- version_ = 0;
- start_ = 0;
- size_ = len;
- byte_order_ = byte_order;
- bytes_ = new char[size_];
-
- if (bytes) {
- end_ = len;
- memcpy(bytes_, bytes, end_);
- } else {
- end_ = 0;
- }
-}
-
-ByteBuffer::~ByteBuffer() {
- delete[] bytes_;
-}
-
-bool ByteBuffer::ReadUInt8(uint8* val) {
- if (!val) return false;
-
- return ReadBytes(reinterpret_cast<char*>(val), 1);
-}
-
-bool ByteBuffer::ReadUInt16(uint16* val) {
- if (!val) return false;
-
- uint16 v;
- if (!ReadBytes(reinterpret_cast<char*>(&v), 2)) {
- return false;
- } else {
- *val = (byte_order_ == ORDER_NETWORK) ? NetworkToHost16(v) : v;
- return true;
- }
-}
-
-bool ByteBuffer::ReadUInt24(uint32* val) {
- if (!val) return false;
-
- uint32 v = 0;
- char* read_into = reinterpret_cast<char*>(&v);
- if (byte_order_ == ORDER_NETWORK || IsHostBigEndian()) {
- ++read_into;
- }
-
- if (!ReadBytes(read_into, 3)) {
- return false;
- } else {
- *val = (byte_order_ == ORDER_NETWORK) ? NetworkToHost32(v) : v;
- return true;
- }
-}
-
-bool ByteBuffer::ReadUInt32(uint32* val) {
- if (!val) return false;
-
- uint32 v;
- if (!ReadBytes(reinterpret_cast<char*>(&v), 4)) {
- return false;
- } else {
- *val = (byte_order_ == ORDER_NETWORK) ? NetworkToHost32(v) : v;
- return true;
- }
-}
-
-bool ByteBuffer::ReadUInt64(uint64* val) {
- if (!val) return false;
-
- uint64 v;
- if (!ReadBytes(reinterpret_cast<char*>(&v), 8)) {
- return false;
- } else {
- *val = (byte_order_ == ORDER_NETWORK) ? NetworkToHost64(v) : v;
- return true;
- }
-}
-
-bool ByteBuffer::ReadString(std::string* val, size_t len) {
- if (!val) return false;
-
- if (len > Length()) {
- return false;
- } else {
- val->append(bytes_ + start_, len);
- start_ += len;
- return true;
- }
-}
-
-bool ByteBuffer::ReadBytes(char* val, size_t len) {
- if (len > Length()) {
- return false;
- } else {
- memcpy(val, bytes_ + start_, len);
- start_ += len;
- return true;
- }
-}
-
-void ByteBuffer::WriteUInt8(uint8 val) {
- WriteBytes(reinterpret_cast<const char*>(&val), 1);
-}
-
-void ByteBuffer::WriteUInt16(uint16 val) {
- uint16 v = (byte_order_ == ORDER_NETWORK) ? HostToNetwork16(val) : val;
- WriteBytes(reinterpret_cast<const char*>(&v), 2);
-}
-
-void ByteBuffer::WriteUInt24(uint32 val) {
- uint32 v = (byte_order_ == ORDER_NETWORK) ? HostToNetwork32(val) : val;
- char* start = reinterpret_cast<char*>(&v);
- if (byte_order_ == ORDER_NETWORK || IsHostBigEndian()) {
- ++start;
- }
- WriteBytes(start, 3);
-}
-
-void ByteBuffer::WriteUInt32(uint32 val) {
- uint32 v = (byte_order_ == ORDER_NETWORK) ? HostToNetwork32(val) : val;
- WriteBytes(reinterpret_cast<const char*>(&v), 4);
-}
-
-void ByteBuffer::WriteUInt64(uint64 val) {
- uint64 v = (byte_order_ == ORDER_NETWORK) ? HostToNetwork64(val) : val;
- WriteBytes(reinterpret_cast<const char*>(&v), 8);
-}
-
-void ByteBuffer::WriteString(const std::string& val) {
- WriteBytes(val.c_str(), val.size());
-}
-
-void ByteBuffer::WriteBytes(const char* val, size_t len) {
- memcpy(ReserveWriteBuffer(len), val, len);
-}
-
-char* ByteBuffer::ReserveWriteBuffer(size_t len) {
- if (Length() + len > Capacity())
- Resize(Length() + len);
-
- char* start = bytes_ + end_;
- end_ += len;
- return start;
-}
-
-void ByteBuffer::Resize(size_t size) {
- size_t len = _min(end_ - start_, size);
- if (size <= size_) {
- // Don't reallocate, just move data backwards
- memmove(bytes_, bytes_ + start_, len);
- } else {
- // Reallocate a larger buffer.
- size_ = _max(size, 3 * size_ / 2);
- char* new_bytes = new char[size_];
- memcpy(new_bytes, bytes_ + start_, len);
- delete [] bytes_;
- bytes_ = new_bytes;
- }
- start_ = 0;
- end_ = len;
- ++version_;
-}
-
-bool ByteBuffer::Consume(size_t size) {
- if (size > Length())
- return false;
- start_ += size;
- return true;
-}
-
-ByteBuffer::ReadPosition ByteBuffer::GetReadPosition() const {
- return ReadPosition(start_, version_);
-}
-
-bool ByteBuffer::SetReadPosition(const ReadPosition &position) {
- if (position.version_ != version_) {
- return false;
- }
- start_ = position.start_;
- return true;
-}
-
-void ByteBuffer::Clear() {
- memset(bytes_, 0, size_);
- start_ = end_ = 0;
- ++version_;
-}
-
-} // namespace talk_base
diff --git a/base/bytebuffer.h b/base/bytebuffer.h
deleted file mode 100644
index a12c59c..0000000
--- a/base/bytebuffer.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_BYTEBUFFER_H_
-#define TALK_BASE_BYTEBUFFER_H_
-
-#include <string>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/constructormagic.h"
-
-namespace talk_base {
-
-class ByteBuffer {
- public:
-
- enum ByteOrder {
- ORDER_NETWORK = 0, // Default, use network byte order (big endian).
- ORDER_HOST, // Use the native order of the host.
- };
-
- // |byte_order| defines order of bytes in the buffer.
- ByteBuffer();
- explicit ByteBuffer(ByteOrder byte_order);
- ByteBuffer(const char* bytes, size_t len);
- ByteBuffer(const char* bytes, size_t len, ByteOrder byte_order);
-
- // Initializes buffer from a zero-terminated string.
- explicit ByteBuffer(const char* bytes);
-
- ~ByteBuffer();
-
- const char* Data() const { return bytes_ + start_; }
- size_t Length() const { return end_ - start_; }
- size_t Capacity() const { return size_ - start_; }
- ByteOrder Order() const { return byte_order_; }
-
- // Read a next value from the buffer. Return false if there isn't
- // enough data left for the specified type.
- bool ReadUInt8(uint8* val);
- bool ReadUInt16(uint16* val);
- bool ReadUInt24(uint32* val);
- bool ReadUInt32(uint32* val);
- bool ReadUInt64(uint64* val);
- bool ReadBytes(char* val, size_t len);
-
- // Appends next |len| bytes from the buffer to |val|. Returns false
- // if there is less than |len| bytes left.
- bool ReadString(std::string* val, size_t len);
-
- // Write value to the buffer. Resizes the buffer when it is
- // neccessary.
- void WriteUInt8(uint8 val);
- void WriteUInt16(uint16 val);
- void WriteUInt24(uint32 val);
- void WriteUInt32(uint32 val);
- void WriteUInt64(uint64 val);
- void WriteString(const std::string& val);
- void WriteBytes(const char* val, size_t len);
-
- // Reserves the given number of bytes and returns a char* that can be written
- // into. Useful for functions that require a char* buffer and not a
- // ByteBuffer.
- char* ReserveWriteBuffer(size_t len);
-
- // Resize the buffer to the specified |size|. This invalidates any remembered
- // seek positions.
- void Resize(size_t size);
-
- // Moves current position |size| bytes forward. Returns false if
- // there is less than |size| bytes left in the buffer. Consume doesn't
- // permanently remove data, so remembered read positions are still valid
- // after this call.
- bool Consume(size_t size);
-
- // Clears the contents of the buffer. After this, Length() will be 0.
- void Clear();
-
- // Used with GetReadPosition/SetReadPosition.
- class ReadPosition {
- friend class ByteBuffer;
- ReadPosition(size_t start, int version)
- : start_(start), version_(version) { }
- size_t start_;
- int version_;
- };
-
- // Remembers the current read position for a future SetReadPosition. Any
- // calls to Shift or Resize in the interim will invalidate the position.
- ReadPosition GetReadPosition() const;
-
- // If the given position is still valid, restores that read position.
- bool SetReadPosition(const ReadPosition &position);
-
- private:
- void Construct(const char* bytes, size_t size, ByteOrder byte_order);
-
- char* bytes_;
- size_t size_;
- size_t start_;
- size_t end_;
- int version_;
- ByteOrder byte_order_;
-
- // There are sensible ways to define these, but they aren't needed in our code
- // base.
- DISALLOW_COPY_AND_ASSIGN(ByteBuffer);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_BYTEBUFFER_H_
diff --git a/base/bytebuffer_unittest.cc b/base/bytebuffer_unittest.cc
deleted file mode 100644
index 2c73453..0000000
--- a/base/bytebuffer_unittest.cc
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/bytebuffer.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-TEST(ByteBufferTest, TestByteOrder) {
- uint16 n16 = 1;
- uint32 n32 = 1;
- uint64 n64 = 1;
-
- EXPECT_EQ(n16, NetworkToHost16(HostToNetwork16(n16)));
- EXPECT_EQ(n32, NetworkToHost32(HostToNetwork32(n32)));
- EXPECT_EQ(n64, NetworkToHost64(HostToNetwork64(n64)));
-
- if (IsHostBigEndian()) {
- // The host is the network (big) endian.
- EXPECT_EQ(n16, HostToNetwork16(n16));
- EXPECT_EQ(n32, HostToNetwork32(n32));
- EXPECT_EQ(n64, HostToNetwork64(n64));
-
- // GetBE converts big endian to little endian here.
- EXPECT_EQ(n16 >> 8, GetBE16(&n16));
- EXPECT_EQ(n32 >> 24, GetBE32(&n32));
- EXPECT_EQ(n64 >> 56, GetBE64(&n64));
- } else {
- // The host is little endian.
- EXPECT_NE(n16, HostToNetwork16(n16));
- EXPECT_NE(n32, HostToNetwork32(n32));
- EXPECT_NE(n64, HostToNetwork64(n64));
-
- // GetBE converts little endian to big endian here.
- EXPECT_EQ(GetBE16(&n16), HostToNetwork16(n16));
- EXPECT_EQ(GetBE32(&n32), HostToNetwork32(n32));
- EXPECT_EQ(GetBE64(&n64), HostToNetwork64(n64));
-
- // GetBE converts little endian to big endian here.
- EXPECT_EQ(n16 << 8, GetBE16(&n16));
- EXPECT_EQ(n32 << 24, GetBE32(&n32));
- EXPECT_EQ(n64 << 56, GetBE64(&n64));
- }
-}
-
-TEST(ByteBufferTest, TestBufferLength) {
- ByteBuffer buffer;
- size_t size = 0;
- EXPECT_EQ(size, buffer.Length());
-
- buffer.WriteUInt8(1);
- ++size;
- EXPECT_EQ(size, buffer.Length());
-
- buffer.WriteUInt16(1);
- size += 2;
- EXPECT_EQ(size, buffer.Length());
-
- buffer.WriteUInt24(1);
- size += 3;
- EXPECT_EQ(size, buffer.Length());
-
- buffer.WriteUInt32(1);
- size += 4;
- EXPECT_EQ(size, buffer.Length());
-
- buffer.WriteUInt64(1);
- size += 8;
- EXPECT_EQ(size, buffer.Length());
-
- EXPECT_TRUE(buffer.Consume(0));
- EXPECT_EQ(size, buffer.Length());
-
- EXPECT_TRUE(buffer.Consume(4));
- size -= 4;
- EXPECT_EQ(size, buffer.Length());
-}
-
-TEST(ByteBufferTest, TestGetSetReadPosition) {
- ByteBuffer buffer("ABCDEF", 6);
- EXPECT_EQ(6U, buffer.Length());
- ByteBuffer::ReadPosition pos(buffer.GetReadPosition());
- EXPECT_TRUE(buffer.SetReadPosition(pos));
- EXPECT_EQ(6U, buffer.Length());
- std::string read;
- EXPECT_TRUE(buffer.ReadString(&read, 3));
- EXPECT_EQ("ABC", read);
- EXPECT_EQ(3U, buffer.Length());
- EXPECT_TRUE(buffer.SetReadPosition(pos));
- EXPECT_EQ(6U, buffer.Length());
- read.clear();
- EXPECT_TRUE(buffer.ReadString(&read, 3));
- EXPECT_EQ("ABC", read);
- EXPECT_EQ(3U, buffer.Length());
- // For a resize by writing Capacity() number of bytes.
- size_t capacity = buffer.Capacity();
- buffer.ReserveWriteBuffer(buffer.Capacity());
- EXPECT_EQ(capacity + 3U, buffer.Length());
- EXPECT_FALSE(buffer.SetReadPosition(pos));
- read.clear();
- EXPECT_TRUE(buffer.ReadString(&read, 3));
- EXPECT_EQ("DEF", read);
-}
-
-TEST(ByteBufferTest, TestReadWriteBuffer) {
- ByteBuffer::ByteOrder orders[2] = { ByteBuffer::ORDER_HOST,
- ByteBuffer::ORDER_NETWORK };
- for (size_t i = 0; i < ARRAY_SIZE(orders); i++) {
- ByteBuffer buffer(orders[i]);
- EXPECT_EQ(orders[i], buffer.Order());
- uint8 ru8;
- EXPECT_FALSE(buffer.ReadUInt8(&ru8));
-
- // Write and read uint8.
- uint8 wu8 = 1;
- buffer.WriteUInt8(wu8);
- EXPECT_TRUE(buffer.ReadUInt8(&ru8));
- EXPECT_EQ(wu8, ru8);
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read uint16.
- uint16 wu16 = (1 << 8) + 1;
- buffer.WriteUInt16(wu16);
- uint16 ru16;
- EXPECT_TRUE(buffer.ReadUInt16(&ru16));
- EXPECT_EQ(wu16, ru16);
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read uint24.
- uint32 wu24 = (3 << 16) + (2 << 8) + 1;
- buffer.WriteUInt24(wu24);
- uint32 ru24;
- EXPECT_TRUE(buffer.ReadUInt24(&ru24));
- EXPECT_EQ(wu24, ru24);
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read uint32.
- uint32 wu32 = (4 << 24) + (3 << 16) + (2 << 8) + 1;
- buffer.WriteUInt32(wu32);
- uint32 ru32;
- EXPECT_TRUE(buffer.ReadUInt32(&ru32));
- EXPECT_EQ(wu32, ru32);
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read uint64.
- uint32 another32 = (8 << 24) + (7 << 16) + (6 << 8) + 5;
- uint64 wu64 = (static_cast<uint64>(another32) << 32) + wu32;
- buffer.WriteUInt64(wu64);
- uint64 ru64;
- EXPECT_TRUE(buffer.ReadUInt64(&ru64));
- EXPECT_EQ(wu64, ru64);
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read string.
- std::string write_string("hello");
- buffer.WriteString(write_string);
- std::string read_string;
- EXPECT_TRUE(buffer.ReadString(&read_string, write_string.size()));
- EXPECT_EQ(write_string, read_string);
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read bytes
- char write_bytes[] = "foo";
- buffer.WriteBytes(write_bytes, 3);
- char read_bytes[3];
- EXPECT_TRUE(buffer.ReadBytes(read_bytes, 3));
- for (int i = 0; i < 3; ++i) {
- EXPECT_EQ(write_bytes[i], read_bytes[i]);
- }
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read reserved buffer space
- char* write_dst = buffer.ReserveWriteBuffer(3);
- memcpy(write_dst, write_bytes, 3);
- memset(read_bytes, 0, 3);
- EXPECT_TRUE(buffer.ReadBytes(read_bytes, 3));
- for (int i = 0; i < 3; ++i) {
- EXPECT_EQ(write_bytes[i], read_bytes[i]);
- }
- EXPECT_EQ(0U, buffer.Length());
-
- // Write and read in order.
- buffer.WriteUInt8(wu8);
- buffer.WriteUInt16(wu16);
- buffer.WriteUInt24(wu24);
- buffer.WriteUInt32(wu32);
- buffer.WriteUInt64(wu64);
- EXPECT_TRUE(buffer.ReadUInt8(&ru8));
- EXPECT_EQ(wu8, ru8);
- EXPECT_TRUE(buffer.ReadUInt16(&ru16));
- EXPECT_EQ(wu16, ru16);
- EXPECT_TRUE(buffer.ReadUInt24(&ru24));
- EXPECT_EQ(wu24, ru24);
- EXPECT_TRUE(buffer.ReadUInt32(&ru32));
- EXPECT_EQ(wu32, ru32);
- EXPECT_TRUE(buffer.ReadUInt64(&ru64));
- EXPECT_EQ(wu64, ru64);
- EXPECT_EQ(0U, buffer.Length());
- }
-}
-
-} // namespace talk_base
diff --git a/base/byteorder.h b/base/byteorder.h
deleted file mode 100644
index cf26a12..0000000
--- a/base/byteorder.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_BYTEORDER_H_
-#define TALK_BASE_BYTEORDER_H_
-
-#if defined(POSIX) && !defined(__native_client__)
-#include <arpa/inet.h>
-#endif
-
-#ifdef WIN32
-#include <stdlib.h>
-#endif
-
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-// Reading and writing of little and big-endian numbers from memory
-// TODO: Optimized versions, with direct read/writes of
-// integers in host-endian format, when the platform supports it.
-
-inline void Set8(void* memory, size_t offset, uint8 v) {
- static_cast<uint8*>(memory)[offset] = v;
-}
-
-inline uint8 Get8(const void* memory, size_t offset) {
- return static_cast<const uint8*>(memory)[offset];
-}
-
-inline void SetBE16(void* memory, uint16 v) {
- Set8(memory, 0, static_cast<uint8>(v >> 8));
- Set8(memory, 1, static_cast<uint8>(v >> 0));
-}
-
-inline void SetBE32(void* memory, uint32 v) {
- Set8(memory, 0, static_cast<uint8>(v >> 24));
- Set8(memory, 1, static_cast<uint8>(v >> 16));
- Set8(memory, 2, static_cast<uint8>(v >> 8));
- Set8(memory, 3, static_cast<uint8>(v >> 0));
-}
-
-inline void SetBE64(void* memory, uint64 v) {
- Set8(memory, 0, static_cast<uint8>(v >> 56));
- Set8(memory, 1, static_cast<uint8>(v >> 48));
- Set8(memory, 2, static_cast<uint8>(v >> 40));
- Set8(memory, 3, static_cast<uint8>(v >> 32));
- Set8(memory, 4, static_cast<uint8>(v >> 24));
- Set8(memory, 5, static_cast<uint8>(v >> 16));
- Set8(memory, 6, static_cast<uint8>(v >> 8));
- Set8(memory, 7, static_cast<uint8>(v >> 0));
-}
-
-inline uint16 GetBE16(const void* memory) {
- return static_cast<uint16>((Get8(memory, 0) << 8) |
- (Get8(memory, 1) << 0));
-}
-
-inline uint32 GetBE32(const void* memory) {
- return (static_cast<uint32>(Get8(memory, 0)) << 24) |
- (static_cast<uint32>(Get8(memory, 1)) << 16) |
- (static_cast<uint32>(Get8(memory, 2)) << 8) |
- (static_cast<uint32>(Get8(memory, 3)) << 0);
-}
-
-inline uint64 GetBE64(const void* memory) {
- return (static_cast<uint64>(Get8(memory, 0)) << 56) |
- (static_cast<uint64>(Get8(memory, 1)) << 48) |
- (static_cast<uint64>(Get8(memory, 2)) << 40) |
- (static_cast<uint64>(Get8(memory, 3)) << 32) |
- (static_cast<uint64>(Get8(memory, 4)) << 24) |
- (static_cast<uint64>(Get8(memory, 5)) << 16) |
- (static_cast<uint64>(Get8(memory, 6)) << 8) |
- (static_cast<uint64>(Get8(memory, 7)) << 0);
-}
-
-inline void SetLE16(void* memory, uint16 v) {
- Set8(memory, 0, static_cast<uint8>(v >> 0));
- Set8(memory, 1, static_cast<uint8>(v >> 8));
-}
-
-inline void SetLE32(void* memory, uint32 v) {
- Set8(memory, 0, static_cast<uint8>(v >> 0));
- Set8(memory, 1, static_cast<uint8>(v >> 8));
- Set8(memory, 2, static_cast<uint8>(v >> 16));
- Set8(memory, 3, static_cast<uint8>(v >> 24));
-}
-
-inline void SetLE64(void* memory, uint64 v) {
- Set8(memory, 0, static_cast<uint8>(v >> 0));
- Set8(memory, 1, static_cast<uint8>(v >> 8));
- Set8(memory, 2, static_cast<uint8>(v >> 16));
- Set8(memory, 3, static_cast<uint8>(v >> 24));
- Set8(memory, 4, static_cast<uint8>(v >> 32));
- Set8(memory, 5, static_cast<uint8>(v >> 40));
- Set8(memory, 6, static_cast<uint8>(v >> 48));
- Set8(memory, 7, static_cast<uint8>(v >> 56));
-}
-
-inline uint16 GetLE16(const void* memory) {
- return static_cast<uint16>((Get8(memory, 0) << 0) |
- (Get8(memory, 1) << 8));
-}
-
-inline uint32 GetLE32(const void* memory) {
- return (static_cast<uint32>(Get8(memory, 0)) << 0) |
- (static_cast<uint32>(Get8(memory, 1)) << 8) |
- (static_cast<uint32>(Get8(memory, 2)) << 16) |
- (static_cast<uint32>(Get8(memory, 3)) << 24);
-}
-
-inline uint64 GetLE64(const void* memory) {
- return (static_cast<uint64>(Get8(memory, 0)) << 0) |
- (static_cast<uint64>(Get8(memory, 1)) << 8) |
- (static_cast<uint64>(Get8(memory, 2)) << 16) |
- (static_cast<uint64>(Get8(memory, 3)) << 24) |
- (static_cast<uint64>(Get8(memory, 4)) << 32) |
- (static_cast<uint64>(Get8(memory, 5)) << 40) |
- (static_cast<uint64>(Get8(memory, 6)) << 48) |
- (static_cast<uint64>(Get8(memory, 7)) << 56);
-}
-
-// Check if the current host is big endian.
-inline bool IsHostBigEndian() {
- static const int number = 1;
- return 0 == *reinterpret_cast<const char*>(&number);
-}
-
-inline uint16 HostToNetwork16(uint16 n) {
- uint16 result;
- SetBE16(&result, n);
- return result;
-}
-
-inline uint32 HostToNetwork32(uint32 n) {
- uint32 result;
- SetBE32(&result, n);
- return result;
-}
-
-inline uint64 HostToNetwork64(uint64 n) {
- uint64 result;
- SetBE64(&result, n);
- return result;
-}
-
-inline uint16 NetworkToHost16(uint16 n) {
- return GetBE16(&n);
-}
-
-inline uint32 NetworkToHost32(uint32 n) {
- return GetBE32(&n);
-}
-
-inline uint64 NetworkToHost64(uint64 n) {
- return GetBE64(&n);
-}
-
-} // namespace talk_base
-
-#endif // TALK_BASE_BYTEORDER_H_
diff --git a/base/byteorder_unittest.cc b/base/byteorder_unittest.cc
deleted file mode 100644
index 01dd26a..0000000
--- a/base/byteorder_unittest.cc
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/byteorder.h"
-
-#include "talk/base/basictypes.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-// Test memory set functions put values into memory in expected order.
-TEST(ByteOrderTest, TestSet) {
- uint8 buf[8] = { 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u };
- Set8(buf, 0, 0xfb);
- Set8(buf, 1, 0x12);
- EXPECT_EQ(0xfb, buf[0]);
- EXPECT_EQ(0x12, buf[1]);
- SetBE16(buf, 0x1234);
- EXPECT_EQ(0x12, buf[0]);
- EXPECT_EQ(0x34, buf[1]);
- SetLE16(buf, 0x1234);
- EXPECT_EQ(0x34, buf[0]);
- EXPECT_EQ(0x12, buf[1]);
- SetBE32(buf, 0x12345678);
- EXPECT_EQ(0x12, buf[0]);
- EXPECT_EQ(0x34, buf[1]);
- EXPECT_EQ(0x56, buf[2]);
- EXPECT_EQ(0x78, buf[3]);
- SetLE32(buf, 0x12345678);
- EXPECT_EQ(0x78, buf[0]);
- EXPECT_EQ(0x56, buf[1]);
- EXPECT_EQ(0x34, buf[2]);
- EXPECT_EQ(0x12, buf[3]);
- SetBE64(buf, UINT64_C(0x0123456789abcdef));
- EXPECT_EQ(0x01, buf[0]);
- EXPECT_EQ(0x23, buf[1]);
- EXPECT_EQ(0x45, buf[2]);
- EXPECT_EQ(0x67, buf[3]);
- EXPECT_EQ(0x89, buf[4]);
- EXPECT_EQ(0xab, buf[5]);
- EXPECT_EQ(0xcd, buf[6]);
- EXPECT_EQ(0xef, buf[7]);
- SetLE64(buf, UINT64_C(0x0123456789abcdef));
- EXPECT_EQ(0xef, buf[0]);
- EXPECT_EQ(0xcd, buf[1]);
- EXPECT_EQ(0xab, buf[2]);
- EXPECT_EQ(0x89, buf[3]);
- EXPECT_EQ(0x67, buf[4]);
- EXPECT_EQ(0x45, buf[5]);
- EXPECT_EQ(0x23, buf[6]);
- EXPECT_EQ(0x01, buf[7]);
-}
-
-// Test memory get functions get values from memory in expected order.
-TEST(ByteOrderTest, TestGet) {
- uint8 buf[8];
- buf[0] = 0x01u;
- buf[1] = 0x23u;
- buf[2] = 0x45u;
- buf[3] = 0x67u;
- buf[4] = 0x89u;
- buf[5] = 0xabu;
- buf[6] = 0xcdu;
- buf[7] = 0xefu;
- EXPECT_EQ(0x01u, Get8(buf, 0));
- EXPECT_EQ(0x23u, Get8(buf, 1));
- EXPECT_EQ(0x0123u, GetBE16(buf));
- EXPECT_EQ(0x2301u, GetLE16(buf));
- EXPECT_EQ(0x01234567u, GetBE32(buf));
- EXPECT_EQ(0x67452301u, GetLE32(buf));
- EXPECT_EQ(UINT64_C(0x0123456789abcdef), GetBE64(buf));
- EXPECT_EQ(UINT64_C(0xefcdab8967452301), GetLE64(buf));
-}
-
-} // namespace talk_base
-
diff --git a/base/callback.h b/base/callback.h
deleted file mode 100644
index 11fbf86..0000000
--- a/base/callback.h
+++ /dev/null
@@ -1,278 +0,0 @@
-// This file was GENERATED by command:
-// pump.py callback.h.pump
-// DO NOT EDIT BY HAND!!!
-
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// To generate callback.h from callback.h.pump, execute:
-// /home/build/google3/third_party/gtest/scripts/pump.py callback.h.pump
-
-// Callbacks are callable object containers. They can hold a function pointer
-// or a function object and behave like a value type. Internally, data is
-// reference-counted, making copies and pass-by-value inexpensive.
-//
-// Callbacks are typed using template arguments. The format is:
-// CallbackN<ReturnType, ParamType1, ..., ParamTypeN>
-// where N is the number of arguments supplied to the callable object.
-// Callbacks are invoked using operator(), just like a function or a function
-// object. Default-constructed callbacks are "empty," and executing an empty
-// callback does nothing. A callback can be made empty by assigning it from
-// a default-constructed callback.
-//
-// Callbacks are similar in purpose to std::function (which isn't available on
-// all platforms we support) and a lightweight alternative to sigslots. Since
-// they effectively hide the type of the object they call, they're useful in
-// breaking dependencies between objects that need to interact with one another.
-// Notably, they can hold the results of Bind(), std::bind*, etc, without
-// needing
-// to know the resulting object type of those calls.
-//
-// Sigslots, on the other hand, provide a fuller feature set, such as multiple
-// subscriptions to a signal, optional thread-safety, and lifetime tracking of
-// slots. When these features are needed, choose sigslots.
-//
-// Example:
-// int sqr(int x) { return x * x; }
-// struct AddK {
-// int k;
-// int operator()(int x) const { return x + k; }
-// } add_k = {5};
-//
-// Callback1<int, int> my_callback;
-// cout << my_callback.empty() << endl; // true
-//
-// my_callback = Callback1<int, int>(&sqr);
-// cout << my_callback.empty() << endl; // false
-// cout << my_callback(3) << endl; // 9
-//
-// my_callback = Callback1<int, int>(add_k);
-// cout << my_callback(10) << endl; // 15
-//
-// my_callback = Callback1<int, int>();
-// cout << my_callback.empty() << endl; // true
-
-#ifndef TALK_BASE_CALLBACK_H_
-#define TALK_BASE_CALLBACK_H_
-
-#include "talk/base/logging.h"
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ref_ptr.h"
-
-namespace talk_base {
-
-template <class R>
-class Callback0 {
- public:
- // Default copy operations are appropriate for this class.
- Callback0() {}
- template <class T> Callback0(const T& functor)
- : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {}
- R operator()() {
- if (empty())
- return R();
- return helper_->Run();
- }
- bool empty() const { return !helper_; }
-
- private:
- struct Helper : RefCountInterface {
- virtual ~Helper() {}
- virtual R Run() = 0;
- };
- template <class T> struct HelperImpl : Helper {
- explicit HelperImpl(const T& functor) : functor_(functor) {}
- virtual R Run() {
- return functor_();
- }
- T functor_;
- };
- scoped_refptr<Helper> helper_;
-};
-
-template <class R,
- class P1>
-class Callback1 {
- public:
- // Default copy operations are appropriate for this class.
- Callback1() {}
- template <class T> Callback1(const T& functor)
- : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {}
- R operator()(P1 p1) {
- if (empty())
- return R();
- return helper_->Run(p1);
- }
- bool empty() const { return !helper_; }
-
- private:
- struct Helper : RefCountInterface {
- virtual ~Helper() {}
- virtual R Run(P1 p1) = 0;
- };
- template <class T> struct HelperImpl : Helper {
- explicit HelperImpl(const T& functor) : functor_(functor) {}
- virtual R Run(P1 p1) {
- return functor_(p1);
- }
- T functor_;
- };
- scoped_refptr<Helper> helper_;
-};
-
-template <class R,
- class P1,
- class P2>
-class Callback2 {
- public:
- // Default copy operations are appropriate for this class.
- Callback2() {}
- template <class T> Callback2(const T& functor)
- : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {}
- R operator()(P1 p1, P2 p2) {
- if (empty())
- return R();
- return helper_->Run(p1, p2);
- }
- bool empty() const { return !helper_; }
-
- private:
- struct Helper : RefCountInterface {
- virtual ~Helper() {}
- virtual R Run(P1 p1, P2 p2) = 0;
- };
- template <class T> struct HelperImpl : Helper {
- explicit HelperImpl(const T& functor) : functor_(functor) {}
- virtual R Run(P1 p1, P2 p2) {
- return functor_(p1, p2);
- }
- T functor_;
- };
- scoped_refptr<Helper> helper_;
-};
-
-template <class R,
- class P1,
- class P2,
- class P3>
-class Callback3 {
- public:
- // Default copy operations are appropriate for this class.
- Callback3() {}
- template <class T> Callback3(const T& functor)
- : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {}
- R operator()(P1 p1, P2 p2, P3 p3) {
- if (empty())
- return R();
- return helper_->Run(p1, p2, p3);
- }
- bool empty() const { return !helper_; }
-
- private:
- struct Helper : RefCountInterface {
- virtual ~Helper() {}
- virtual R Run(P1 p1, P2 p2, P3 p3) = 0;
- };
- template <class T> struct HelperImpl : Helper {
- explicit HelperImpl(const T& functor) : functor_(functor) {}
- virtual R Run(P1 p1, P2 p2, P3 p3) {
- return functor_(p1, p2, p3);
- }
- T functor_;
- };
- scoped_refptr<Helper> helper_;
-};
-
-template <class R,
- class P1,
- class P2,
- class P3,
- class P4>
-class Callback4 {
- public:
- // Default copy operations are appropriate for this class.
- Callback4() {}
- template <class T> Callback4(const T& functor)
- : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {}
- R operator()(P1 p1, P2 p2, P3 p3, P4 p4) {
- if (empty())
- return R();
- return helper_->Run(p1, p2, p3, p4);
- }
- bool empty() const { return !helper_; }
-
- private:
- struct Helper : RefCountInterface {
- virtual ~Helper() {}
- virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4) = 0;
- };
- template <class T> struct HelperImpl : Helper {
- explicit HelperImpl(const T& functor) : functor_(functor) {}
- virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4) {
- return functor_(p1, p2, p3, p4);
- }
- T functor_;
- };
- scoped_refptr<Helper> helper_;
-};
-
-template <class R,
- class P1,
- class P2,
- class P3,
- class P4,
- class P5>
-class Callback5 {
- public:
- // Default copy operations are appropriate for this class.
- Callback5() {}
- template <class T> Callback5(const T& functor)
- : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {}
- R operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
- if (empty())
- return R();
- return helper_->Run(p1, p2, p3, p4, p5);
- }
- bool empty() const { return !helper_; }
-
- private:
- struct Helper : RefCountInterface {
- virtual ~Helper() {}
- virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) = 0;
- };
- template <class T> struct HelperImpl : Helper {
- explicit HelperImpl(const T& functor) : functor_(functor) {}
- virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
- return functor_(p1, p2, p3, p4, p5);
- }
- T functor_;
- };
- scoped_refptr<Helper> helper_;
-};
-} // namespace talk_base
-
-#endif // TALK_BASE_CALLBACK_H_
diff --git a/base/callback.h.pump b/base/callback.h.pump
deleted file mode 100644
index 458eac7..0000000
--- a/base/callback.h.pump
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// To generate callback.h from callback.h.pump, execute:
-// /home/build/google3/third_party/gtest/scripts/pump.py callback.h.pump
-
-// Callbacks are callable object containers. They can hold a function pointer
-// or a function object and behave like a value type. Internally, data is
-// reference-counted, making copies and pass-by-value inexpensive.
-//
-// Callbacks are typed using template arguments. The format is:
-// CallbackN<ReturnType, ParamType1, ..., ParamTypeN>
-// where N is the number of arguments supplied to the callable object.
-// Callbacks are invoked using operator(), just like a function or a function
-// object. Default-constructed callbacks are "empty," and executing an empty
-// callback does nothing. A callback can be made empty by assigning it from
-// a default-constructed callback.
-//
-// Callbacks are similar in purpose to std::function (which isn't available on
-// all platforms we support) and a lightweight alternative to sigslots. Since
-// they effectively hide the type of the object they call, they're useful in
-// breaking dependencies between objects that need to interact with one another.
-// Notably, they can hold the results of Bind(), std::bind*, etc, without needing
-// to know the resulting object type of those calls.
-//
-// Sigslots, on the other hand, provide a fuller feature set, such as multiple
-// subscriptions to a signal, optional thread-safety, and lifetime tracking of
-// slots. When these features are needed, choose sigslots.
-//
-// Example:
-// int sqr(int x) { return x * x; }
-// struct AddK {
-// int k;
-// int operator()(int x) const { return x + k; }
-// } add_k = {5};
-//
-// Callback1<int, int> my_callback;
-// cout << my_callback.empty() << endl; // true
-//
-// my_callback = Callback1<int, int>(&sqr);
-// cout << my_callback.empty() << endl; // false
-// cout << my_callback(3) << endl; // 9
-//
-// my_callback = Callback1<int, int>(add_k);
-// cout << my_callback(10) << endl; // 15
-//
-// my_callback = Callback1<int, int>();
-// cout << my_callback.empty() << endl; // true
-
-#ifndef TALK_BASE_CALLBACK_H_
-#define TALK_BASE_CALLBACK_H_
-
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ref_ptr.h"
-
-namespace talk_base {
-
-$var n = 5
-$range i 0..n
-$for i [[
-$range j 1..i
-
-template <class R$for j [[,
- class P$j]]>
-class Callback$i {
- public:
- // Default copy operations are appropriate for this class.
- Callback$i() {}
- template <class T> Callback$i(const T& functor)
- : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {}
- R operator()($for j , [[P$j p$j]]) {
- if (empty())
- return R();
- return helper_->Run($for j , [[p$j]]);
- }
- bool empty() const { return !helper_; }
-
- private:
- struct Helper : RefCountInterface {
- virtual ~Helper() {}
- virtual R Run($for j , [[P$j p$j]]) = 0;
- };
- template <class T> struct HelperImpl : Helper {
- explicit HelperImpl(const T& functor) : functor_(functor) {}
- virtual R Run($for j , [[P$j p$j]]) {
- return functor_($for j , [[p$j]]);
- }
- T functor_;
- };
- scoped_refptr<Helper> helper_;
-};
-
-]]
-} // namespace talk_base
-
-#endif // TALK_BASE_CALLBACK_H_
diff --git a/base/callback_unittest.cc b/base/callback_unittest.cc
deleted file mode 100644
index c7ca00f..0000000
--- a/base/callback_unittest.cc
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/bind.h"
-#include "talk/base/callback.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-namespace {
-
-void f() {}
-int g() { return 42; }
-int h(int x) { return x * x; }
-void i(int& x) { x *= x; } // NOLINT: Testing refs
-
-struct BindTester {
- int a() { return 24; }
- int b(int x) const { return x * x; }
-};
-
-} // namespace
-
-TEST(CallbackTest, VoidReturn) {
- Callback0<void> cb;
- EXPECT_TRUE(cb.empty());
- cb(); // Executing an empty callback should not crash.
- cb = Callback0<void>(&f);
- EXPECT_FALSE(cb.empty());
- cb();
-}
-
-TEST(CallbackTest, IntReturn) {
- Callback0<int> cb;
- EXPECT_TRUE(cb.empty());
- cb = Callback0<int>(&g);
- EXPECT_FALSE(cb.empty());
- EXPECT_EQ(42, cb());
- EXPECT_EQ(42, cb());
-}
-
-TEST(CallbackTest, OneParam) {
- Callback1<int, int> cb1(&h);
- EXPECT_FALSE(cb1.empty());
- EXPECT_EQ(9, cb1(-3));
- EXPECT_EQ(100, cb1(10));
-
- // Try clearing a callback.
- cb1 = Callback1<int, int>();
- EXPECT_TRUE(cb1.empty());
-
- // Try a callback with a ref parameter.
- Callback1<void, int&> cb2(&i);
- int x = 3;
- cb2(x);
- EXPECT_EQ(9, x);
- cb2(x);
- EXPECT_EQ(81, x);
-}
-
-TEST(CallbackTest, WithBind) {
- BindTester t;
- Callback0<int> cb1 = Bind(&BindTester::a, &t);
- EXPECT_EQ(24, cb1());
- EXPECT_EQ(24, cb1());
- cb1 = Bind(&BindTester::b, &t, 10);
- EXPECT_EQ(100, cb1());
- EXPECT_EQ(100, cb1());
- cb1 = Bind(&BindTester::b, &t, 5);
- EXPECT_EQ(25, cb1());
- EXPECT_EQ(25, cb1());
-}
-
-} // namespace talk_base
diff --git a/base/checks.cc b/base/checks.cc
deleted file mode 100644
index 5466783..0000000
--- a/base/checks.cc
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-
-#include "talk/base/checks.h"
-#include "talk/base/logging.h"
-
-void Fatal(const char* file, int line, const char* format, ...) {
- char msg[256];
-
- va_list arguments;
- va_start(arguments, format);
- vsnprintf(msg, sizeof(msg), format, arguments);
- va_end(arguments);
-
- LOG(LS_ERROR) << "\n\n#\n# Fatal error in " << file
- << ", line " << line << "\n#" << msg
- << "\n#\n";
- abort();
-}
diff --git a/base/checks.h b/base/checks.h
deleted file mode 100644
index 83ad372..0000000
--- a/base/checks.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// This module contains some basic debugging facilities.
-// Originally comes from shared/commandlineflags/checks.h
-
-#ifndef TALK_BASE_CHECKS_H_
-#define TALK_BASE_CHECKS_H_
-
-#include <string.h>
-
-// Prints an error message to stderr and aborts execution.
-void Fatal(const char* file, int line, const char* format, ...);
-
-
-// The UNREACHABLE macro is very useful during development.
-#define UNREACHABLE() \
- Fatal(__FILE__, __LINE__, "unreachable code")
-
-#endif // TALK_BASE_CHECKS_H_
diff --git a/base/common.cc b/base/common.cc
deleted file mode 100644
index 9f63aa4..0000000
--- a/base/common.cc
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <signal.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-
-#if WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#endif // WIN32
-
-#if OSX
-#include <CoreServices/CoreServices.h>
-#endif // OSX
-
-#include <algorithm>
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-
-//////////////////////////////////////////////////////////////////////
-// Assertions
-//////////////////////////////////////////////////////////////////////
-
-namespace talk_base {
-
-void Break() {
-#if WIN32
- ::DebugBreak();
-#else // !WIN32
- // On POSIX systems, SIGTRAP signals debuggers to break without killing the
- // process. If a debugger isn't attached, the uncaught SIGTRAP will crash the
- // app.
- raise(SIGTRAP);
-#endif
- // If a debugger wasn't attached, we will have crashed by this point. If a
- // debugger is attached, we'll continue from here.
-}
-
-static AssertLogger custom_assert_logger_ = NULL;
-
-void SetCustomAssertLogger(AssertLogger logger) {
- custom_assert_logger_ = logger;
-}
-
-void LogAssert(const char* function, const char* file, int line,
- const char* expression) {
- if (custom_assert_logger_) {
- custom_assert_logger_(function, file, line, expression);
- } else {
- LOG(LS_ERROR) << file << "(" << line << ")" << ": ASSERT FAILED: "
- << expression << " @ " << function;
- }
-}
-
-bool IsOdd(int n) {
- return (n & 0x1);
-}
-
-bool IsEven(int n) {
- return !IsOdd(n);
-}
-
-} // namespace talk_base
diff --git a/base/common.h b/base/common.h
deleted file mode 100644
index ed7d59e..0000000
--- a/base/common.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_COMMON_H_ // NOLINT
-#define TALK_BASE_COMMON_H_
-
-#include "talk/base/basictypes.h"
-#include "talk/base/constructormagic.h"
-
-#if defined(_MSC_VER)
-// warning C4355: 'this' : used in base member initializer list
-#pragma warning(disable:4355)
-#endif
-
-//////////////////////////////////////////////////////////////////////
-// General Utilities
-//////////////////////////////////////////////////////////////////////
-
-// Note: UNUSED is also defined in basictypes.h
-#ifndef UNUSED
-#define UNUSED(x) Unused(static_cast<const void*>(&x))
-#define UNUSED2(x, y) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y))
-#define UNUSED3(x, y, z) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y)); \
- Unused(static_cast<const void*>(&z))
-#define UNUSED4(x, y, z, a) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y)); \
- Unused(static_cast<const void*>(&z)); \
- Unused(static_cast<const void*>(&a))
-#define UNUSED5(x, y, z, a, b) Unused(static_cast<const void*>(&x)); \
- Unused(static_cast<const void*>(&y)); \
- Unused(static_cast<const void*>(&z)); \
- Unused(static_cast<const void*>(&a)); \
- Unused(static_cast<const void*>(&b))
-inline void Unused(const void*) {}
-#endif // UNUSED
-
-#ifndef WIN32
-
-#ifndef strnicmp
-#define strnicmp(x, y, n) strncasecmp(x, y, n)
-#endif
-
-#ifndef stricmp
-#define stricmp(x, y) strcasecmp(x, y)
-#endif
-
-// TODO(fbarchard): Remove this. std::max should be used everywhere in the code.
-// NOMINMAX must be defined where we include <windows.h>.
-#define stdmax(x, y) std::max(x, y)
-#else
-#define stdmax(x, y) talk_base::_max(x, y)
-#endif
-
-#define ARRAY_SIZE(x) (static_cast<int>(sizeof(x) / sizeof(x[0])))
-
-/////////////////////////////////////////////////////////////////////////////
-// Assertions
-/////////////////////////////////////////////////////////////////////////////
-
-#ifndef ENABLE_DEBUG
-#define ENABLE_DEBUG _DEBUG
-#endif // !defined(ENABLE_DEBUG)
-
-// Even for release builds, allow for the override of LogAssert. Though no
-// macro is provided, this can still be used for explicit runtime asserts
-// and allow applications to override the assert behavior.
-
-namespace talk_base {
-
-
-// If a debugger is attached, triggers a debugger breakpoint. If a debugger is
-// not attached, forces program termination.
-void Break();
-
-// LogAssert writes information about an assertion to the log. It's called by
-// Assert (and from the ASSERT macro in debug mode) before any other action
-// is taken (e.g. breaking the debugger, abort()ing, etc.).
-void LogAssert(const char* function, const char* file, int line,
- const char* expression);
-
-typedef void (*AssertLogger)(const char* function,
- const char* file,
- int line,
- const char* expression);
-
-// Sets a custom assert logger to be used instead of the default LogAssert
-// behavior. To clear the custom assert logger, pass NULL for |logger| and the
-// default behavior will be restored. Only one custom assert logger can be set
-// at a time, so this should generally be set during application startup and
-// only by one component.
-void SetCustomAssertLogger(AssertLogger logger);
-
-bool IsOdd(int n);
-
-bool IsEven(int n);
-
-} // namespace talk_base
-
-#if ENABLE_DEBUG
-
-namespace talk_base {
-
-inline bool Assert(bool result, const char* function, const char* file,
- int line, const char* expression) {
- if (!result) {
- LogAssert(function, file, line, expression);
- Break();
- return false;
- }
- return true;
-}
-
-} // namespace talk_base
-
-#if defined(_MSC_VER) && _MSC_VER < 1300
-#define __FUNCTION__ ""
-#endif
-
-#ifndef ASSERT
-#define ASSERT(x) \
- (void)talk_base::Assert((x), __FUNCTION__, __FILE__, __LINE__, #x)
-#endif
-
-#ifndef VERIFY
-#define VERIFY(x) talk_base::Assert((x), __FUNCTION__, __FILE__, __LINE__, #x)
-#endif
-
-#else // !ENABLE_DEBUG
-
-namespace talk_base {
-
-inline bool ImplicitCastToBool(bool result) { return result; }
-
-} // namespace talk_base
-
-#ifndef ASSERT
-#define ASSERT(x) (void)0
-#endif
-
-#ifndef VERIFY
-#define VERIFY(x) talk_base::ImplicitCastToBool(x)
-#endif
-
-#endif // !ENABLE_DEBUG
-
-#define COMPILE_TIME_ASSERT(expr) char CTA_UNIQUE_NAME[expr]
-#define CTA_UNIQUE_NAME CTA_MAKE_NAME(__LINE__)
-#define CTA_MAKE_NAME(line) CTA_MAKE_NAME2(line)
-#define CTA_MAKE_NAME2(line) constraint_ ## line
-
-// Forces compiler to inline, even against its better judgement. Use wisely.
-#if defined(__GNUC__)
-#define FORCE_INLINE __attribute__((always_inline))
-#elif defined(WIN32)
-#define FORCE_INLINE __forceinline
-#else
-#define FORCE_INLINE
-#endif
-
-// Borrowed from Chromium's base/compiler_specific.h.
-// Annotate a virtual method indicating it must be overriding a virtual
-// method in the parent class.
-// Use like:
-// virtual void foo() OVERRIDE;
-#if defined(WIN32)
-#define OVERRIDE override
-#elif defined(__clang__)
-// Clang defaults to C++03 and warns about using override. Squelch that.
-// Intentionally no push/pop here so all users of OVERRIDE ignore the warning
-// too. This is like passing -Wno-c++11-extensions, except that GCC won't die
-// (because it won't see this pragma).
-#pragma clang diagnostic ignored "-Wc++11-extensions"
-#define OVERRIDE override
-#elif defined(__GNUC__) && __cplusplus >= 201103 && \
- (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= 40700
-// GCC 4.7 supports explicit virtual overrides when C++11 support is enabled.
-#define OVERRIDE override
-#else
-#define OVERRIDE
-#endif
-
-// Annotate a function indicating the caller must examine the return value.
-// Use like:
-// int foo() WARN_UNUSED_RESULT;
-// To explicitly ignore a result, see |ignore_result()| in <base/basictypes.h>.
-// TODO(ajm): Hack to avoid multiple definitions until the base/ of webrtc and
-// libjingle are merged.
-#if !defined(WARN_UNUSED_RESULT)
-#if defined(__GNUC__)
-#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
-#else
-#define WARN_UNUSED_RESULT
-#endif
-#endif // WARN_UNUSED_RESULT
-
-#endif // TALK_BASE_COMMON_H_ // NOLINT
diff --git a/base/compile_assert.h b/base/compile_assert.h
deleted file mode 100644
index 7252d08..0000000
--- a/base/compile_assert.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * libjingle
- * Copyright 2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// COMPILE_ASSERT macro, borrowed from google3/base/macros.h.
-#ifndef TALK_BASE_COMPILE_ASSERT_H_
-#define TALK_BASE_COMPILE_ASSERT_H_
-
-// The COMPILE_ASSERT macro can be used to verify that a compile time
-// expression is true. For example, you could use it to verify the
-// size of a static array:
-//
-// COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES,
-// content_type_names_incorrect_size);
-//
-// or to make sure a struct is smaller than a certain size:
-//
-// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
-//
-// The second argument to the macro is the name of the variable. If
-// the expression is false, most compilers will issue a warning/error
-// containing the name of the variable.
-
-// TODO(ajm): Hack to avoid multiple definitions until the base/ of webrtc and
-// libjingle are merged.
-#if !defined(COMPILE_ASSERT)
-template <bool>
-struct CompileAssert {
-};
-
-#define COMPILE_ASSERT(expr, msg) \
- typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] // NOLINT
-#endif // COMPILE_ASSERT
-
-// Implementation details of COMPILE_ASSERT:
-//
-// - COMPILE_ASSERT works by defining an array type that has -1
-// elements (and thus is invalid) when the expression is false.
-//
-// - The simpler definition
-//
-// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
-//
-// does not work, as gcc supports variable-length arrays whose sizes
-// are determined at run-time (this is gcc's extension and not part
-// of the C++ standard). As a result, gcc fails to reject the
-// following code with the simple definition:
-//
-// int foo;
-// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
-// // not a compile-time constant.
-//
-// - By using the type CompileAssert<(bool(expr))>, we ensures that
-// expr is a compile-time constant. (Template arguments must be
-// determined at compile-time.)
-//
-// - The outer parentheses in CompileAssert<(bool(expr))> are necessary
-// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written
-//
-// CompileAssert<bool(expr)>
-//
-// instead, these compilers will refuse to compile
-//
-// COMPILE_ASSERT(5 > 0, some_message);
-//
-// (They seem to think the ">" in "5 > 0" marks the end of the
-// template argument list.)
-//
-// - The array size is (bool(expr) ? 1 : -1), instead of simply
-//
-// ((expr) ? 1 : -1).
-//
-// This is to avoid running into a bug in MS VC 7.1, which
-// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
-
-#endif // TALK_BASE_COMPILE_ASSERT_H_
diff --git a/base/constructormagic.h b/base/constructormagic.h
deleted file mode 100644
index 3023044..0000000
--- a/base/constructormagic.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_CONSTRUCTORMAGIC_H_
-#define TALK_BASE_CONSTRUCTORMAGIC_H_
-
-#define DISALLOW_ASSIGN(TypeName) \
- void operator=(const TypeName&)
-
-// A macro to disallow the evil copy constructor and operator= functions
-// This should be used in the private: declarations for a class.
-// Undefine this, just in case. Some third-party includes have their own
-// version.
-#undef DISALLOW_COPY_AND_ASSIGN
-#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
- TypeName(const TypeName&); \
- DISALLOW_ASSIGN(TypeName)
-
-// Alternative, less-accurate legacy name.
-#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) \
- DISALLOW_COPY_AND_ASSIGN(TypeName)
-
-// A macro to disallow all the implicit constructors, namely the
-// default constructor, copy constructor and operator= functions.
-//
-// This should be used in the private: declarations for a class
-// that wants to prevent anyone from instantiating it. This is
-// especially useful for classes containing only static methods.
-#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
- TypeName(); \
- DISALLOW_EVIL_CONSTRUCTORS(TypeName)
-
-
-#endif // TALK_BASE_CONSTRUCTORMAGIC_H_
diff --git a/base/cpumonitor.cc b/base/cpumonitor.cc
deleted file mode 100644
index aaec772..0000000
--- a/base/cpumonitor.cc
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * libjingle
- * Copyright 2010 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/cpumonitor.h"
-
-#include <string>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/systeminfo.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#include <winternl.h>
-#endif
-
-#ifdef POSIX
-#include <sys/time.h>
-#endif
-
-#if defined(IOS) || defined(OSX)
-#include <mach/mach_host.h>
-#include <mach/mach_init.h>
-#include <mach/mach_port.h>
-#include <mach/host_info.h>
-#include <mach/task.h>
-#endif // defined(IOS) || defined(OSX)
-
-#if defined(LINUX) || defined(ANDROID)
-#include <sys/resource.h>
-#include <errno.h>
-#include <stdio.h>
-#include "talk/base/fileutils.h"
-#include "talk/base/pathutils.h"
-#endif // defined(LINUX) || defined(ANDROID)
-
-#if defined(IOS) || defined(OSX)
-static uint64 TimeValueTToInt64(const time_value_t &time_value) {
- return talk_base::kNumMicrosecsPerSec * time_value.seconds +
- time_value.microseconds;
-}
-#endif // defined(IOS) || defined(OSX)
-
-// How CpuSampler works
-// When threads switch, the time they spent is accumulated to system counters.
-// The time can be treated as user, kernel or idle.
-// user time is applications.
-// kernel time is the OS, including the thread switching code itself.
-// typically kernel time indicates IO.
-// idle time is a process that wastes time when nothing is ready to run.
-//
-// User time is broken down by process (application). One of the applications
-// is the current process. When you add up all application times, this is
-// system time. If only your application is running, system time should be the
-// same as process time.
-//
-// All cores contribute to these accumulators. A dual core process is able to
-// process twice as many cycles as a single core. The actual code efficiency
-// may be worse, due to contention, but the available cycles is exactly twice
-// as many, and the cpu load will reflect the efficiency. Hyperthreads behave
-// the same way. The load will reflect 200%, but the actual amount of work
-// completed will be much less than a true dual core.
-//
-// Total available performance is the sum of all accumulators.
-// If you tracked this for 1 second, it would essentially give you the clock
-// rate - number of cycles per second.
-// Speed step / Turbo Boost is not considered, so infact more processing time
-// may be available.
-
-namespace talk_base {
-
-// Note Tests on Windows show 600 ms is minimum stable interval for Windows 7.
-static const int32 kDefaultInterval = 950; // Slightly under 1 second.
-
-CpuSampler::CpuSampler()
- : min_load_interval_(kDefaultInterval)
-#ifdef WIN32
- , get_system_times_(NULL),
- nt_query_system_information_(NULL),
- force_fallback_(false)
-#endif
- {
-}
-
-CpuSampler::~CpuSampler() {
-}
-
-// Set minimum interval in ms between computing new load values. Default 950.
-void CpuSampler::set_load_interval(int min_load_interval) {
- min_load_interval_ = min_load_interval;
-}
-
-bool CpuSampler::Init() {
- sysinfo_.reset(new SystemInfo);
- cpus_ = sysinfo_->GetMaxCpus();
- if (cpus_ == 0) {
- return false;
- }
-#ifdef WIN32
- // Note that GetSystemTimes is available in Windows XP SP1 or later.
- // http://msdn.microsoft.com/en-us/library/ms724400.aspx
- // NtQuerySystemInformation is used as a fallback.
- if (!force_fallback_) {
- get_system_times_ = GetProcAddress(GetModuleHandle(L"kernel32.dll"),
- "GetSystemTimes");
- }
- nt_query_system_information_ = GetProcAddress(GetModuleHandle(L"ntdll.dll"),
- "NtQuerySystemInformation");
- if ((get_system_times_ == NULL) && (nt_query_system_information_ == NULL)) {
- return false;
- }
-#endif
-#if defined(LINUX) || defined(ANDROID)
- Pathname sname("/proc/stat");
- sfile_.reset(Filesystem::OpenFile(sname, "rb"));
- if (!sfile_) {
- LOG_ERR(LS_ERROR) << "open proc/stat failed:";
- return false;
- }
- if (!sfile_->DisableBuffering()) {
- LOG_ERR(LS_ERROR) << "could not disable buffering for proc/stat";
- return false;
- }
-#endif // defined(LINUX) || defined(ANDROID)
- GetProcessLoad(); // Initialize values.
- GetSystemLoad();
- // Help next user call return valid data by recomputing load.
- process_.prev_load_time_ = 0u;
- system_.prev_load_time_ = 0u;
- return true;
-}
-
-float CpuSampler::UpdateCpuLoad(uint64 current_total_times,
- uint64 current_cpu_times,
- uint64 *prev_total_times,
- uint64 *prev_cpu_times) {
- float result = 0.f;
- if (current_total_times < *prev_total_times ||
- current_cpu_times < *prev_cpu_times) {
- LOG(LS_ERROR) << "Inconsistent time values are passed. ignored";
- } else {
- const uint64 cpu_diff = current_cpu_times - *prev_cpu_times;
- const uint64 total_diff = current_total_times - *prev_total_times;
- result = (total_diff == 0ULL ? 0.f :
- static_cast<float>(1.0f * cpu_diff / total_diff));
- if (result > static_cast<float>(cpus_)) {
- result = static_cast<float>(cpus_);
- }
- *prev_total_times = current_total_times;
- *prev_cpu_times = current_cpu_times;
- }
- return result;
-}
-
-float CpuSampler::GetSystemLoad() {
- uint32 timenow = Time();
- int elapsed = static_cast<int>(TimeDiff(timenow, system_.prev_load_time_));
- if (min_load_interval_ != 0 && system_.prev_load_time_ != 0u &&
- elapsed < min_load_interval_) {
- return system_.prev_load_;
- }
-#ifdef WIN32
- uint64 total_times, cpu_times;
-
- typedef BOOL (_stdcall *GST_PROC)(LPFILETIME, LPFILETIME, LPFILETIME);
- typedef NTSTATUS (WINAPI *QSI_PROC)(SYSTEM_INFORMATION_CLASS,
- PVOID, ULONG, PULONG);
-
- GST_PROC get_system_times = reinterpret_cast<GST_PROC>(get_system_times_);
- QSI_PROC nt_query_system_information = reinterpret_cast<QSI_PROC>(
- nt_query_system_information_);
-
- if (get_system_times) {
- FILETIME idle_time, kernel_time, user_time;
- if (!get_system_times(&idle_time, &kernel_time, &user_time)) {
- LOG(LS_ERROR) << "::GetSystemTimes() failed: " << ::GetLastError();
- return 0.f;
- }
- // kernel_time includes Kernel idle time, so no need to
- // include cpu_time as total_times
- total_times = ToUInt64(kernel_time) + ToUInt64(user_time);
- cpu_times = total_times - ToUInt64(idle_time);
-
- } else {
- if (nt_query_system_information) {
- ULONG returned_length = 0;
- scoped_ptr<SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[]> processor_info(
- new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[cpus_]);
- nt_query_system_information(
- ::SystemProcessorPerformanceInformation,
- reinterpret_cast<void*>(processor_info.get()),
- cpus_ * sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION),
- &returned_length);
-
- if (returned_length !=
- (cpus_ * sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION))) {
- LOG(LS_ERROR) << "NtQuerySystemInformation has unexpected size";
- return 0.f;
- }
-
- uint64 current_idle = 0;
- uint64 current_kernel = 0;
- uint64 current_user = 0;
- for (int ix = 0; ix < cpus_; ++ix) {
- current_idle += processor_info[ix].IdleTime.QuadPart;
- current_kernel += processor_info[ix].UserTime.QuadPart;
- current_user += processor_info[ix].KernelTime.QuadPart;
- }
- total_times = current_kernel + current_user;
- cpu_times = total_times - current_idle;
- } else {
- return 0.f;
- }
- }
-#endif // WIN32
-
-#if defined(IOS) || defined(OSX)
- mach_port_t mach_host = mach_host_self();
- host_cpu_load_info_data_t cpu_info;
- mach_msg_type_number_t info_count = HOST_CPU_LOAD_INFO_COUNT;
- kern_return_t kr = host_statistics(mach_host, HOST_CPU_LOAD_INFO,
- reinterpret_cast<host_info_t>(&cpu_info),
- &info_count);
- mach_port_deallocate(mach_task_self(), mach_host);
- if (KERN_SUCCESS != kr) {
- LOG(LS_ERROR) << "::host_statistics() failed";
- return 0.f;
- }
-
- const uint64 cpu_times = cpu_info.cpu_ticks[CPU_STATE_NICE] +
- cpu_info.cpu_ticks[CPU_STATE_SYSTEM] +
- cpu_info.cpu_ticks[CPU_STATE_USER];
- const uint64 total_times = cpu_times + cpu_info.cpu_ticks[CPU_STATE_IDLE];
-#endif // defined(IOS) || defined(OSX)
-
-#if defined(LINUX) || defined(ANDROID)
- if (!sfile_) {
- LOG(LS_ERROR) << "Invalid handle for proc/stat";
- return 0.f;
- }
- std::string statbuf;
- sfile_->SetPosition(0);
- if (!sfile_->ReadLine(&statbuf)) {
- LOG_ERR(LS_ERROR) << "Could not read proc/stat file";
- return 0.f;
- }
-
- unsigned long long user;
- unsigned long long nice;
- unsigned long long system;
- unsigned long long idle;
- if (sscanf(statbuf.c_str(), "cpu %Lu %Lu %Lu %Lu",
- &user, &nice,
- &system, &idle) != 4) {
- LOG_ERR(LS_ERROR) << "Could not parse cpu info";
- return 0.f;
- }
- const uint64 cpu_times = nice + system + user;
- const uint64 total_times = cpu_times + idle;
-#endif // defined(LINUX) || defined(ANDROID)
-
-#if defined(__native_client__)
- // TODO(ryanpetrie): Implement this via PPAPI when it's available.
- const uint64 cpu_times = 0;
- const uint64 total_times = 0;
-#endif // defined(__native_client__)
-
- system_.prev_load_time_ = timenow;
- system_.prev_load_ = UpdateCpuLoad(total_times,
- cpu_times * cpus_,
- &system_.prev_total_times_,
- &system_.prev_cpu_times_);
- return system_.prev_load_;
-}
-
-float CpuSampler::GetProcessLoad() {
- uint32 timenow = Time();
- int elapsed = static_cast<int>(TimeDiff(timenow, process_.prev_load_time_));
- if (min_load_interval_ != 0 && process_.prev_load_time_ != 0u &&
- elapsed < min_load_interval_) {
- return process_.prev_load_;
- }
-#ifdef WIN32
- FILETIME current_file_time;
- ::GetSystemTimeAsFileTime(¤t_file_time);
-
- FILETIME create_time, exit_time, kernel_time, user_time;
- if (!::GetProcessTimes(::GetCurrentProcess(),
- &create_time, &exit_time, &kernel_time, &user_time)) {
- LOG(LS_ERROR) << "::GetProcessTimes() failed: " << ::GetLastError();
- return 0.f;
- }
-
- const uint64 total_times =
- ToUInt64(current_file_time) - ToUInt64(create_time);
- const uint64 cpu_times =
- (ToUInt64(kernel_time) + ToUInt64(user_time));
-#endif // WIN32
-
-#ifdef POSIX
- // Common to both OSX and Linux.
- struct timeval tv;
- gettimeofday(&tv, NULL);
- const uint64 total_times = tv.tv_sec * kNumMicrosecsPerSec + tv.tv_usec;
-#endif
-
-#if defined(IOS) || defined(OSX)
- // Get live thread usage.
- task_thread_times_info task_times_info;
- mach_msg_type_number_t info_count = TASK_THREAD_TIMES_INFO_COUNT;
-
- if (KERN_SUCCESS != task_info(mach_task_self(), TASK_THREAD_TIMES_INFO,
- reinterpret_cast<task_info_t>(&task_times_info),
- &info_count)) {
- LOG(LS_ERROR) << "::task_info(TASK_THREAD_TIMES_INFO) failed";
- return 0.f;
- }
-
- // Get terminated thread usage.
- task_basic_info task_term_info;
- info_count = TASK_BASIC_INFO_COUNT;
- if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO,
- reinterpret_cast<task_info_t>(&task_term_info),
- &info_count)) {
- LOG(LS_ERROR) << "::task_info(TASK_BASIC_INFO) failed";
- return 0.f;
- }
-
- const uint64 cpu_times = (TimeValueTToInt64(task_times_info.user_time) +
- TimeValueTToInt64(task_times_info.system_time) +
- TimeValueTToInt64(task_term_info.user_time) +
- TimeValueTToInt64(task_term_info.system_time));
-#endif // defined(IOS) || defined(OSX)
-
-#if defined(LINUX) || defined(ANDROID)
- rusage usage;
- if (getrusage(RUSAGE_SELF, &usage) < 0) {
- LOG_ERR(LS_ERROR) << "getrusage failed";
- return 0.f;
- }
-
- const uint64 cpu_times =
- (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) * kNumMicrosecsPerSec +
- usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
-#endif // defined(LINUX) || defined(ANDROID)
-
-#if defined(__native_client__)
- // TODO(ryanpetrie): Implement this via PPAPI when it's available.
- const uint64 cpu_times = 0;
-#endif // defined(__native_client__)
-
- process_.prev_load_time_ = timenow;
- process_.prev_load_ = UpdateCpuLoad(total_times,
- cpu_times,
- &process_.prev_total_times_,
- &process_.prev_cpu_times_);
- return process_.prev_load_;
-}
-
-int CpuSampler::GetMaxCpus() const {
- return cpus_;
-}
-
-int CpuSampler::GetCurrentCpus() {
- return sysinfo_->GetCurCpus();
-}
-
-///////////////////////////////////////////////////////////////////
-// Implementation of class CpuMonitor.
-CpuMonitor::CpuMonitor(Thread* thread)
- : monitor_thread_(thread) {
-}
-
-CpuMonitor::~CpuMonitor() {
- Stop();
-}
-
-void CpuMonitor::set_thread(Thread* thread) {
- ASSERT(monitor_thread_ == NULL || monitor_thread_ == thread);
- monitor_thread_ = thread;
-}
-
-bool CpuMonitor::Start(int period_ms) {
- if (!monitor_thread_ || !sampler_.Init()) return false;
-
- monitor_thread_->SignalQueueDestroyed.connect(
- this, &CpuMonitor::OnMessageQueueDestroyed);
-
- period_ms_ = period_ms;
- monitor_thread_->PostDelayed(period_ms_, this);
-
- return true;
-}
-
-void CpuMonitor::Stop() {
- if (monitor_thread_) {
- monitor_thread_->Clear(this);
- }
-}
-
-void CpuMonitor::OnMessage(Message* msg) {
- int max_cpus = sampler_.GetMaxCpus();
- int current_cpus = sampler_.GetCurrentCpus();
- float process_load = sampler_.GetProcessLoad();
- float system_load = sampler_.GetSystemLoad();
- SignalUpdate(current_cpus, max_cpus, process_load, system_load);
-
- if (monitor_thread_) {
- monitor_thread_->PostDelayed(period_ms_, this);
- }
-}
-
-} // namespace talk_base
diff --git a/base/cpumonitor.h b/base/cpumonitor.h
deleted file mode 100644
index e0c3655..0000000
--- a/base/cpumonitor.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * libjingle
- * Copyright 2010 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_CPUMONITOR_H_
-#define TALK_BASE_CPUMONITOR_H_
-
-#include "talk/base/basictypes.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#if defined(LINUX) || defined(ANDROID)
-#include "talk/base/stream.h"
-#endif // defined(LINUX) || defined(ANDROID)
-
-namespace talk_base {
-class Thread;
-class SystemInfo;
-
-struct CpuStats {
- CpuStats()
- : prev_total_times_(0),
- prev_cpu_times_(0),
- prev_load_(0.f),
- prev_load_time_(0u) {
- }
-
- uint64 prev_total_times_;
- uint64 prev_cpu_times_;
- float prev_load_; // Previous load value.
- uint32 prev_load_time_; // Time previous load value was taken.
-};
-
-// CpuSampler samples the process and system load.
-class CpuSampler {
- public:
- CpuSampler();
- ~CpuSampler();
-
- // Initialize CpuSampler. Returns true if successful.
- bool Init();
-
- // Set minimum interval in ms between computing new load values.
- // Default 950 ms. Set to 0 to disable interval.
- void set_load_interval(int min_load_interval);
-
- // Return CPU load of current process as a float from 0 to 1.
- float GetProcessLoad();
-
- // Return CPU load of current process as a float from 0 to 1.
- float GetSystemLoad();
-
- // Return number of cpus. Includes hyperthreads.
- int GetMaxCpus() const;
-
- // Return current number of cpus available to this process.
- int GetCurrentCpus();
-
- // For testing. Allows forcing of fallback to using NTDLL functions.
- void set_force_fallback(bool fallback) {
-#ifdef WIN32
- force_fallback_ = fallback;
-#endif
- }
-
- private:
- float UpdateCpuLoad(uint64 current_total_times,
- uint64 current_cpu_times,
- uint64 *prev_total_times,
- uint64 *prev_cpu_times);
- CpuStats process_;
- CpuStats system_;
- int cpus_;
- int min_load_interval_; // Minimum time between computing new load.
- scoped_ptr<SystemInfo> sysinfo_;
-#ifdef WIN32
- void* get_system_times_;
- void* nt_query_system_information_;
- bool force_fallback_;
-#endif
-#if defined(LINUX) || defined(ANDROID)
- // File for reading /proc/stat
- scoped_ptr<FileStream> sfile_;
-#endif // defined(LINUX) || defined(ANDROID)
-};
-
-// CpuMonitor samples and signals the CPU load periodically.
-class CpuMonitor
- : public talk_base::MessageHandler, public sigslot::has_slots<> {
- public:
- explicit CpuMonitor(Thread* thread);
- virtual ~CpuMonitor();
- void set_thread(Thread* thread);
-
- bool Start(int period_ms);
- void Stop();
- // Signal parameters are current cpus, max cpus, process load and system load.
- sigslot::signal4<int, int, float, float> SignalUpdate;
-
- protected:
- // Override virtual method of parent MessageHandler.
- virtual void OnMessage(talk_base::Message* msg);
- // Clear the monitor thread and stop sending it messages if the thread goes
- // away before our lifetime.
- void OnMessageQueueDestroyed() { monitor_thread_ = NULL; }
-
- private:
- Thread* monitor_thread_;
- CpuSampler sampler_;
- int period_ms_;
-
- DISALLOW_COPY_AND_ASSIGN(CpuMonitor);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_CPUMONITOR_H_
diff --git a/base/cpumonitor_unittest.cc b/base/cpumonitor_unittest.cc
deleted file mode 100644
index cdc3e6b..0000000
--- a/base/cpumonitor_unittest.cc
+++ /dev/null
@@ -1,405 +0,0 @@
-/*
- * libjingle
- * Copyright 2010 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <iomanip>
-#include <iostream>
-#include <vector>
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif
-
-#include "talk/base/cpumonitor.h"
-#include "talk/base/flags.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-#include "talk/base/timing.h"
-
-namespace talk_base {
-
-static const int kMaxCpus = 1024;
-static const int kSettleTime = 100; // Amount of time to between tests.
-static const int kIdleTime = 500; // Amount of time to be idle in ms.
-static const int kBusyTime = 1000; // Amount of time to be busy in ms.
-static const int kLongInterval = 2000; // Interval longer than busy times
-
-class BusyThread : public talk_base::Thread {
- public:
- BusyThread(double load, double duration, double interval) :
- load_(load), duration_(duration), interval_(interval) {
- }
- virtual ~BusyThread() {
- Stop();
- }
- void Run() {
- Timing time;
- double busy_time = interval_ * load_ / 100.0;
- for (;;) {
- time.BusyWait(busy_time);
- time.IdleWait(interval_ - busy_time);
- if (duration_) {
- duration_ -= interval_;
- if (duration_ <= 0) {
- break;
- }
- }
- }
- }
- private:
- double load_;
- double duration_;
- double interval_;
-};
-
-class CpuLoadListener : public sigslot::has_slots<> {
- public:
- CpuLoadListener()
- : current_cpus_(0),
- cpus_(0),
- process_load_(.0f),
- system_load_(.0f),
- count_(0) {
- }
-
- void OnCpuLoad(int current_cpus, int cpus, float proc_load, float sys_load) {
- current_cpus_ = current_cpus;
- cpus_ = cpus;
- process_load_ = proc_load;
- system_load_ = sys_load;
- ++count_;
- }
-
- int current_cpus() const { return current_cpus_; }
- int cpus() const { return cpus_; }
- float process_load() const { return process_load_; }
- float system_load() const { return system_load_; }
- int count() const { return count_; }
-
- private:
- int current_cpus_;
- int cpus_;
- float process_load_;
- float system_load_;
- int count_;
-};
-
-// Set affinity (which cpu to run on), but respecting FLAG_affinity:
-// -1 means no affinity - run on whatever cpu is available.
-// 0 .. N means run on specific cpu. The tool will create N threads and call
-// SetThreadAffinity on 0 to N - 1 as cpu. FLAG_affinity sets the first cpu
-// so the range becomes affinity to affinity + N - 1
-// Note that this function affects Windows scheduling, effectively giving
-// the thread with affinity for a specified CPU more priority on that CPU.
-bool SetThreadAffinity(BusyThread* t, int cpu, int affinity) {
-#ifdef WIN32
- if (affinity >= 0) {
- return ::SetThreadAffinityMask(t->GetHandle(),
- 1 << (cpu + affinity)) != FALSE;
- }
-#endif
- return true;
-}
-
-bool SetThreadPriority(BusyThread* t, int prio) {
- if (!prio) {
- return true;
- }
- bool ok = t->SetPriority(static_cast<talk_base::ThreadPriority>(prio));
- if (!ok) {
- std::cout << "Error setting thread priority." << std::endl;
- }
- return ok;
-}
-
-int CpuLoad(double cpuload, double duration, int numthreads,
- int priority, double interval, int affinity) {
- int ret = 0;
- std::vector<BusyThread*> threads;
- for (int i = 0; i < numthreads; ++i) {
- threads.push_back(new BusyThread(cpuload, duration, interval));
- // NOTE(fbarchard): Priority must be done before Start.
- if (!SetThreadPriority(threads[i], priority) ||
- !threads[i]->Start() ||
- !SetThreadAffinity(threads[i], i, affinity)) {
- ret = 1;
- break;
- }
- }
- // Wait on each thread
- if (ret == 0) {
- for (int i = 0; i < numthreads; ++i) {
- threads[i]->Stop();
- }
- }
-
- for (int i = 0; i < numthreads; ++i) {
- delete threads[i];
- }
- return ret;
-}
-
-// Make 2 CPUs busy
-static void CpuTwoBusyLoop(int busytime) {
- CpuLoad(100.0, busytime / 1000.0, 2, 1, 0.050, -1);
-}
-
-// Make 1 CPUs busy
-static void CpuBusyLoop(int busytime) {
- CpuLoad(100.0, busytime / 1000.0, 1, 1, 0.050, -1);
-}
-
-// Make 1 use half CPU time.
-static void CpuHalfBusyLoop(int busytime) {
- CpuLoad(50.0, busytime / 1000.0, 1, 1, 0.050, -1);
-}
-
-void TestCpuSampler(bool test_proc, bool test_sys, bool force_fallback) {
- CpuSampler sampler;
- sampler.set_force_fallback(force_fallback);
- EXPECT_TRUE(sampler.Init());
- sampler.set_load_interval(100);
- int cpus = sampler.GetMaxCpus();
-
- // Test1: CpuSampler under idle situation.
- Thread::SleepMs(kSettleTime);
- sampler.GetProcessLoad();
- sampler.GetSystemLoad();
-
- Thread::SleepMs(kIdleTime);
-
- float proc_idle = 0.f, sys_idle = 0.f;
- if (test_proc) {
- proc_idle = sampler.GetProcessLoad();
- }
- if (test_sys) {
- sys_idle = sampler.GetSystemLoad();
- }
- if (test_proc) {
- LOG(LS_INFO) << "ProcessLoad Idle: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << proc_idle;
- EXPECT_GE(proc_idle, 0.f);
- EXPECT_LE(proc_idle, static_cast<float>(cpus));
- }
- if (test_sys) {
- LOG(LS_INFO) << "SystemLoad Idle: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << sys_idle;
- EXPECT_GE(sys_idle, 0.f);
- EXPECT_LE(sys_idle, static_cast<float>(cpus));
- }
-
- // Test2: CpuSampler with main process at 50% busy.
- Thread::SleepMs(kSettleTime);
- sampler.GetProcessLoad();
- sampler.GetSystemLoad();
-
- CpuHalfBusyLoop(kBusyTime);
-
- float proc_halfbusy = 0.f, sys_halfbusy = 0.f;
- if (test_proc) {
- proc_halfbusy = sampler.GetProcessLoad();
- }
- if (test_sys) {
- sys_halfbusy = sampler.GetSystemLoad();
- }
- if (test_proc) {
- LOG(LS_INFO) << "ProcessLoad Halfbusy: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << proc_halfbusy;
- EXPECT_GE(proc_halfbusy, 0.f);
- EXPECT_LE(proc_halfbusy, static_cast<float>(cpus));
- }
- if (test_sys) {
- LOG(LS_INFO) << "SystemLoad Halfbusy: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << sys_halfbusy;
- EXPECT_GE(sys_halfbusy, 0.f);
- EXPECT_LE(sys_halfbusy, static_cast<float>(cpus));
- }
-
- // Test3: CpuSampler with main process busy.
- Thread::SleepMs(kSettleTime);
- sampler.GetProcessLoad();
- sampler.GetSystemLoad();
-
- CpuBusyLoop(kBusyTime);
-
- float proc_busy = 0.f, sys_busy = 0.f;
- if (test_proc) {
- proc_busy = sampler.GetProcessLoad();
- }
- if (test_sys) {
- sys_busy = sampler.GetSystemLoad();
- }
- if (test_proc) {
- LOG(LS_INFO) << "ProcessLoad Busy: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << proc_busy;
- EXPECT_GE(proc_busy, 0.f);
- EXPECT_LE(proc_busy, static_cast<float>(cpus));
- }
- if (test_sys) {
- LOG(LS_INFO) << "SystemLoad Busy: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << sys_busy;
- EXPECT_GE(sys_busy, 0.f);
- EXPECT_LE(sys_busy, static_cast<float>(cpus));
- }
-
- // Test4: CpuSampler with 2 cpus process busy.
- if (cpus >= 2) {
- Thread::SleepMs(kSettleTime);
- sampler.GetProcessLoad();
- sampler.GetSystemLoad();
-
- CpuTwoBusyLoop(kBusyTime);
-
- float proc_twobusy = 0.f, sys_twobusy = 0.f;
- if (test_proc) {
- proc_twobusy = sampler.GetProcessLoad();
- }
- if (test_sys) {
- sys_twobusy = sampler.GetSystemLoad();
- }
- if (test_proc) {
- LOG(LS_INFO) << "ProcessLoad 2 CPU Busy:"
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << proc_twobusy;
- EXPECT_GE(proc_twobusy, 0.f);
- EXPECT_LE(proc_twobusy, static_cast<float>(cpus));
- }
- if (test_sys) {
- LOG(LS_INFO) << "SystemLoad 2 CPU Busy: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << sys_twobusy;
- EXPECT_GE(sys_twobusy, 0.f);
- EXPECT_LE(sys_twobusy, static_cast<float>(cpus));
- }
- }
-
- // Test5: CpuSampler with idle process after being busy.
- Thread::SleepMs(kSettleTime);
- sampler.GetProcessLoad();
- sampler.GetSystemLoad();
-
- Thread::SleepMs(kIdleTime);
-
- if (test_proc) {
- proc_idle = sampler.GetProcessLoad();
- }
- if (test_sys) {
- sys_idle = sampler.GetSystemLoad();
- }
- if (test_proc) {
- LOG(LS_INFO) << "ProcessLoad Idle: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << proc_idle;
- EXPECT_GE(proc_idle, 0.f);
- EXPECT_LE(proc_idle, proc_busy);
- }
- if (test_sys) {
- LOG(LS_INFO) << "SystemLoad Idle: "
- << std::setiosflags(std::ios_base::fixed)
- << std::setprecision(2) << std::setw(6) << sys_idle;
- EXPECT_GE(sys_idle, 0.f);
- EXPECT_LE(sys_idle, static_cast<float>(cpus));
- }
-}
-
-TEST(CpuMonitorTest, TestCpus) {
- CpuSampler sampler;
- EXPECT_TRUE(sampler.Init());
- int current_cpus = sampler.GetCurrentCpus();
- int cpus = sampler.GetMaxCpus();
- LOG(LS_INFO) << "Current Cpus: " << std::setw(9) << current_cpus;
- LOG(LS_INFO) << "Maximum Cpus: " << std::setw(9) << cpus;
- EXPECT_GT(cpus, 0);
- EXPECT_LE(cpus, kMaxCpus);
- EXPECT_GT(current_cpus, 0);
- EXPECT_LE(current_cpus, cpus);
-}
-
-#ifdef WIN32
-// Tests overall system CpuSampler using legacy OS fallback code if applicable.
-TEST(CpuMonitorTest, TestGetSystemLoadForceFallback) {
- TestCpuSampler(false, true, true);
-}
-#endif
-
-// Tests both process and system functions in use at same time.
-TEST(CpuMonitorTest, TestGetBothLoad) {
- TestCpuSampler(true, true, false);
-}
-
-// Tests a query less than the interval produces the same value.
-TEST(CpuMonitorTest, TestInterval) {
- CpuSampler sampler;
- EXPECT_TRUE(sampler.Init());
-
- // Test1: Set interval to large value so sampler will not update.
- sampler.set_load_interval(kLongInterval);
-
- sampler.GetProcessLoad();
- sampler.GetSystemLoad();
-
- float proc_orig = sampler.GetProcessLoad();
- float sys_orig = sampler.GetSystemLoad();
-
- Thread::SleepMs(kIdleTime);
-
- float proc_halftime = sampler.GetProcessLoad();
- float sys_halftime = sampler.GetSystemLoad();
-
- EXPECT_EQ(proc_orig, proc_halftime);
- EXPECT_EQ(sys_orig, sys_halftime);
-}
-
-TEST(CpuMonitorTest, TestCpuMonitor) {
- CpuMonitor monitor(Thread::Current());
- CpuLoadListener listener;
- monitor.SignalUpdate.connect(&listener, &CpuLoadListener::OnCpuLoad);
- EXPECT_TRUE(monitor.Start(10));
- // We have checked cpu load more than twice.
- EXPECT_TRUE_WAIT(listener.count() > 2, 1000);
- EXPECT_GT(listener.current_cpus(), 0);
- EXPECT_GT(listener.cpus(), 0);
- EXPECT_GE(listener.process_load(), .0f);
- EXPECT_GE(listener.system_load(), .0f);
-
- monitor.Stop();
- // Wait 20 ms to ake sure all signals are delivered.
- Thread::Current()->ProcessMessages(20);
- int old_count = listener.count();
- Thread::Current()->ProcessMessages(20);
- // Verfy no more siganls.
- EXPECT_EQ(old_count, listener.count());
-}
-
-} // namespace talk_base
diff --git a/base/crc32.cc b/base/crc32.cc
deleted file mode 100644
index 82998ee..0000000
--- a/base/crc32.cc
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/crc32.h"
-
-#include "talk/base/basicdefs.h"
-
-namespace talk_base {
-
-// This implementation is based on the sample implementation in RFC 1952.
-
-// CRC32 polynomial, in reversed form.
-// See RFC 1952, or http://en.wikipedia.org/wiki/Cyclic_redundancy_check
-static const uint32 kCrc32Polynomial = 0xEDB88320;
-static uint32 kCrc32Table[256] = { 0 };
-
-static void EnsureCrc32TableInited() {
- if (kCrc32Table[ARRAY_SIZE(kCrc32Table) - 1])
- return; // already inited
- for (uint32 i = 0; i < ARRAY_SIZE(kCrc32Table); ++i) {
- uint32 c = i;
- for (size_t j = 0; j < 8; ++j) {
- if (c & 1) {
- c = kCrc32Polynomial ^ (c >> 1);
- } else {
- c >>= 1;
- }
- }
- kCrc32Table[i] = c;
- }
-}
-
-uint32 UpdateCrc32(uint32 start, const void* buf, size_t len) {
- EnsureCrc32TableInited();
-
- uint32 c = start ^ 0xFFFFFFFF;
- const uint8* u = static_cast<const uint8*>(buf);
- for (size_t i = 0; i < len; ++i) {
- c = kCrc32Table[(c ^ u[i]) & 0xFF] ^ (c >> 8);
- }
- return c ^ 0xFFFFFFFF;
-}
-
-} // namespace talk_base
-
diff --git a/base/crc32.h b/base/crc32.h
deleted file mode 100644
index 144158b..0000000
--- a/base/crc32.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_CRC32_H_
-#define TALK_BASE_CRC32_H_
-
-#include <string>
-
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-// Updates a CRC32 checksum with |len| bytes from |buf|. |initial| holds the
-// checksum result from the previous update; for the first call, it should be 0.
-uint32 UpdateCrc32(uint32 initial, const void* buf, size_t len);
-
-// Computes a CRC32 checksum using |len| bytes from |buf|.
-inline uint32 ComputeCrc32(const void* buf, size_t len) {
- return UpdateCrc32(0, buf, len);
-}
-inline uint32 ComputeCrc32(const std::string& str) {
- return ComputeCrc32(str.c_str(), str.size());
-}
-
-} // namespace talk_base
-
-#endif // TALK_BASE_CRC32_H_
diff --git a/base/crc32_unittest.cc b/base/crc32_unittest.cc
deleted file mode 100644
index 24333d3..0000000
--- a/base/crc32_unittest.cc
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/crc32.h"
-#include "talk/base/gunit.h"
-
-#include <string>
-
-namespace talk_base {
-
-TEST(Crc32Test, TestBasic) {
- EXPECT_EQ(0U, ComputeCrc32(""));
- EXPECT_EQ(0x352441C2U, ComputeCrc32("abc"));
- EXPECT_EQ(0x171A3F5FU,
- ComputeCrc32("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"));
-}
-
-TEST(Crc32Test, TestMultipleUpdates) {
- std::string input =
- "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
- uint32 c = 0;
- for (size_t i = 0; i < input.size(); ++i) {
- c = UpdateCrc32(c, &input[i], 1);
- }
- EXPECT_EQ(0x171A3F5FU, c);
-}
-
-} // namespace talk_base
diff --git a/base/criticalsection.h b/base/criticalsection.h
deleted file mode 100644
index c6ffbc0..0000000
--- a/base/criticalsection.h
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_CRITICALSECTION_H__
-#define TALK_BASE_CRITICALSECTION_H__
-
-#include "talk/base/constructormagic.h"
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif
-
-#ifdef POSIX
-#include <pthread.h>
-#endif
-
-#ifdef _DEBUG
-#define CS_TRACK_OWNER 1
-#endif // _DEBUG
-
-#if CS_TRACK_OWNER
-#define TRACK_OWNER(x) x
-#else // !CS_TRACK_OWNER
-#define TRACK_OWNER(x)
-#endif // !CS_TRACK_OWNER
-
-namespace talk_base {
-
-#ifdef WIN32
-class CriticalSection {
- public:
- CriticalSection() {
- InitializeCriticalSection(&crit_);
- // Windows docs say 0 is not a valid thread id
- TRACK_OWNER(thread_ = 0);
- }
- ~CriticalSection() {
- DeleteCriticalSection(&crit_);
- }
- void Enter() {
- EnterCriticalSection(&crit_);
- TRACK_OWNER(thread_ = GetCurrentThreadId());
- }
- bool TryEnter() {
- if (TryEnterCriticalSection(&crit_) != FALSE) {
- TRACK_OWNER(thread_ = GetCurrentThreadId());
- return true;
- }
- return false;
- }
- void Leave() {
- TRACK_OWNER(thread_ = 0);
- LeaveCriticalSection(&crit_);
- }
-
-#if CS_TRACK_OWNER
- bool CurrentThreadIsOwner() const { return thread_ == GetCurrentThreadId(); }
-#endif // CS_TRACK_OWNER
-
- private:
- CRITICAL_SECTION crit_;
- TRACK_OWNER(DWORD thread_); // The section's owning thread id
-};
-#endif // WIN32
-
-#ifdef POSIX
-class CriticalSection {
- public:
- CriticalSection() {
- pthread_mutexattr_t mutex_attribute;
- pthread_mutexattr_init(&mutex_attribute);
- pthread_mutexattr_settype(&mutex_attribute, PTHREAD_MUTEX_RECURSIVE);
- pthread_mutex_init(&mutex_, &mutex_attribute);
- pthread_mutexattr_destroy(&mutex_attribute);
- TRACK_OWNER(thread_ = 0);
- }
- ~CriticalSection() {
- pthread_mutex_destroy(&mutex_);
- }
- void Enter() {
- pthread_mutex_lock(&mutex_);
- TRACK_OWNER(thread_ = pthread_self());
- }
- bool TryEnter() {
- if (pthread_mutex_trylock(&mutex_) == 0) {
- TRACK_OWNER(thread_ = pthread_self());
- return true;
- }
- return false;
- }
- void Leave() {
- TRACK_OWNER(thread_ = 0);
- pthread_mutex_unlock(&mutex_);
- }
-
-#if CS_TRACK_OWNER
- bool CurrentThreadIsOwner() const { return pthread_equal(thread_, pthread_self()); }
-#endif // CS_TRACK_OWNER
-
- private:
- pthread_mutex_t mutex_;
- TRACK_OWNER(pthread_t thread_);
-};
-#endif // POSIX
-
-// CritScope, for serializing execution through a scope.
-class CritScope {
- public:
- explicit CritScope(CriticalSection *pcrit) {
- pcrit_ = pcrit;
- pcrit_->Enter();
- }
- ~CritScope() {
- pcrit_->Leave();
- }
- private:
- CriticalSection *pcrit_;
- DISALLOW_COPY_AND_ASSIGN(CritScope);
-};
-
-// Tries to lock a critical section on construction via
-// CriticalSection::TryEnter, and unlocks on destruction if the
-// lock was taken. Never blocks.
-//
-// IMPORTANT: Unlike CritScope, the lock may not be owned by this thread in
-// subsequent code. Users *must* check locked() to determine if the
-// lock was taken. If you're not calling locked(), you're doing it wrong!
-class TryCritScope {
- public:
- explicit TryCritScope(CriticalSection *pcrit) {
- pcrit_ = pcrit;
- locked_ = pcrit_->TryEnter();
- }
- ~TryCritScope() {
- if (locked_) {
- pcrit_->Leave();
- }
- }
- bool locked() const {
- return locked_;
- }
- private:
- CriticalSection *pcrit_;
- bool locked_;
- DISALLOW_COPY_AND_ASSIGN(TryCritScope);
-};
-
-// TODO: Move this to atomicops.h, which can't be done easily because of
-// complex compile rules.
-class AtomicOps {
- public:
-#ifdef WIN32
- // Assumes sizeof(int) == sizeof(LONG), which it is on Win32 and Win64.
- static int Increment(int* i) {
- return ::InterlockedIncrement(reinterpret_cast<LONG*>(i));
- }
- static int Decrement(int* i) {
- return ::InterlockedDecrement(reinterpret_cast<LONG*>(i));
- }
-#else
- static int Increment(int* i) {
- return __sync_add_and_fetch(i, 1);
- }
- static int Decrement(int* i) {
- return __sync_sub_and_fetch(i, 1);
- }
-#endif
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_CRITICALSECTION_H__
diff --git a/base/criticalsection_unittest.cc b/base/criticalsection_unittest.cc
deleted file mode 100644
index 0bb34b7..0000000
--- a/base/criticalsection_unittest.cc
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * libjingle
- * Copyright 2014, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <set>
-#include <vector>
-
-#include "talk/base/criticalsection.h"
-#include "talk/base/event.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scopedptrcollection.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-namespace {
-
-const int kLongTime = 10000; // 10 seconds
-const int kNumThreads = 16;
-const int kOperationsToRun = 1000;
-
-template <class T>
-class AtomicOpRunner : public MessageHandler {
- public:
- explicit AtomicOpRunner(int initial_value)
- : value_(initial_value),
- threads_active_(0),
- start_event_(true, false),
- done_event_(true, false) {}
-
- int value() const { return value_; }
-
- bool Run() {
- // Signal all threads to start.
- start_event_.Set();
-
- // Wait for all threads to finish.
- return done_event_.Wait(kLongTime);
- }
-
- void SetExpectedThreadCount(int count) {
- threads_active_ = count;
- }
-
- virtual void OnMessage(Message* msg) {
- std::vector<int> values;
- values.reserve(kOperationsToRun);
-
- // Wait to start.
- ASSERT_TRUE(start_event_.Wait(kLongTime));
-
- // Generate a bunch of values by updating value_ atomically.
- for (int i = 0; i < kOperationsToRun; ++i) {
- values.push_back(T::AtomicOp(&value_));
- }
-
- { // Add them all to the set.
- CritScope cs(&all_values_crit_);
- for (size_t i = 0; i < values.size(); ++i) {
- std::pair<std::set<int>::iterator, bool> result =
- all_values_.insert(values[i]);
- // Each value should only be taken by one thread, so if this value
- // has already been added, something went wrong.
- EXPECT_TRUE(result.second)
- << "Thread=" << Thread::Current() << " value=" << values[i];
- }
- }
-
- // Signal that we're done.
- if (AtomicOps::Decrement(&threads_active_) == 0) {
- done_event_.Set();
- }
- }
-
- private:
- int value_;
- int threads_active_;
- CriticalSection all_values_crit_;
- std::set<int> all_values_;
- Event start_event_;
- Event done_event_;
-};
-
-struct IncrementOp {
- static int AtomicOp(int* i) { return AtomicOps::Increment(i); }
-};
-
-struct DecrementOp {
- static int AtomicOp(int* i) { return AtomicOps::Decrement(i); }
-};
-
-void StartThreads(ScopedPtrCollection<Thread>* threads,
- MessageHandler* handler) {
- for (int i = 0; i < kNumThreads; ++i) {
- Thread* thread = new Thread();
- thread->Start();
- thread->Post(handler);
- threads->PushBack(thread);
- }
-}
-
-} // namespace
-
-TEST(AtomicOpsTest, Simple) {
- int value = 0;
- EXPECT_EQ(1, AtomicOps::Increment(&value));
- EXPECT_EQ(1, value);
- EXPECT_EQ(2, AtomicOps::Increment(&value));
- EXPECT_EQ(2, value);
- EXPECT_EQ(1, AtomicOps::Decrement(&value));
- EXPECT_EQ(1, value);
- EXPECT_EQ(0, AtomicOps::Decrement(&value));
- EXPECT_EQ(0, value);
-}
-
-TEST(AtomicOpsTest, Increment) {
- // Create and start lots of threads.
- AtomicOpRunner<IncrementOp> runner(0);
- ScopedPtrCollection<Thread> threads;
- StartThreads(&threads, &runner);
- runner.SetExpectedThreadCount(kNumThreads);
-
- // Release the hounds!
- EXPECT_TRUE(runner.Run());
- EXPECT_EQ(kOperationsToRun * kNumThreads, runner.value());
-}
-
-TEST(AtomicOpsTest, Decrement) {
- // Create and start lots of threads.
- AtomicOpRunner<DecrementOp> runner(kOperationsToRun * kNumThreads);
- ScopedPtrCollection<Thread> threads;
- StartThreads(&threads, &runner);
- runner.SetExpectedThreadCount(kNumThreads);
-
- // Release the hounds!
- EXPECT_TRUE(runner.Run());
- EXPECT_EQ(0, runner.value());
-}
-
-} // namespace talk_base
diff --git a/base/cryptstring.h b/base/cryptstring.h
deleted file mode 100644
index 600474f..0000000
--- a/base/cryptstring.h
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _TALK_BASE_CRYPTSTRING_H_
-#define _TALK_BASE_CRYPTSTRING_H_
-
-#include <string.h>
-
-#include <string>
-#include <vector>
-
-#include "talk/base/linked_ptr.h"
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-class CryptStringImpl {
-public:
- virtual ~CryptStringImpl() {}
- virtual size_t GetLength() const = 0;
- virtual void CopyTo(char * dest, bool nullterminate) const = 0;
- virtual std::string UrlEncode() const = 0;
- virtual CryptStringImpl * Copy() const = 0;
- virtual void CopyRawTo(std::vector<unsigned char> * dest) const = 0;
-};
-
-class EmptyCryptStringImpl : public CryptStringImpl {
-public:
- virtual ~EmptyCryptStringImpl() {}
- virtual size_t GetLength() const { return 0; }
- virtual void CopyTo(char * dest, bool nullterminate) const {
- if (nullterminate) {
- *dest = '\0';
- }
- }
- virtual std::string UrlEncode() const { return ""; }
- virtual CryptStringImpl * Copy() const { return new EmptyCryptStringImpl(); }
- virtual void CopyRawTo(std::vector<unsigned char> * dest) const {
- dest->clear();
- }
-};
-
-class CryptString {
-public:
- CryptString() : impl_(new EmptyCryptStringImpl()) {}
- size_t GetLength() const { return impl_->GetLength(); }
- void CopyTo(char * dest, bool nullterminate) const { impl_->CopyTo(dest, nullterminate); }
- CryptString(const CryptString & other) : impl_(other.impl_->Copy()) {}
- explicit CryptString(const CryptStringImpl & impl) : impl_(impl.Copy()) {}
- CryptString & operator=(const CryptString & other) {
- if (this != &other) {
- impl_.reset(other.impl_->Copy());
- }
- return *this;
- }
- void Clear() { impl_.reset(new EmptyCryptStringImpl()); }
- std::string UrlEncode() const { return impl_->UrlEncode(); }
- void CopyRawTo(std::vector<unsigned char> * dest) const {
- return impl_->CopyRawTo(dest);
- }
-
-private:
- scoped_ptr<const CryptStringImpl> impl_;
-};
-
-
-// Used for constructing strings where a password is involved and we
-// need to ensure that we zero memory afterwards
-class FormatCryptString {
-public:
- FormatCryptString() {
- storage_ = new char[32];
- capacity_ = 32;
- length_ = 0;
- storage_[0] = 0;
- }
-
- void Append(const std::string & text) {
- Append(text.data(), text.length());
- }
-
- void Append(const char * data, size_t length) {
- EnsureStorage(length_ + length + 1);
- memcpy(storage_ + length_, data, length);
- length_ += length;
- storage_[length_] = '\0';
- }
-
- void Append(const CryptString * password) {
- size_t len = password->GetLength();
- EnsureStorage(length_ + len + 1);
- password->CopyTo(storage_ + length_, true);
- length_ += len;
- }
-
- size_t GetLength() {
- return length_;
- }
-
- const char * GetData() {
- return storage_;
- }
-
-
- // Ensures storage of at least n bytes
- void EnsureStorage(size_t n) {
- if (capacity_ >= n) {
- return;
- }
-
- size_t old_capacity = capacity_;
- char * old_storage = storage_;
-
- for (;;) {
- capacity_ *= 2;
- if (capacity_ >= n)
- break;
- }
-
- storage_ = new char[capacity_];
-
- if (old_capacity) {
- memcpy(storage_, old_storage, length_);
-
- // zero memory in a way that an optimizer won't optimize it out
- old_storage[0] = 0;
- for (size_t i = 1; i < old_capacity; i++) {
- old_storage[i] = old_storage[i - 1];
- }
- delete[] old_storage;
- }
- }
-
- ~FormatCryptString() {
- if (capacity_) {
- storage_[0] = 0;
- for (size_t i = 1; i < capacity_; i++) {
- storage_[i] = storage_[i - 1];
- }
- }
- delete[] storage_;
- }
-private:
- char * storage_;
- size_t capacity_;
- size_t length_;
-};
-
-class InsecureCryptStringImpl : public CryptStringImpl {
- public:
- std::string& password() { return password_; }
- const std::string& password() const { return password_; }
-
- virtual ~InsecureCryptStringImpl() {}
- virtual size_t GetLength() const { return password_.size(); }
- virtual void CopyTo(char * dest, bool nullterminate) const {
- memcpy(dest, password_.data(), password_.size());
- if (nullterminate) dest[password_.size()] = 0;
- }
- virtual std::string UrlEncode() const { return password_; }
- virtual CryptStringImpl * Copy() const {
- InsecureCryptStringImpl * copy = new InsecureCryptStringImpl;
- copy->password() = password_;
- return copy;
- }
- virtual void CopyRawTo(std::vector<unsigned char> * dest) const {
- dest->resize(password_.size());
- memcpy(&dest->front(), password_.data(), password_.size());
- }
- private:
- std::string password_;
-};
-
-}
-
-#endif // _TALK_BASE_CRYPTSTRING_H_
diff --git a/base/dbus.cc b/base/dbus.cc
deleted file mode 100644
index 78e717a..0000000
--- a/base/dbus.cc
+++ /dev/null
@@ -1,413 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_DBUS_GLIB
-
-#include "talk/base/dbus.h"
-
-#include <glib.h>
-
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-// Avoid static object construction/destruction on startup/shutdown.
-static pthread_once_t g_dbus_init_once = PTHREAD_ONCE_INIT;
-static LibDBusGlibSymbolTable *g_dbus_symbol = NULL;
-
-// Releases DBus-Glib symbols.
-static void ReleaseDBusGlibSymbol() {
- if (g_dbus_symbol != NULL) {
- delete g_dbus_symbol;
- g_dbus_symbol = NULL;
- }
-}
-
-// Loads DBus-Glib symbols.
-static void InitializeDBusGlibSymbol() {
- // This is thread safe.
- if (NULL == g_dbus_symbol) {
- g_dbus_symbol = new LibDBusGlibSymbolTable();
-
- // Loads dbus-glib
- if (NULL == g_dbus_symbol || !g_dbus_symbol->Load()) {
- LOG(LS_WARNING) << "Failed to load dbus-glib symbol table.";
- ReleaseDBusGlibSymbol();
- } else {
- // Nothing we can do if atexit() failed. Just ignore its returned value.
- atexit(ReleaseDBusGlibSymbol);
- }
- }
-}
-
-inline static LibDBusGlibSymbolTable *GetSymbols() {
- return DBusMonitor::GetDBusGlibSymbolTable();
-}
-
-// Implementation of class DBusSigMessageData
-DBusSigMessageData::DBusSigMessageData(DBusMessage *message)
- : TypedMessageData<DBusMessage *>(message) {
- GetSymbols()->dbus_message_ref()(data());
-}
-
-DBusSigMessageData::~DBusSigMessageData() {
- GetSymbols()->dbus_message_unref()(data());
-}
-
-// Implementation of class DBusSigFilter
-
-// Builds a DBus filter string from given DBus path, interface and member.
-std::string DBusSigFilter::BuildFilterString(const std::string &path,
- const std::string &interface,
- const std::string &member) {
- std::string ret(DBUS_TYPE "='" DBUS_SIGNAL "'");
- if (!path.empty()) {
- ret += ("," DBUS_PATH "='");
- ret += path;
- ret += "'";
- }
- if (!interface.empty()) {
- ret += ("," DBUS_INTERFACE "='");
- ret += interface;
- ret += "'";
- }
- if (!member.empty()) {
- ret += ("," DBUS_MEMBER "='");
- ret += member;
- ret += "'";
- }
- return ret;
-}
-
-// Forwards the message to the given instance.
-DBusHandlerResult DBusSigFilter::DBusCallback(DBusConnection *dbus_conn,
- DBusMessage *message,
- void *instance) {
- ASSERT(instance);
- if (instance) {
- return static_cast<DBusSigFilter *>(instance)->Callback(message);
- }
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-// Posts a message to caller thread.
-DBusHandlerResult DBusSigFilter::Callback(DBusMessage *message) {
- if (caller_thread_) {
- caller_thread_->Post(this, DSM_SIGNAL, new DBusSigMessageData(message));
- }
- // Don't "eat" the message here. Let it pop up.
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-// From MessageHandler.
-void DBusSigFilter::OnMessage(Message *message) {
- if (message != NULL && DSM_SIGNAL == message->message_id) {
- DBusSigMessageData *msg =
- static_cast<DBusSigMessageData *>(message->pdata);
- if (msg) {
- ProcessSignal(msg->data());
- delete msg;
- }
- }
-}
-
-// Definition of private class DBusMonitoringThread.
-// It creates a worker-thread to listen signals on DBus. The worker-thread will
-// be running in a priate GMainLoop forever until either Stop() has been invoked
-// or it hits an error.
-class DBusMonitor::DBusMonitoringThread : public talk_base::Thread {
- public:
- explicit DBusMonitoringThread(DBusMonitor *monitor,
- GMainContext *context,
- GMainLoop *mainloop,
- std::vector<DBusSigFilter *> *filter_list)
- : monitor_(monitor),
- context_(context),
- mainloop_(mainloop),
- connection_(NULL),
- idle_source_(NULL),
- filter_list_(filter_list) {
- ASSERT(monitor_);
- ASSERT(context_);
- ASSERT(mainloop_);
- ASSERT(filter_list_);
- }
-
- virtual ~DBusMonitoringThread() {
- Stop();
- }
-
- // Override virtual method of Thread. Context: worker-thread.
- virtual void Run() {
- ASSERT(NULL == connection_);
-
- // Setup DBus connection and start monitoring.
- monitor_->OnMonitoringStatusChanged(DMS_INITIALIZING);
- if (!Setup()) {
- LOG(LS_ERROR) << "DBus monitoring setup failed.";
- monitor_->OnMonitoringStatusChanged(DMS_FAILED);
- CleanUp();
- return;
- }
- monitor_->OnMonitoringStatusChanged(DMS_RUNNING);
- g_main_loop_run(mainloop_);
- monitor_->OnMonitoringStatusChanged(DMS_STOPPED);
-
- // Done normally. Clean up DBus connection.
- CleanUp();
- return;
- }
-
- // Override virtual method of Thread. Context: caller-thread.
- virtual void Stop() {
- ASSERT(NULL == idle_source_);
- // Add an idle source and let the gmainloop quit on idle.
- idle_source_ = g_idle_source_new();
- if (idle_source_) {
- g_source_set_callback(idle_source_, &Idle, this, NULL);
- g_source_attach(idle_source_, context_);
- } else {
- LOG(LS_ERROR) << "g_idle_source_new() failed.";
- QuitGMainloop(); // Try to quit anyway.
- }
-
- Thread::Stop(); // Wait for the thread.
- }
-
- private:
- // Registers all DBus filters.
- void RegisterAllFilters() {
- ASSERT(NULL != GetSymbols()->dbus_g_connection_get_connection()(
- connection_));
-
- for (std::vector<DBusSigFilter *>::iterator it = filter_list_->begin();
- it != filter_list_->end(); ++it) {
- DBusSigFilter *filter = (*it);
- if (!filter) {
- LOG(LS_ERROR) << "DBusSigFilter list corrupted.";
- continue;
- }
-
- GetSymbols()->dbus_bus_add_match()(
- GetSymbols()->dbus_g_connection_get_connection()(connection_),
- filter->filter().c_str(), NULL);
-
- if (!GetSymbols()->dbus_connection_add_filter()(
- GetSymbols()->dbus_g_connection_get_connection()(connection_),
- &DBusSigFilter::DBusCallback, filter, NULL)) {
- LOG(LS_ERROR) << "dbus_connection_add_filter() failed."
- << "Filter: " << filter->filter();
- continue;
- }
- }
- }
-
- // Unregisters all DBus filters.
- void UnRegisterAllFilters() {
- ASSERT(NULL != GetSymbols()->dbus_g_connection_get_connection()(
- connection_));
-
- for (std::vector<DBusSigFilter *>::iterator it = filter_list_->begin();
- it != filter_list_->end(); ++it) {
- DBusSigFilter *filter = (*it);
- if (!filter) {
- LOG(LS_ERROR) << "DBusSigFilter list corrupted.";
- continue;
- }
- GetSymbols()->dbus_connection_remove_filter()(
- GetSymbols()->dbus_g_connection_get_connection()(connection_),
- &DBusSigFilter::DBusCallback, filter);
- }
- }
-
- // Sets up the monitoring thread.
- bool Setup() {
- g_main_context_push_thread_default(context_);
-
- // Start connection to dbus.
- // If dbus daemon is not running, returns false immediately.
- connection_ = GetSymbols()->dbus_g_bus_get_private()(monitor_->type_,
- context_, NULL);
- if (NULL == connection_) {
- LOG(LS_ERROR) << "dbus_g_bus_get_private() unable to get connection.";
- return false;
- }
- if (NULL == GetSymbols()->dbus_g_connection_get_connection()(connection_)) {
- LOG(LS_ERROR) << "dbus_g_connection_get_connection() returns NULL. "
- << "DBus daemon is probably not running.";
- return false;
- }
-
- // Application don't exit if DBus daemon die.
- GetSymbols()->dbus_connection_set_exit_on_disconnect()(
- GetSymbols()->dbus_g_connection_get_connection()(connection_), FALSE);
-
- // Connect all filters.
- RegisterAllFilters();
-
- return true;
- }
-
- // Cleans up the monitoring thread.
- void CleanUp() {
- if (idle_source_) {
- // We did an attach() with the GSource, so we need to destroy() it.
- g_source_destroy(idle_source_);
- // We need to unref() the GSource to end the last reference we got.
- g_source_unref(idle_source_);
- idle_source_ = NULL;
- }
- if (connection_) {
- if (GetSymbols()->dbus_g_connection_get_connection()(connection_)) {
- UnRegisterAllFilters();
- GetSymbols()->dbus_connection_close()(
- GetSymbols()->dbus_g_connection_get_connection()(connection_));
- }
- GetSymbols()->dbus_g_connection_unref()(connection_);
- connection_ = NULL;
- }
- g_main_loop_unref(mainloop_);
- mainloop_ = NULL;
- g_main_context_unref(context_);
- context_ = NULL;
- }
-
- // Handles callback on Idle. We only add this source when ready to stop.
- static gboolean Idle(gpointer data) {
- static_cast<DBusMonitoringThread *>(data)->QuitGMainloop();
- return TRUE;
- }
-
- // We only hit this when ready to quit.
- void QuitGMainloop() {
- g_main_loop_quit(mainloop_);
- }
-
- DBusMonitor *monitor_;
-
- GMainContext *context_;
- GMainLoop *mainloop_;
- DBusGConnection *connection_;
- GSource *idle_source_;
-
- std::vector<DBusSigFilter *> *filter_list_;
-};
-
-// Implementation of class DBusMonitor
-
-// Returns DBus-Glib symbol handle. Initialize it first if hasn't.
-LibDBusGlibSymbolTable *DBusMonitor::GetDBusGlibSymbolTable() {
- // This is multi-thread safe.
- pthread_once(&g_dbus_init_once, InitializeDBusGlibSymbol);
-
- return g_dbus_symbol;
-};
-
-// Creates an instance of DBusMonitor
-DBusMonitor *DBusMonitor::Create(DBusBusType type) {
- if (NULL == DBusMonitor::GetDBusGlibSymbolTable()) {
- return NULL;
- }
- return new DBusMonitor(type);
-}
-
-DBusMonitor::DBusMonitor(DBusBusType type)
- : type_(type),
- status_(DMS_NOT_INITIALIZED),
- monitoring_thread_(NULL) {
- ASSERT(type_ == DBUS_BUS_SYSTEM || type_ == DBUS_BUS_SESSION);
-}
-
-DBusMonitor::~DBusMonitor() {
- StopMonitoring();
-}
-
-bool DBusMonitor::AddFilter(DBusSigFilter *filter) {
- if (monitoring_thread_) {
- return false;
- }
- if (!filter) {
- return false;
- }
- filter_list_.push_back(filter);
- return true;
-}
-
-bool DBusMonitor::StartMonitoring() {
- if (!monitoring_thread_) {
- g_type_init();
- g_thread_init(NULL);
- GetSymbols()->dbus_g_thread_init()();
-
- GMainContext *context = g_main_context_new();
- if (NULL == context) {
- LOG(LS_ERROR) << "g_main_context_new() failed.";
- return false;
- }
-
- GMainLoop *mainloop = g_main_loop_new(context, FALSE);
- if (NULL == mainloop) {
- LOG(LS_ERROR) << "g_main_loop_new() failed.";
- g_main_context_unref(context);
- return false;
- }
-
- monitoring_thread_ = new DBusMonitoringThread(this, context, mainloop,
- &filter_list_);
- if (monitoring_thread_ == NULL) {
- LOG(LS_ERROR) << "Failed to create DBus monitoring thread.";
- g_main_context_unref(context);
- g_main_loop_unref(mainloop);
- return false;
- }
- monitoring_thread_->Start();
- }
- return true;
-}
-
-bool DBusMonitor::StopMonitoring() {
- if (monitoring_thread_) {
- monitoring_thread_->Stop();
- monitoring_thread_ = NULL;
- }
- return true;
-}
-
-DBusMonitor::DBusMonitorStatus DBusMonitor::GetStatus() {
- return status_;
-}
-
-void DBusMonitor::OnMonitoringStatusChanged(DBusMonitorStatus status) {
- status_ = status;
-}
-
-#undef LATE
-
-} // namespace talk_base
-
-#endif // HAVE_DBUS_GLIB
diff --git a/base/dbus.h b/base/dbus.h
deleted file mode 100644
index 7dce350..0000000
--- a/base/dbus.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_DBUS_H_
-#define TALK_BASE_DBUS_H_
-
-#ifdef HAVE_DBUS_GLIB
-
-#include <dbus/dbus.h>
-
-#include <string>
-#include <vector>
-
-#include "talk/base/libdbusglibsymboltable.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-#define DBUS_TYPE "type"
-#define DBUS_SIGNAL "signal"
-#define DBUS_PATH "path"
-#define DBUS_INTERFACE "interface"
-#define DBUS_MEMBER "member"
-
-#ifdef CHROMEOS
-#define CROS_PM_PATH "/"
-#define CROS_PM_INTERFACE "org.chromium.PowerManager"
-#define CROS_SIG_POWERCHANGED "PowerStateChanged"
-#define CROS_VALUE_SLEEP "mem"
-#define CROS_VALUE_RESUME "on"
-#else
-#define UP_PATH "/org/freedesktop/UPower"
-#define UP_INTERFACE "org.freedesktop.UPower"
-#define UP_SIG_SLEEPING "Sleeping"
-#define UP_SIG_RESUMING "Resuming"
-#endif // CHROMEOS
-
-// Wraps a DBus messages.
-class DBusSigMessageData : public TypedMessageData<DBusMessage *> {
- public:
- explicit DBusSigMessageData(DBusMessage *message);
- ~DBusSigMessageData();
-};
-
-// DBusSigFilter is an abstract class that defines the interface of DBus
-// signal handling.
-// The subclasses implement ProcessSignal() for various purposes.
-// When a DBus signal comes, a DSM_SIGNAL message is posted to the caller thread
-// which will then invokes ProcessSignal().
-class DBusSigFilter : protected MessageHandler {
- public:
- enum DBusSigMessage { DSM_SIGNAL };
-
- // This filter string should ususally come from BuildFilterString()
- explicit DBusSigFilter(const std::string &filter)
- : caller_thread_(Thread::Current()), filter_(filter) {
- }
-
- // Builds a DBus monitor filter string from given DBus path, interface, and
- // member.
- // See http://dbus.freedesktop.org/doc/api/html/group__DBusConnection.html
- static std::string BuildFilterString(const std::string &path,
- const std::string &interface,
- const std::string &member);
-
- // Handles callback on DBus messages by DBus system.
- static DBusHandlerResult DBusCallback(DBusConnection *dbus_conn,
- DBusMessage *message,
- void *instance);
-
- // Handles callback on DBus messages to each DBusSigFilter instance.
- DBusHandlerResult Callback(DBusMessage *message);
-
- // From MessageHandler.
- virtual void OnMessage(Message *message);
-
- // Returns the DBus monitor filter string.
- const std::string &filter() const { return filter_; }
-
- private:
- // On caller thread.
- virtual void ProcessSignal(DBusMessage *message) = 0;
-
- Thread *caller_thread_;
- const std::string filter_;
-};
-
-// DBusMonitor is a class for DBus signal monitoring.
-//
-// The caller-thread calls AddFilter() first to add the signals that it wants to
-// monitor and then calls StartMonitoring() to start the monitoring.
-// This will create a worker-thread which listens on DBus connection and sends
-// DBus signals back through the callback.
-// The worker-thread will be running forever until either StopMonitoring() is
-// called from the caller-thread or the worker-thread hit some error.
-//
-// Programming model:
-// 1. Caller-thread: Creates an object of DBusMonitor.
-// 2. Caller-thread: Calls DBusMonitor::AddFilter() one or several times.
-// 3. Caller-thread: StartMonitoring().
-// ...
-// 4. Worker-thread: DBus signal recieved. Post a message to caller-thread.
-// 5. Caller-thread: DBusFilterBase::ProcessSignal() is invoked.
-// ...
-// 6. Caller-thread: StopMonitoring().
-//
-// Assumption:
-// AddFilter(), StartMonitoring(), and StopMonitoring() methods are called by
-// a single thread. Hence, there is no need to make them thread safe.
-class DBusMonitor {
- public:
- // Status of DBus monitoring.
- enum DBusMonitorStatus {
- DMS_NOT_INITIALIZED, // Not initialized.
- DMS_INITIALIZING, // Initializing the monitoring thread.
- DMS_RUNNING, // Monitoring.
- DMS_STOPPED, // Not monitoring. Stopped normally.
- DMS_FAILED, // Not monitoring. Failed.
- };
-
- // Returns the DBus-Glib symbol table.
- // We should only use this function to access DBus-Glib symbols.
- static LibDBusGlibSymbolTable *GetDBusGlibSymbolTable();
-
- // Creates an instance of DBusMonitor.
- static DBusMonitor *Create(DBusBusType type);
- ~DBusMonitor();
-
- // Adds a filter to DBusMonitor.
- bool AddFilter(DBusSigFilter *filter);
-
- // Starts DBus message monitoring.
- bool StartMonitoring();
-
- // Stops DBus message monitoring.
- bool StopMonitoring();
-
- // Gets the status of DBus monitoring.
- DBusMonitorStatus GetStatus();
-
- private:
- // Forward declaration. Defined in the .cc file.
- class DBusMonitoringThread;
-
- explicit DBusMonitor(DBusBusType type);
-
- // Updates status_ when monitoring status has changed.
- void OnMonitoringStatusChanged(DBusMonitorStatus status);
-
- DBusBusType type_;
- DBusMonitorStatus status_;
- DBusMonitoringThread *monitoring_thread_;
- std::vector<DBusSigFilter *> filter_list_;
-};
-
-} // namespace talk_base
-
-#endif // HAVE_DBUS_GLIB
-
-#endif // TALK_BASE_DBUS_H_
diff --git a/base/dbus_unittest.cc b/base/dbus_unittest.cc
deleted file mode 100644
index 94f01c0..0000000
--- a/base/dbus_unittest.cc
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_DBUS_GLIB
-
-#include "talk/base/dbus.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-#define SIG_NAME "NameAcquired"
-
-static const uint32 kTimeoutMs = 5000U;
-
-class DBusSigFilterTest : public DBusSigFilter {
- public:
- // DBusSigFilterTest listens on DBus service itself for "NameAcquired" signal.
- // This signal should be received when the application connects to DBus
- // service and gains ownership of a name.
- // http://dbus.freedesktop.org/doc/dbus-specification.html
- DBusSigFilterTest()
- : DBusSigFilter(GetFilter()),
- message_received_(false) {
- }
-
- bool MessageReceived() {
- return message_received_;
- }
-
- private:
- static std::string GetFilter() {
- return talk_base::DBusSigFilter::BuildFilterString("", "", SIG_NAME);
- }
-
- // Implement virtual method of DBusSigFilter. On caller thread.
- virtual void ProcessSignal(DBusMessage *message) {
- EXPECT_TRUE(message != NULL);
- message_received_ = true;
- }
-
- bool message_received_;
-};
-
-TEST(DBusMonitorTest, StartStopStartStop) {
- DBusSigFilterTest filter;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor;
- monitor.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- if (monitor) {
- EXPECT_TRUE(monitor->AddFilter(&filter));
-
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_NOT_INITIALIZED);
-
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor->GetStatus(), kTimeoutMs);
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
-
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor->GetStatus(), kTimeoutMs);
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_RUNNING);
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
- } else {
- LOG(LS_WARNING) << "DBus Monitor not started. Skipping test.";
- }
-}
-
-// DBusMonitorTest listens on DBus service itself for "NameAcquired" signal.
-// This signal should be received when the application connects to DBus
-// service and gains ownership of a name.
-// This test is to make sure that we capture the "NameAcquired" signal.
-TEST(DBusMonitorTest, ReceivedNameAcquiredSignal) {
- DBusSigFilterTest filter;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor;
- monitor.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- if (monitor) {
- EXPECT_TRUE(monitor->AddFilter(&filter));
-
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor->GetStatus(), kTimeoutMs);
- EXPECT_TRUE_WAIT(filter.MessageReceived(), kTimeoutMs);
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
- } else {
- LOG(LS_WARNING) << "DBus Monitor not started. Skipping test.";
- }
-}
-
-TEST(DBusMonitorTest, ConcurrentMonitors) {
- DBusSigFilterTest filter1;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor1;
- monitor1.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- if (monitor1) {
- EXPECT_TRUE(monitor1->AddFilter(&filter1));
- DBusSigFilterTest filter2;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor2;
- monitor2.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- EXPECT_TRUE(monitor2->AddFilter(&filter2));
-
- EXPECT_TRUE(monitor1->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor1->GetStatus(), kTimeoutMs);
- EXPECT_TRUE(monitor2->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor2->GetStatus(), kTimeoutMs);
-
- EXPECT_TRUE_WAIT(filter2.MessageReceived(), kTimeoutMs);
- EXPECT_TRUE(monitor2->StopMonitoring());
- EXPECT_EQ(monitor2->GetStatus(), DBusMonitor::DMS_STOPPED);
-
- EXPECT_TRUE_WAIT(filter1.MessageReceived(), kTimeoutMs);
- EXPECT_TRUE(monitor1->StopMonitoring());
- EXPECT_EQ(monitor1->GetStatus(), DBusMonitor::DMS_STOPPED);
- } else {
- LOG(LS_WARNING) << "DBus Monitor not started. Skipping test.";
- }
-}
-
-TEST(DBusMonitorTest, ConcurrentFilters) {
- DBusSigFilterTest filter1;
- DBusSigFilterTest filter2;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor;
- monitor.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- if (monitor) {
- EXPECT_TRUE(monitor->AddFilter(&filter1));
- EXPECT_TRUE(monitor->AddFilter(&filter2));
-
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor->GetStatus(), kTimeoutMs);
-
- EXPECT_TRUE_WAIT(filter1.MessageReceived(), kTimeoutMs);
- EXPECT_TRUE_WAIT(filter2.MessageReceived(), kTimeoutMs);
-
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
- } else {
- LOG(LS_WARNING) << "DBus Monitor not started. Skipping test.";
- }
-}
-
-TEST(DBusMonitorTest, NoAddFilterIfRunning) {
- DBusSigFilterTest filter1;
- DBusSigFilterTest filter2;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor;
- monitor.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- if (monitor) {
- EXPECT_TRUE(monitor->AddFilter(&filter1));
-
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor->GetStatus(), kTimeoutMs);
- EXPECT_FALSE(monitor->AddFilter(&filter2));
-
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
- } else {
- LOG(LS_WARNING) << "DBus Monitor not started. Skipping test.";
- }
-}
-
-TEST(DBusMonitorTest, AddFilterAfterStop) {
- DBusSigFilterTest filter1;
- DBusSigFilterTest filter2;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor;
- monitor.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- if (monitor) {
- EXPECT_TRUE(monitor->AddFilter(&filter1));
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor->GetStatus(), kTimeoutMs);
- EXPECT_TRUE_WAIT(filter1.MessageReceived(), kTimeoutMs);
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
-
- EXPECT_TRUE(monitor->AddFilter(&filter2));
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_EQ_WAIT(DBusMonitor::DMS_RUNNING, monitor->GetStatus(), kTimeoutMs);
- EXPECT_TRUE_WAIT(filter1.MessageReceived(), kTimeoutMs);
- EXPECT_TRUE_WAIT(filter2.MessageReceived(), kTimeoutMs);
- EXPECT_TRUE(monitor->StopMonitoring());
- EXPECT_EQ(monitor->GetStatus(), DBusMonitor::DMS_STOPPED);
- } else {
- LOG(LS_WARNING) << "DBus Monitor not started. Skipping test.";
- }
-}
-
-TEST(DBusMonitorTest, StopRightAfterStart) {
- DBusSigFilterTest filter;
- talk_base::scoped_ptr<talk_base::DBusMonitor> monitor;
- monitor.reset(talk_base::DBusMonitor::Create(DBUS_BUS_SYSTEM));
- if (monitor) {
- EXPECT_TRUE(monitor->AddFilter(&filter));
-
- EXPECT_TRUE(monitor->StartMonitoring());
- EXPECT_TRUE(monitor->StopMonitoring());
-
- // Stop the monitoring thread right after it had been started.
- // If the monitoring thread got a chance to receive a DBus signal, it would
- // post a message to the main thread and signal the main thread wakeup.
- // This message will be cleaned out automatically when the filter get
- // destructed. Here we also consume the wakeup signal (if there is one) so
- // that the testing (main) thread is reset to a clean state.
- talk_base::Thread::Current()->ProcessMessages(1);
- } else {
- LOG(LS_WARNING) << "DBus Monitor not started.";
- }
-}
-
-TEST(DBusSigFilter, BuildFilterString) {
- EXPECT_EQ(DBusSigFilter::BuildFilterString("", "", ""),
- (DBUS_TYPE "='" DBUS_SIGNAL "'"));
- EXPECT_EQ(DBusSigFilter::BuildFilterString("p", "", ""),
- (DBUS_TYPE "='" DBUS_SIGNAL "'," DBUS_PATH "='p'"));
- EXPECT_EQ(DBusSigFilter::BuildFilterString("p","i", ""),
- (DBUS_TYPE "='" DBUS_SIGNAL "'," DBUS_PATH "='p',"
- DBUS_INTERFACE "='i'"));
- EXPECT_EQ(DBusSigFilter::BuildFilterString("p","i","m"),
- (DBUS_TYPE "='" DBUS_SIGNAL "'," DBUS_PATH "='p',"
- DBUS_INTERFACE "='i'," DBUS_MEMBER "='m'"));
-}
-
-} // namespace talk_base
-
-#endif // HAVE_DBUS_GLIB
diff --git a/base/diskcache.cc b/base/diskcache.cc
deleted file mode 100644
index afaf9d2..0000000
--- a/base/diskcache.cc
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <time.h>
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif
-
-#include "talk/base/common.h"
-#include "talk/base/diskcache.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-
-#ifdef _DEBUG
-#define TRANSPARENT_CACHE_NAMES 1
-#else // !_DEBUG
-#define TRANSPARENT_CACHE_NAMES 0
-#endif // !_DEBUG
-
-namespace talk_base {
-
-class DiskCache;
-
-///////////////////////////////////////////////////////////////////////////////
-// DiskCacheAdapter
-///////////////////////////////////////////////////////////////////////////////
-
-class DiskCacheAdapter : public StreamAdapterInterface {
-public:
- DiskCacheAdapter(const DiskCache* cache, const std::string& id, size_t index,
- StreamInterface* stream)
- : StreamAdapterInterface(stream), cache_(cache), id_(id), index_(index)
- { }
- virtual ~DiskCacheAdapter() {
- Close();
- cache_->ReleaseResource(id_, index_);
- }
-
-private:
- const DiskCache* cache_;
- std::string id_;
- size_t index_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// DiskCache
-///////////////////////////////////////////////////////////////////////////////
-
-DiskCache::DiskCache() : max_cache_(0), total_size_(0), total_accessors_(0) {
-}
-
-DiskCache::~DiskCache() {
- ASSERT(0 == total_accessors_);
-}
-
-bool DiskCache::Initialize(const std::string& folder, size_t size) {
- if (!folder_.empty() || !Filesystem::CreateFolder(folder))
- return false;
-
- folder_ = folder;
- max_cache_ = size;
- ASSERT(0 == total_size_);
-
- if (!InitializeEntries())
- return false;
-
- return CheckLimit();
-}
-
-bool DiskCache::Purge() {
- if (folder_.empty())
- return false;
-
- if (total_accessors_ > 0) {
- LOG_F(LS_WARNING) << "Cache files open";
- return false;
- }
-
- if (!PurgeFiles())
- return false;
-
- map_.clear();
- return true;
-}
-
-bool DiskCache::LockResource(const std::string& id) {
- Entry* entry = GetOrCreateEntry(id, true);
- if (LS_LOCKED == entry->lock_state)
- return false;
- if ((LS_UNLOCKED == entry->lock_state) && (entry->accessors > 0))
- return false;
- if ((total_size_ > max_cache_) && !CheckLimit()) {
- LOG_F(LS_WARNING) << "Cache overfull";
- return false;
- }
- entry->lock_state = LS_LOCKED;
- return true;
-}
-
-StreamInterface* DiskCache::WriteResource(const std::string& id, size_t index) {
- Entry* entry = GetOrCreateEntry(id, false);
- if (LS_LOCKED != entry->lock_state)
- return NULL;
-
- size_t previous_size = 0;
- std::string filename(IdToFilename(id, index));
- FileStream::GetSize(filename, &previous_size);
- ASSERT(previous_size <= entry->size);
- if (previous_size > entry->size) {
- previous_size = entry->size;
- }
-
- scoped_ptr<FileStream> file(new FileStream);
- if (!file->Open(filename, "wb", NULL)) {
- LOG_F(LS_ERROR) << "Couldn't create cache file";
- return NULL;
- }
-
- entry->streams = stdmax(entry->streams, index + 1);
- entry->size -= previous_size;
- total_size_ -= previous_size;
-
- entry->accessors += 1;
- total_accessors_ += 1;
- return new DiskCacheAdapter(this, id, index, file.release());
-}
-
-bool DiskCache::UnlockResource(const std::string& id) {
- Entry* entry = GetOrCreateEntry(id, false);
- if (LS_LOCKED != entry->lock_state)
- return false;
-
- if (entry->accessors > 0) {
- entry->lock_state = LS_UNLOCKING;
- } else {
- entry->lock_state = LS_UNLOCKED;
- entry->last_modified = time(0);
- CheckLimit();
- }
- return true;
-}
-
-StreamInterface* DiskCache::ReadResource(const std::string& id,
- size_t index) const {
- const Entry* entry = GetEntry(id);
- if (LS_UNLOCKED != entry->lock_state)
- return NULL;
- if (index >= entry->streams)
- return NULL;
-
- scoped_ptr<FileStream> file(new FileStream);
- if (!file->Open(IdToFilename(id, index), "rb", NULL))
- return NULL;
-
- entry->accessors += 1;
- total_accessors_ += 1;
- return new DiskCacheAdapter(this, id, index, file.release());
-}
-
-bool DiskCache::HasResource(const std::string& id) const {
- const Entry* entry = GetEntry(id);
- return (NULL != entry) && (entry->streams > 0);
-}
-
-bool DiskCache::HasResourceStream(const std::string& id, size_t index) const {
- const Entry* entry = GetEntry(id);
- if ((NULL == entry) || (index >= entry->streams))
- return false;
-
- std::string filename = IdToFilename(id, index);
-
- return FileExists(filename);
-}
-
-bool DiskCache::DeleteResource(const std::string& id) {
- Entry* entry = GetOrCreateEntry(id, false);
- if (!entry)
- return true;
-
- if ((LS_UNLOCKED != entry->lock_state) || (entry->accessors > 0))
- return false;
-
- bool success = true;
- for (size_t index = 0; index < entry->streams; ++index) {
- std::string filename = IdToFilename(id, index);
-
- if (!FileExists(filename))
- continue;
-
- if (!DeleteFile(filename)) {
- LOG_F(LS_ERROR) << "Couldn't remove cache file: " << filename;
- success = false;
- }
- }
-
- total_size_ -= entry->size;
- map_.erase(id);
- return success;
-}
-
-bool DiskCache::CheckLimit() {
-#ifdef _DEBUG
- // Temporary check to make sure everything is working correctly.
- size_t cache_size = 0;
- for (EntryMap::iterator it = map_.begin(); it != map_.end(); ++it) {
- cache_size += it->second.size;
- }
- ASSERT(cache_size == total_size_);
-#endif // _DEBUG
-
- // TODO: Replace this with a non-brain-dead algorithm for clearing out the
- // oldest resources... something that isn't O(n^2)
- while (total_size_ > max_cache_) {
- EntryMap::iterator oldest = map_.end();
- for (EntryMap::iterator it = map_.begin(); it != map_.end(); ++it) {
- if ((LS_UNLOCKED != it->second.lock_state) || (it->second.accessors > 0))
- continue;
- oldest = it;
- break;
- }
- if (oldest == map_.end()) {
- LOG_F(LS_WARNING) << "All resources are locked!";
- return false;
- }
- for (EntryMap::iterator it = oldest++; it != map_.end(); ++it) {
- if (it->second.last_modified < oldest->second.last_modified) {
- oldest = it;
- }
- }
- if (!DeleteResource(oldest->first)) {
- LOG_F(LS_ERROR) << "Couldn't delete from cache!";
- return false;
- }
- }
- return true;
-}
-
-std::string DiskCache::IdToFilename(const std::string& id, size_t index) const {
-#ifdef TRANSPARENT_CACHE_NAMES
- // This escapes colons and other filesystem characters, so the user can't open
- // special devices (like "COM1:"), or access other directories.
- size_t buffer_size = id.length()*3 + 1;
- char* buffer = new char[buffer_size];
- encode(buffer, buffer_size, id.data(), id.length(),
- unsafe_filename_characters(), '%');
- // TODO: ASSERT(strlen(buffer) < FileSystem::MaxBasenameLength());
-#else // !TRANSPARENT_CACHE_NAMES
- // We might want to just use a hash of the filename at some point, both for
- // obfuscation, and to avoid both filename length and escaping issues.
- ASSERT(false);
-#endif // !TRANSPARENT_CACHE_NAMES
-
- char extension[32];
- sprintfn(extension, ARRAY_SIZE(extension), ".%u", index);
-
- Pathname pathname;
- pathname.SetFolder(folder_);
- pathname.SetBasename(buffer);
- pathname.SetExtension(extension);
-
-#ifdef TRANSPARENT_CACHE_NAMES
- delete [] buffer;
-#endif // TRANSPARENT_CACHE_NAMES
-
- return pathname.pathname();
-}
-
-bool DiskCache::FilenameToId(const std::string& filename, std::string* id,
- size_t* index) const {
- Pathname pathname(filename);
- unsigned tempdex;
- if (1 != sscanf(pathname.extension().c_str(), ".%u", &tempdex))
- return false;
-
- *index = static_cast<size_t>(tempdex);
-
- size_t buffer_size = pathname.basename().length() + 1;
- char* buffer = new char[buffer_size];
- decode(buffer, buffer_size, pathname.basename().data(),
- pathname.basename().length(), '%');
- id->assign(buffer);
- delete [] buffer;
- return true;
-}
-
-DiskCache::Entry* DiskCache::GetOrCreateEntry(const std::string& id,
- bool create) {
- EntryMap::iterator it = map_.find(id);
- if (it != map_.end())
- return &it->second;
- if (!create)
- return NULL;
- Entry e;
- e.lock_state = LS_UNLOCKED;
- e.accessors = 0;
- e.size = 0;
- e.streams = 0;
- e.last_modified = time(0);
- it = map_.insert(EntryMap::value_type(id, e)).first;
- return &it->second;
-}
-
-void DiskCache::ReleaseResource(const std::string& id, size_t index) const {
- const Entry* entry = GetEntry(id);
- if (!entry) {
- LOG_F(LS_WARNING) << "Missing cache entry";
- ASSERT(false);
- return;
- }
-
- entry->accessors -= 1;
- total_accessors_ -= 1;
-
- if (LS_UNLOCKED != entry->lock_state) {
- // This is safe, because locked resources only issue WriteResource, which
- // is non-const. Think about a better way to handle it.
- DiskCache* this2 = const_cast<DiskCache*>(this);
- Entry* entry2 = this2->GetOrCreateEntry(id, false);
-
- size_t new_size = 0;
- std::string filename(IdToFilename(id, index));
- FileStream::GetSize(filename, &new_size);
- entry2->size += new_size;
- this2->total_size_ += new_size;
-
- if ((LS_UNLOCKING == entry->lock_state) && (0 == entry->accessors)) {
- entry2->last_modified = time(0);
- entry2->lock_state = LS_UNLOCKED;
- this2->CheckLimit();
- }
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/diskcache.h b/base/diskcache.h
deleted file mode 100644
index c5a1dfc..0000000
--- a/base/diskcache.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_DISKCACHE_H__
-#define TALK_BASE_DISKCACHE_H__
-
-#include <map>
-#include <string>
-
-#ifdef WIN32
-#undef UnlockResource
-#endif // WIN32
-
-namespace talk_base {
-
-class StreamInterface;
-
-///////////////////////////////////////////////////////////////////////////////
-// DiskCache - An LRU cache of streams, stored on disk.
-//
-// Streams are identified by a unique resource id. Multiple streams can be
-// associated with each resource id, distinguished by an index. When old
-// resources are flushed from the cache, all streams associated with those
-// resources are removed together.
-// DiskCache is designed to persist across executions of the program. It is
-// safe for use from an arbitrary number of users on a single thread, but not
-// from multiple threads or other processes.
-///////////////////////////////////////////////////////////////////////////////
-
-class DiskCache {
-public:
- DiskCache();
- virtual ~DiskCache();
-
- bool Initialize(const std::string& folder, size_t size);
- bool Purge();
-
- bool LockResource(const std::string& id);
- StreamInterface* WriteResource(const std::string& id, size_t index);
- bool UnlockResource(const std::string& id);
-
- StreamInterface* ReadResource(const std::string& id, size_t index) const;
-
- bool HasResource(const std::string& id) const;
- bool HasResourceStream(const std::string& id, size_t index) const;
- bool DeleteResource(const std::string& id);
-
- protected:
- virtual bool InitializeEntries() = 0;
- virtual bool PurgeFiles() = 0;
-
- virtual bool FileExists(const std::string& filename) const = 0;
- virtual bool DeleteFile(const std::string& filename) const = 0;
-
- enum LockState { LS_UNLOCKED, LS_LOCKED, LS_UNLOCKING };
- struct Entry {
- LockState lock_state;
- mutable size_t accessors;
- size_t size;
- size_t streams;
- time_t last_modified;
- };
- typedef std::map<std::string, Entry> EntryMap;
- friend class DiskCacheAdapter;
-
- bool CheckLimit();
-
- std::string IdToFilename(const std::string& id, size_t index) const;
- bool FilenameToId(const std::string& filename, std::string* id,
- size_t* index) const;
-
- const Entry* GetEntry(const std::string& id) const {
- return const_cast<DiskCache*>(this)->GetOrCreateEntry(id, false);
- }
- Entry* GetOrCreateEntry(const std::string& id, bool create);
-
- void ReleaseResource(const std::string& id, size_t index) const;
-
- std::string folder_;
- size_t max_cache_, total_size_;
- EntryMap map_;
- mutable size_t total_accessors_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// CacheLock - Automatically manage locking and unlocking, with optional
-// rollback semantics
-///////////////////////////////////////////////////////////////////////////////
-
-class CacheLock {
-public:
- CacheLock(DiskCache* cache, const std::string& id, bool rollback = false)
- : cache_(cache), id_(id), rollback_(rollback)
- {
- locked_ = cache_->LockResource(id_);
- }
- ~CacheLock() {
- if (locked_) {
- cache_->UnlockResource(id_);
- if (rollback_) {
- cache_->DeleteResource(id_);
- }
- }
- }
- bool IsLocked() const { return locked_; }
- void Commit() { rollback_ = false; }
-
-private:
- DiskCache* cache_;
- std::string id_;
- bool rollback_, locked_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_DISKCACHE_H__
diff --git a/base/diskcache_win32.cc b/base/diskcache_win32.cc
deleted file mode 100644
index b49ed81..0000000
--- a/base/diskcache_win32.cc
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/win32.h"
-#include <shellapi.h>
-#include <shlobj.h>
-#include <tchar.h>
-
-#include <time.h>
-
-#include "talk/base/common.h"
-#include "talk/base/diskcache.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-
-#include "talk/base/diskcache_win32.h"
-
-namespace talk_base {
-
-bool DiskCacheWin32::InitializeEntries() {
- // Note: We could store the cache information in a separate file, for faster
- // initialization. Figuring it out empirically works, too.
-
- std::wstring path16 = ToUtf16(folder_);
- path16.append(1, '*');
-
- WIN32_FIND_DATA find_data;
- HANDLE find_handle = FindFirstFile(path16.c_str(), &find_data);
- if (find_handle != INVALID_HANDLE_VALUE) {
- do {
- size_t index;
- std::string id;
- if (!FilenameToId(ToUtf8(find_data.cFileName), &id, &index))
- continue;
-
- Entry* entry = GetOrCreateEntry(id, true);
- entry->size += find_data.nFileSizeLow;
- total_size_ += find_data.nFileSizeLow;
- entry->streams = _max(entry->streams, index + 1);
- FileTimeToUnixTime(find_data.ftLastWriteTime, &entry->last_modified);
-
- } while (FindNextFile(find_handle, &find_data));
-
- FindClose(find_handle);
- }
-
- return true;
-}
-
-bool DiskCacheWin32::PurgeFiles() {
- std::wstring path16 = ToUtf16(folder_);
- path16.append(1, '*');
- path16.append(1, '\0');
-
- SHFILEOPSTRUCT file_op = { 0 };
- file_op.wFunc = FO_DELETE;
- file_op.pFrom = path16.c_str();
- file_op.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
- | FOF_NORECURSION | FOF_FILESONLY;
- if (0 != SHFileOperation(&file_op)) {
- LOG_F(LS_ERROR) << "Couldn't delete cache files";
- return false;
- }
-
- return true;
-}
-
-bool DiskCacheWin32::FileExists(const std::string& filename) const {
- DWORD result = ::GetFileAttributes(ToUtf16(filename).c_str());
- return (INVALID_FILE_ATTRIBUTES != result);
-}
-
-bool DiskCacheWin32::DeleteFile(const std::string& filename) const {
- return ::DeleteFile(ToUtf16(filename).c_str()) != 0;
-}
-
-}
diff --git a/base/diskcache_win32.h b/base/diskcache_win32.h
deleted file mode 100644
index a5e8de5..0000000
--- a/base/diskcache_win32.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_DISKCACHEWIN32_H__
-#define TALK_BASE_DISKCACHEWIN32_H__
-
-#include "talk/base/diskcache.h"
-
-namespace talk_base {
-
-class DiskCacheWin32 : public DiskCache {
- protected:
- virtual bool InitializeEntries();
- virtual bool PurgeFiles();
-
- virtual bool FileExists(const std::string& filename) const;
- virtual bool DeleteFile(const std::string& filename) const;
-};
-
-}
-
-#endif // TALK_BASE_DISKCACHEWIN32_H__
diff --git a/base/dscp.h b/base/dscp.h
deleted file mode 100644
index c71ee3e..0000000
--- a/base/dscp.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * libjingle
- * Copyright 2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_DSCP_H_
-#define TALK_BASE_DSCP_H_
-
-namespace talk_base {
-// Differentiated Services Code Point.
-// See http://tools.ietf.org/html/rfc2474 for details.
-enum DiffServCodePoint {
- DSCP_NO_CHANGE = -1,
- DSCP_DEFAULT = 0, // Same as DSCP_CS0
- DSCP_CS0 = 0, // The default
- DSCP_CS1 = 8, // Bulk/background traffic
- DSCP_AF11 = 10,
- DSCP_AF12 = 12,
- DSCP_AF13 = 14,
- DSCP_CS2 = 16,
- DSCP_AF21 = 18,
- DSCP_AF22 = 20,
- DSCP_AF23 = 22,
- DSCP_CS3 = 24,
- DSCP_AF31 = 26,
- DSCP_AF32 = 28,
- DSCP_AF33 = 30,
- DSCP_CS4 = 32,
- DSCP_AF41 = 34, // Video
- DSCP_AF42 = 36, // Video
- DSCP_AF43 = 38, // Video
- DSCP_CS5 = 40, // Video
- DSCP_EF = 46, // Voice
- DSCP_CS6 = 48, // Voice
- DSCP_CS7 = 56, // Control messages
-};
-
-} // namespace talk_base
-
- #endif // TALK_BASE_DSCP_H_
diff --git a/base/event.cc b/base/event.cc
deleted file mode 100644
index 410c658..0000000
--- a/base/event.cc
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/event.h"
-
-#if defined(WIN32)
-#include <windows.h>
-#elif defined(POSIX)
-#include <pthread.h>
-#include <sys/time.h>
-#include <time.h>
-#else
-#error "Must define either WIN32 or POSIX."
-#endif
-
-namespace talk_base {
-
-#if defined(WIN32)
-
-Event::Event(bool manual_reset, bool initially_signaled)
- : is_manual_reset_(manual_reset),
- is_initially_signaled_(initially_signaled) {
- event_handle_ = ::CreateEvent(NULL, // Security attributes.
- is_manual_reset_,
- is_initially_signaled_,
- NULL); // Name.
- ASSERT(event_handle_ != NULL);
-}
-
-Event::~Event() {
- CloseHandle(event_handle_);
-}
-
-void Event::Set() {
- SetEvent(event_handle_);
-}
-
-void Event::Reset() {
- ResetEvent(event_handle_);
-}
-
-bool Event::Wait(int cms) {
- DWORD ms = (cms == kForever)? INFINITE : cms;
- return (WaitForSingleObject(event_handle_, ms) == WAIT_OBJECT_0);
-}
-
-#elif defined(POSIX)
-
-Event::Event(bool manual_reset, bool initially_signaled)
- : is_manual_reset_(manual_reset),
- event_status_(initially_signaled) {
- VERIFY(pthread_mutex_init(&event_mutex_, NULL) == 0);
- VERIFY(pthread_cond_init(&event_cond_, NULL) == 0);
-}
-
-Event::~Event() {
- pthread_mutex_destroy(&event_mutex_);
- pthread_cond_destroy(&event_cond_);
-}
-
-void Event::Set() {
- pthread_mutex_lock(&event_mutex_);
- event_status_ = true;
- pthread_cond_broadcast(&event_cond_);
- pthread_mutex_unlock(&event_mutex_);
-}
-
-void Event::Reset() {
- pthread_mutex_lock(&event_mutex_);
- event_status_ = false;
- pthread_mutex_unlock(&event_mutex_);
-}
-
-bool Event::Wait(int cms) {
- pthread_mutex_lock(&event_mutex_);
- int error = 0;
-
- if (cms != kForever) {
- // Converting from seconds and microseconds (1e-6) plus
- // milliseconds (1e-3) to seconds and nanoseconds (1e-9).
-
- struct timespec ts;
-#if HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
- // Use relative time version, which tends to be more efficient for
- // pthread implementations where provided (like on Android).
- ts.tv_sec = cms / 1000;
- ts.tv_nsec = (cms % 1000) * 1000000;
-#else
- struct timeval tv;
- gettimeofday(&tv, NULL);
-
- ts.tv_sec = tv.tv_sec + (cms / 1000);
- ts.tv_nsec = tv.tv_usec * 1000 + (cms % 1000) * 1000000;
-
- // Handle overflow.
- if (ts.tv_nsec >= 1000000000) {
- ts.tv_sec++;
- ts.tv_nsec -= 1000000000;
- }
-#endif
-
- while (!event_status_ && error == 0) {
-#if HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
- error = pthread_cond_timedwait_relative_np(
- &event_cond_, &event_mutex_, &ts);
-#else
- error = pthread_cond_timedwait(&event_cond_, &event_mutex_, &ts);
-#endif
- }
- } else {
- while (!event_status_ && error == 0)
- error = pthread_cond_wait(&event_cond_, &event_mutex_);
- }
-
- // NOTE(liulk): Exactly one thread will auto-reset this event. All
- // the other threads will think it's unsignaled. This seems to be
- // consistent with auto-reset events in WIN32.
- if (error == 0 && !is_manual_reset_)
- event_status_ = false;
-
- pthread_mutex_unlock(&event_mutex_);
-
- return (error == 0);
-}
-
-#endif
-
-} // namespace talk_base
diff --git a/base/event.h b/base/event.h
deleted file mode 100644
index 72edae8..0000000
--- a/base/event.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_EVENT_H__
-#define TALK_BASE_EVENT_H__
-
-#if defined(WIN32)
-#include "talk/base/win32.h" // NOLINT: consider this a system header.
-#elif defined(POSIX)
-#include <pthread.h>
-#else
-#error "Must define either WIN32 or POSIX."
-#endif
-
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-class Event {
- public:
- Event(bool manual_reset, bool initially_signaled);
- ~Event();
-
- void Set();
- void Reset();
- bool Wait(int cms);
-
- private:
- bool is_manual_reset_;
-
-#if defined(WIN32)
- bool is_initially_signaled_;
- HANDLE event_handle_;
-#elif defined(POSIX)
- bool event_status_;
- pthread_mutex_t event_mutex_;
- pthread_cond_t event_cond_;
-#endif
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_EVENT_H__
diff --git a/base/event_unittest.cc b/base/event_unittest.cc
deleted file mode 100644
index 5a3c1c6..0000000
--- a/base/event_unittest.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/event.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-TEST(EventTest, InitiallySignaled) {
- Event event(false, true);
- ASSERT_TRUE(event.Wait(0));
-}
-
-TEST(EventTest, ManualReset) {
- Event event(true, false);
- ASSERT_FALSE(event.Wait(0));
-
- event.Set();
- ASSERT_TRUE(event.Wait(0));
- ASSERT_TRUE(event.Wait(0));
-
- event.Reset();
- ASSERT_FALSE(event.Wait(0));
-}
-
-TEST(EventTest, AutoReset) {
- Event event(false, false);
- ASSERT_FALSE(event.Wait(0));
-
- event.Set();
- ASSERT_TRUE(event.Wait(0));
- ASSERT_FALSE(event.Wait(0));
-}
-
-} // namespace talk_base
diff --git a/base/fakecpumonitor.h b/base/fakecpumonitor.h
deleted file mode 100644
index 8b8e36d..0000000
--- a/base/fakecpumonitor.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * libjingle
- * Copyright 2013 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_FAKECPUMONITOR_H_
-#define TALK_BASE_FAKECPUMONITOR_H_
-
-#include "talk/base/cpumonitor.h"
-
-namespace talk_base {
-
-class FakeCpuMonitor : public talk_base::CpuMonitor {
- public:
- explicit FakeCpuMonitor(Thread* thread)
- : CpuMonitor(thread) {
- }
- ~FakeCpuMonitor() {
- }
-
- virtual void OnMessage(talk_base::Message* msg) {
- }
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_FAKECPUMONITOR_H_
diff --git a/base/fakenetwork.h b/base/fakenetwork.h
deleted file mode 100644
index 3bdc97f..0000000
--- a/base/fakenetwork.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * libjingle
- * Copyright 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_FAKENETWORK_H_
-#define TALK_BASE_FAKENETWORK_H_
-
-#include <string>
-#include <vector>
-
-#include "talk/base/network.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-const int kFakeIPv4NetworkPrefixLength = 24;
-const int kFakeIPv6NetworkPrefixLength = 64;
-
-// Fake network manager that allows us to manually specify the IPs to use.
-class FakeNetworkManager : public NetworkManagerBase,
- public MessageHandler {
- public:
- FakeNetworkManager()
- : thread_(Thread::Current()),
- next_index_(0),
- started_(false),
- sent_first_update_(false) {
- }
-
- typedef std::vector<SocketAddress> IfaceList;
-
- void AddInterface(const SocketAddress& iface) {
- // ensure a unique name for the interface
- SocketAddress address("test" + talk_base::ToString(next_index_++), 0);
- address.SetResolvedIP(iface.ipaddr());
- ifaces_.push_back(address);
- DoUpdateNetworks();
- }
-
- void RemoveInterface(const SocketAddress& iface) {
- for (IfaceList::iterator it = ifaces_.begin();
- it != ifaces_.end(); ++it) {
- if (it->EqualIPs(iface)) {
- ifaces_.erase(it);
- break;
- }
- }
- DoUpdateNetworks();
- }
-
- virtual void StartUpdating() {
- if (started_) {
- if (sent_first_update_)
- SignalNetworksChanged();
- return;
- }
-
- started_ = true;
- sent_first_update_ = false;
- thread_->Post(this);
- }
-
- virtual void StopUpdating() {
- started_ = false;
- }
-
- // MessageHandler interface.
- virtual void OnMessage(Message* msg) {
- DoUpdateNetworks();
- }
-
- private:
- void DoUpdateNetworks() {
- if (!started_)
- return;
- std::vector<Network*> networks;
- for (IfaceList::iterator it = ifaces_.begin();
- it != ifaces_.end(); ++it) {
- int prefix_length = 0;
- if (it->ipaddr().family() == AF_INET) {
- prefix_length = kFakeIPv4NetworkPrefixLength;
- } else if (it->ipaddr().family() == AF_INET6) {
- prefix_length = kFakeIPv6NetworkPrefixLength;
- }
- IPAddress prefix = TruncateIP(it->ipaddr(), prefix_length);
- scoped_ptr<Network> net(new Network(it->hostname(),
- it->hostname(),
- prefix,
- prefix_length));
- net->AddIP(it->ipaddr());
- networks.push_back(net.release());
- }
- bool changed;
- MergeNetworkList(networks, &changed);
- if (changed || !sent_first_update_) {
- SignalNetworksChanged();
- sent_first_update_ = true;
- }
- }
-
- Thread* thread_;
- IfaceList ifaces_;
- int next_index_;
- bool started_;
- bool sent_first_update_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_FAKENETWORK_H_
diff --git a/base/fakesslidentity.h b/base/fakesslidentity.h
deleted file mode 100644
index fbe5e64..0000000
--- a/base/fakesslidentity.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, The Libjingle Authors.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_FAKESSLIDENTITY_H_
-#define TALK_BASE_FAKESSLIDENTITY_H_
-
-#include <algorithm>
-#include <vector>
-
-#include "talk/base/messagedigest.h"
-#include "talk/base/sslidentity.h"
-
-namespace talk_base {
-
-class FakeSSLCertificate : public talk_base::SSLCertificate {
- public:
- // SHA-1 is the default digest algorithm because it is available in all build
- // configurations used for unit testing.
- explicit FakeSSLCertificate(const std::string& data)
- : data_(data), digest_algorithm_(DIGEST_SHA_1) {}
- explicit FakeSSLCertificate(const std::vector<std::string>& certs)
- : data_(certs.front()), digest_algorithm_(DIGEST_SHA_1) {
- std::vector<std::string>::const_iterator it;
- // Skip certs[0].
- for (it = certs.begin() + 1; it != certs.end(); ++it) {
- certs_.push_back(FakeSSLCertificate(*it));
- }
- }
- virtual FakeSSLCertificate* GetReference() const {
- return new FakeSSLCertificate(*this);
- }
- virtual std::string ToPEMString() const {
- return data_;
- }
- virtual void ToDER(Buffer* der_buffer) const {
- std::string der_string;
- VERIFY(SSLIdentity::PemToDer(kPemTypeCertificate, data_, &der_string));
- der_buffer->SetData(der_string.c_str(), der_string.size());
- }
- void set_digest_algorithm(const std::string& algorithm) {
- digest_algorithm_ = algorithm;
- }
- virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const {
- *algorithm = digest_algorithm_;
- return true;
- }
- virtual bool ComputeDigest(const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length) const {
- *length = talk_base::ComputeDigest(algorithm, data_.c_str(), data_.size(),
- digest, size);
- return (*length != 0);
- }
- virtual bool GetChain(SSLCertChain** chain) const {
- if (certs_.empty())
- return false;
- std::vector<SSLCertificate*> new_certs(certs_.size());
- std::transform(certs_.begin(), certs_.end(), new_certs.begin(), DupCert);
- *chain = new SSLCertChain(new_certs);
- return true;
- }
-
- private:
- static FakeSSLCertificate* DupCert(FakeSSLCertificate cert) {
- return cert.GetReference();
- }
- std::string data_;
- std::vector<FakeSSLCertificate> certs_;
- std::string digest_algorithm_;
-};
-
-class FakeSSLIdentity : public talk_base::SSLIdentity {
- public:
- explicit FakeSSLIdentity(const std::string& data) : cert_(data) {}
- explicit FakeSSLIdentity(const FakeSSLCertificate& cert) : cert_(cert) {}
- virtual FakeSSLIdentity* GetReference() const {
- return new FakeSSLIdentity(*this);
- }
- virtual const FakeSSLCertificate& certificate() const { return cert_; }
- private:
- FakeSSLCertificate cert_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_FAKESSLIDENTITY_H_
diff --git a/base/faketaskrunner.h b/base/faketaskrunner.h
deleted file mode 100644
index 6b5b035..0000000
--- a/base/faketaskrunner.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// A fake TaskRunner for use in unit tests.
-
-#ifndef TALK_BASE_FAKETASKRUNNER_H_
-#define TALK_BASE_FAKETASKRUNNER_H_
-
-#include "talk/base/taskparent.h"
-#include "talk/base/taskrunner.h"
-
-namespace talk_base {
-
-class FakeTaskRunner : public TaskRunner {
- public:
- FakeTaskRunner() : current_time_(0) {}
- virtual ~FakeTaskRunner() {}
-
- virtual void WakeTasks() { RunTasks(); }
-
- virtual int64 CurrentTime() {
- // Implement if needed.
- return current_time_++;
- }
-
- int64 current_time_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_FAKETASKRUNNER_H_
diff --git a/base/filelock.cc b/base/filelock.cc
deleted file mode 100644
index 77a474a..0000000
--- a/base/filelock.cc
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/filelock.h"
-
-#include "talk/base/fileutils.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-FileLock::FileLock(const std::string& path, FileStream* file)
- : path_(path), file_(file) {
-}
-
-FileLock::~FileLock() {
- MaybeUnlock();
-}
-
-void FileLock::Unlock() {
- LOG_F(LS_INFO);
- MaybeUnlock();
-}
-
-void FileLock::MaybeUnlock() {
- if (file_) {
- LOG(LS_INFO) << "Unlocking:" << path_;
- file_->Close();
- Filesystem::DeleteFile(path_);
- file_.reset();
- }
-}
-
-FileLock* FileLock::TryLock(const std::string& path) {
- FileStream* stream = new FileStream();
- bool ok = false;
-#ifdef WIN32
- // Open and lock in a single operation.
- ok = stream->OpenShare(path, "a", _SH_DENYRW, NULL);
-#else // Linux and OSX
- ok = stream->Open(path, "a", NULL) && stream->TryLock();
-#endif
- if (ok) {
- return new FileLock(path, stream);
- } else {
- // Something failed, either we didn't succeed to open the
- // file or we failed to lock it. Anyway remove the heap
- // allocated object and then return NULL to indicate failure.
- delete stream;
- return NULL;
- }
-}
-
-} // namespace talk_base
diff --git a/base/filelock.h b/base/filelock.h
deleted file mode 100644
index a4936f5..0000000
--- a/base/filelock.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_FILELOCK_H_
-#define TALK_BASE_FILELOCK_H_
-
-#include <string>
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-class FileStream;
-
-// Implements a very simple cross process lock based on a file.
-// When Lock(...) is called we try to open/create the file in read/write
-// mode without any sharing. (Or locking it with flock(...) on Unix)
-// If the process crash the OS will make sure that the file descriptor
-// is released and another process can accuire the lock.
-// This doesn't work on ancient OSX/Linux versions if used on NFS.
-// (Nfs-client before: ~2.6 and Linux Kernel < 2.6.)
-class FileLock {
- public:
- virtual ~FileLock();
-
- // Attempts to lock the file. The caller owns the returned
- // lock object. Returns NULL if the file already was locked.
- static FileLock* TryLock(const std::string& path);
- void Unlock();
-
- protected:
- FileLock(const std::string& path, FileStream* file);
-
- private:
- void MaybeUnlock();
-
- std::string path_;
- scoped_ptr<FileStream> file_;
-
- DISALLOW_EVIL_CONSTRUCTORS(FileLock);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_FILELOCK_H_
diff --git a/base/filelock_unittest.cc b/base/filelock_unittest.cc
deleted file mode 100644
index e585f91..0000000
--- a/base/filelock_unittest.cc
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/event.h"
-#include "talk/base/filelock.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-const static std::string kLockFile = "TestLockFile";
-const static int kTimeoutMS = 5000;
-
-class FileLockTest : public testing::Test, public Runnable {
- public:
- FileLockTest() : done_(false, false), thread_lock_failed_(false) {
- }
-
- virtual void Run(Thread* t) {
- scoped_ptr<FileLock> lock(FileLock::TryLock(temp_file_.pathname()));
- // The lock is already owned by the main thread of
- // this test, therefore the TryLock(...) call should fail.
- thread_lock_failed_ = lock.get() == NULL;
- done_.Set();
- }
-
- protected:
- virtual void SetUp() {
- thread_lock_failed_ = false;
- Filesystem::GetAppTempFolder(&temp_dir_);
- temp_file_ = Pathname(temp_dir_.pathname(), kLockFile);
- }
-
- void LockOnThread() {
- locker_.Start(this);
- done_.Wait(kTimeoutMS);
- }
-
- Event done_;
- Thread locker_;
- bool thread_lock_failed_;
- Pathname temp_dir_;
- Pathname temp_file_;
-};
-
-TEST_F(FileLockTest, TestLockFileDeleted) {
- scoped_ptr<FileLock> lock(FileLock::TryLock(temp_file_.pathname()));
- EXPECT_TRUE(lock.get() != NULL);
- EXPECT_FALSE(Filesystem::IsAbsent(temp_file_.pathname()));
- lock->Unlock();
- EXPECT_TRUE(Filesystem::IsAbsent(temp_file_.pathname()));
-}
-
-TEST_F(FileLockTest, TestLock) {
- scoped_ptr<FileLock> lock(FileLock::TryLock(temp_file_.pathname()));
- EXPECT_TRUE(lock.get() != NULL);
-}
-
-TEST_F(FileLockTest, TestLockX2) {
- scoped_ptr<FileLock> lock1(FileLock::TryLock(temp_file_.pathname()));
- EXPECT_TRUE(lock1.get() != NULL);
-
- scoped_ptr<FileLock> lock2(FileLock::TryLock(temp_file_.pathname()));
- EXPECT_TRUE(lock2.get() == NULL);
-}
-
-TEST_F(FileLockTest, TestThreadedLock) {
- scoped_ptr<FileLock> lock(FileLock::TryLock(temp_file_.pathname()));
- EXPECT_TRUE(lock.get() != NULL);
-
- LockOnThread();
- EXPECT_TRUE(thread_lock_failed_);
-}
-
-} // namespace talk_base
diff --git a/base/fileutils.cc b/base/fileutils.cc
deleted file mode 100644
index 72797f3..0000000
--- a/base/fileutils.cc
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <assert.h>
-
-#ifdef WIN32
-// TODO(grunell): Remove io.h includes when Chromium has started
-// to use AEC in each source. http://crbug.com/264611.
-#include <io.h>
-#include "talk/base/win32.h"
-#endif
-
-#include "talk/base/pathutils.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/stream.h"
-
-#ifdef WIN32
-#include "talk/base/win32filesystem.h"
-#else
-#include "talk/base/unixfilesystem.h"
-#endif
-
-#ifndef WIN32
-#define MAX_PATH 260
-#endif
-
-namespace talk_base {
-
-//////////////////////////
-// Directory Iterator //
-//////////////////////////
-
-// A DirectoryIterator is created with a given directory. It originally points
-// to the first file in the directory, and can be advanecd with Next(). This
-// allows you to get information about each file.
-
- // Constructor
-DirectoryIterator::DirectoryIterator()
-#ifdef _WIN32
- : handle_(INVALID_HANDLE_VALUE) {
-#else
- : dir_(NULL), dirent_(NULL) {
-#endif
-}
-
- // Destructor
-DirectoryIterator::~DirectoryIterator() {
-#ifdef WIN32
- if (handle_ != INVALID_HANDLE_VALUE)
- ::FindClose(handle_);
-#else
- if (dir_)
- closedir(dir_);
-#endif
-}
-
- // Starts traversing a directory.
- // dir is the directory to traverse
- // returns true if the directory exists and is valid
-bool DirectoryIterator::Iterate(const Pathname &dir) {
- directory_ = dir.pathname();
-#ifdef WIN32
- if (handle_ != INVALID_HANDLE_VALUE)
- ::FindClose(handle_);
- std::string d = dir.pathname() + '*';
- handle_ = ::FindFirstFile(ToUtf16(d).c_str(), &data_);
- if (handle_ == INVALID_HANDLE_VALUE)
- return false;
-#else
- if (dir_ != NULL)
- closedir(dir_);
- dir_ = ::opendir(directory_.c_str());
- if (dir_ == NULL)
- return false;
- dirent_ = readdir(dir_);
- if (dirent_ == NULL)
- return false;
-
- if (::stat(std::string(directory_ + Name()).c_str(), &stat_) != 0)
- return false;
-#endif
- return true;
-}
-
- // Advances to the next file
- // returns true if there were more files in the directory.
-bool DirectoryIterator::Next() {
-#ifdef WIN32
- return ::FindNextFile(handle_, &data_) == TRUE;
-#else
- dirent_ = ::readdir(dir_);
- if (dirent_ == NULL)
- return false;
-
- return ::stat(std::string(directory_ + Name()).c_str(), &stat_) == 0;
-#endif
-}
-
- // returns true if the file currently pointed to is a directory
-bool DirectoryIterator::IsDirectory() const {
-#ifdef WIN32
- return (data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FALSE;
-#else
- return S_ISDIR(stat_.st_mode);
-#endif
-}
-
- // returns the name of the file currently pointed to
-std::string DirectoryIterator::Name() const {
-#ifdef WIN32
- return ToUtf8(data_.cFileName);
-#else
- assert(dirent_ != NULL);
- return dirent_->d_name;
-#endif
-}
-
- // returns the size of the file currently pointed to
-size_t DirectoryIterator::FileSize() const {
-#ifndef WIN32
- return stat_.st_size;
-#else
- return data_.nFileSizeLow;
-#endif
-}
-
- // returns the last modified time of this file
-time_t DirectoryIterator::FileModifyTime() const {
-#ifdef WIN32
- time_t val;
- FileTimeToUnixTime(data_.ftLastWriteTime, &val);
- return val;
-#else
- return stat_.st_mtime;
-#endif
-}
-
-FilesystemInterface* Filesystem::default_filesystem_ = NULL;
-
-FilesystemInterface *Filesystem::EnsureDefaultFilesystem() {
- if (!default_filesystem_) {
-#ifdef WIN32
- default_filesystem_ = new Win32Filesystem();
-#else
- default_filesystem_ = new UnixFilesystem();
-#endif
- }
- return default_filesystem_;
-}
-
-bool FilesystemInterface::CopyFolder(const Pathname &old_path,
- const Pathname &new_path) {
- bool success = true;
- VERIFY(IsFolder(old_path));
- Pathname new_dir;
- new_dir.SetFolder(new_path.pathname());
- Pathname old_dir;
- old_dir.SetFolder(old_path.pathname());
- if (!CreateFolder(new_dir))
- return false;
- DirectoryIterator *di = IterateDirectory();
- if (!di)
- return false;
- if (di->Iterate(old_dir.pathname())) {
- do {
- if (di->Name() == "." || di->Name() == "..")
- continue;
- Pathname source;
- Pathname dest;
- source.SetFolder(old_dir.pathname());
- dest.SetFolder(new_path.pathname());
- source.SetFilename(di->Name());
- dest.SetFilename(di->Name());
- if (!CopyFileOrFolder(source, dest))
- success = false;
- } while (di->Next());
- }
- delete di;
- return success;
-}
-
-bool FilesystemInterface::DeleteFolderContents(const Pathname &folder) {
- bool success = true;
- VERIFY(IsFolder(folder));
- DirectoryIterator *di = IterateDirectory();
- if (!di)
- return false;
- if (di->Iterate(folder)) {
- do {
- if (di->Name() == "." || di->Name() == "..")
- continue;
- Pathname subdir;
- subdir.SetFolder(folder.pathname());
- if (di->IsDirectory()) {
- subdir.AppendFolder(di->Name());
- if (!DeleteFolderAndContents(subdir)) {
- success = false;
- }
- } else {
- subdir.SetFilename(di->Name());
- if (!DeleteFile(subdir)) {
- success = false;
- }
- }
- } while (di->Next());
- }
- delete di;
- return success;
-}
-
-bool FilesystemInterface::CleanAppTempFolder() {
- Pathname path;
- if (!GetAppTempFolder(&path))
- return false;
- if (IsAbsent(path))
- return true;
- if (!IsTemporaryPath(path)) {
- ASSERT(false);
- return false;
- }
- return DeleteFolderContents(path);
-}
-
-Pathname Filesystem::GetCurrentDirectory() {
- return EnsureDefaultFilesystem()->GetCurrentDirectory();
-}
-
-bool CreateUniqueFile(Pathname& path, bool create_empty) {
- LOG(LS_INFO) << "Path " << path.pathname() << std::endl;
- // If no folder is supplied, use the temporary folder
- if (path.folder().empty()) {
- Pathname temporary_path;
- if (!Filesystem::GetTemporaryFolder(temporary_path, true, NULL)) {
- printf("Get temp failed\n");
- return false;
- }
- path.SetFolder(temporary_path.pathname());
- }
-
- // If no filename is supplied, use a temporary name
- if (path.filename().empty()) {
- std::string folder(path.folder());
- std::string filename = Filesystem::TempFilename(folder, "gt");
- path.SetPathname(filename);
- if (!create_empty) {
- Filesystem::DeleteFile(path.pathname());
- }
- return true;
- }
-
- // Otherwise, create a unique name based on the given filename
- // foo.txt -> foo-N.txt
- const std::string basename = path.basename();
- const size_t MAX_VERSION = 100;
- size_t version = 0;
- while (version < MAX_VERSION) {
- std::string pathname = path.pathname();
-
- if (!Filesystem::IsFile(pathname)) {
- if (create_empty) {
- FileStream* fs = Filesystem::OpenFile(pathname, "w");
- delete fs;
- }
- return true;
- }
- version += 1;
- char version_base[MAX_PATH];
- sprintfn(version_base, ARRAY_SIZE(version_base), "%s-%u",
- basename.c_str(), version);
- path.SetBasename(version_base);
- }
- return true;
-}
-
-// Taken from Chromium's base/platform_file_*.cc.
-// TODO(grunell): Remove when Chromium has started to use AEC in each source.
-// http://crbug.com/264611.
-FILE* FdopenPlatformFileForWriting(PlatformFile file) {
-#if defined(WIN32)
- if (file == kInvalidPlatformFileValue)
- return NULL;
- int fd = _open_osfhandle(reinterpret_cast<intptr_t>(file), 0);
- if (fd < 0)
- return NULL;
- return _fdopen(fd, "w");
-#else
- return fdopen(file, "w");
-#endif
-}
-
-bool ClosePlatformFile(PlatformFile file) {
-#if defined(WIN32)
- return CloseHandle(file) != 0;
-#else
- return close(file);
-#endif
-}
-
-} // namespace talk_base
diff --git a/base/fileutils.h b/base/fileutils.h
deleted file mode 100644
index e58f76c..0000000
--- a/base/fileutils.h
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_FILEUTILS_H_
-#define TALK_BASE_FILEUTILS_H_
-
-#include <string>
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#else
-#include <dirent.h>
-#include <stdio.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-#endif
-
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-class FileStream;
-class Pathname;
-
-//////////////////////////
-// Directory Iterator //
-//////////////////////////
-
-// A DirectoryIterator is created with a given directory. It originally points
-// to the first file in the directory, and can be advanecd with Next(). This
-// allows you to get information about each file.
-
-class DirectoryIterator {
- friend class Filesystem;
- public:
- // Constructor
- DirectoryIterator();
- // Destructor
- virtual ~DirectoryIterator();
-
- // Starts traversing a directory
- // dir is the directory to traverse
- // returns true if the directory exists and is valid
- // The iterator will point to the first entry in the directory
- virtual bool Iterate(const Pathname &path);
-
- // Advances to the next file
- // returns true if there were more files in the directory.
- virtual bool Next();
-
- // returns true if the file currently pointed to is a directory
- virtual bool IsDirectory() const;
-
- // returns the name of the file currently pointed to
- virtual std::string Name() const;
-
- // returns the size of the file currently pointed to
- virtual size_t FileSize() const;
-
- // returns the last modified time of the file currently pointed to
- virtual time_t FileModifyTime() const;
-
- // checks whether current file is a special directory file "." or ".."
- bool IsDots() const {
- std::string filename(Name());
- return (filename.compare(".") == 0) || (filename.compare("..") == 0);
- }
-
- private:
- std::string directory_;
-#ifdef WIN32
- WIN32_FIND_DATA data_;
- HANDLE handle_;
-#else
- DIR *dir_;
- struct dirent *dirent_;
- struct stat stat_;
-#endif
-};
-
-enum FileTimeType { FTT_CREATED, FTT_MODIFIED, FTT_ACCESSED };
-
-class FilesystemInterface {
- public:
- virtual ~FilesystemInterface() {}
-
- // Returns a DirectoryIterator for a given pathname.
- // TODO: Do fancy abstracted stuff
- virtual DirectoryIterator *IterateDirectory() {
- return new DirectoryIterator();
- }
-
- // Opens a file. Returns an open StreamInterface if function succeeds.
- // Otherwise, returns NULL.
- // TODO: Add an error param to indicate failure reason, similar to
- // FileStream::Open
- virtual FileStream *OpenFile(const Pathname &filename,
- const std::string &mode) = 0;
-
- // Atomically creates an empty file accessible only to the current user if one
- // does not already exist at the given path, otherwise fails. This is the only
- // secure way to create a file in a shared temp directory (e.g., C:\Temp on
- // Windows or /tmp on Linux).
- // Note that if it is essential that a file be successfully created then the
- // app must generate random names and retry on failure, or else it will be
- // vulnerable to a trivial DoS.
- virtual bool CreatePrivateFile(const Pathname &filename) = 0;
-
- // This will attempt to delete the path located at filename.
- // It ASSERTS and returns false if the path points to a folder or a
- // non-existent file.
- virtual bool DeleteFile(const Pathname &filename) = 0;
-
- // This will attempt to delete the empty folder located at 'folder'
- // It ASSERTS and returns false if the path points to a file or a non-existent
- // folder. It fails normally if the folder is not empty or can otherwise
- // not be deleted.
- virtual bool DeleteEmptyFolder(const Pathname &folder) = 0;
-
- // This will call IterateDirectory, to get a directory iterator, and then
- // call DeleteFolderAndContents and DeleteFile on every path contained in this
- // folder. If the folder is empty, this returns true.
- virtual bool DeleteFolderContents(const Pathname &folder);
-
- // This deletes the contents of a folder, recursively, and then deletes
- // the folder itself.
- virtual bool DeleteFolderAndContents(const Pathname &folder) {
- return DeleteFolderContents(folder) && DeleteEmptyFolder(folder);
- }
-
- // This will delete whatever is located at path, be it a file or a folder.
- // If it is a folder, it will delete it recursively by calling
- // DeleteFolderAndContents
- bool DeleteFileOrFolder(const Pathname &path) {
- if (IsFolder(path))
- return DeleteFolderAndContents(path);
- else
- return DeleteFile(path);
- }
-
- // Creates a directory. This will call itself recursively to create /foo/bar
- // even if /foo does not exist. Returns true if the function succeeds.
- virtual bool CreateFolder(const Pathname &pathname) = 0;
-
- // This moves a file from old_path to new_path, where "old_path" is a
- // plain file. This ASSERTs and returns false if old_path points to a
- // directory, and returns true if the function succeeds.
- // If the new path is on a different volume than the old path, this function
- // will attempt to copy and, if that succeeds, delete the old path.
- virtual bool MoveFolder(const Pathname &old_path,
- const Pathname &new_path) = 0;
-
- // This moves a directory from old_path to new_path, where "old_path" is a
- // directory. This ASSERTs and returns false if old_path points to a plain
- // file, and returns true if the function succeeds.
- // If the new path is on a different volume, this function will attempt to
- // copy and if that succeeds, delete the old path.
- virtual bool MoveFile(const Pathname &old_path, const Pathname &new_path) = 0;
-
- // This attempts to move whatever is located at old_path to new_path,
- // be it a file or folder.
- bool MoveFileOrFolder(const Pathname &old_path, const Pathname &new_path) {
- if (IsFile(old_path)) {
- return MoveFile(old_path, new_path);
- } else {
- return MoveFolder(old_path, new_path);
- }
- }
-
- // This copies a file from old_path to new_path. This method ASSERTs and
- // returns false if old_path is a folder, and returns true if the copy
- // succeeds.
- virtual bool CopyFile(const Pathname &old_path, const Pathname &new_path) = 0;
-
- // This copies a folder from old_path to new_path.
- bool CopyFolder(const Pathname &old_path, const Pathname &new_path);
-
- bool CopyFileOrFolder(const Pathname &old_path, const Pathname &new_path) {
- if (IsFile(old_path))
- return CopyFile(old_path, new_path);
- else
- return CopyFolder(old_path, new_path);
- }
-
- // Returns true if pathname refers to a directory
- virtual bool IsFolder(const Pathname& pathname) = 0;
-
- // Returns true if pathname refers to a file
- virtual bool IsFile(const Pathname& pathname) = 0;
-
- // Returns true if pathname refers to no filesystem object, every parent
- // directory either exists, or is also absent.
- virtual bool IsAbsent(const Pathname& pathname) = 0;
-
- // Returns true if pathname represents a temporary location on the system.
- virtual bool IsTemporaryPath(const Pathname& pathname) = 0;
-
- // A folder appropriate for storing temporary files (Contents are
- // automatically deleted when the program exits)
- virtual bool GetTemporaryFolder(Pathname &path, bool create,
- const std::string *append) = 0;
-
- virtual std::string TempFilename(const Pathname &dir,
- const std::string &prefix) = 0;
-
- // Determines the size of the file indicated by path.
- virtual bool GetFileSize(const Pathname& path, size_t* size) = 0;
-
- // Determines a timestamp associated with the file indicated by path.
- virtual bool GetFileTime(const Pathname& path, FileTimeType which,
- time_t* time) = 0;
-
- // Returns the path to the running application.
- // Note: This is not guaranteed to work on all platforms. Be aware of the
- // limitations before using it, and robustly handle failure.
- virtual bool GetAppPathname(Pathname* path) = 0;
-
- // Get a folder that is unique to the current application, which is suitable
- // for sharing data between executions of the app. If the per_user arg is
- // true, the folder is also specific to the current user.
- virtual bool GetAppDataFolder(Pathname* path, bool per_user) = 0;
-
- // Get a temporary folder that is unique to the current user and application.
- // TODO: Re-evaluate the goals of this function. We probably just need any
- // directory that won't collide with another existing directory, and which
- // will be cleaned up when the program exits.
- virtual bool GetAppTempFolder(Pathname* path) = 0;
-
- // Delete the contents of the folder returned by GetAppTempFolder
- bool CleanAppTempFolder();
-
- virtual bool GetDiskFreeSpace(const Pathname& path, int64 *freebytes) = 0;
-
- // Returns the absolute path of the current directory.
- virtual Pathname GetCurrentDirectory() = 0;
-
- // Note: These might go into some shared config section later, but they're
- // used by some methods in this interface, so we're leaving them here for now.
- void SetOrganizationName(const std::string& organization) {
- organization_name_ = organization;
- }
- void GetOrganizationName(std::string* organization) {
- ASSERT(NULL != organization);
- *organization = organization_name_;
- }
- void SetApplicationName(const std::string& application) {
- application_name_ = application;
- }
- void GetApplicationName(std::string* application) {
- ASSERT(NULL != application);
- *application = application_name_;
- }
-
- protected:
- std::string organization_name_;
- std::string application_name_;
-};
-
-class Filesystem {
- public:
- static FilesystemInterface *default_filesystem() {
- ASSERT(default_filesystem_ != NULL);
- return default_filesystem_;
- }
-
- static void set_default_filesystem(FilesystemInterface *filesystem) {
- default_filesystem_ = filesystem;
- }
-
- static FilesystemInterface *swap_default_filesystem(
- FilesystemInterface *filesystem) {
- FilesystemInterface *cur = default_filesystem_;
- default_filesystem_ = filesystem;
- return cur;
- }
-
- static DirectoryIterator *IterateDirectory() {
- return EnsureDefaultFilesystem()->IterateDirectory();
- }
-
- static bool CreateFolder(const Pathname &pathname) {
- return EnsureDefaultFilesystem()->CreateFolder(pathname);
- }
-
- static FileStream *OpenFile(const Pathname &filename,
- const std::string &mode) {
- return EnsureDefaultFilesystem()->OpenFile(filename, mode);
- }
-
- static bool CreatePrivateFile(const Pathname &filename) {
- return EnsureDefaultFilesystem()->CreatePrivateFile(filename);
- }
-
- static bool DeleteFile(const Pathname &filename) {
- return EnsureDefaultFilesystem()->DeleteFile(filename);
- }
-
- static bool DeleteEmptyFolder(const Pathname &folder) {
- return EnsureDefaultFilesystem()->DeleteEmptyFolder(folder);
- }
-
- static bool DeleteFolderContents(const Pathname &folder) {
- return EnsureDefaultFilesystem()->DeleteFolderContents(folder);
- }
-
- static bool DeleteFolderAndContents(const Pathname &folder) {
- return EnsureDefaultFilesystem()->DeleteFolderAndContents(folder);
- }
-
- static bool MoveFolder(const Pathname &old_path, const Pathname &new_path) {
- return EnsureDefaultFilesystem()->MoveFolder(old_path, new_path);
- }
-
- static bool MoveFile(const Pathname &old_path, const Pathname &new_path) {
- return EnsureDefaultFilesystem()->MoveFile(old_path, new_path);
- }
-
- static bool CopyFolder(const Pathname &old_path, const Pathname &new_path) {
- return EnsureDefaultFilesystem()->CopyFolder(old_path, new_path);
- }
-
- static bool CopyFile(const Pathname &old_path, const Pathname &new_path) {
- return EnsureDefaultFilesystem()->CopyFile(old_path, new_path);
- }
-
- static bool IsFolder(const Pathname& pathname) {
- return EnsureDefaultFilesystem()->IsFolder(pathname);
- }
-
- static bool IsFile(const Pathname &pathname) {
- return EnsureDefaultFilesystem()->IsFile(pathname);
- }
-
- static bool IsAbsent(const Pathname &pathname) {
- return EnsureDefaultFilesystem()->IsAbsent(pathname);
- }
-
- static bool IsTemporaryPath(const Pathname& pathname) {
- return EnsureDefaultFilesystem()->IsTemporaryPath(pathname);
- }
-
- static bool GetTemporaryFolder(Pathname &path, bool create,
- const std::string *append) {
- return EnsureDefaultFilesystem()->GetTemporaryFolder(path, create, append);
- }
-
- static std::string TempFilename(const Pathname &dir,
- const std::string &prefix) {
- return EnsureDefaultFilesystem()->TempFilename(dir, prefix);
- }
-
- static bool GetFileSize(const Pathname& path, size_t* size) {
- return EnsureDefaultFilesystem()->GetFileSize(path, size);
- }
-
- static bool GetFileTime(const Pathname& path, FileTimeType which,
- time_t* time) {
- return EnsureDefaultFilesystem()->GetFileTime(path, which, time);
- }
-
- static bool GetAppPathname(Pathname* path) {
- return EnsureDefaultFilesystem()->GetAppPathname(path);
- }
-
- static bool GetAppDataFolder(Pathname* path, bool per_user) {
- return EnsureDefaultFilesystem()->GetAppDataFolder(path, per_user);
- }
-
- static bool GetAppTempFolder(Pathname* path) {
- return EnsureDefaultFilesystem()->GetAppTempFolder(path);
- }
-
- static bool CleanAppTempFolder() {
- return EnsureDefaultFilesystem()->CleanAppTempFolder();
- }
-
- static bool GetDiskFreeSpace(const Pathname& path, int64 *freebytes) {
- return EnsureDefaultFilesystem()->GetDiskFreeSpace(path, freebytes);
- }
-
- // Definition has to be in the .cc file due to returning forward-declared
- // Pathname by value.
- static Pathname GetCurrentDirectory();
-
- static void SetOrganizationName(const std::string& organization) {
- EnsureDefaultFilesystem()->SetOrganizationName(organization);
- }
-
- static void GetOrganizationName(std::string* organization) {
- EnsureDefaultFilesystem()->GetOrganizationName(organization);
- }
-
- static void SetApplicationName(const std::string& application) {
- EnsureDefaultFilesystem()->SetApplicationName(application);
- }
-
- static void GetApplicationName(std::string* application) {
- EnsureDefaultFilesystem()->GetApplicationName(application);
- }
-
- private:
- static FilesystemInterface* default_filesystem_;
-
- static FilesystemInterface *EnsureDefaultFilesystem();
- DISALLOW_IMPLICIT_CONSTRUCTORS(Filesystem);
-};
-
-class FilesystemScope{
- public:
- explicit FilesystemScope(FilesystemInterface *new_fs) {
- old_fs_ = Filesystem::swap_default_filesystem(new_fs);
- }
- ~FilesystemScope() {
- Filesystem::set_default_filesystem(old_fs_);
- }
- private:
- FilesystemInterface* old_fs_;
- DISALLOW_IMPLICIT_CONSTRUCTORS(FilesystemScope);
-};
-
-// Generates a unique filename based on the input path. If no path component
-// is specified, it uses the temporary directory. If a filename is provided,
-// up to 100 variations of form basename-N.extension are tried. When
-// create_empty is true, an empty file of this name is created (which
-// decreases the chance of a temporary filename collision with another
-// process).
-bool CreateUniqueFile(Pathname& path, bool create_empty);
-
-// Taken from Chromium's base/platform_file.h.
-// Don't use ClosePlatformFile to close a file opened with FdopenPlatformFile.
-// Use fclose instead.
-// TODO(grunell): Remove when Chromium has started to use AEC in each source.
-// http://crbug.com/264611.
-#if defined(WIN32)
-typedef HANDLE PlatformFile;
-const PlatformFile kInvalidPlatformFileValue = INVALID_HANDLE_VALUE;
-#elif defined(POSIX)
-typedef int PlatformFile;
-const PlatformFile kInvalidPlatformFileValue = -1;
-#else
-#error Unsupported platform
-#endif
-
-FILE* FdopenPlatformFileForWriting(PlatformFile file);
-bool ClosePlatformFile(PlatformFile file);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_FILEUTILS_H_
diff --git a/base/fileutils_mock.h b/base/fileutils_mock.h
deleted file mode 100644
index b91e802..0000000
--- a/base/fileutils_mock.h
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_FILEUTILS_MOCK_H_
-#define TALK_BASE_FILEUTILS_MOCK_H_
-
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-class FakeFileStream : public FileStream {
- public:
- explicit FakeFileStream(const std::string & contents) :
- string_stream_(contents)
- {}
-
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- return string_stream_.Read(buffer, buffer_len, read, error);
- }
-
- virtual void Close() {
- return string_stream_.Close();
- }
- virtual bool GetSize(size_t* size) const {
- return string_stream_.GetSize(size);
- }
-
- private:
- StringStream string_stream_;
-};
-
-class FakeDirectoryIterator : public DirectoryIterator {
- public:
- typedef std::pair<std::string, std::string> File;
-
- /*
- * files should be sorted by directory
- * put '/' at the end of file if you want it to be a directory
- *
- * Sample list:
- * /var/dir/file1
- * /var/dir/file2
- * /var/dir/subdir1/
- * /var/dir/subdir2/
- * /var/dir2/file2
- * /var/dir3/
- *
- * you can call Iterate for any path: /var, /var/dir, /var/dir2
- * unrelated files will be ignored
- */
- explicit FakeDirectoryIterator(const std::vector<File>& all_files) :
- all_files_(all_files) {}
-
- virtual bool Iterate(const Pathname& path) {
- path_iterator_ = all_files_.begin();
- path_ = path.pathname();
-
- // make sure path ends end with '/'
- if (path_.rfind(Pathname::DefaultFolderDelimiter()) != path_.size() - 1)
- path_ += Pathname::DefaultFolderDelimiter();
-
- return FakeDirectoryIterator::Search(std::string(""));
- }
-
- virtual bool Next() {
- std::string current_name = Name();
- path_iterator_++;
- return FakeDirectoryIterator::Search(current_name);
- }
-
- bool Search(const std::string& current_name) {
- for (; path_iterator_ != all_files_.end(); path_iterator_++) {
- if (path_iterator_->first.find(path_) == 0
- && Name().compare(current_name) != 0) {
- return true;
- }
- }
-
- return false;
- }
-
- virtual bool IsDirectory() const {
- std::string sub_path = path_iterator_->first;
-
- return std::string::npos !=
- sub_path.find(Pathname::DefaultFolderDelimiter(), path_.size());
- }
-
- virtual std::string Name() const {
- std::string sub_path = path_iterator_->first;
-
- // path - top level path (ex. /var/lib)
- // sub_path - subpath under top level path (ex. /var/lib/dir/dir/file )
- // find shortest non-trivial common path. (ex. /var/lib/dir)
- size_t start = path_.size();
- size_t end = sub_path.find(Pathname::DefaultFolderDelimiter(), start);
-
- if (end != std::string::npos) {
- return sub_path.substr(start, end - start);
- } else {
- return sub_path.substr(start);
- }
- }
-
- private:
- const std::vector<File> all_files_;
-
- std::string path_;
- std::vector<File>::const_iterator path_iterator_;
-};
-
-class FakeFileSystem : public FilesystemInterface {
- public:
- typedef std::pair<std::string, std::string> File;
-
- explicit FakeFileSystem(const std::vector<File>& all_files) :
- all_files_(all_files) {}
-
- virtual DirectoryIterator *IterateDirectory() {
- return new FakeDirectoryIterator(all_files_);
- }
-
- virtual FileStream * OpenFile(
- const Pathname &filename,
- const std::string &mode) {
- std::vector<File>::const_iterator i_files = all_files_.begin();
- std::string path = filename.pathname();
-
- for (; i_files != all_files_.end(); i_files++) {
- if (i_files->first.compare(path) == 0) {
- return new FakeFileStream(i_files->second);
- }
- }
-
- return NULL;
- }
-
- bool CreatePrivateFile(const Pathname &filename) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool DeleteFile(const Pathname &filename) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool DeleteEmptyFolder(const Pathname &folder) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool DeleteFolderContents(const Pathname &folder) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool DeleteFolderAndContents(const Pathname &folder) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool CreateFolder(const Pathname &pathname) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool MoveFolder(const Pathname &old_path, const Pathname &new_path) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool MoveFile(const Pathname &old_path, const Pathname &new_path) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool CopyFile(const Pathname &old_path, const Pathname &new_path) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool IsFolder(const Pathname &pathname) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool IsFile(const Pathname &pathname) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool IsAbsent(const Pathname &pathname) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool IsTemporaryPath(const Pathname &pathname) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool GetTemporaryFolder(Pathname &path, bool create,
- const std::string *append) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- std::string TempFilename(const Pathname &dir, const std::string &prefix) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return std::string();
- }
- bool GetFileSize(const Pathname &path, size_t *size) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool GetFileTime(const Pathname &path, FileTimeType which,
- time_t* time) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool GetAppPathname(Pathname *path) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool GetAppDataFolder(Pathname *path, bool per_user) {
- EXPECT_TRUE(per_user) << "Unsupported operation";
-#ifdef WIN32
- path->SetPathname("c:\\Users\\test_user", "");
-#else
- path->SetPathname("/home/user/test_user", "");
-#endif
- return true;
- }
- bool GetAppTempFolder(Pathname *path) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- bool GetDiskFreeSpace(const Pathname &path, int64 *freebytes) {
- EXPECT_TRUE(false) << "Unsupported operation";
- return false;
- }
- Pathname GetCurrentDirectory() {
- return Pathname();
- }
-
- private:
- const std::vector<File> all_files_;
-};
-} // namespace talk_base
-
-#endif // TALK_BASE_FILEUTILS_MOCK_H_
diff --git a/base/fileutils_unittest.cc b/base/fileutils_unittest.cc
deleted file mode 100644
index 992ea82..0000000
--- a/base/fileutils_unittest.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-// Make sure we can get a temp folder for the later tests.
-TEST(FilesystemTest, GetTemporaryFolder) {
- Pathname path;
- EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, NULL));
-}
-
-// Test creating a temp file, reading it back in, and deleting it.
-TEST(FilesystemTest, TestOpenFile) {
- Pathname path;
- EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, NULL));
- path.SetPathname(Filesystem::TempFilename(path, "ut"));
-
- FileStream* fs;
- char buf[256];
- size_t bytes;
-
- fs = Filesystem::OpenFile(path, "wb");
- ASSERT_TRUE(fs != NULL);
- EXPECT_EQ(SR_SUCCESS, fs->Write("test", 4, &bytes, NULL));
- EXPECT_EQ(4U, bytes);
- delete fs;
-
- EXPECT_TRUE(Filesystem::IsFile(path));
-
- fs = Filesystem::OpenFile(path, "rb");
- ASSERT_TRUE(fs != NULL);
- EXPECT_EQ(SR_SUCCESS, fs->Read(buf, sizeof(buf), &bytes, NULL));
- EXPECT_EQ(4U, bytes);
- delete fs;
-
- EXPECT_TRUE(Filesystem::DeleteFile(path));
- EXPECT_FALSE(Filesystem::IsFile(path));
-}
-
-// Test opening a non-existent file.
-TEST(FilesystemTest, TestOpenBadFile) {
- Pathname path;
- EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, NULL));
- path.SetFilename("not an actual file");
-
- EXPECT_FALSE(Filesystem::IsFile(path));
-
- FileStream* fs = Filesystem::OpenFile(path, "rb");
- EXPECT_FALSE(fs != NULL);
-}
-
-// Test that CreatePrivateFile fails for existing files and succeeds for
-// non-existent ones.
-TEST(FilesystemTest, TestCreatePrivateFile) {
- Pathname path;
- EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, NULL));
- path.SetFilename("private_file_test");
-
- // First call should succeed because the file doesn't exist yet.
- EXPECT_TRUE(Filesystem::CreatePrivateFile(path));
- // Next call should fail, because now it exists.
- EXPECT_FALSE(Filesystem::CreatePrivateFile(path));
-
- // Verify that we have permission to open the file for reading and writing.
- scoped_ptr<FileStream> fs(Filesystem::OpenFile(path, "wb"));
- EXPECT_TRUE(fs.get() != NULL);
- // Have to close the file on Windows before it will let us delete it.
- fs.reset();
-
- // Verify that we have permission to delete the file.
- EXPECT_TRUE(Filesystem::DeleteFile(path));
-}
-
-// Test checking for free disk space.
-TEST(FilesystemTest, TestGetDiskFreeSpace) {
- // Note that we should avoid picking any file/folder which could be located
- // at the remotely mounted drive/device.
- Pathname path;
- ASSERT_TRUE(Filesystem::GetAppDataFolder(&path, true));
-
- int64 free1 = 0;
- EXPECT_TRUE(Filesystem::IsFolder(path));
- EXPECT_FALSE(Filesystem::IsFile(path));
- EXPECT_TRUE(Filesystem::GetDiskFreeSpace(path, &free1));
- EXPECT_GT(free1, 0);
-
- int64 free2 = 0;
- path.AppendFolder("this_folder_doesnt_exist");
- EXPECT_FALSE(Filesystem::IsFolder(path));
- EXPECT_TRUE(Filesystem::IsAbsent(path));
- EXPECT_TRUE(Filesystem::GetDiskFreeSpace(path, &free2));
- // These should be the same disk, and disk free space should not have changed
- // by more than 1% between the two calls.
- EXPECT_LT(static_cast<int64>(free1 * .9), free2);
- EXPECT_LT(free2, static_cast<int64>(free1 * 1.1));
-
- int64 free3 = 0;
- path.clear();
- EXPECT_TRUE(path.empty());
- EXPECT_TRUE(Filesystem::GetDiskFreeSpace(path, &free3));
- // Current working directory may not be where exe is.
- // EXPECT_LT(static_cast<int64>(free1 * .9), free3);
- // EXPECT_LT(free3, static_cast<int64>(free1 * 1.1));
- EXPECT_GT(free3, 0);
-}
-
-// Tests that GetCurrentDirectory() returns something.
-TEST(FilesystemTest, TestGetCurrentDirectory) {
- EXPECT_FALSE(Filesystem::GetCurrentDirectory().empty());
-}
-
-// Tests that GetAppPathname returns something.
-TEST(FilesystemTest, TestGetAppPathname) {
- Pathname path;
- EXPECT_TRUE(Filesystem::GetAppPathname(&path));
- EXPECT_FALSE(path.empty());
-}
-
-} // namespace talk_base
diff --git a/base/firewallsocketserver.cc b/base/firewallsocketserver.cc
deleted file mode 100644
index 4a8a66d..0000000
--- a/base/firewallsocketserver.cc
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/firewallsocketserver.h"
-
-#include <assert.h>
-
-#include <algorithm>
-
-#include "talk/base/asyncsocket.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-class FirewallSocket : public AsyncSocketAdapter {
- public:
- FirewallSocket(FirewallSocketServer* server, AsyncSocket* socket, int type)
- : AsyncSocketAdapter(socket), server_(server), type_(type) {
- }
-
- virtual int Connect(const SocketAddress& addr) {
- if (type_ == SOCK_STREAM) {
- if (!server_->Check(FP_TCP, GetLocalAddress(), addr)) {
- LOG(LS_VERBOSE) << "FirewallSocket outbound TCP connection from "
- << GetLocalAddress().ToSensitiveString() << " to "
- << addr.ToSensitiveString() << " denied";
- // TODO: Handle this asynchronously.
- SetError(EHOSTUNREACH);
- return SOCKET_ERROR;
- }
- }
- return AsyncSocketAdapter::Connect(addr);
- }
- virtual int Send(const void* pv, size_t cb) {
- return SendTo(pv, cb, GetRemoteAddress());
- }
- virtual int SendTo(const void* pv, size_t cb, const SocketAddress& addr) {
- if (type_ == SOCK_DGRAM) {
- if (!server_->Check(FP_UDP, GetLocalAddress(), addr)) {
- LOG(LS_VERBOSE) << "FirewallSocket outbound UDP packet from "
- << GetLocalAddress().ToSensitiveString() << " to "
- << addr.ToSensitiveString() << " dropped";
- return static_cast<int>(cb);
- }
- }
- return AsyncSocketAdapter::SendTo(pv, cb, addr);
- }
- virtual int Recv(void* pv, size_t cb) {
- SocketAddress addr;
- return RecvFrom(pv, cb, &addr);
- }
- virtual int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) {
- if (type_ == SOCK_DGRAM) {
- while (true) {
- int res = AsyncSocketAdapter::RecvFrom(pv, cb, paddr);
- if (res <= 0)
- return res;
- if (server_->Check(FP_UDP, *paddr, GetLocalAddress()))
- return res;
- LOG(LS_VERBOSE) << "FirewallSocket inbound UDP packet from "
- << paddr->ToSensitiveString() << " to "
- << GetLocalAddress().ToSensitiveString() << " dropped";
- }
- }
- return AsyncSocketAdapter::RecvFrom(pv, cb, paddr);
- }
-
- virtual int Listen(int backlog) {
- if (!server_->tcp_listen_enabled()) {
- LOG(LS_VERBOSE) << "FirewallSocket listen attempt denied";
- return -1;
- }
-
- return AsyncSocketAdapter::Listen(backlog);
- }
- virtual AsyncSocket* Accept(SocketAddress* paddr) {
- SocketAddress addr;
- while (AsyncSocket* sock = AsyncSocketAdapter::Accept(&addr)) {
- if (server_->Check(FP_TCP, addr, GetLocalAddress())) {
- if (paddr)
- *paddr = addr;
- return sock;
- }
- sock->Close();
- delete sock;
- LOG(LS_VERBOSE) << "FirewallSocket inbound TCP connection from "
- << addr.ToSensitiveString() << " to "
- << GetLocalAddress().ToSensitiveString() << " denied";
- }
- return 0;
- }
-
- private:
- FirewallSocketServer* server_;
- int type_;
-};
-
-FirewallSocketServer::FirewallSocketServer(SocketServer* server,
- FirewallManager* manager,
- bool should_delete_server)
- : server_(server), manager_(manager),
- should_delete_server_(should_delete_server),
- udp_sockets_enabled_(true), tcp_sockets_enabled_(true),
- tcp_listen_enabled_(true) {
- if (manager_)
- manager_->AddServer(this);
-}
-
-FirewallSocketServer::~FirewallSocketServer() {
- if (manager_)
- manager_->RemoveServer(this);
-
- if (server_ && should_delete_server_) {
- delete server_;
- server_ = NULL;
- }
-}
-
-void FirewallSocketServer::AddRule(bool allow, FirewallProtocol p,
- FirewallDirection d,
- const SocketAddress& addr) {
- SocketAddress src, dst;
- if (d == FD_IN) {
- dst = addr;
- } else {
- src = addr;
- }
- AddRule(allow, p, src, dst);
-}
-
-
-void FirewallSocketServer::AddRule(bool allow, FirewallProtocol p,
- const SocketAddress& src,
- const SocketAddress& dst) {
- Rule r;
- r.allow = allow;
- r.p = p;
- r.src = src;
- r.dst = dst;
- CritScope scope(&crit_);
- rules_.push_back(r);
-}
-
-void FirewallSocketServer::ClearRules() {
- CritScope scope(&crit_);
- rules_.clear();
-}
-
-bool FirewallSocketServer::Check(FirewallProtocol p,
- const SocketAddress& src,
- const SocketAddress& dst) {
- CritScope scope(&crit_);
- for (size_t i = 0; i < rules_.size(); ++i) {
- const Rule& r = rules_[i];
- if ((r.p != p) && (r.p != FP_ANY))
- continue;
- if ((r.src.ipaddr() != src.ipaddr()) && !r.src.IsNil())
- continue;
- if ((r.src.port() != src.port()) && (r.src.port() != 0))
- continue;
- if ((r.dst.ipaddr() != dst.ipaddr()) && !r.dst.IsNil())
- continue;
- if ((r.dst.port() != dst.port()) && (r.dst.port() != 0))
- continue;
- return r.allow;
- }
- return true;
-}
-
-Socket* FirewallSocketServer::CreateSocket(int type) {
- return CreateSocket(AF_INET, type);
-}
-
-Socket* FirewallSocketServer::CreateSocket(int family, int type) {
- return WrapSocket(server_->CreateAsyncSocket(family, type), type);
-}
-
-AsyncSocket* FirewallSocketServer::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* FirewallSocketServer::CreateAsyncSocket(int family, int type) {
- return WrapSocket(server_->CreateAsyncSocket(family, type), type);
-}
-
-AsyncSocket* FirewallSocketServer::WrapSocket(AsyncSocket* sock, int type) {
- if (!sock ||
- (type == SOCK_STREAM && !tcp_sockets_enabled_) ||
- (type == SOCK_DGRAM && !udp_sockets_enabled_)) {
- LOG(LS_VERBOSE) << "FirewallSocketServer socket creation denied";
- delete sock;
- return NULL;
- }
- return new FirewallSocket(this, sock, type);
-}
-
-FirewallManager::FirewallManager() {
-}
-
-FirewallManager::~FirewallManager() {
- assert(servers_.empty());
-}
-
-void FirewallManager::AddServer(FirewallSocketServer* server) {
- CritScope scope(&crit_);
- servers_.push_back(server);
-}
-
-void FirewallManager::RemoveServer(FirewallSocketServer* server) {
- CritScope scope(&crit_);
- servers_.erase(std::remove(servers_.begin(), servers_.end(), server),
- servers_.end());
-}
-
-void FirewallManager::AddRule(bool allow, FirewallProtocol p,
- FirewallDirection d, const SocketAddress& addr) {
- CritScope scope(&crit_);
- for (std::vector<FirewallSocketServer*>::const_iterator it =
- servers_.begin(); it != servers_.end(); ++it) {
- (*it)->AddRule(allow, p, d, addr);
- }
-}
-
-void FirewallManager::ClearRules() {
- CritScope scope(&crit_);
- for (std::vector<FirewallSocketServer*>::const_iterator it =
- servers_.begin(); it != servers_.end(); ++it) {
- (*it)->ClearRules();
- }
-}
-
-} // namespace talk_base
diff --git a/base/firewallsocketserver.h b/base/firewallsocketserver.h
deleted file mode 100644
index aa63c11..0000000
--- a/base/firewallsocketserver.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_FIREWALLSOCKETSERVER_H_
-#define TALK_BASE_FIREWALLSOCKETSERVER_H_
-
-#include <vector>
-#include "talk/base/socketserver.h"
-#include "talk/base/criticalsection.h"
-
-namespace talk_base {
-
-class FirewallManager;
-
-// This SocketServer shim simulates a rule-based firewall server.
-
-enum FirewallProtocol { FP_UDP, FP_TCP, FP_ANY };
-enum FirewallDirection { FD_IN, FD_OUT, FD_ANY };
-
-class FirewallSocketServer : public SocketServer {
- public:
- FirewallSocketServer(SocketServer * server,
- FirewallManager * manager = NULL,
- bool should_delete_server = false);
- virtual ~FirewallSocketServer();
-
- SocketServer* socketserver() const { return server_; }
- void set_socketserver(SocketServer* server) {
- if (server_ && should_delete_server_) {
- delete server_;
- server_ = NULL;
- should_delete_server_ = false;
- }
- server_ = server;
- }
-
- // Settings to control whether CreateSocket or Socket::Listen succeed.
- void set_udp_sockets_enabled(bool enabled) { udp_sockets_enabled_ = enabled; }
- void set_tcp_sockets_enabled(bool enabled) { tcp_sockets_enabled_ = enabled; }
- bool tcp_listen_enabled() const { return tcp_listen_enabled_; }
- void set_tcp_listen_enabled(bool enabled) { tcp_listen_enabled_ = enabled; }
-
- // Rules govern the behavior of Connect/Accept/Send/Recv attempts.
- void AddRule(bool allow, FirewallProtocol p = FP_ANY,
- FirewallDirection d = FD_ANY,
- const SocketAddress& addr = SocketAddress());
- void AddRule(bool allow, FirewallProtocol p,
- const SocketAddress& src, const SocketAddress& dst);
- void ClearRules();
-
- bool Check(FirewallProtocol p,
- const SocketAddress& src, const SocketAddress& dst);
-
- virtual Socket* CreateSocket(int type);
- virtual Socket* CreateSocket(int family, int type);
-
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- virtual void SetMessageQueue(MessageQueue* queue) {
- server_->SetMessageQueue(queue);
- }
- virtual bool Wait(int cms, bool process_io) {
- return server_->Wait(cms, process_io);
- }
- virtual void WakeUp() {
- return server_->WakeUp();
- }
-
- Socket * WrapSocket(Socket * sock, int type);
- AsyncSocket * WrapSocket(AsyncSocket * sock, int type);
-
- private:
- SocketServer * server_;
- FirewallManager * manager_;
- CriticalSection crit_;
- struct Rule {
- bool allow;
- FirewallProtocol p;
- FirewallDirection d;
- SocketAddress src;
- SocketAddress dst;
- };
- std::vector<Rule> rules_;
- bool should_delete_server_;
- bool udp_sockets_enabled_;
- bool tcp_sockets_enabled_;
- bool tcp_listen_enabled_;
-};
-
-// FirewallManager allows you to manage firewalls in multiple threads together
-
-class FirewallManager {
- public:
- FirewallManager();
- ~FirewallManager();
-
- void AddServer(FirewallSocketServer * server);
- void RemoveServer(FirewallSocketServer * server);
-
- void AddRule(bool allow, FirewallProtocol p = FP_ANY,
- FirewallDirection d = FD_ANY,
- const SocketAddress& addr = SocketAddress());
- void ClearRules();
-
- private:
- CriticalSection crit_;
- std::vector<FirewallSocketServer *> servers_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_FIREWALLSOCKETSERVER_H_
diff --git a/base/flags.cc b/base/flags.cc
deleted file mode 100644
index 10aee04..0000000
--- a/base/flags.cc
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#include <shellapi.h>
-#endif
-
-#include "talk/base/flags.h"
-
-
-// -----------------------------------------------------------------------------
-// Implementation of Flag
-
-Flag::Flag(const char* file, const char* name, const char* comment,
- Type type, void* variable, FlagValue default__)
- : file_(file),
- name_(name),
- comment_(comment),
- type_(type),
- variable_(reinterpret_cast<FlagValue*>(variable)),
- default_(default__) {
- FlagList::Register(this);
-}
-
-
-void Flag::SetToDefault() {
- // Note that we cannot simply do '*variable_ = default_;' since
- // flag variables are not really of type FlagValue and thus may
- // be smaller! The FlagValue union is simply 'overlayed' on top
- // of a flag variable for convenient access. Since union members
- // are guarantee to be aligned at the beginning, this works.
- switch (type_) {
- case Flag::BOOL:
- variable_->b = default_.b;
- return;
- case Flag::INT:
- variable_->i = default_.i;
- return;
- case Flag::FLOAT:
- variable_->f = default_.f;
- return;
- case Flag::STRING:
- variable_->s = default_.s;
- return;
- }
- UNREACHABLE();
-}
-
-
-static const char* Type2String(Flag::Type type) {
- switch (type) {
- case Flag::BOOL: return "bool";
- case Flag::INT: return "int";
- case Flag::FLOAT: return "float";
- case Flag::STRING: return "string";
- }
- UNREACHABLE();
- return NULL;
-}
-
-
-static void PrintFlagValue(Flag::Type type, FlagValue* p) {
- switch (type) {
- case Flag::BOOL:
- printf("%s", (p->b ? "true" : "false"));
- return;
- case Flag::INT:
- printf("%d", p->i);
- return;
- case Flag::FLOAT:
- printf("%f", p->f);
- return;
- case Flag::STRING:
- printf("%s", p->s);
- return;
- }
- UNREACHABLE();
-}
-
-
-void Flag::Print(bool print_current_value) {
- printf(" --%s (%s) type: %s default: ", name_, comment_,
- Type2String(type_));
- PrintFlagValue(type_, &default_);
- if (print_current_value) {
- printf(" current value: ");
- PrintFlagValue(type_, variable_);
- }
- printf("\n");
-}
-
-
-// -----------------------------------------------------------------------------
-// Implementation of FlagList
-
-Flag* FlagList::list_ = NULL;
-
-
-FlagList::FlagList() {
- list_ = NULL;
-}
-
-void FlagList::Print(const char* file, bool print_current_value) {
- // Since flag registration is likely by file (= C++ file),
- // we don't need to sort by file and still get grouped output.
- const char* current = NULL;
- for (Flag* f = list_; f != NULL; f = f->next()) {
- if (file == NULL || file == f->file()) {
- if (current != f->file()) {
- printf("Flags from %s:\n", f->file());
- current = f->file();
- }
- f->Print(print_current_value);
- }
- }
-}
-
-
-Flag* FlagList::Lookup(const char* name) {
- Flag* f = list_;
- while (f != NULL && strcmp(name, f->name()) != 0)
- f = f->next();
- return f;
-}
-
-
-void FlagList::SplitArgument(const char* arg,
- char* buffer, int buffer_size,
- const char** name, const char** value,
- bool* is_bool) {
- *name = NULL;
- *value = NULL;
- *is_bool = false;
-
- if (*arg == '-') {
- // find the begin of the flag name
- arg++; // remove 1st '-'
- if (*arg == '-')
- arg++; // remove 2nd '-'
- if (arg[0] == 'n' && arg[1] == 'o') {
- arg += 2; // remove "no"
- *is_bool = true;
- }
- *name = arg;
-
- // find the end of the flag name
- while (*arg != '\0' && *arg != '=')
- arg++;
-
- // get the value if any
- if (*arg == '=') {
- // make a copy so we can NUL-terminate flag name
- int n = static_cast<int>(arg - *name);
- if (n >= buffer_size)
- Fatal(__FILE__, __LINE__, "CHECK(%s) failed", "n < buffer_size");
- memcpy(buffer, *name, n * sizeof(char));
- buffer[n] = '\0';
- *name = buffer;
- // get the value
- *value = arg + 1;
- }
- }
-}
-
-
-int FlagList::SetFlagsFromCommandLine(int* argc, const char** argv,
- bool remove_flags) {
- // parse arguments
- for (int i = 1; i < *argc; /* see below */) {
- int j = i; // j > 0
- const char* arg = argv[i++];
-
- // split arg into flag components
- char buffer[1024];
- const char* name;
- const char* value;
- bool is_bool;
- SplitArgument(arg, buffer, sizeof buffer, &name, &value, &is_bool);
-
- if (name != NULL) {
- // lookup the flag
- Flag* flag = Lookup(name);
- if (flag == NULL) {
- fprintf(stderr, "Error: unrecognized flag %s\n", arg);
- return j;
- }
-
- // if we still need a flag value, use the next argument if available
- if (flag->type() != Flag::BOOL && value == NULL) {
- if (i < *argc) {
- value = argv[i++];
- } else {
- fprintf(stderr, "Error: missing value for flag %s of type %s\n",
- arg, Type2String(flag->type()));
- return j;
- }
- }
-
- // set the flag
- char empty[] = { '\0' };
- char* endp = empty;
- switch (flag->type()) {
- case Flag::BOOL:
- *flag->bool_variable() = !is_bool;
- break;
- case Flag::INT:
- *flag->int_variable() = strtol(value, &endp, 10);
- break;
- case Flag::FLOAT:
- *flag->float_variable() = strtod(value, &endp);
- break;
- case Flag::STRING:
- *flag->string_variable() = value;
- break;
- }
-
- // handle errors
- if ((flag->type() == Flag::BOOL && value != NULL) ||
- (flag->type() != Flag::BOOL && is_bool) ||
- *endp != '\0') {
- fprintf(stderr, "Error: illegal value for flag %s of type %s\n",
- arg, Type2String(flag->type()));
- return j;
- }
-
- // remove the flag & value from the command
- if (remove_flags)
- while (j < i)
- argv[j++] = NULL;
- }
- }
-
- // shrink the argument list
- if (remove_flags) {
- int j = 1;
- for (int i = 1; i < *argc; i++) {
- if (argv[i] != NULL)
- argv[j++] = argv[i];
- }
- *argc = j;
- }
-
- // parsed all flags successfully
- return 0;
-}
-
-void FlagList::Register(Flag* flag) {
- assert(flag != NULL && strlen(flag->name()) > 0);
- if (Lookup(flag->name()) != NULL)
- Fatal(flag->file(), 0, "flag %s declared twice", flag->name());
- flag->next_ = list_;
- list_ = flag;
-}
-
-#ifdef WIN32
-WindowsCommandLineArguments::WindowsCommandLineArguments() {
- // start by getting the command line.
- LPTSTR command_line = ::GetCommandLine();
- // now, convert it to a list of wide char strings.
- LPWSTR *wide_argv = ::CommandLineToArgvW(command_line, &argc_);
- // now allocate an array big enough to hold that many string pointers.
- argv_ = new char*[argc_];
-
- // iterate over the returned wide strings;
- for(int i = 0; i < argc_; ++i) {
- std::string s = talk_base::ToUtf8(wide_argv[i], wcslen(wide_argv[i]));
- char *buffer = new char[s.length() + 1];
- talk_base::strcpyn(buffer, s.length() + 1, s.c_str());
-
- // make sure the argv array has the right string at this point.
- argv_[i] = buffer;
- }
- LocalFree(wide_argv);
-}
-
-WindowsCommandLineArguments::~WindowsCommandLineArguments() {
- // need to free each string in the array, and then the array.
- for(int i = 0; i < argc_; i++) {
- delete[] argv_[i];
- }
-
- delete[] argv_;
-}
-#endif // WIN32
-
diff --git a/base/flags.h b/base/flags.h
deleted file mode 100644
index f22e125..0000000
--- a/base/flags.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-// Originally comes from shared/commandlineflags/flags.h
-
-// Flags are defined and declared using DEFINE_xxx and DECLARE_xxx macros,
-// where xxx is the flag type. Flags are referred to via FLAG_yyy,
-// where yyy is the flag name. For intialization and iteration of flags,
-// see the FlagList class. For full programmatic access to any
-// flag, see the Flag class.
-//
-// The implementation only relies and basic C++ functionality
-// and needs no special library or STL support.
-
-#ifndef TALK_BASE_FLAGS_H__
-#define TALK_BASE_FLAGS_H__
-
-#include <assert.h>
-
-#include "talk/base/checks.h"
-#include "talk/base/common.h"
-
-// Internal use only.
-union FlagValue {
- // Note: Because in C++ non-bool values are silently converted into
- // bool values ('bool b = "false";' results in b == true!), we pass
- // and int argument to New_BOOL as this appears to be safer - sigh.
- // In particular, it prevents the (not uncommon!) bug where a bool
- // flag is defined via: DEFINE_bool(flag, "false", "some comment");.
- static FlagValue New_BOOL(int b) {
- FlagValue v;
- v.b = (b != 0);
- return v;
- }
-
- static FlagValue New_INT(int i) {
- FlagValue v;
- v.i = i;
- return v;
- }
-
- static FlagValue New_FLOAT(float f) {
- FlagValue v;
- v.f = f;
- return v;
- }
-
- static FlagValue New_STRING(const char* s) {
- FlagValue v;
- v.s = s;
- return v;
- }
-
- bool b;
- int i;
- double f;
- const char* s;
-};
-
-
-// Each flag can be accessed programmatically via a Flag object.
-class Flag {
- public:
- enum Type { BOOL, INT, FLOAT, STRING };
-
- // Internal use only.
- Flag(const char* file, const char* name, const char* comment,
- Type type, void* variable, FlagValue default_);
-
- // General flag information
- const char* file() const { return file_; }
- const char* name() const { return name_; }
- const char* comment() const { return comment_; }
-
- // Flag type
- Type type() const { return type_; }
-
- // Flag variables
- bool* bool_variable() const {
- assert(type_ == BOOL);
- return &variable_->b;
- }
-
- int* int_variable() const {
- assert(type_ == INT);
- return &variable_->i;
- }
-
- double* float_variable() const {
- assert(type_ == FLOAT);
- return &variable_->f;
- }
-
- const char** string_variable() const {
- assert(type_ == STRING);
- return &variable_->s;
- }
-
- // Default values
- bool bool_default() const {
- assert(type_ == BOOL);
- return default_.b;
- }
-
- int int_default() const {
- assert(type_ == INT);
- return default_.i;
- }
-
- double float_default() const {
- assert(type_ == FLOAT);
- return default_.f;
- }
-
- const char* string_default() const {
- assert(type_ == STRING);
- return default_.s;
- }
-
- // Resets a flag to its default value
- void SetToDefault();
-
- // Iteration support
- Flag* next() const { return next_; }
-
- // Prints flag information. The current flag value is only printed
- // if print_current_value is set.
- void Print(bool print_current_value);
-
- private:
- const char* file_;
- const char* name_;
- const char* comment_;
-
- Type type_;
- FlagValue* variable_;
- FlagValue default_;
-
- Flag* next_;
-
- friend class FlagList; // accesses next_
-};
-
-
-// Internal use only.
-#define DEFINE_FLAG(type, c_type, name, default, comment) \
- /* define and initialize the flag */ \
- c_type FLAG_##name = (default); \
- /* register the flag */ \
- static Flag Flag_##name(__FILE__, #name, (comment), \
- Flag::type, &FLAG_##name, \
- FlagValue::New_##type(default))
-
-
-// Internal use only.
-#define DECLARE_FLAG(c_type, name) \
- /* declare the external flag */ \
- extern c_type FLAG_##name
-
-
-// Use the following macros to define a new flag:
-#define DEFINE_bool(name, default, comment) \
- DEFINE_FLAG(BOOL, bool, name, default, comment)
-#define DEFINE_int(name, default, comment) \
- DEFINE_FLAG(INT, int, name, default, comment)
-#define DEFINE_float(name, default, comment) \
- DEFINE_FLAG(FLOAT, double, name, default, comment)
-#define DEFINE_string(name, default, comment) \
- DEFINE_FLAG(STRING, const char*, name, default, comment)
-
-
-// Use the following macros to declare a flag defined elsewhere:
-#define DECLARE_bool(name) DECLARE_FLAG(bool, name)
-#define DECLARE_int(name) DECLARE_FLAG(int, name)
-#define DECLARE_float(name) DECLARE_FLAG(double, name)
-#define DECLARE_string(name) DECLARE_FLAG(const char*, name)
-
-
-// The global list of all flags.
-class FlagList {
- public:
- FlagList();
-
- // The NULL-terminated list of all flags. Traverse with Flag::next().
- static Flag* list() { return list_; }
-
- // If file != NULL, prints information for all flags defined in file;
- // otherwise prints information for all flags in all files. The current
- // flag value is only printed if print_current_value is set.
- static void Print(const char* file, bool print_current_value);
-
- // Lookup a flag by name. Returns the matching flag or NULL.
- static Flag* Lookup(const char* name);
-
- // Helper function to parse flags: Takes an argument arg and splits it into
- // a flag name and flag value (or NULL if they are missing). is_bool is set
- // if the arg started with "-no" or "--no". The buffer may be used to NUL-
- // terminate the name, it must be large enough to hold any possible name.
- static void SplitArgument(const char* arg,
- char* buffer, int buffer_size,
- const char** name, const char** value,
- bool* is_bool);
-
- // Set the flag values by parsing the command line. If remove_flags
- // is set, the flags and associated values are removed from (argc,
- // argv). Returns 0 if no error occurred. Otherwise, returns the
- // argv index > 0 for the argument where an error occurred. In that
- // case, (argc, argv) will remain unchanged indepdendent of the
- // remove_flags value, and no assumptions about flag settings should
- // be made.
- //
- // The following syntax for flags is accepted (both '-' and '--' are ok):
- //
- // --flag (bool flags only)
- // --noflag (bool flags only)
- // --flag=value (non-bool flags only, no spaces around '=')
- // --flag value (non-bool flags only)
- static int SetFlagsFromCommandLine(int* argc,
- const char** argv,
- bool remove_flags);
- static inline int SetFlagsFromCommandLine(int* argc,
- char** argv,
- bool remove_flags) {
- return SetFlagsFromCommandLine(argc, const_cast<const char**>(argv),
- remove_flags);
- }
-
- // Registers a new flag. Called during program initialization. Not
- // thread-safe.
- static void Register(Flag* flag);
-
- private:
- static Flag* list_;
-};
-
-#ifdef WIN32
-// A helper class to translate Windows command line arguments into UTF8,
-// which then allows us to just pass them to the flags system.
-// This encapsulates all the work of getting the command line and translating
-// it to an array of 8-bit strings; all you have to do is create one of these,
-// and then call argc() and argv().
-class WindowsCommandLineArguments {
- public:
- WindowsCommandLineArguments();
- ~WindowsCommandLineArguments();
-
- int argc() { return argc_; }
- char **argv() { return argv_; }
- private:
- int argc_;
- char **argv_;
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(WindowsCommandLineArguments);
-};
-#endif // WIN32
-
-
-#endif // SHARED_COMMANDLINEFLAGS_FLAGS_H__
diff --git a/base/gunit.h b/base/gunit.h
deleted file mode 100644
index e56dd6f..0000000
--- a/base/gunit.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_GUNIT_H_
-#define TALK_BASE_GUNIT_H_
-
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
-#if defined(ANDROID) || defined(GTEST_RELATIVE_PATH)
-#include "gtest/gtest.h"
-#else
-#include "testing/base/public/gunit.h"
-#endif
-
-// Wait until "ex" is true, or "timeout" expires.
-#define WAIT(ex, timeout) \
- for (uint32 start = talk_base::Time(); \
- !(ex) && talk_base::Time() < start + timeout;) \
- talk_base::Thread::Current()->ProcessMessages(1);
-
-// This returns the result of the test in res, so that we don't re-evaluate
-// the expression in the XXXX_WAIT macros below, since that causes problems
-// when the expression is only true the first time you check it.
-#define WAIT_(ex, timeout, res) \
- do { \
- uint32 start = talk_base::Time(); \
- res = (ex); \
- while (!res && talk_base::Time() < start + timeout) { \
- talk_base::Thread::Current()->ProcessMessages(1); \
- res = (ex); \
- } \
- } while (0);
-
-// The typical EXPECT_XXXX and ASSERT_XXXXs, but done until true or a timeout.
-#define EXPECT_TRUE_WAIT(ex, timeout) \
- do { \
- bool res; \
- WAIT_(ex, timeout, res); \
- if (!res) EXPECT_TRUE(ex); \
- } while (0);
-
-#define EXPECT_EQ_WAIT(v1, v2, timeout) \
- do { \
- bool res; \
- WAIT_(v1 == v2, timeout, res); \
- if (!res) EXPECT_EQ(v1, v2); \
- } while (0);
-
-#define ASSERT_TRUE_WAIT(ex, timeout) \
- do { \
- bool res; \
- WAIT_(ex, timeout, res); \
- if (!res) ASSERT_TRUE(ex); \
- } while (0);
-
-#define ASSERT_EQ_WAIT(v1, v2, timeout) \
- do { \
- bool res; \
- WAIT_(v1 == v2, timeout, res); \
- if (!res) ASSERT_EQ(v1, v2); \
- } while (0);
-
-// Version with a "soft" timeout and a margin. This logs if the timeout is
-// exceeded, but it only fails if the expression still isn't true after the
-// margin time passes.
-#define EXPECT_TRUE_WAIT_MARGIN(ex, timeout, margin) \
- do { \
- bool res; \
- WAIT_(ex, timeout, res); \
- if (res) { \
- break; \
- } \
- LOG(LS_WARNING) << "Expression " << #ex << " still not true after " << \
- timeout << "ms; waiting an additional " << margin << "ms"; \
- WAIT_(ex, margin, res); \
- if (!res) { \
- EXPECT_TRUE(ex); \
- } \
- } while (0);
-
-#endif // TALK_BASE_GUNIT_H_
diff --git a/base/gunit_prod.h b/base/gunit_prod.h
deleted file mode 100644
index bf5e88a..0000000
--- a/base/gunit_prod.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_GUNIT_PROD_H_
-#define TALK_BASE_GUNIT_PROD_H_
-
-#if defined(ANDROID)
-// Android doesn't use gtest at all, so anything that relies on gtest should
-// check this define first.
-#define NO_GTEST
-#elif defined (GTEST_RELATIVE_PATH)
-#include "gtest/gtest_prod.h"
-#else
-#include "testing/base/gunit_prod.h"
-#endif
-
-#endif // TALK_BASE_GUNIT_PROD_H_
diff --git a/base/helpers.cc b/base/helpers.cc
deleted file mode 100644
index 691a813..0000000
--- a/base/helpers.cc
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/helpers.h"
-
-#include <limits>
-
-#if defined(FEATURE_ENABLE_SSL)
-#include "talk/base/sslconfig.h"
-#if defined(SSL_USE_OPENSSL)
-#include <openssl/rand.h>
-#elif defined(SSL_USE_NSS_RNG)
-#include "pk11func.h"
-#else
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <ntsecapi.h>
-#endif // WIN32
-#endif // else
-#endif // FEATURE_ENABLED_SSL
-
-#include "talk/base/base64.h"
-#include "talk/base/basictypes.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/timeutils.h"
-
-// Protect against max macro inclusion.
-#undef max
-
-namespace talk_base {
-
-// Base class for RNG implementations.
-class RandomGenerator {
- public:
- virtual ~RandomGenerator() {}
- virtual bool Init(const void* seed, size_t len) = 0;
- virtual bool Generate(void* buf, size_t len) = 0;
-};
-
-#if defined(SSL_USE_OPENSSL)
-// The OpenSSL RNG. Need to make sure it doesn't run out of entropy.
-class SecureRandomGenerator : public RandomGenerator {
- public:
- SecureRandomGenerator() : inited_(false) {
- }
- ~SecureRandomGenerator() {
- }
- virtual bool Init(const void* seed, size_t len) {
- // By default, seed from the system state.
- if (!inited_) {
- if (RAND_poll() <= 0) {
- return false;
- }
- inited_ = true;
- }
- // Allow app data to be mixed in, if provided.
- if (seed) {
- RAND_seed(seed, len);
- }
- return true;
- }
- virtual bool Generate(void* buf, size_t len) {
- if (!inited_ && !Init(NULL, 0)) {
- return false;
- }
- return (RAND_bytes(reinterpret_cast<unsigned char*>(buf), len) > 0);
- }
-
- private:
- bool inited_;
-};
-
-#elif defined(SSL_USE_NSS_RNG)
-// The NSS RNG.
-class SecureRandomGenerator : public RandomGenerator {
- public:
- SecureRandomGenerator() {}
- ~SecureRandomGenerator() {}
- virtual bool Init(const void* seed, size_t len) {
- return true;
- }
- virtual bool Generate(void* buf, size_t len) {
- return (PK11_GenerateRandom(reinterpret_cast<unsigned char*>(buf),
- static_cast<int>(len)) == SECSuccess);
- }
-};
-
-#else
-#ifdef WIN32
-class SecureRandomGenerator : public RandomGenerator {
- public:
- SecureRandomGenerator() : advapi32_(NULL), rtl_gen_random_(NULL) {}
- ~SecureRandomGenerator() {
- FreeLibrary(advapi32_);
- }
-
- virtual bool Init(const void* seed, size_t seed_len) {
- // We don't do any additional seeding on Win32, we just use the CryptoAPI
- // RNG (which is exposed as a hidden function off of ADVAPI32 so that we
- // don't need to drag in all of CryptoAPI)
- if (rtl_gen_random_) {
- return true;
- }
-
- advapi32_ = LoadLibrary(L"advapi32.dll");
- if (!advapi32_) {
- return false;
- }
-
- rtl_gen_random_ = reinterpret_cast<RtlGenRandomProc>(
- GetProcAddress(advapi32_, "SystemFunction036"));
- if (!rtl_gen_random_) {
- FreeLibrary(advapi32_);
- return false;
- }
-
- return true;
- }
- virtual bool Generate(void* buf, size_t len) {
- if (!rtl_gen_random_ && !Init(NULL, 0)) {
- return false;
- }
- return (rtl_gen_random_(buf, static_cast<int>(len)) != FALSE);
- }
-
- private:
- typedef BOOL (WINAPI *RtlGenRandomProc)(PVOID, ULONG);
- HINSTANCE advapi32_;
- RtlGenRandomProc rtl_gen_random_;
-};
-
-#elif !defined(FEATURE_ENABLE_SSL)
-
-// No SSL implementation -- use rand()
-class SecureRandomGenerator : public RandomGenerator {
- public:
- virtual bool Init(const void* seed, size_t len) {
- if (len >= 4) {
- srand(*reinterpret_cast<const int*>(seed));
- } else {
- srand(*reinterpret_cast<const char*>(seed));
- }
- return true;
- }
- virtual bool Generate(void* buf, size_t len) {
- char* bytes = reinterpret_cast<char*>(buf);
- for (size_t i = 0; i < len; ++i) {
- bytes[i] = static_cast<char>(rand());
- }
- return true;
- }
-};
-
-#else
-
-#error No SSL implementation has been selected!
-
-#endif // WIN32
-#endif
-
-// A test random generator, for predictable output.
-class TestRandomGenerator : public RandomGenerator {
- public:
- TestRandomGenerator() : seed_(7) {
- }
- ~TestRandomGenerator() {
- }
- virtual bool Init(const void* seed, size_t len) {
- return true;
- }
- virtual bool Generate(void* buf, size_t len) {
- for (size_t i = 0; i < len; ++i) {
- static_cast<uint8*>(buf)[i] = static_cast<uint8>(GetRandom());
- }
- return true;
- }
-
- private:
- int GetRandom() {
- return ((seed_ = seed_ * 214013L + 2531011L) >> 16) & 0x7fff;
- }
- int seed_;
-};
-
-// TODO: Use Base64::Base64Table instead.
-static const char BASE64[64] = {
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
- 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
- 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
-};
-
-namespace {
-
-// This round about way of creating a global RNG is to safe-guard against
-// indeterminant static initialization order.
-scoped_ptr<RandomGenerator>& GetGlobalRng() {
- LIBJINGLE_DEFINE_STATIC_LOCAL(scoped_ptr<RandomGenerator>, global_rng,
- (new SecureRandomGenerator()));
- return global_rng;
-}
-
-RandomGenerator& Rng() {
- return *GetGlobalRng();
-}
-
-} // namespace
-
-void SetRandomTestMode(bool test) {
- if (!test) {
- GetGlobalRng().reset(new SecureRandomGenerator());
- } else {
- GetGlobalRng().reset(new TestRandomGenerator());
- }
-}
-
-bool InitRandom(int seed) {
- return InitRandom(reinterpret_cast<const char*>(&seed), sizeof(seed));
-}
-
-bool InitRandom(const char* seed, size_t len) {
- if (!Rng().Init(seed, len)) {
- LOG(LS_ERROR) << "Failed to init random generator!";
- return false;
- }
- return true;
-}
-
-std::string CreateRandomString(size_t len) {
- std::string str;
- CreateRandomString(len, &str);
- return str;
-}
-
-bool CreateRandomString(size_t len,
- const char* table, int table_size,
- std::string* str) {
- str->clear();
- scoped_ptr<uint8[]> bytes(new uint8[len]);
- if (!Rng().Generate(bytes.get(), len)) {
- LOG(LS_ERROR) << "Failed to generate random string!";
- return false;
- }
- str->reserve(len);
- for (size_t i = 0; i < len; ++i) {
- str->push_back(table[bytes[i] % table_size]);
- }
- return true;
-}
-
-bool CreateRandomString(size_t len, std::string* str) {
- return CreateRandomString(len, BASE64, 64, str);
-}
-
-bool CreateRandomString(size_t len, const std::string& table,
- std::string* str) {
- return CreateRandomString(len, table.c_str(),
- static_cast<int>(table.size()), str);
-}
-
-uint32 CreateRandomId() {
- uint32 id;
- if (!Rng().Generate(&id, sizeof(id))) {
- LOG(LS_ERROR) << "Failed to generate random id!";
- }
- return id;
-}
-
-uint64 CreateRandomId64() {
- return static_cast<uint64>(CreateRandomId()) << 32 | CreateRandomId();
-}
-
-uint32 CreateRandomNonZeroId() {
- uint32 id;
- do {
- id = CreateRandomId();
- } while (id == 0);
- return id;
-}
-
-double CreateRandomDouble() {
- return CreateRandomId() / (std::numeric_limits<uint32>::max() +
- std::numeric_limits<double>::epsilon());
-}
-
-} // namespace talk_base
diff --git a/base/helpers.h b/base/helpers.h
deleted file mode 100644
index a297554..0000000
--- a/base/helpers.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_HELPERS_H_
-#define TALK_BASE_HELPERS_H_
-
-#include <string>
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-// For testing, we can return predictable data.
-void SetRandomTestMode(bool test);
-
-// Initializes the RNG, and seeds it with the specified entropy.
-bool InitRandom(int seed);
-bool InitRandom(const char* seed, size_t len);
-
-// Generates a (cryptographically) random string of the given length.
-// We generate base64 values so that they will be printable.
-// WARNING: could silently fail. Use the version below instead.
-std::string CreateRandomString(size_t length);
-
-// Generates a (cryptographically) random string of the given length.
-// We generate base64 values so that they will be printable.
-// Return false if the random number generator failed.
-bool CreateRandomString(size_t length, std::string* str);
-
-// Generates a (cryptographically) random string of the given length,
-// with characters from the given table. Return false if the random
-// number generator failed.
-bool CreateRandomString(size_t length, const std::string& table,
- std::string* str);
-
-// Generates a random id.
-uint32 CreateRandomId();
-
-// Generates a 64 bit random id.
-uint64 CreateRandomId64();
-
-// Generates a random id > 0.
-uint32 CreateRandomNonZeroId();
-
-// Generates a random double between 0.0 (inclusive) and 1.0 (exclusive).
-double CreateRandomDouble();
-
-} // namespace talk_base
-
-#endif // TALK_BASE_HELPERS_H_
diff --git a/base/helpers_unittest.cc b/base/helpers_unittest.cc
deleted file mode 100644
index c2cfdb1..0000000
--- a/base/helpers_unittest.cc
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/ssladapter.h"
-
-namespace talk_base {
-
-class RandomTest : public testing::Test {
- public:
- static void SetUpTestCase() {
- talk_base::InitializeSSL();
- }
-
- static void TearDownTestCase() {
- talk_base::CleanupSSL();
- }
-};
-
-TEST_F(RandomTest, TestCreateRandomId) {
- CreateRandomId();
-}
-
-TEST_F(RandomTest, TestCreateRandomDouble) {
- for (int i = 0; i < 100; ++i) {
- double r = CreateRandomDouble();
- EXPECT_GE(r, 0.0);
- EXPECT_LT(r, 1.0);
- }
-}
-
-TEST_F(RandomTest, TestCreateNonZeroRandomId) {
- EXPECT_NE(0U, CreateRandomNonZeroId());
-}
-
-TEST_F(RandomTest, TestCreateRandomString) {
- std::string random = CreateRandomString(256);
- EXPECT_EQ(256U, random.size());
- std::string random2;
- EXPECT_TRUE(CreateRandomString(256, &random2));
- EXPECT_NE(random, random2);
- EXPECT_EQ(256U, random2.size());
-}
-
-TEST_F(RandomTest, TestCreateRandomForTest) {
- // Make sure we get the output we expect.
- SetRandomTestMode(true);
- EXPECT_EQ(2154761789U, CreateRandomId());
- EXPECT_EQ("h0ISP4S5SJKH/9EY", CreateRandomString(16));
-
- // Reset and make sure we get the same output.
- SetRandomTestMode(true);
- EXPECT_EQ(2154761789U, CreateRandomId());
- EXPECT_EQ("h0ISP4S5SJKH/9EY", CreateRandomString(16));
-
- // Test different character sets.
- SetRandomTestMode(true);
- std::string str;
- EXPECT_TRUE(CreateRandomString(16, "a", &str));
- EXPECT_EQ("aaaaaaaaaaaaaaaa", str);
- EXPECT_TRUE(CreateRandomString(16, "abc", &str));
- EXPECT_EQ("acbccaaaabbaacbb", str);
-
- // Turn off test mode for other tests.
- SetRandomTestMode(false);
-}
-
-} // namespace talk_base
diff --git a/base/httpbase.cc b/base/httpbase.cc
deleted file mode 100644
index 7d54ab8..0000000
--- a/base/httpbase.cc
+++ /dev/null
@@ -1,897 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Copyright 2005 Google Inc. All Rights Reserved.
-//
-
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#else // !WIN32
-#define SEC_E_CERT_EXPIRED (-2146893016)
-#endif // !WIN32
-
-#include "talk/base/common.h"
-#include "talk/base/httpbase.h"
-#include "talk/base/logging.h"
-#include "talk/base/socket.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// Helpers
-//////////////////////////////////////////////////////////////////////
-
-bool MatchHeader(const char* str, size_t len, HttpHeader header) {
- const char* const header_str = ToString(header);
- const size_t header_len = strlen(header_str);
- return (len == header_len) && (_strnicmp(str, header_str, header_len) == 0);
-}
-
-enum {
- MSG_READ
-};
-
-//////////////////////////////////////////////////////////////////////
-// HttpParser
-//////////////////////////////////////////////////////////////////////
-
-HttpParser::HttpParser() {
- reset();
-}
-
-HttpParser::~HttpParser() {
-}
-
-void
-HttpParser::reset() {
- state_ = ST_LEADER;
- chunked_ = false;
- data_size_ = SIZE_UNKNOWN;
-}
-
-HttpParser::ProcessResult
-HttpParser::Process(const char* buffer, size_t len, size_t* processed,
- HttpError* error) {
- *processed = 0;
- *error = HE_NONE;
-
- if (state_ >= ST_COMPLETE) {
- ASSERT(false);
- return PR_COMPLETE;
- }
-
- while (true) {
- if (state_ < ST_DATA) {
- size_t pos = *processed;
- while ((pos < len) && (buffer[pos] != '\n')) {
- pos += 1;
- }
- if (pos >= len) {
- break; // don't have a full header
- }
- const char* line = buffer + *processed;
- size_t len = (pos - *processed);
- *processed = pos + 1;
- while ((len > 0) && isspace(static_cast<unsigned char>(line[len-1]))) {
- len -= 1;
- }
- ProcessResult result = ProcessLine(line, len, error);
- LOG(LS_VERBOSE) << "Processed line, result=" << result;
-
- if (PR_CONTINUE != result) {
- return result;
- }
- } else if (data_size_ == 0) {
- if (chunked_) {
- state_ = ST_CHUNKTERM;
- } else {
- return PR_COMPLETE;
- }
- } else {
- size_t available = len - *processed;
- if (available <= 0) {
- break; // no more data
- }
- if ((data_size_ != SIZE_UNKNOWN) && (available > data_size_)) {
- available = data_size_;
- }
- size_t read = 0;
- ProcessResult result = ProcessData(buffer + *processed, available, read,
- error);
- LOG(LS_VERBOSE) << "Processed data, result: " << result << " read: "
- << read << " err: " << error;
-
- if (PR_CONTINUE != result) {
- return result;
- }
- *processed += read;
- if (data_size_ != SIZE_UNKNOWN) {
- data_size_ -= read;
- }
- }
- }
-
- return PR_CONTINUE;
-}
-
-HttpParser::ProcessResult
-HttpParser::ProcessLine(const char* line, size_t len, HttpError* error) {
- LOG_F(LS_VERBOSE) << " state: " << state_ << " line: "
- << std::string(line, len) << " len: " << len << " err: "
- << error;
-
- switch (state_) {
- case ST_LEADER:
- state_ = ST_HEADERS;
- return ProcessLeader(line, len, error);
-
- case ST_HEADERS:
- if (len > 0) {
- const char* value = strchrn(line, len, ':');
- if (!value) {
- *error = HE_PROTOCOL;
- return PR_COMPLETE;
- }
- size_t nlen = (value - line);
- const char* eol = line + len;
- do {
- value += 1;
- } while ((value < eol) && isspace(static_cast<unsigned char>(*value)));
- size_t vlen = eol - value;
- if (MatchHeader(line, nlen, HH_CONTENT_LENGTH)) {
- // sscanf isn't safe with strings that aren't null-terminated, and there
- // is no guarantee that |value| is.
- // Create a local copy that is null-terminated.
- std::string value_str(value, vlen);
- unsigned int temp_size;
- if (sscanf(value_str.c_str(), "%u", &temp_size) != 1) {
- *error = HE_PROTOCOL;
- return PR_COMPLETE;
- }
- data_size_ = static_cast<size_t>(temp_size);
- } else if (MatchHeader(line, nlen, HH_TRANSFER_ENCODING)) {
- if ((vlen == 7) && (_strnicmp(value, "chunked", 7) == 0)) {
- chunked_ = true;
- } else if ((vlen == 8) && (_strnicmp(value, "identity", 8) == 0)) {
- chunked_ = false;
- } else {
- *error = HE_PROTOCOL;
- return PR_COMPLETE;
- }
- }
- return ProcessHeader(line, nlen, value, vlen, error);
- } else {
- state_ = chunked_ ? ST_CHUNKSIZE : ST_DATA;
- return ProcessHeaderComplete(chunked_, data_size_, error);
- }
- break;
-
- case ST_CHUNKSIZE:
- if (len > 0) {
- char* ptr = NULL;
- data_size_ = strtoul(line, &ptr, 16);
- if (ptr != line + len) {
- *error = HE_PROTOCOL;
- return PR_COMPLETE;
- }
- state_ = (data_size_ == 0) ? ST_TRAILERS : ST_DATA;
- } else {
- *error = HE_PROTOCOL;
- return PR_COMPLETE;
- }
- break;
-
- case ST_CHUNKTERM:
- if (len > 0) {
- *error = HE_PROTOCOL;
- return PR_COMPLETE;
- } else {
- state_ = chunked_ ? ST_CHUNKSIZE : ST_DATA;
- }
- break;
-
- case ST_TRAILERS:
- if (len == 0) {
- return PR_COMPLETE;
- }
- // *error = onHttpRecvTrailer();
- break;
-
- default:
- ASSERT(false);
- break;
- }
-
- return PR_CONTINUE;
-}
-
-bool
-HttpParser::is_valid_end_of_input() const {
- return (state_ == ST_DATA) && (data_size_ == SIZE_UNKNOWN);
-}
-
-void
-HttpParser::complete(HttpError error) {
- if (state_ < ST_COMPLETE) {
- state_ = ST_COMPLETE;
- OnComplete(error);
- }
-}
-
-//////////////////////////////////////////////////////////////////////
-// HttpBase::DocumentStream
-//////////////////////////////////////////////////////////////////////
-
-class BlockingMemoryStream : public ExternalMemoryStream {
-public:
- BlockingMemoryStream(char* buffer, size_t size)
- : ExternalMemoryStream(buffer, size) { }
-
- virtual StreamResult DoReserve(size_t size, int* error) {
- return (buffer_length_ >= size) ? SR_SUCCESS : SR_BLOCK;
- }
-};
-
-class HttpBase::DocumentStream : public StreamInterface {
-public:
- DocumentStream(HttpBase* base) : base_(base), error_(HE_DEFAULT) { }
-
- virtual StreamState GetState() const {
- if (NULL == base_)
- return SS_CLOSED;
- if (HM_RECV == base_->mode_)
- return SS_OPEN;
- return SS_OPENING;
- }
-
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- if (!base_) {
- if (error) *error = error_;
- return (HE_NONE == error_) ? SR_EOS : SR_ERROR;
- }
-
- if (HM_RECV != base_->mode_) {
- return SR_BLOCK;
- }
-
- // DoReceiveLoop writes http document data to the StreamInterface* document
- // member of HttpData. In this case, we want this data to be written
- // directly to our buffer. To accomplish this, we wrap our buffer with a
- // StreamInterface, and replace the existing document with our wrapper.
- // When the method returns, we restore the old document. Ideally, we would
- // pass our StreamInterface* to DoReceiveLoop, but due to the callbacks
- // of HttpParser, we would still need to store the pointer temporarily.
- scoped_ptr<StreamInterface>
- stream(new BlockingMemoryStream(reinterpret_cast<char*>(buffer),
- buffer_len));
-
- // Replace the existing document with our wrapped buffer.
- base_->data_->document.swap(stream);
-
- // Pump the I/O loop. DoReceiveLoop is guaranteed not to attempt to
- // complete the I/O process, which means that our wrapper is not in danger
- // of being deleted. To ensure this, DoReceiveLoop returns true when it
- // wants complete to be called. We make sure to uninstall our wrapper
- // before calling complete().
- HttpError http_error;
- bool complete = base_->DoReceiveLoop(&http_error);
-
- // Reinstall the original output document.
- base_->data_->document.swap(stream);
-
- // If we reach the end of the receive stream, we disconnect our stream
- // adapter from the HttpBase, and further calls to read will either return
- // EOS or ERROR, appropriately. Finally, we call complete().
- StreamResult result = SR_BLOCK;
- if (complete) {
- HttpBase* base = Disconnect(http_error);
- if (error) *error = error_;
- result = (HE_NONE == error_) ? SR_EOS : SR_ERROR;
- base->complete(http_error);
- }
-
- // Even if we are complete, if some data was read we must return SUCCESS.
- // Future Reads will return EOS or ERROR based on the error_ variable.
- size_t position;
- stream->GetPosition(&position);
- if (position > 0) {
- if (read) *read = position;
- result = SR_SUCCESS;
- }
- return result;
- }
-
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (error) *error = -1;
- return SR_ERROR;
- }
-
- virtual void Close() {
- if (base_) {
- HttpBase* base = Disconnect(HE_NONE);
- if (HM_RECV == base->mode_ && base->http_stream_) {
- // Read I/O could have been stalled on the user of this DocumentStream,
- // so restart the I/O process now that we've removed ourselves.
- base->http_stream_->PostEvent(SE_READ, 0);
- }
- }
- }
-
- virtual bool GetAvailable(size_t* size) const {
- if (!base_ || HM_RECV != base_->mode_)
- return false;
- size_t data_size = base_->GetDataRemaining();
- if (SIZE_UNKNOWN == data_size)
- return false;
- if (size)
- *size = data_size;
- return true;
- }
-
- HttpBase* Disconnect(HttpError error) {
- ASSERT(NULL != base_);
- ASSERT(NULL != base_->doc_stream_);
- HttpBase* base = base_;
- base_->doc_stream_ = NULL;
- base_ = NULL;
- error_ = error;
- return base;
- }
-
-private:
- HttpBase* base_;
- HttpError error_;
-};
-
-//////////////////////////////////////////////////////////////////////
-// HttpBase
-//////////////////////////////////////////////////////////////////////
-
-HttpBase::HttpBase() : mode_(HM_NONE), data_(NULL), notify_(NULL),
- http_stream_(NULL), doc_stream_(NULL) {
-}
-
-HttpBase::~HttpBase() {
- ASSERT(HM_NONE == mode_);
-}
-
-bool
-HttpBase::isConnected() const {
- return (http_stream_ != NULL) && (http_stream_->GetState() == SS_OPEN);
-}
-
-bool
-HttpBase::attach(StreamInterface* stream) {
- if ((mode_ != HM_NONE) || (http_stream_ != NULL) || (stream == NULL)) {
- ASSERT(false);
- return false;
- }
- http_stream_ = stream;
- http_stream_->SignalEvent.connect(this, &HttpBase::OnHttpStreamEvent);
- mode_ = (http_stream_->GetState() == SS_OPENING) ? HM_CONNECT : HM_NONE;
- return true;
-}
-
-StreamInterface*
-HttpBase::detach() {
- ASSERT(HM_NONE == mode_);
- if (mode_ != HM_NONE) {
- return NULL;
- }
- StreamInterface* stream = http_stream_;
- http_stream_ = NULL;
- if (stream) {
- stream->SignalEvent.disconnect(this);
- }
- return stream;
-}
-
-void
-HttpBase::send(HttpData* data) {
- ASSERT(HM_NONE == mode_);
- if (mode_ != HM_NONE) {
- return;
- } else if (!isConnected()) {
- OnHttpStreamEvent(http_stream_, SE_CLOSE, HE_DISCONNECTED);
- return;
- }
-
- mode_ = HM_SEND;
- data_ = data;
- len_ = 0;
- ignore_data_ = chunk_data_ = false;
-
- if (data_->document) {
- data_->document->SignalEvent.connect(this, &HttpBase::OnDocumentEvent);
- }
-
- std::string encoding;
- if (data_->hasHeader(HH_TRANSFER_ENCODING, &encoding)
- && (encoding == "chunked")) {
- chunk_data_ = true;
- }
-
- len_ = data_->formatLeader(buffer_, sizeof(buffer_));
- len_ += strcpyn(buffer_ + len_, sizeof(buffer_) - len_, "\r\n");
-
- header_ = data_->begin();
- if (header_ == data_->end()) {
- // We must call this at least once, in the case where there are no headers.
- queue_headers();
- }
-
- flush_data();
-}
-
-void
-HttpBase::recv(HttpData* data) {
- ASSERT(HM_NONE == mode_);
- if (mode_ != HM_NONE) {
- return;
- } else if (!isConnected()) {
- OnHttpStreamEvent(http_stream_, SE_CLOSE, HE_DISCONNECTED);
- return;
- }
-
- mode_ = HM_RECV;
- data_ = data;
- len_ = 0;
- ignore_data_ = chunk_data_ = false;
-
- reset();
- if (doc_stream_) {
- doc_stream_->SignalEvent(doc_stream_, SE_OPEN | SE_READ, 0);
- } else {
- read_and_process_data();
- }
-}
-
-void
-HttpBase::abort(HttpError err) {
- if (mode_ != HM_NONE) {
- if (http_stream_ != NULL) {
- http_stream_->Close();
- }
- do_complete(err);
- }
-}
-
-StreamInterface* HttpBase::GetDocumentStream() {
- if (doc_stream_)
- return NULL;
- doc_stream_ = new DocumentStream(this);
- return doc_stream_;
-}
-
-HttpError HttpBase::HandleStreamClose(int error) {
- if (http_stream_ != NULL) {
- http_stream_->Close();
- }
- if (error == 0) {
- if ((mode_ == HM_RECV) && is_valid_end_of_input()) {
- return HE_NONE;
- } else {
- return HE_DISCONNECTED;
- }
- } else if (error == SOCKET_EACCES) {
- return HE_AUTH;
- } else if (error == SEC_E_CERT_EXPIRED) {
- return HE_CERTIFICATE_EXPIRED;
- }
- LOG_F(LS_ERROR) << "(" << error << ")";
- return (HM_CONNECT == mode_) ? HE_CONNECT_FAILED : HE_SOCKET_ERROR;
-}
-
-bool HttpBase::DoReceiveLoop(HttpError* error) {
- ASSERT(HM_RECV == mode_);
- ASSERT(NULL != error);
-
- // Do to the latency between receiving read notifications from
- // pseudotcpchannel, we rely on repeated calls to read in order to acheive
- // ideal throughput. The number of reads is limited to prevent starving
- // the caller.
-
- size_t loop_count = 0;
- const size_t kMaxReadCount = 20;
- bool process_requires_more_data = false;
- do {
- // The most frequent use of this function is response to new data available
- // on http_stream_. Therefore, we optimize by attempting to read from the
- // network first (as opposed to processing existing data first).
-
- if (len_ < sizeof(buffer_)) {
- // Attempt to buffer more data.
- size_t read;
- int read_error;
- StreamResult read_result = http_stream_->Read(buffer_ + len_,
- sizeof(buffer_) - len_,
- &read, &read_error);
- switch (read_result) {
- case SR_SUCCESS:
- ASSERT(len_ + read <= sizeof(buffer_));
- len_ += read;
- break;
- case SR_BLOCK:
- if (process_requires_more_data) {
- // We're can't make progress until more data is available.
- return false;
- }
- // Attempt to process the data already in our buffer.
- break;
- case SR_EOS:
- // Clean close, with no error. Fall through to HandleStreamClose.
- read_error = 0;
- case SR_ERROR:
- *error = HandleStreamClose(read_error);
- return true;
- }
- } else if (process_requires_more_data) {
- // We have too much unprocessed data in our buffer. This should only
- // occur when a single HTTP header is longer than the buffer size (32K).
- // Anything longer than that is almost certainly an error.
- *error = HE_OVERFLOW;
- return true;
- }
-
- // Process data in our buffer. Process is not guaranteed to process all
- // the buffered data. In particular, it will wait until a complete
- // protocol element (such as http header, or chunk size) is available,
- // before processing it in its entirety. Also, it is valid and sometimes
- // necessary to call Process with an empty buffer, since the state machine
- // may have interrupted state transitions to complete.
- size_t processed;
- ProcessResult process_result = Process(buffer_, len_, &processed,
- error);
- ASSERT(processed <= len_);
- len_ -= processed;
- memmove(buffer_, buffer_ + processed, len_);
- switch (process_result) {
- case PR_CONTINUE:
- // We need more data to make progress.
- process_requires_more_data = true;
- break;
- case PR_BLOCK:
- // We're stalled on writing the processed data.
- return false;
- case PR_COMPLETE:
- // *error already contains the correct code.
- return true;
- }
- } while (++loop_count <= kMaxReadCount);
-
- LOG_F(LS_WARNING) << "danger of starvation";
- return false;
-}
-
-void
-HttpBase::read_and_process_data() {
- HttpError error;
- if (DoReceiveLoop(&error)) {
- complete(error);
- }
-}
-
-void
-HttpBase::flush_data() {
- ASSERT(HM_SEND == mode_);
-
- // When send_required is true, no more buffering can occur without a network
- // write.
- bool send_required = (len_ >= sizeof(buffer_));
-
- while (true) {
- ASSERT(len_ <= sizeof(buffer_));
-
- // HTTP is inherently sensitive to round trip latency, since a frequent use
- // case is for small requests and responses to be sent back and forth, and
- // the lack of pipelining forces a single request to take a minimum of the
- // round trip time. As a result, it is to our benefit to pack as much data
- // into each packet as possible. Thus, we defer network writes until we've
- // buffered as much data as possible.
-
- if (!send_required && (header_ != data_->end())) {
- // First, attempt to queue more header data.
- send_required = queue_headers();
- }
-
- if (!send_required && data_->document) {
- // Next, attempt to queue document data.
-
- const size_t kChunkDigits = 8;
- size_t offset, reserve;
- if (chunk_data_) {
- // Reserve characters at the start for X-byte hex value and \r\n
- offset = len_ + kChunkDigits + 2;
- // ... and 2 characters at the end for \r\n
- reserve = offset + 2;
- } else {
- offset = len_;
- reserve = offset;
- }
-
- if (reserve >= sizeof(buffer_)) {
- send_required = true;
- } else {
- size_t read;
- int error;
- StreamResult result = data_->document->Read(buffer_ + offset,
- sizeof(buffer_) - reserve,
- &read, &error);
- if (result == SR_SUCCESS) {
- ASSERT(reserve + read <= sizeof(buffer_));
- if (chunk_data_) {
- // Prepend the chunk length in hex.
- // Note: sprintfn appends a null terminator, which is why we can't
- // combine it with the line terminator.
- sprintfn(buffer_ + len_, kChunkDigits + 1, "%.*x",
- kChunkDigits, read);
- // Add line terminator to the chunk length.
- memcpy(buffer_ + len_ + kChunkDigits, "\r\n", 2);
- // Add line terminator to the end of the chunk.
- memcpy(buffer_ + offset + read, "\r\n", 2);
- }
- len_ = reserve + read;
- } else if (result == SR_BLOCK) {
- // Nothing to do but flush data to the network.
- send_required = true;
- } else if (result == SR_EOS) {
- if (chunk_data_) {
- // Append the empty chunk and empty trailers, then turn off
- // chunking.
- ASSERT(len_ + 5 <= sizeof(buffer_));
- memcpy(buffer_ + len_, "0\r\n\r\n", 5);
- len_ += 5;
- chunk_data_ = false;
- } else if (0 == len_) {
- // No more data to read, and no more data to write.
- do_complete();
- return;
- }
- // Although we are done reading data, there is still data which needs
- // to be flushed to the network.
- send_required = true;
- } else {
- LOG_F(LS_ERROR) << "Read error: " << error;
- do_complete(HE_STREAM);
- return;
- }
- }
- }
-
- if (0 == len_) {
- // No data currently available to send.
- if (!data_->document) {
- // If there is no source document, that means we're done.
- do_complete();
- }
- return;
- }
-
- size_t written;
- int error;
- StreamResult result = http_stream_->Write(buffer_, len_, &written, &error);
- if (result == SR_SUCCESS) {
- ASSERT(written <= len_);
- len_ -= written;
- memmove(buffer_, buffer_ + written, len_);
- send_required = false;
- } else if (result == SR_BLOCK) {
- if (send_required) {
- // Nothing more we can do until network is writeable.
- return;
- }
- } else {
- ASSERT(result == SR_ERROR);
- LOG_F(LS_ERROR) << "error";
- OnHttpStreamEvent(http_stream_, SE_CLOSE, error);
- return;
- }
- }
-
- ASSERT(false);
-}
-
-bool
-HttpBase::queue_headers() {
- ASSERT(HM_SEND == mode_);
- while (header_ != data_->end()) {
- size_t len = sprintfn(buffer_ + len_, sizeof(buffer_) - len_,
- "%.*s: %.*s\r\n",
- header_->first.size(), header_->first.data(),
- header_->second.size(), header_->second.data());
- if (len_ + len < sizeof(buffer_) - 3) {
- len_ += len;
- ++header_;
- } else if (len_ == 0) {
- LOG(WARNING) << "discarding header that is too long: " << header_->first;
- ++header_;
- } else {
- // Not enough room for the next header, write to network first.
- return true;
- }
- }
- // End of headers
- len_ += strcpyn(buffer_ + len_, sizeof(buffer_) - len_, "\r\n");
- return false;
-}
-
-void
-HttpBase::do_complete(HttpError err) {
- ASSERT(mode_ != HM_NONE);
- HttpMode mode = mode_;
- mode_ = HM_NONE;
- if (data_ && data_->document) {
- data_->document->SignalEvent.disconnect(this);
- }
- data_ = NULL;
- if ((HM_RECV == mode) && doc_stream_) {
- ASSERT(HE_NONE != err); // We should have Disconnected doc_stream_ already.
- DocumentStream* ds = doc_stream_;
- ds->Disconnect(err);
- ds->SignalEvent(ds, SE_CLOSE, err);
- }
- if (notify_) {
- notify_->onHttpComplete(mode, err);
- }
-}
-
-//
-// Stream Signals
-//
-
-void
-HttpBase::OnHttpStreamEvent(StreamInterface* stream, int events, int error) {
- ASSERT(stream == http_stream_);
- if ((events & SE_OPEN) && (mode_ == HM_CONNECT)) {
- do_complete();
- return;
- }
-
- if ((events & SE_WRITE) && (mode_ == HM_SEND)) {
- flush_data();
- return;
- }
-
- if ((events & SE_READ) && (mode_ == HM_RECV)) {
- if (doc_stream_) {
- doc_stream_->SignalEvent(doc_stream_, SE_READ, 0);
- } else {
- read_and_process_data();
- }
- return;
- }
-
- if ((events & SE_CLOSE) == 0)
- return;
-
- HttpError http_error = HandleStreamClose(error);
- if (mode_ == HM_RECV) {
- complete(http_error);
- } else if (mode_ != HM_NONE) {
- do_complete(http_error);
- } else if (notify_) {
- notify_->onHttpClosed(http_error);
- }
-}
-
-void
-HttpBase::OnDocumentEvent(StreamInterface* stream, int events, int error) {
- ASSERT(stream == data_->document.get());
- if ((events & SE_WRITE) && (mode_ == HM_RECV)) {
- read_and_process_data();
- return;
- }
-
- if ((events & SE_READ) && (mode_ == HM_SEND)) {
- flush_data();
- return;
- }
-
- if (events & SE_CLOSE) {
- LOG_F(LS_ERROR) << "Read error: " << error;
- do_complete(HE_STREAM);
- return;
- }
-}
-
-//
-// HttpParser Implementation
-//
-
-HttpParser::ProcessResult
-HttpBase::ProcessLeader(const char* line, size_t len, HttpError* error) {
- *error = data_->parseLeader(line, len);
- return (HE_NONE == *error) ? PR_CONTINUE : PR_COMPLETE;
-}
-
-HttpParser::ProcessResult
-HttpBase::ProcessHeader(const char* name, size_t nlen, const char* value,
- size_t vlen, HttpError* error) {
- std::string sname(name, nlen), svalue(value, vlen);
- data_->addHeader(sname, svalue);
- return PR_CONTINUE;
-}
-
-HttpParser::ProcessResult
-HttpBase::ProcessHeaderComplete(bool chunked, size_t& data_size,
- HttpError* error) {
- StreamInterface* old_docstream = doc_stream_;
- if (notify_) {
- *error = notify_->onHttpHeaderComplete(chunked, data_size);
- // The request must not be aborted as a result of this callback.
- ASSERT(NULL != data_);
- }
- if ((HE_NONE == *error) && data_->document) {
- data_->document->SignalEvent.connect(this, &HttpBase::OnDocumentEvent);
- }
- if (HE_NONE != *error) {
- return PR_COMPLETE;
- }
- if (old_docstream != doc_stream_) {
- // Break out of Process loop, since our I/O model just changed.
- return PR_BLOCK;
- }
- return PR_CONTINUE;
-}
-
-HttpParser::ProcessResult
-HttpBase::ProcessData(const char* data, size_t len, size_t& read,
- HttpError* error) {
- if (ignore_data_ || !data_->document) {
- read = len;
- return PR_CONTINUE;
- }
- int write_error = 0;
- switch (data_->document->Write(data, len, &read, &write_error)) {
- case SR_SUCCESS:
- return PR_CONTINUE;
- case SR_BLOCK:
- return PR_BLOCK;
- case SR_EOS:
- LOG_F(LS_ERROR) << "Unexpected EOS";
- *error = HE_STREAM;
- return PR_COMPLETE;
- case SR_ERROR:
- default:
- LOG_F(LS_ERROR) << "Write error: " << write_error;
- *error = HE_STREAM;
- return PR_COMPLETE;
- }
-}
-
-void
-HttpBase::OnComplete(HttpError err) {
- LOG_F(LS_VERBOSE);
- do_complete(err);
-}
-
-} // namespace talk_base
diff --git a/base/httpbase.h b/base/httpbase.h
deleted file mode 100644
index 97527eb..0000000
--- a/base/httpbase.h
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Copyright 2005 Google Inc. All Rights Reserved.
-//
-
-
-#ifndef TALK_BASE_HTTPBASE_H__
-#define TALK_BASE_HTTPBASE_H__
-
-#include "talk/base/httpcommon.h"
-
-namespace talk_base {
-
-class StreamInterface;
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpParser - Parses an HTTP stream provided via Process and end_of_input, and
-// generates events for:
-// Structural Elements: Leader, Headers, Document Data
-// Events: End of Headers, End of Document, Errors
-///////////////////////////////////////////////////////////////////////////////
-
-class HttpParser {
-public:
- enum ProcessResult { PR_CONTINUE, PR_BLOCK, PR_COMPLETE };
- HttpParser();
- virtual ~HttpParser();
-
- void reset();
- ProcessResult Process(const char* buffer, size_t len, size_t* processed,
- HttpError* error);
- bool is_valid_end_of_input() const;
- void complete(HttpError err);
-
- size_t GetDataRemaining() const { return data_size_; }
-
-protected:
- ProcessResult ProcessLine(const char* line, size_t len, HttpError* error);
-
- // HttpParser Interface
- virtual ProcessResult ProcessLeader(const char* line, size_t len,
- HttpError* error) = 0;
- virtual ProcessResult ProcessHeader(const char* name, size_t nlen,
- const char* value, size_t vlen,
- HttpError* error) = 0;
- virtual ProcessResult ProcessHeaderComplete(bool chunked, size_t& data_size,
- HttpError* error) = 0;
- virtual ProcessResult ProcessData(const char* data, size_t len, size_t& read,
- HttpError* error) = 0;
- virtual void OnComplete(HttpError err) = 0;
-
-private:
- enum State {
- ST_LEADER, ST_HEADERS,
- ST_CHUNKSIZE, ST_CHUNKTERM, ST_TRAILERS,
- ST_DATA, ST_COMPLETE
- } state_;
- bool chunked_;
- size_t data_size_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// IHttpNotify
-///////////////////////////////////////////////////////////////////////////////
-
-enum HttpMode { HM_NONE, HM_CONNECT, HM_RECV, HM_SEND };
-
-class IHttpNotify {
-public:
- virtual ~IHttpNotify() {}
- virtual HttpError onHttpHeaderComplete(bool chunked, size_t& data_size) = 0;
- virtual void onHttpComplete(HttpMode mode, HttpError err) = 0;
- virtual void onHttpClosed(HttpError err) = 0;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpBase - Provides a state machine for implementing HTTP-based components.
-// Attach HttpBase to a StreamInterface which represents a bidirectional HTTP
-// stream, and then call send() or recv() to initiate sending or receiving one
-// side of an HTTP transaction. By default, HttpBase operates as an I/O pump,
-// moving data from the HTTP stream to the HttpData object and vice versa.
-// However, it can also operate in stream mode, in which case the user of the
-// stream interface drives I/O via calls to Read().
-///////////////////////////////////////////////////////////////////////////////
-
-class HttpBase
-: private HttpParser,
- public sigslot::has_slots<>
-{
-public:
- HttpBase();
- virtual ~HttpBase();
-
- void notify(IHttpNotify* notify) { notify_ = notify; }
- bool attach(StreamInterface* stream);
- StreamInterface* stream() { return http_stream_; }
- StreamInterface* detach();
- bool isConnected() const;
-
- void send(HttpData* data);
- void recv(HttpData* data);
- void abort(HttpError err);
-
- HttpMode mode() const { return mode_; }
-
- void set_ignore_data(bool ignore) { ignore_data_ = ignore; }
- bool ignore_data() const { return ignore_data_; }
-
- // Obtaining this stream puts HttpBase into stream mode until the stream
- // is closed. HttpBase can only expose one open stream interface at a time.
- // Further calls will return NULL.
- StreamInterface* GetDocumentStream();
-
-protected:
- // Do cleanup when the http stream closes (error may be 0 for a clean
- // shutdown), and return the error code to signal.
- HttpError HandleStreamClose(int error);
-
- // DoReceiveLoop acts as a data pump, pulling data from the http stream,
- // pushing it through the HttpParser, and then populating the HttpData object
- // based on the callbacks from the parser. One of the most interesting
- // callbacks is ProcessData, which provides the actual http document body.
- // This data is then written to the HttpData::document. As a result, data
- // flows from the network to the document, with some incidental protocol
- // parsing in between.
- // Ideally, we would pass in the document* to DoReceiveLoop, to more easily
- // support GetDocumentStream(). However, since the HttpParser is callback
- // driven, we are forced to store the pointer somewhere until the callback
- // is triggered.
- // Returns true if the received document has finished, and
- // HttpParser::complete should be called.
- bool DoReceiveLoop(HttpError* err);
-
- void read_and_process_data();
- void flush_data();
- bool queue_headers();
- void do_complete(HttpError err = HE_NONE);
-
- void OnHttpStreamEvent(StreamInterface* stream, int events, int error);
- void OnDocumentEvent(StreamInterface* stream, int events, int error);
-
- // HttpParser Interface
- virtual ProcessResult ProcessLeader(const char* line, size_t len,
- HttpError* error);
- virtual ProcessResult ProcessHeader(const char* name, size_t nlen,
- const char* value, size_t vlen,
- HttpError* error);
- virtual ProcessResult ProcessHeaderComplete(bool chunked, size_t& data_size,
- HttpError* error);
- virtual ProcessResult ProcessData(const char* data, size_t len, size_t& read,
- HttpError* error);
- virtual void OnComplete(HttpError err);
-
-private:
- class DocumentStream;
- friend class DocumentStream;
-
- enum { kBufferSize = 32 * 1024 };
-
- HttpMode mode_;
- HttpData* data_;
- IHttpNotify* notify_;
- StreamInterface* http_stream_;
- DocumentStream* doc_stream_;
- char buffer_[kBufferSize];
- size_t len_;
-
- bool ignore_data_, chunk_data_;
- HttpData::const_iterator header_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_HTTPBASE_H__
diff --git a/base/httpbase_unittest.cc b/base/httpbase_unittest.cc
deleted file mode 100644
index bd1796d..0000000
--- a/base/httpbase_unittest.cc
+++ /dev/null
@@ -1,537 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/httpbase.h"
-#include "talk/base/testutils.h"
-
-namespace talk_base {
-
-const char* const kHttpResponse =
- "HTTP/1.1 200\r\n"
- "Connection: Keep-Alive\r\n"
- "Content-Type: text/plain\r\n"
- "Proxy-Authorization: 42\r\n"
- "Transfer-Encoding: chunked\r\n"
- "\r\n"
- "00000008\r\n"
- "Goodbye!\r\n"
- "0\r\n\r\n";
-
-const char* const kHttpEmptyResponse =
- "HTTP/1.1 200\r\n"
- "Connection: Keep-Alive\r\n"
- "Content-Length: 0\r\n"
- "Proxy-Authorization: 42\r\n"
- "\r\n";
-
-const char* const kHttpResponsePrefix =
- "HTTP/1.1 200\r\n"
- "Connection: Keep-Alive\r\n"
- "Content-Type: text/plain\r\n"
- "Proxy-Authorization: 42\r\n"
- "Transfer-Encoding: chunked\r\n"
- "\r\n"
- "8\r\n"
- "Goodbye!\r\n";
-
-class HttpBaseTest : public testing::Test, public IHttpNotify {
-public:
- enum EventType { E_HEADER_COMPLETE, E_COMPLETE, E_CLOSED };
- struct Event {
- EventType event;
- bool chunked;
- size_t data_size;
- HttpMode mode;
- HttpError err;
- };
- HttpBaseTest() : mem(NULL), obtain_stream(false), http_stream(NULL) { }
-
- virtual void SetUp() { }
- virtual void TearDown() {
- delete http_stream;
- // Avoid an ASSERT, in case a test doesn't clean up properly
- base.abort(HE_NONE);
- }
-
- virtual HttpError onHttpHeaderComplete(bool chunked, size_t& data_size) {
- LOG_F(LS_VERBOSE) << "chunked: " << chunked << " size: " << data_size;
- Event e = { E_HEADER_COMPLETE, chunked, data_size, HM_NONE, HE_NONE};
- events.push_back(e);
- if (obtain_stream) {
- ObtainDocumentStream();
- }
- return HE_NONE;
- }
- virtual void onHttpComplete(HttpMode mode, HttpError err) {
- LOG_F(LS_VERBOSE) << "mode: " << mode << " err: " << err;
- Event e = { E_COMPLETE, false, 0, mode, err };
- events.push_back(e);
- }
- virtual void onHttpClosed(HttpError err) {
- LOG_F(LS_VERBOSE) << "err: " << err;
- Event e = { E_CLOSED, false, 0, HM_NONE, err };
- events.push_back(e);
- }
-
- void SetupSource(const char* response);
-
- void VerifyHeaderComplete(size_t event_count, bool empty_doc);
- void VerifyDocumentContents(const char* expected_data,
- size_t expected_length = SIZE_UNKNOWN);
-
- void ObtainDocumentStream();
- void VerifyDocumentStreamIsOpening();
- void VerifyDocumentStreamOpenEvent();
- void ReadDocumentStreamData(const char* expected_data);
- void VerifyDocumentStreamIsEOS();
-
- void SetupDocument(const char* response);
- void VerifySourceContents(const char* expected_data,
- size_t expected_length = SIZE_UNKNOWN);
-
- void VerifyTransferComplete(HttpMode mode, HttpError error);
-
- HttpBase base;
- MemoryStream* mem;
- HttpResponseData data;
-
- // The source of http data, and source events
- testing::StreamSource src;
- std::vector<Event> events;
-
- // Document stream, and stream events
- bool obtain_stream;
- StreamInterface* http_stream;
- testing::StreamSink sink;
-};
-
-void HttpBaseTest::SetupSource(const char* http_data) {
- LOG_F(LS_VERBOSE) << "Enter";
-
- src.SetState(SS_OPENING);
- src.QueueString(http_data);
-
- base.notify(this);
- base.attach(&src);
- EXPECT_TRUE(events.empty());
-
- src.SetState(SS_OPEN);
- ASSERT_EQ(1U, events.size());
- EXPECT_EQ(E_COMPLETE, events[0].event);
- EXPECT_EQ(HM_CONNECT, events[0].mode);
- EXPECT_EQ(HE_NONE, events[0].err);
- events.clear();
-
- mem = new MemoryStream;
- data.document.reset(mem);
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::VerifyHeaderComplete(size_t event_count, bool empty_doc) {
- LOG_F(LS_VERBOSE) << "Enter";
-
- ASSERT_EQ(event_count, events.size());
- EXPECT_EQ(E_HEADER_COMPLETE, events[0].event);
-
- std::string header;
- EXPECT_EQ(HVER_1_1, data.version);
- EXPECT_EQ(static_cast<uint32>(HC_OK), data.scode);
- EXPECT_TRUE(data.hasHeader(HH_PROXY_AUTHORIZATION, &header));
- EXPECT_EQ("42", header);
- EXPECT_TRUE(data.hasHeader(HH_CONNECTION, &header));
- EXPECT_EQ("Keep-Alive", header);
-
- if (empty_doc) {
- EXPECT_FALSE(events[0].chunked);
- EXPECT_EQ(0U, events[0].data_size);
-
- EXPECT_TRUE(data.hasHeader(HH_CONTENT_LENGTH, &header));
- EXPECT_EQ("0", header);
- } else {
- EXPECT_TRUE(events[0].chunked);
- EXPECT_EQ(SIZE_UNKNOWN, events[0].data_size);
-
- EXPECT_TRUE(data.hasHeader(HH_CONTENT_TYPE, &header));
- EXPECT_EQ("text/plain", header);
- EXPECT_TRUE(data.hasHeader(HH_TRANSFER_ENCODING, &header));
- EXPECT_EQ("chunked", header);
- }
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::VerifyDocumentContents(const char* expected_data,
- size_t expected_length) {
- LOG_F(LS_VERBOSE) << "Enter";
-
- if (SIZE_UNKNOWN == expected_length) {
- expected_length = strlen(expected_data);
- }
- EXPECT_EQ(mem, data.document.get());
-
- size_t length;
- mem->GetSize(&length);
- EXPECT_EQ(expected_length, length);
- EXPECT_TRUE(0 == memcmp(expected_data, mem->GetBuffer(), length));
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::ObtainDocumentStream() {
- LOG_F(LS_VERBOSE) << "Enter";
- EXPECT_FALSE(http_stream);
- http_stream = base.GetDocumentStream();
- ASSERT_TRUE(NULL != http_stream);
- sink.Monitor(http_stream);
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::VerifyDocumentStreamIsOpening() {
- LOG_F(LS_VERBOSE) << "Enter";
- ASSERT_TRUE(NULL != http_stream);
- EXPECT_EQ(0, sink.Events(http_stream));
- EXPECT_EQ(SS_OPENING, http_stream->GetState());
-
- size_t read = 0;
- char buffer[5] = { 0 };
- EXPECT_EQ(SR_BLOCK, http_stream->Read(buffer, sizeof(buffer), &read, NULL));
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::VerifyDocumentStreamOpenEvent() {
- LOG_F(LS_VERBOSE) << "Enter";
-
- ASSERT_TRUE(NULL != http_stream);
- EXPECT_EQ(SE_OPEN | SE_READ, sink.Events(http_stream));
- EXPECT_EQ(SS_OPEN, http_stream->GetState());
-
- // HTTP headers haven't arrived yet
- EXPECT_EQ(0U, events.size());
- EXPECT_EQ(static_cast<uint32>(HC_INTERNAL_SERVER_ERROR), data.scode);
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::ReadDocumentStreamData(const char* expected_data) {
- LOG_F(LS_VERBOSE) << "Enter";
-
- ASSERT_TRUE(NULL != http_stream);
- EXPECT_EQ(SS_OPEN, http_stream->GetState());
-
- // Pump the HTTP I/O using Read, and verify the results.
- size_t verified_length = 0;
- const size_t expected_length = strlen(expected_data);
- while (verified_length < expected_length) {
- size_t read = 0;
- char buffer[5] = { 0 };
- size_t amt_to_read = _min(expected_length - verified_length, sizeof(buffer));
- EXPECT_EQ(SR_SUCCESS, http_stream->Read(buffer, amt_to_read, &read, NULL));
- EXPECT_EQ(amt_to_read, read);
- EXPECT_TRUE(0 == memcmp(expected_data + verified_length, buffer, read));
- verified_length += read;
- }
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::VerifyDocumentStreamIsEOS() {
- LOG_F(LS_VERBOSE) << "Enter";
-
- ASSERT_TRUE(NULL != http_stream);
- size_t read = 0;
- char buffer[5] = { 0 };
- EXPECT_EQ(SR_EOS, http_stream->Read(buffer, sizeof(buffer), &read, NULL));
- EXPECT_EQ(SS_CLOSED, http_stream->GetState());
-
- // When EOS is caused by Read, we don't expect SE_CLOSE
- EXPECT_EQ(0, sink.Events(http_stream));
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::SetupDocument(const char* document_data) {
- LOG_F(LS_VERBOSE) << "Enter";
- src.SetState(SS_OPEN);
-
- base.notify(this);
- base.attach(&src);
- EXPECT_TRUE(events.empty());
-
- if (document_data) {
- // Note: we could just call data.set_success("text/plain", mem), but that
- // won't allow us to use the chunked transfer encoding.
- mem = new MemoryStream(document_data);
- data.document.reset(mem);
- data.setHeader(HH_CONTENT_TYPE, "text/plain");
- data.setHeader(HH_TRANSFER_ENCODING, "chunked");
- } else {
- data.setHeader(HH_CONTENT_LENGTH, "0");
- }
- data.scode = HC_OK;
- data.setHeader(HH_PROXY_AUTHORIZATION, "42");
- data.setHeader(HH_CONNECTION, "Keep-Alive");
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::VerifySourceContents(const char* expected_data,
- size_t expected_length) {
- LOG_F(LS_VERBOSE) << "Enter";
- if (SIZE_UNKNOWN == expected_length) {
- expected_length = strlen(expected_data);
- }
- std::string contents = src.ReadData();
- EXPECT_EQ(expected_length, contents.length());
- EXPECT_TRUE(0 == memcmp(expected_data, contents.data(), expected_length));
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-void HttpBaseTest::VerifyTransferComplete(HttpMode mode, HttpError error) {
- LOG_F(LS_VERBOSE) << "Enter";
- // Verify that http operation has completed
- ASSERT_TRUE(events.size() > 0);
- size_t last_event = events.size() - 1;
- EXPECT_EQ(E_COMPLETE, events[last_event].event);
- EXPECT_EQ(mode, events[last_event].mode);
- EXPECT_EQ(error, events[last_event].err);
- LOG_F(LS_VERBOSE) << "Exit";
-}
-
-//
-// Tests
-//
-
-TEST_F(HttpBaseTest, SupportsSend) {
- // Queue response document
- SetupDocument("Goodbye!");
-
- // Begin send
- base.send(&data);
-
- // Send completed successfully
- VerifyTransferComplete(HM_SEND, HE_NONE);
- VerifySourceContents(kHttpResponse);
-}
-
-TEST_F(HttpBaseTest, SupportsSendNoDocument) {
- // Queue response document
- SetupDocument(NULL);
-
- // Begin send
- base.send(&data);
-
- // Send completed successfully
- VerifyTransferComplete(HM_SEND, HE_NONE);
- VerifySourceContents(kHttpEmptyResponse);
-}
-
-TEST_F(HttpBaseTest, SignalsCompleteOnInterruptedSend) {
- // This test is attempting to expose a bug that occurs when a particular
- // base objects is used for receiving, and then used for sending. In
- // particular, the HttpParser state is different after receiving. Simulate
- // that here.
- SetupSource(kHttpResponse);
- base.recv(&data);
- VerifyTransferComplete(HM_RECV, HE_NONE);
-
- src.Clear();
- data.clear(true);
- events.clear();
- base.detach();
-
- // Queue response document
- SetupDocument("Goodbye!");
-
- // Prevent entire response from being sent
- const size_t kInterruptedLength = strlen(kHttpResponse) - 1;
- src.SetWriteBlock(kInterruptedLength);
-
- // Begin send
- base.send(&data);
-
- // Document is mostly complete, but no completion signal yet.
- EXPECT_TRUE(events.empty());
- VerifySourceContents(kHttpResponse, kInterruptedLength);
-
- src.SetState(SS_CLOSED);
-
- // Send completed with disconnect error, and no additional data.
- VerifyTransferComplete(HM_SEND, HE_DISCONNECTED);
- EXPECT_TRUE(src.ReadData().empty());
-}
-
-TEST_F(HttpBaseTest, SupportsReceiveViaDocumentPush) {
- // Queue response document
- SetupSource(kHttpResponse);
-
- // Begin receive
- base.recv(&data);
-
- // Document completed successfully
- VerifyHeaderComplete(2, false);
- VerifyTransferComplete(HM_RECV, HE_NONE);
- VerifyDocumentContents("Goodbye!");
-}
-
-TEST_F(HttpBaseTest, SupportsReceiveViaStreamPull) {
- // Switch to pull mode
- ObtainDocumentStream();
- VerifyDocumentStreamIsOpening();
-
- // Queue response document
- SetupSource(kHttpResponse);
- VerifyDocumentStreamIsOpening();
-
- // Begin receive
- base.recv(&data);
-
- // Pull document data
- VerifyDocumentStreamOpenEvent();
- ReadDocumentStreamData("Goodbye!");
- VerifyDocumentStreamIsEOS();
-
- // Document completed successfully
- VerifyHeaderComplete(2, false);
- VerifyTransferComplete(HM_RECV, HE_NONE);
- VerifyDocumentContents("");
-}
-
-TEST_F(HttpBaseTest, DISABLED_AllowsCloseStreamBeforeDocumentIsComplete) {
-
- // TODO: Remove extra logging once test failure is understood
- int old_sev = talk_base::LogMessage::GetLogToDebug();
- talk_base::LogMessage::LogToDebug(LS_VERBOSE);
-
-
- // Switch to pull mode
- ObtainDocumentStream();
- VerifyDocumentStreamIsOpening();
-
- // Queue response document
- SetupSource(kHttpResponse);
- VerifyDocumentStreamIsOpening();
-
- // Begin receive
- base.recv(&data);
-
- // Pull some of the data
- VerifyDocumentStreamOpenEvent();
- ReadDocumentStreamData("Goodb");
-
- // We've seen the header by now
- VerifyHeaderComplete(1, false);
-
- // Close the pull stream, this will transition back to push I/O.
- http_stream->Close();
- Thread::Current()->ProcessMessages(0);
-
- // Remainder of document completed successfully
- VerifyTransferComplete(HM_RECV, HE_NONE);
- VerifyDocumentContents("ye!");
-
- talk_base::LogMessage::LogToDebug(old_sev);
-}
-
-TEST_F(HttpBaseTest, AllowsGetDocumentStreamInResponseToHttpHeader) {
- // Queue response document
- SetupSource(kHttpResponse);
-
- // Switch to pull mode in response to header arrival
- obtain_stream = true;
-
- // Begin receive
- base.recv(&data);
-
- // We've already seen the header, but not data has arrived
- VerifyHeaderComplete(1, false);
- VerifyDocumentContents("");
-
- // Pull the document data
- ReadDocumentStreamData("Goodbye!");
- VerifyDocumentStreamIsEOS();
-
- // Document completed successfully
- VerifyTransferComplete(HM_RECV, HE_NONE);
- VerifyDocumentContents("");
-}
-
-TEST_F(HttpBaseTest, AllowsGetDocumentStreamWithEmptyDocumentBody) {
- // Queue empty response document
- SetupSource(kHttpEmptyResponse);
-
- // Switch to pull mode in response to header arrival
- obtain_stream = true;
-
- // Begin receive
- base.recv(&data);
-
- // We've already seen the header, but not data has arrived
- VerifyHeaderComplete(1, true);
- VerifyDocumentContents("");
-
- // The document is still open, until we attempt to read
- ASSERT_TRUE(NULL != http_stream);
- EXPECT_EQ(SS_OPEN, http_stream->GetState());
-
- // Attempt to read data, and discover EOS
- VerifyDocumentStreamIsEOS();
-
- // Document completed successfully
- VerifyTransferComplete(HM_RECV, HE_NONE);
- VerifyDocumentContents("");
-}
-
-TEST_F(HttpBaseTest, SignalsDocumentStreamCloseOnUnexpectedClose) {
- // Switch to pull mode
- ObtainDocumentStream();
- VerifyDocumentStreamIsOpening();
-
- // Queue response document
- SetupSource(kHttpResponsePrefix);
- VerifyDocumentStreamIsOpening();
-
- // Begin receive
- base.recv(&data);
-
- // Pull document data
- VerifyDocumentStreamOpenEvent();
- ReadDocumentStreamData("Goodbye!");
-
- // Simulate unexpected close
- src.SetState(SS_CLOSED);
-
- // Observe error event on document stream
- EXPECT_EQ(testing::SSE_ERROR, sink.Events(http_stream));
-
- // Future reads give an error
- int error = 0;
- char buffer[5] = { 0 };
- EXPECT_EQ(SR_ERROR, http_stream->Read(buffer, sizeof(buffer), NULL, &error));
- EXPECT_EQ(HE_DISCONNECTED, error);
-
- // Document completed with error
- VerifyHeaderComplete(2, false);
- VerifyTransferComplete(HM_RECV, HE_DISCONNECTED);
- VerifyDocumentContents("");
-}
-
-} // namespace talk_base
diff --git a/base/httpclient.cc b/base/httpclient.cc
deleted file mode 100644
index 5bee911..0000000
--- a/base/httpclient.cc
+++ /dev/null
@@ -1,846 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <time.h>
-
-#include "talk/base/httpcommon-inl.h"
-
-#include "talk/base/asyncsocket.h"
-#include "talk/base/common.h"
-#include "talk/base/diskcache.h"
-#include "talk/base/httpclient.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/socketstream.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// Helpers
-//////////////////////////////////////////////////////////////////////
-
-namespace {
-
-const size_t kCacheHeader = 0;
-const size_t kCacheBody = 1;
-
-// Convert decimal string to integer
-bool HttpStringToUInt(const std::string& str, size_t* val) {
- ASSERT(NULL != val);
- char* eos = NULL;
- *val = strtoul(str.c_str(), &eos, 10);
- return (*eos == '\0');
-}
-
-bool HttpShouldCache(const HttpTransaction& t) {
- bool verb_allows_cache = (t.request.verb == HV_GET)
- || (t.request.verb == HV_HEAD);
- bool is_range_response = t.response.hasHeader(HH_CONTENT_RANGE, NULL);
- bool has_expires = t.response.hasHeader(HH_EXPIRES, NULL);
- bool request_allows_cache =
- has_expires || (std::string::npos != t.request.path.find('?'));
- bool response_allows_cache =
- has_expires || HttpCodeIsCacheable(t.response.scode);
-
- bool may_cache = verb_allows_cache
- && request_allows_cache
- && response_allows_cache
- && !is_range_response;
-
- std::string value;
- if (t.response.hasHeader(HH_CACHE_CONTROL, &value)) {
- HttpAttributeList directives;
- HttpParseAttributes(value.data(), value.size(), directives);
- // Response Directives Summary:
- // public - always cacheable
- // private - do not cache in a shared cache
- // no-cache - may cache, but must revalidate whether fresh or stale
- // no-store - sensitive information, do not cache or store in any way
- // max-age - supplants Expires for staleness
- // s-maxage - use as max-age for shared caches, ignore otherwise
- // must-revalidate - may cache, but must revalidate after stale
- // proxy-revalidate - shared cache must revalidate
- if (HttpHasAttribute(directives, "no-store", NULL)) {
- may_cache = false;
- } else if (HttpHasAttribute(directives, "public", NULL)) {
- may_cache = true;
- }
- }
- return may_cache;
-}
-
-enum HttpCacheState {
- HCS_FRESH, // In cache, may use
- HCS_STALE, // In cache, must revalidate
- HCS_NONE // Not in cache
-};
-
-HttpCacheState HttpGetCacheState(const HttpTransaction& t) {
- // Temporaries
- std::string s_temp;
- time_t u_temp;
-
- // Current time
- size_t now = time(0);
-
- HttpAttributeList cache_control;
- if (t.response.hasHeader(HH_CACHE_CONTROL, &s_temp)) {
- HttpParseAttributes(s_temp.data(), s_temp.size(), cache_control);
- }
-
- // Compute age of cache document
- time_t date;
- if (!t.response.hasHeader(HH_DATE, &s_temp)
- || !HttpDateToSeconds(s_temp, &date))
- return HCS_NONE;
-
- // TODO: Timestamp when cache request sent and response received?
- time_t request_time = date;
- time_t response_time = date;
-
- time_t apparent_age = 0;
- if (response_time > date) {
- apparent_age = response_time - date;
- }
-
- size_t corrected_received_age = apparent_age;
- size_t i_temp;
- if (t.response.hasHeader(HH_AGE, &s_temp)
- && HttpStringToUInt(s_temp, (&i_temp))) {
- u_temp = static_cast<time_t>(i_temp);
- corrected_received_age = stdmax(apparent_age, u_temp);
- }
-
- size_t response_delay = response_time - request_time;
- size_t corrected_initial_age = corrected_received_age + response_delay;
- size_t resident_time = now - response_time;
- size_t current_age = corrected_initial_age + resident_time;
-
- // Compute lifetime of document
- size_t lifetime;
- if (HttpHasAttribute(cache_control, "max-age", &s_temp)) {
- lifetime = atoi(s_temp.c_str());
- } else if (t.response.hasHeader(HH_EXPIRES, &s_temp)
- && HttpDateToSeconds(s_temp, &u_temp)) {
- lifetime = u_temp - date;
- } else if (t.response.hasHeader(HH_LAST_MODIFIED, &s_temp)
- && HttpDateToSeconds(s_temp, &u_temp)) {
- // TODO: Issue warning 113 if age > 24 hours
- lifetime = static_cast<size_t>(now - u_temp) / 10;
- } else {
- return HCS_STALE;
- }
-
- return (lifetime > current_age) ? HCS_FRESH : HCS_STALE;
-}
-
-enum HttpValidatorStrength {
- HVS_NONE,
- HVS_WEAK,
- HVS_STRONG
-};
-
-HttpValidatorStrength
-HttpRequestValidatorLevel(const HttpRequestData& request) {
- if (HV_GET != request.verb)
- return HVS_STRONG;
- return request.hasHeader(HH_RANGE, NULL) ? HVS_STRONG : HVS_WEAK;
-}
-
-HttpValidatorStrength
-HttpResponseValidatorLevel(const HttpResponseData& response) {
- std::string value;
- if (response.hasHeader(HH_ETAG, &value)) {
- bool is_weak = (strnicmp(value.c_str(), "W/", 2) == 0);
- return is_weak ? HVS_WEAK : HVS_STRONG;
- }
- if (response.hasHeader(HH_LAST_MODIFIED, &value)) {
- time_t last_modified, date;
- if (HttpDateToSeconds(value, &last_modified)
- && response.hasHeader(HH_DATE, &value)
- && HttpDateToSeconds(value, &date)
- && (last_modified + 60 < date)) {
- return HVS_STRONG;
- }
- return HVS_WEAK;
- }
- return HVS_NONE;
-}
-
-std::string GetCacheID(const HttpRequestData& request) {
- std::string id, url;
- id.append(ToString(request.verb));
- id.append("_");
- request.getAbsoluteUri(&url);
- id.append(url);
- return id;
-}
-
-} // anonymous namespace
-
-//////////////////////////////////////////////////////////////////////
-// Public Helpers
-//////////////////////////////////////////////////////////////////////
-
-bool HttpWriteCacheHeaders(const HttpResponseData* response,
- StreamInterface* output, size_t* size) {
- size_t length = 0;
- // Write all unknown and end-to-end headers to a cache file
- for (HttpData::const_iterator it = response->begin();
- it != response->end(); ++it) {
- HttpHeader header;
- if (FromString(header, it->first) && !HttpHeaderIsEndToEnd(header))
- continue;
- length += it->first.length() + 2 + it->second.length() + 2;
- if (!output)
- continue;
- std::string formatted_header(it->first);
- formatted_header.append(": ");
- formatted_header.append(it->second);
- formatted_header.append("\r\n");
- StreamResult result = output->WriteAll(formatted_header.data(),
- formatted_header.length(),
- NULL, NULL);
- if (SR_SUCCESS != result) {
- return false;
- }
- }
- if (output && (SR_SUCCESS != output->WriteAll("\r\n", 2, NULL, NULL))) {
- return false;
- }
- length += 2;
- if (size)
- *size = length;
- return true;
-}
-
-bool HttpReadCacheHeaders(StreamInterface* input, HttpResponseData* response,
- HttpData::HeaderCombine combine) {
- while (true) {
- std::string formatted_header;
- StreamResult result = input->ReadLine(&formatted_header);
- if ((SR_EOS == result) || (1 == formatted_header.size())) {
- break;
- }
- if (SR_SUCCESS != result) {
- return false;
- }
- size_t end_of_name = formatted_header.find(':');
- if (std::string::npos == end_of_name) {
- LOG_F(LS_WARNING) << "Malformed cache header";
- continue;
- }
- size_t start_of_value = end_of_name + 1;
- size_t end_of_value = formatted_header.length();
- while ((start_of_value < end_of_value)
- && isspace(formatted_header[start_of_value]))
- ++start_of_value;
- while ((start_of_value < end_of_value)
- && isspace(formatted_header[end_of_value-1]))
- --end_of_value;
- size_t value_length = end_of_value - start_of_value;
-
- std::string name(formatted_header.substr(0, end_of_name));
- std::string value(formatted_header.substr(start_of_value, value_length));
- response->changeHeader(name, value, combine);
- }
- return true;
-}
-
-//////////////////////////////////////////////////////////////////////
-// HttpClient
-//////////////////////////////////////////////////////////////////////
-
-const size_t kDefaultRetries = 1;
-const size_t kMaxRedirects = 5;
-
-HttpClient::HttpClient(const std::string& agent, StreamPool* pool,
- HttpTransaction* transaction)
- : agent_(agent), pool_(pool),
- transaction_(transaction), free_transaction_(false),
- retries_(kDefaultRetries), attempt_(0), redirects_(0),
- redirect_action_(REDIRECT_DEFAULT),
- uri_form_(URI_DEFAULT), cache_(NULL), cache_state_(CS_READY),
- resolver_(NULL) {
- base_.notify(this);
- if (NULL == transaction_) {
- free_transaction_ = true;
- transaction_ = new HttpTransaction;
- }
-}
-
-HttpClient::~HttpClient() {
- base_.notify(NULL);
- base_.abort(HE_SHUTDOWN);
- if (resolver_) {
- resolver_->Destroy(false);
- }
- release();
- if (free_transaction_)
- delete transaction_;
-}
-
-void HttpClient::reset() {
- server_.Clear();
- request().clear(true);
- response().clear(true);
- context_.reset();
- redirects_ = 0;
- base_.abort(HE_OPERATION_CANCELLED);
-}
-
-void HttpClient::OnResolveResult(AsyncResolverInterface* resolver) {
- if (resolver != resolver_) {
- return;
- }
- int error = resolver_->GetError();
- server_ = resolver_->address();
- resolver_->Destroy(false);
- resolver_ = NULL;
- if (error != 0) {
- LOG(LS_ERROR) << "Error " << error << " resolving name: "
- << server_;
- onHttpComplete(HM_CONNECT, HE_CONNECT_FAILED);
- } else {
- connect();
- }
-}
-
-void HttpClient::StartDNSLookup() {
- resolver_ = new AsyncResolver();
- resolver_->SignalDone.connect(this, &HttpClient::OnResolveResult);
- resolver_->Start(server_);
-}
-
-void HttpClient::set_server(const SocketAddress& address) {
- server_ = address;
- // Setting 'Host' here allows it to be overridden before starting the request,
- // if necessary.
- request().setHeader(HH_HOST, HttpAddress(server_, false), true);
-}
-
-StreamInterface* HttpClient::GetDocumentStream() {
- return base_.GetDocumentStream();
-}
-
-void HttpClient::start() {
- if (base_.mode() != HM_NONE) {
- // call reset() to abort an in-progress request
- ASSERT(false);
- return;
- }
-
- ASSERT(!IsCacheActive());
-
- if (request().hasHeader(HH_TRANSFER_ENCODING, NULL)) {
- // Exact size must be known on the client. Instead of using chunked
- // encoding, wrap data with auto-caching file or memory stream.
- ASSERT(false);
- return;
- }
-
- attempt_ = 0;
-
- // If no content has been specified, using length of 0.
- request().setHeader(HH_CONTENT_LENGTH, "0", false);
-
- if (!agent_.empty()) {
- request().setHeader(HH_USER_AGENT, agent_, false);
- }
-
- UriForm uri_form = uri_form_;
- if (PROXY_HTTPS == proxy_.type) {
- // Proxies require absolute form
- uri_form = URI_ABSOLUTE;
- request().version = HVER_1_0;
- request().setHeader(HH_PROXY_CONNECTION, "Keep-Alive", false);
- } else {
- request().setHeader(HH_CONNECTION, "Keep-Alive", false);
- }
-
- if (URI_ABSOLUTE == uri_form) {
- // Convert to absolute uri form
- std::string url;
- if (request().getAbsoluteUri(&url)) {
- request().path = url;
- } else {
- LOG(LS_WARNING) << "Couldn't obtain absolute uri";
- }
- } else if (URI_RELATIVE == uri_form) {
- // Convert to relative uri form
- std::string host, path;
- if (request().getRelativeUri(&host, &path)) {
- request().setHeader(HH_HOST, host);
- request().path = path;
- } else {
- LOG(LS_WARNING) << "Couldn't obtain relative uri";
- }
- }
-
- if ((NULL != cache_) && CheckCache()) {
- return;
- }
-
- connect();
-}
-
-void HttpClient::connect() {
- int stream_err;
- if (server_.IsUnresolvedIP()) {
- StartDNSLookup();
- return;
- }
- StreamInterface* stream = pool_->RequestConnectedStream(server_, &stream_err);
- if (stream == NULL) {
- ASSERT(0 != stream_err);
- LOG(LS_ERROR) << "RequestConnectedStream error: " << stream_err;
- onHttpComplete(HM_CONNECT, HE_CONNECT_FAILED);
- } else {
- base_.attach(stream);
- if (stream->GetState() == SS_OPEN) {
- base_.send(&transaction_->request);
- }
- }
-}
-
-void HttpClient::prepare_get(const std::string& url) {
- reset();
- Url<char> purl(url);
- set_server(SocketAddress(purl.host(), purl.port()));
- request().verb = HV_GET;
- request().path = purl.full_path();
-}
-
-void HttpClient::prepare_post(const std::string& url,
- const std::string& content_type,
- StreamInterface* request_doc) {
- reset();
- Url<char> purl(url);
- set_server(SocketAddress(purl.host(), purl.port()));
- request().verb = HV_POST;
- request().path = purl.full_path();
- request().setContent(content_type, request_doc);
-}
-
-void HttpClient::release() {
- if (StreamInterface* stream = base_.detach()) {
- pool_->ReturnConnectedStream(stream);
- }
-}
-
-bool HttpClient::ShouldRedirect(std::string* location) const {
- // TODO: Unittest redirection.
- if ((REDIRECT_NEVER == redirect_action_)
- || !HttpCodeIsRedirection(response().scode)
- || !response().hasHeader(HH_LOCATION, location)
- || (redirects_ >= kMaxRedirects))
- return false;
- return (REDIRECT_ALWAYS == redirect_action_)
- || (HC_SEE_OTHER == response().scode)
- || (HV_HEAD == request().verb)
- || (HV_GET == request().verb);
-}
-
-bool HttpClient::BeginCacheFile() {
- ASSERT(NULL != cache_);
- ASSERT(CS_READY == cache_state_);
-
- std::string id = GetCacheID(request());
- CacheLock lock(cache_, id, true);
- if (!lock.IsLocked()) {
- LOG_F(LS_WARNING) << "Couldn't lock cache";
- return false;
- }
-
- if (HE_NONE != WriteCacheHeaders(id)) {
- return false;
- }
-
- scoped_ptr<StreamInterface> stream(cache_->WriteResource(id, kCacheBody));
- if (!stream) {
- LOG_F(LS_ERROR) << "Couldn't open body cache";
- return false;
- }
- lock.Commit();
-
- // Let's secretly replace the response document with Folgers Crystals,
- // er, StreamTap, so that we can mirror the data to our cache.
- StreamInterface* output = response().document.release();
- if (!output) {
- output = new NullStream;
- }
- StreamTap* tap = new StreamTap(output, stream.release());
- response().document.reset(tap);
- return true;
-}
-
-HttpError HttpClient::WriteCacheHeaders(const std::string& id) {
- scoped_ptr<StreamInterface> stream(cache_->WriteResource(id, kCacheHeader));
- if (!stream) {
- LOG_F(LS_ERROR) << "Couldn't open header cache";
- return HE_CACHE;
- }
-
- if (!HttpWriteCacheHeaders(&transaction_->response, stream.get(), NULL)) {
- LOG_F(LS_ERROR) << "Couldn't write header cache";
- return HE_CACHE;
- }
-
- return HE_NONE;
-}
-
-void HttpClient::CompleteCacheFile() {
- // Restore previous response document
- StreamTap* tap = static_cast<StreamTap*>(response().document.release());
- response().document.reset(tap->Detach());
-
- int error;
- StreamResult result = tap->GetTapResult(&error);
-
- // Delete the tap and cache stream (which completes cache unlock)
- delete tap;
-
- if (SR_SUCCESS != result) {
- LOG(LS_ERROR) << "Cache file error: " << error;
- cache_->DeleteResource(GetCacheID(request()));
- }
-}
-
-bool HttpClient::CheckCache() {
- ASSERT(NULL != cache_);
- ASSERT(CS_READY == cache_state_);
-
- std::string id = GetCacheID(request());
- if (!cache_->HasResource(id)) {
- // No cache file available
- return false;
- }
-
- HttpError error = ReadCacheHeaders(id, true);
-
- if (HE_NONE == error) {
- switch (HttpGetCacheState(*transaction_)) {
- case HCS_FRESH:
- // Cache content is good, read from cache
- break;
- case HCS_STALE:
- // Cache content may be acceptable. Issue a validation request.
- if (PrepareValidate()) {
- return false;
- }
- // Couldn't validate, fall through.
- case HCS_NONE:
- // Cache content is not useable. Issue a regular request.
- response().clear(false);
- return false;
- }
- }
-
- if (HE_NONE == error) {
- error = ReadCacheBody(id);
- cache_state_ = CS_READY;
- }
-
- if (HE_CACHE == error) {
- LOG_F(LS_WARNING) << "Cache failure, continuing with normal request";
- response().clear(false);
- return false;
- }
-
- SignalHttpClientComplete(this, error);
- return true;
-}
-
-HttpError HttpClient::ReadCacheHeaders(const std::string& id, bool override) {
- scoped_ptr<StreamInterface> stream(cache_->ReadResource(id, kCacheHeader));
- if (!stream) {
- return HE_CACHE;
- }
-
- HttpData::HeaderCombine combine =
- override ? HttpData::HC_REPLACE : HttpData::HC_AUTO;
-
- if (!HttpReadCacheHeaders(stream.get(), &transaction_->response, combine)) {
- LOG_F(LS_ERROR) << "Error reading cache headers";
- return HE_CACHE;
- }
-
- response().scode = HC_OK;
- return HE_NONE;
-}
-
-HttpError HttpClient::ReadCacheBody(const std::string& id) {
- cache_state_ = CS_READING;
-
- HttpError error = HE_NONE;
-
- size_t data_size;
- scoped_ptr<StreamInterface> stream(cache_->ReadResource(id, kCacheBody));
- if (!stream || !stream->GetAvailable(&data_size)) {
- LOG_F(LS_ERROR) << "Unavailable cache body";
- error = HE_CACHE;
- } else {
- error = OnHeaderAvailable(false, false, data_size);
- }
-
- if ((HE_NONE == error)
- && (HV_HEAD != request().verb)
- && response().document) {
- char buffer[1024 * 64];
- StreamResult result = Flow(stream.get(), buffer, ARRAY_SIZE(buffer),
- response().document.get());
- if (SR_SUCCESS != result) {
- error = HE_STREAM;
- }
- }
-
- return error;
-}
-
-bool HttpClient::PrepareValidate() {
- ASSERT(CS_READY == cache_state_);
- // At this point, request() contains the pending request, and response()
- // contains the cached response headers. Reformat the request to validate
- // the cached content.
- HttpValidatorStrength vs_required = HttpRequestValidatorLevel(request());
- HttpValidatorStrength vs_available = HttpResponseValidatorLevel(response());
- if (vs_available < vs_required) {
- return false;
- }
- std::string value;
- if (response().hasHeader(HH_ETAG, &value)) {
- request().addHeader(HH_IF_NONE_MATCH, value);
- }
- if (response().hasHeader(HH_LAST_MODIFIED, &value)) {
- request().addHeader(HH_IF_MODIFIED_SINCE, value);
- }
- response().clear(false);
- cache_state_ = CS_VALIDATING;
- return true;
-}
-
-HttpError HttpClient::CompleteValidate() {
- ASSERT(CS_VALIDATING == cache_state_);
-
- std::string id = GetCacheID(request());
-
- // Merge cached headers with new headers
- HttpError error = ReadCacheHeaders(id, false);
- if (HE_NONE != error) {
- // Rewrite merged headers to cache
- CacheLock lock(cache_, id);
- error = WriteCacheHeaders(id);
- }
- if (HE_NONE != error) {
- error = ReadCacheBody(id);
- }
- return error;
-}
-
-HttpError HttpClient::OnHeaderAvailable(bool ignore_data, bool chunked,
- size_t data_size) {
- // If we are ignoring the data, this is an intermediate header.
- // TODO: don't signal intermediate headers. Instead, do all header-dependent
- // processing now, and either set up the next request, or fail outright.
- // TODO: by default, only write response documents with a success code.
- SignalHeaderAvailable(this, !ignore_data, ignore_data ? 0 : data_size);
- if (!ignore_data && !chunked && (data_size != SIZE_UNKNOWN)
- && response().document) {
- // Attempt to pre-allocate space for the downloaded data.
- if (!response().document->ReserveSize(data_size)) {
- return HE_OVERFLOW;
- }
- }
- return HE_NONE;
-}
-
-//
-// HttpBase Implementation
-//
-
-HttpError HttpClient::onHttpHeaderComplete(bool chunked, size_t& data_size) {
- if (CS_VALIDATING == cache_state_) {
- if (HC_NOT_MODIFIED == response().scode) {
- return CompleteValidate();
- }
- // Should we remove conditional headers from request?
- cache_state_ = CS_READY;
- cache_->DeleteResource(GetCacheID(request()));
- // Continue processing response as normal
- }
-
- ASSERT(!IsCacheActive());
- if ((request().verb == HV_HEAD) || !HttpCodeHasBody(response().scode)) {
- // HEAD requests and certain response codes contain no body
- data_size = 0;
- }
- if (ShouldRedirect(NULL)
- || ((HC_PROXY_AUTHENTICATION_REQUIRED == response().scode)
- && (PROXY_HTTPS == proxy_.type))) {
- // We're going to issue another request, so ignore the incoming data.
- base_.set_ignore_data(true);
- }
-
- HttpError error = OnHeaderAvailable(base_.ignore_data(), chunked, data_size);
- if (HE_NONE != error) {
- return error;
- }
-
- if ((NULL != cache_)
- && !base_.ignore_data()
- && HttpShouldCache(*transaction_)) {
- if (BeginCacheFile()) {
- cache_state_ = CS_WRITING;
- }
- }
- return HE_NONE;
-}
-
-void HttpClient::onHttpComplete(HttpMode mode, HttpError err) {
- if (((HE_DISCONNECTED == err) || (HE_CONNECT_FAILED == err)
- || (HE_SOCKET_ERROR == err))
- && (HC_INTERNAL_SERVER_ERROR == response().scode)
- && (attempt_ < retries_)) {
- // If the response code has not changed from the default, then we haven't
- // received anything meaningful from the server, so we are eligible for a
- // retry.
- ++attempt_;
- if (request().document && !request().document->Rewind()) {
- // Unable to replay the request document.
- err = HE_STREAM;
- } else {
- release();
- connect();
- return;
- }
- } else if (err != HE_NONE) {
- // fall through
- } else if (mode == HM_CONNECT) {
- base_.send(&transaction_->request);
- return;
- } else if ((mode == HM_SEND) || HttpCodeIsInformational(response().scode)) {
- // If you're interested in informational headers, catch
- // SignalHeaderAvailable.
- base_.recv(&transaction_->response);
- return;
- } else {
- if (!HttpShouldKeepAlive(response())) {
- LOG(LS_VERBOSE) << "HttpClient: closing socket";
- base_.stream()->Close();
- }
- std::string location;
- if (ShouldRedirect(&location)) {
- Url<char> purl(location);
- set_server(SocketAddress(purl.host(), purl.port()));
- request().path = purl.full_path();
- if (response().scode == HC_SEE_OTHER) {
- request().verb = HV_GET;
- request().clearHeader(HH_CONTENT_TYPE);
- request().clearHeader(HH_CONTENT_LENGTH);
- request().document.reset();
- } else if (request().document && !request().document->Rewind()) {
- // Unable to replay the request document.
- ASSERT(REDIRECT_ALWAYS == redirect_action_);
- err = HE_STREAM;
- }
- if (err == HE_NONE) {
- ++redirects_;
- context_.reset();
- response().clear(false);
- release();
- start();
- return;
- }
- } else if ((HC_PROXY_AUTHENTICATION_REQUIRED == response().scode)
- && (PROXY_HTTPS == proxy_.type)) {
- std::string authorization, auth_method;
- HttpData::const_iterator begin = response().begin(HH_PROXY_AUTHENTICATE);
- HttpData::const_iterator end = response().end(HH_PROXY_AUTHENTICATE);
- for (HttpData::const_iterator it = begin; it != end; ++it) {
- HttpAuthContext *context = context_.get();
- HttpAuthResult res = HttpAuthenticate(
- it->second.data(), it->second.size(),
- proxy_.address,
- ToString(request().verb), request().path,
- proxy_.username, proxy_.password,
- context, authorization, auth_method);
- context_.reset(context);
- if (res == HAR_RESPONSE) {
- request().setHeader(HH_PROXY_AUTHORIZATION, authorization);
- if (request().document && !request().document->Rewind()) {
- err = HE_STREAM;
- } else {
- // Explicitly do not reset the HttpAuthContext
- response().clear(false);
- // TODO: Reuse socket when authenticating?
- release();
- start();
- return;
- }
- } else if (res == HAR_IGNORE) {
- LOG(INFO) << "Ignoring Proxy-Authenticate: " << auth_method;
- continue;
- } else {
- break;
- }
- }
- }
- }
- if (CS_WRITING == cache_state_) {
- CompleteCacheFile();
- cache_state_ = CS_READY;
- } else if (CS_READING == cache_state_) {
- cache_state_ = CS_READY;
- }
- release();
- SignalHttpClientComplete(this, err);
-}
-
-void HttpClient::onHttpClosed(HttpError err) {
- // This shouldn't occur, since we return the stream to the pool upon command
- // completion.
- ASSERT(false);
-}
-
-//////////////////////////////////////////////////////////////////////
-// HttpClientDefault
-//////////////////////////////////////////////////////////////////////
-
-HttpClientDefault::HttpClientDefault(SocketFactory* factory,
- const std::string& agent,
- HttpTransaction* transaction)
- : ReuseSocketPool(factory ? factory : Thread::Current()->socketserver()),
- HttpClient(agent, NULL, transaction) {
- set_pool(this);
-}
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/httpclient.h b/base/httpclient.h
deleted file mode 100644
index 03deb22..0000000
--- a/base/httpclient.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_HTTPCLIENT_H__
-#define TALK_BASE_HTTPCLIENT_H__
-
-#include "talk/base/common.h"
-#include "talk/base/httpbase.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/proxyinfo.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/socketpool.h"
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// Client-specific http utilities
-//////////////////////////////////////////////////////////////////////
-
-// Write cache-relevant response headers to output stream. If size is non-null,
-// it contains the length of the output in bytes. output may be null if only
-// the length is desired.
-bool HttpWriteCacheHeaders(const HttpResponseData* response,
- StreamInterface* output, size_t* size);
-// Read cached headers from a stream, and them merge them into the response
-// object using the specified combine operation.
-bool HttpReadCacheHeaders(StreamInterface* input,
- HttpResponseData* response,
- HttpData::HeaderCombine combine);
-
-//////////////////////////////////////////////////////////////////////
-// HttpClient
-// Implements an HTTP 1.1 client.
-//////////////////////////////////////////////////////////////////////
-
-class DiskCache;
-class HttpClient;
-class IPNetPool;
-
-class SignalThread;
-// What to do: Define STRICT_HTTP_ERROR=1 in your makefile. Use HttpError in
-// your code (HttpErrorType should only be used for code that is shared
-// with groups which have not yet migrated).
-#if STRICT_HTTP_ERROR
-typedef HttpError HttpErrorType;
-#else // !STRICT_HTTP_ERROR
-typedef int HttpErrorType;
-#endif // !STRICT_HTTP_ERROR
-
-class HttpClient : private IHttpNotify, public sigslot::has_slots<> {
-public:
- // If HttpRequestData and HttpResponseData objects are provided, they must
- // be freed by the caller. Otherwise, an internal object is allocated.
- HttpClient(const std::string& agent, StreamPool* pool,
- HttpTransaction* transaction = NULL);
- virtual ~HttpClient();
-
- void set_pool(StreamPool* pool) { pool_ = pool; }
-
- void set_agent(const std::string& agent) { agent_ = agent; }
- const std::string& agent() const { return agent_; }
-
- void set_proxy(const ProxyInfo& proxy) { proxy_ = proxy; }
- const ProxyInfo& proxy() const { return proxy_; }
-
- // Request retries occur when the connection closes before the beginning of
- // an http response is received. In these cases, the http server may have
- // timed out the keepalive connection before it received our request. Note
- // that if a request document cannot be rewound, no retry is made. The
- // default is 1.
- void set_request_retries(size_t retries) { retries_ = retries; }
- size_t request_retries() const { return retries_; }
-
- enum RedirectAction { REDIRECT_DEFAULT, REDIRECT_ALWAYS, REDIRECT_NEVER };
- void set_redirect_action(RedirectAction action) { redirect_action_ = action; }
- RedirectAction redirect_action() const { return redirect_action_; }
- // Deprecated
- void set_fail_redirect(bool fail_redirect) {
- redirect_action_ = REDIRECT_NEVER;
- }
- bool fail_redirect() const { return (REDIRECT_NEVER == redirect_action_); }
-
- enum UriForm { URI_DEFAULT, URI_ABSOLUTE, URI_RELATIVE };
- void set_uri_form(UriForm form) { uri_form_ = form; }
- UriForm uri_form() const { return uri_form_; }
-
- void set_cache(DiskCache* cache) { ASSERT(!IsCacheActive()); cache_ = cache; }
- bool cache_enabled() const { return (NULL != cache_); }
-
- // reset clears the server, request, and response structures. It will also
- // abort an active request.
- void reset();
-
- void set_server(const SocketAddress& address);
- const SocketAddress& server() const { return server_; }
-
- // Note: in order for HttpClient to retry a POST in response to
- // an authentication challenge, a redirect response, or socket disconnection,
- // the request document must support 'replaying' by calling Rewind() on it.
- // In the case where just a subset of a stream should be used as the request
- // document, the stream may be wrapped with the StreamSegment adapter.
- HttpTransaction* transaction() { return transaction_; }
- const HttpTransaction* transaction() const { return transaction_; }
- HttpRequestData& request() { return transaction_->request; }
- const HttpRequestData& request() const { return transaction_->request; }
- HttpResponseData& response() { return transaction_->response; }
- const HttpResponseData& response() const { return transaction_->response; }
-
- // convenience methods
- void prepare_get(const std::string& url);
- void prepare_post(const std::string& url, const std::string& content_type,
- StreamInterface* request_doc);
-
- // Convert HttpClient to a pull-based I/O model.
- StreamInterface* GetDocumentStream();
-
- // After you finish setting up your request, call start.
- void start();
-
- // Signalled when the header has finished downloading, before the document
- // content is processed. You may change the response document in response
- // to this signal. The second parameter indicates whether this is an
- // intermediate (false) or final (true) header. An intermediate header is
- // one that generates another request, such as a redirect or authentication
- // challenge. The third parameter indicates the length of the response
- // document, or else SIZE_UNKNOWN. Note: Do NOT abort the request in response
- // to this signal.
- sigslot::signal3<HttpClient*,bool,size_t> SignalHeaderAvailable;
- // Signalled when the current request finishes. On success, err is 0.
- sigslot::signal2<HttpClient*,HttpErrorType> SignalHttpClientComplete;
-
-protected:
- void connect();
- void release();
-
- bool ShouldRedirect(std::string* location) const;
-
- bool BeginCacheFile();
- HttpError WriteCacheHeaders(const std::string& id);
- void CompleteCacheFile();
-
- bool CheckCache();
- HttpError ReadCacheHeaders(const std::string& id, bool override);
- HttpError ReadCacheBody(const std::string& id);
-
- bool PrepareValidate();
- HttpError CompleteValidate();
-
- HttpError OnHeaderAvailable(bool ignore_data, bool chunked, size_t data_size);
-
- void StartDNSLookup();
- void OnResolveResult(AsyncResolverInterface* resolver);
-
- // IHttpNotify Interface
- virtual HttpError onHttpHeaderComplete(bool chunked, size_t& data_size);
- virtual void onHttpComplete(HttpMode mode, HttpError err);
- virtual void onHttpClosed(HttpError err);
-
-private:
- enum CacheState { CS_READY, CS_WRITING, CS_READING, CS_VALIDATING };
- bool IsCacheActive() const { return (cache_state_ > CS_READY); }
-
- std::string agent_;
- StreamPool* pool_;
- HttpBase base_;
- SocketAddress server_;
- ProxyInfo proxy_;
- HttpTransaction* transaction_;
- bool free_transaction_;
- size_t retries_, attempt_, redirects_;
- RedirectAction redirect_action_;
- UriForm uri_form_;
- scoped_ptr<HttpAuthContext> context_;
- DiskCache* cache_;
- CacheState cache_state_;
- AsyncResolverInterface* resolver_;
-};
-
-//////////////////////////////////////////////////////////////////////
-// HttpClientDefault - Default implementation of HttpClient
-//////////////////////////////////////////////////////////////////////
-
-class HttpClientDefault : public ReuseSocketPool, public HttpClient {
-public:
- HttpClientDefault(SocketFactory* factory, const std::string& agent,
- HttpTransaction* transaction = NULL);
-};
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_HTTPCLIENT_H__
diff --git a/base/httpcommon-inl.h b/base/httpcommon-inl.h
deleted file mode 100644
index c9eaffc..0000000
--- a/base/httpcommon-inl.h
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_HTTPCOMMON_INL_H__
-#define TALK_BASE_HTTPCOMMON_INL_H__
-
-#include "talk/base/common.h"
-#include "talk/base/httpcommon.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// Url
-///////////////////////////////////////////////////////////////////////////////
-
-template<class CTYPE>
-void Url<CTYPE>::do_set_url(const CTYPE* val, size_t len) {
- if (ascnicmp(val, "http://", 7) == 0) {
- val += 7; len -= 7;
- secure_ = false;
- } else if (ascnicmp(val, "https://", 8) == 0) {
- val += 8; len -= 8;
- secure_ = true;
- } else {
- clear();
- return;
- }
- const CTYPE* path = strchrn(val, len, static_cast<CTYPE>('/'));
- if (!path) {
- path = val + len;
- }
- size_t address_length = (path - val);
- do_set_address(val, address_length);
- do_set_full_path(path, len - address_length);
-}
-
-template<class CTYPE>
-void Url<CTYPE>::do_set_address(const CTYPE* val, size_t len) {
- if (const CTYPE* at = strchrn(val, len, static_cast<CTYPE>('@'))) {
- // Everything before the @ is a user:password combo, so skip it.
- len -= at - val + 1;
- val = at + 1;
- }
- if (const CTYPE* colon = strchrn(val, len, static_cast<CTYPE>(':'))) {
- host_.assign(val, colon - val);
- // Note: In every case, we're guaranteed that colon is followed by a null,
- // or non-numeric character.
- port_ = static_cast<uint16>(::strtoul(colon + 1, NULL, 10));
- // TODO: Consider checking for invalid data following port number.
- } else {
- host_.assign(val, len);
- port_ = HttpDefaultPort(secure_);
- }
-}
-
-template<class CTYPE>
-void Url<CTYPE>::do_set_full_path(const CTYPE* val, size_t len) {
- const CTYPE* query = strchrn(val, len, static_cast<CTYPE>('?'));
- if (!query) {
- query = val + len;
- }
- size_t path_length = (query - val);
- if (0 == path_length) {
- // TODO: consider failing in this case.
- path_.assign(1, static_cast<CTYPE>('/'));
- } else {
- ASSERT(val[0] == static_cast<CTYPE>('/'));
- path_.assign(val, path_length);
- }
- query_.assign(query, len - path_length);
-}
-
-template<class CTYPE>
-void Url<CTYPE>::do_get_url(string* val) const {
- CTYPE protocol[9];
- asccpyn(protocol, ARRAY_SIZE(protocol), secure_ ? "https://" : "http://");
- val->append(protocol);
- do_get_address(val);
- do_get_full_path(val);
-}
-
-template<class CTYPE>
-void Url<CTYPE>::do_get_address(string* val) const {
- val->append(host_);
- if (port_ != HttpDefaultPort(secure_)) {
- CTYPE format[5], port[32];
- asccpyn(format, ARRAY_SIZE(format), ":%hu");
- sprintfn(port, ARRAY_SIZE(port), format, port_);
- val->append(port);
- }
-}
-
-template<class CTYPE>
-void Url<CTYPE>::do_get_full_path(string* val) const {
- val->append(path_);
- val->append(query_);
-}
-
-template<class CTYPE>
-bool Url<CTYPE>::get_attribute(const string& name, string* value) const {
- if (query_.empty())
- return false;
-
- std::string::size_type pos = query_.find(name, 1);
- if (std::string::npos == pos)
- return false;
-
- pos += name.length() + 1;
- if ((pos > query_.length()) || (static_cast<CTYPE>('=') != query_[pos-1]))
- return false;
-
- std::string::size_type end = query_.find(static_cast<CTYPE>('&'), pos);
- if (std::string::npos == end) {
- end = query_.length();
- }
- value->assign(query_.substr(pos, end - pos));
- return true;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_HTTPCOMMON_INL_H__
diff --git a/base/httpcommon.cc b/base/httpcommon.cc
deleted file mode 100644
index ec7ffd2..0000000
--- a/base/httpcommon.cc
+++ /dev/null
@@ -1,1062 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <time.h>
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#define SECURITY_WIN32
-#include <security.h>
-#endif
-
-#include "talk/base/httpcommon-inl.h"
-
-#include "talk/base/base64.h"
-#include "talk/base/common.h"
-#include "talk/base/cryptstring.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/stringdigest.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-
-namespace talk_base {
-
-#ifdef WIN32
-extern const ConstantLabel SECURITY_ERRORS[];
-#endif
-
-//////////////////////////////////////////////////////////////////////
-// Enum - TODO: expose globally later?
-//////////////////////////////////////////////////////////////////////
-
-bool find_string(size_t& index, const std::string& needle,
- const char* const haystack[], size_t max_index) {
- for (index=0; index<max_index; ++index) {
- if (_stricmp(needle.c_str(), haystack[index]) == 0) {
- return true;
- }
- }
- return false;
-}
-
-template<class E>
-struct Enum {
- static const char** Names;
- static size_t Size;
-
- static inline const char* Name(E val) { return Names[val]; }
- static inline bool Parse(E& val, const std::string& name) {
- size_t index;
- if (!find_string(index, name, Names, Size))
- return false;
- val = static_cast<E>(index);
- return true;
- }
-
- E val;
-
- inline operator E&() { return val; }
- inline Enum& operator=(E rhs) { val = rhs; return *this; }
-
- inline const char* name() const { return Name(val); }
- inline bool assign(const std::string& name) { return Parse(val, name); }
- inline Enum& operator=(const std::string& rhs) { assign(rhs); return *this; }
-};
-
-#define ENUM(e,n) \
- template<> const char** Enum<e>::Names = n; \
- template<> size_t Enum<e>::Size = sizeof(n)/sizeof(n[0])
-
-//////////////////////////////////////////////////////////////////////
-// HttpCommon
-//////////////////////////////////////////////////////////////////////
-
-static const char* kHttpVersions[HVER_LAST+1] = {
- "1.0", "1.1", "Unknown"
-};
-ENUM(HttpVersion, kHttpVersions);
-
-static const char* kHttpVerbs[HV_LAST+1] = {
- "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD"
-};
-ENUM(HttpVerb, kHttpVerbs);
-
-static const char* kHttpHeaders[HH_LAST+1] = {
- "Age",
- "Cache-Control",
- "Connection",
- "Content-Disposition",
- "Content-Length",
- "Content-Range",
- "Content-Type",
- "Cookie",
- "Date",
- "ETag",
- "Expires",
- "Host",
- "If-Modified-Since",
- "If-None-Match",
- "Keep-Alive",
- "Last-Modified",
- "Location",
- "Proxy-Authenticate",
- "Proxy-Authorization",
- "Proxy-Connection",
- "Range",
- "Set-Cookie",
- "TE",
- "Trailers",
- "Transfer-Encoding",
- "Upgrade",
- "User-Agent",
- "WWW-Authenticate",
-};
-ENUM(HttpHeader, kHttpHeaders);
-
-const char* ToString(HttpVersion version) {
- return Enum<HttpVersion>::Name(version);
-}
-
-bool FromString(HttpVersion& version, const std::string& str) {
- return Enum<HttpVersion>::Parse(version, str);
-}
-
-const char* ToString(HttpVerb verb) {
- return Enum<HttpVerb>::Name(verb);
-}
-
-bool FromString(HttpVerb& verb, const std::string& str) {
- return Enum<HttpVerb>::Parse(verb, str);
-}
-
-const char* ToString(HttpHeader header) {
- return Enum<HttpHeader>::Name(header);
-}
-
-bool FromString(HttpHeader& header, const std::string& str) {
- return Enum<HttpHeader>::Parse(header, str);
-}
-
-bool HttpCodeHasBody(uint32 code) {
- return !HttpCodeIsInformational(code)
- && (code != HC_NO_CONTENT) && (code != HC_NOT_MODIFIED);
-}
-
-bool HttpCodeIsCacheable(uint32 code) {
- switch (code) {
- case HC_OK:
- case HC_NON_AUTHORITATIVE:
- case HC_PARTIAL_CONTENT:
- case HC_MULTIPLE_CHOICES:
- case HC_MOVED_PERMANENTLY:
- case HC_GONE:
- return true;
- default:
- return false;
- }
-}
-
-bool HttpHeaderIsEndToEnd(HttpHeader header) {
- switch (header) {
- case HH_CONNECTION:
- case HH_KEEP_ALIVE:
- case HH_PROXY_AUTHENTICATE:
- case HH_PROXY_AUTHORIZATION:
- case HH_PROXY_CONNECTION: // Note part of RFC... this is non-standard header
- case HH_TE:
- case HH_TRAILERS:
- case HH_TRANSFER_ENCODING:
- case HH_UPGRADE:
- return false;
- default:
- return true;
- }
-}
-
-bool HttpHeaderIsCollapsible(HttpHeader header) {
- switch (header) {
- case HH_SET_COOKIE:
- case HH_PROXY_AUTHENTICATE:
- case HH_WWW_AUTHENTICATE:
- return false;
- default:
- return true;
- }
-}
-
-bool HttpShouldKeepAlive(const HttpData& data) {
- std::string connection;
- if ((data.hasHeader(HH_PROXY_CONNECTION, &connection)
- || data.hasHeader(HH_CONNECTION, &connection))) {
- return (_stricmp(connection.c_str(), "Keep-Alive") == 0);
- }
- return (data.version >= HVER_1_1);
-}
-
-namespace {
-
-inline bool IsEndOfAttributeName(size_t pos, size_t len, const char * data) {
- if (pos >= len)
- return true;
- if (isspace(static_cast<unsigned char>(data[pos])))
- return true;
- // The reason for this complexity is that some attributes may contain trailing
- // equal signs (like base64 tokens in Negotiate auth headers)
- if ((pos+1 < len) && (data[pos] == '=') &&
- !isspace(static_cast<unsigned char>(data[pos+1])) &&
- (data[pos+1] != '=')) {
- return true;
- }
- return false;
-}
-
-// TODO: unittest for EscapeAttribute and HttpComposeAttributes.
-
-std::string EscapeAttribute(const std::string& attribute) {
- const size_t kMaxLength = attribute.length() * 2 + 1;
- char* buffer = STACK_ARRAY(char, kMaxLength);
- size_t len = escape(buffer, kMaxLength, attribute.data(), attribute.length(),
- "\"", '\\');
- return std::string(buffer, len);
-}
-
-} // anonymous namespace
-
-void HttpComposeAttributes(const HttpAttributeList& attributes, char separator,
- std::string* composed) {
- std::stringstream ss;
- for (size_t i=0; i<attributes.size(); ++i) {
- if (i > 0) {
- ss << separator << " ";
- }
- ss << attributes[i].first;
- if (!attributes[i].second.empty()) {
- ss << "=\"" << EscapeAttribute(attributes[i].second) << "\"";
- }
- }
- *composed = ss.str();
-}
-
-void HttpParseAttributes(const char * data, size_t len,
- HttpAttributeList& attributes) {
- size_t pos = 0;
- while (true) {
- // Skip leading whitespace
- while ((pos < len) && isspace(static_cast<unsigned char>(data[pos]))) {
- ++pos;
- }
-
- // End of attributes?
- if (pos >= len)
- return;
-
- // Find end of attribute name
- size_t start = pos;
- while (!IsEndOfAttributeName(pos, len, data)) {
- ++pos;
- }
-
- HttpAttribute attribute;
- attribute.first.assign(data + start, data + pos);
-
- // Attribute has value?
- if ((pos < len) && (data[pos] == '=')) {
- ++pos; // Skip '='
- // Check if quoted value
- if ((pos < len) && (data[pos] == '"')) {
- while (++pos < len) {
- if (data[pos] == '"') {
- ++pos;
- break;
- }
- if ((data[pos] == '\\') && (pos + 1 < len))
- ++pos;
- attribute.second.append(1, data[pos]);
- }
- } else {
- while ((pos < len) &&
- !isspace(static_cast<unsigned char>(data[pos])) &&
- (data[pos] != ',')) {
- attribute.second.append(1, data[pos++]);
- }
- }
- }
-
- attributes.push_back(attribute);
- if ((pos < len) && (data[pos] == ',')) ++pos; // Skip ','
- }
-}
-
-bool HttpHasAttribute(const HttpAttributeList& attributes,
- const std::string& name,
- std::string* value) {
- for (HttpAttributeList::const_iterator it = attributes.begin();
- it != attributes.end(); ++it) {
- if (it->first == name) {
- if (value) {
- *value = it->second;
- }
- return true;
- }
- }
- return false;
-}
-
-bool HttpHasNthAttribute(HttpAttributeList& attributes,
- size_t index,
- std::string* name,
- std::string* value) {
- if (index >= attributes.size())
- return false;
-
- if (name)
- *name = attributes[index].first;
- if (value)
- *value = attributes[index].second;
- return true;
-}
-
-bool HttpDateToSeconds(const std::string& date, time_t* seconds) {
- const char* const kTimeZones[] = {
- "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
- "A", "B", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M",
- "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"
- };
- const int kTimeZoneOffsets[] = {
- 0, 0, -5, -4, -6, -5, -7, -6, -8, -7,
- -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12,
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
- };
-
- ASSERT(NULL != seconds);
- struct tm tval;
- memset(&tval, 0, sizeof(tval));
- char month[4], zone[6];
- memset(month, 0, sizeof(month));
- memset(zone, 0, sizeof(zone));
-
- if (7 != sscanf(date.c_str(), "%*3s, %d %3s %d %d:%d:%d %5c",
- &tval.tm_mday, month, &tval.tm_year,
- &tval.tm_hour, &tval.tm_min, &tval.tm_sec, zone)) {
- return false;
- }
- switch (toupper(month[2])) {
- case 'N': tval.tm_mon = (month[1] == 'A') ? 0 : 5; break;
- case 'B': tval.tm_mon = 1; break;
- case 'R': tval.tm_mon = (month[0] == 'M') ? 2 : 3; break;
- case 'Y': tval.tm_mon = 4; break;
- case 'L': tval.tm_mon = 6; break;
- case 'G': tval.tm_mon = 7; break;
- case 'P': tval.tm_mon = 8; break;
- case 'T': tval.tm_mon = 9; break;
- case 'V': tval.tm_mon = 10; break;
- case 'C': tval.tm_mon = 11; break;
- }
- tval.tm_year -= 1900;
- size_t gmt, non_gmt = mktime(&tval);
- if ((zone[0] == '+') || (zone[0] == '-')) {
- if (!isdigit(zone[1]) || !isdigit(zone[2])
- || !isdigit(zone[3]) || !isdigit(zone[4])) {
- return false;
- }
- int hours = (zone[1] - '0') * 10 + (zone[2] - '0');
- int minutes = (zone[3] - '0') * 10 + (zone[4] - '0');
- int offset = (hours * 60 + minutes) * 60;
- gmt = non_gmt + ((zone[0] == '+') ? offset : -offset);
- } else {
- size_t zindex;
- if (!find_string(zindex, zone, kTimeZones, ARRAY_SIZE(kTimeZones))) {
- return false;
- }
- gmt = non_gmt + kTimeZoneOffsets[zindex] * 60 * 60;
- }
- // TODO: Android should support timezone, see b/2441195
-#if defined(OSX) || defined(ANDROID) || defined(BSD)
- tm *tm_for_timezone = localtime((time_t *)&gmt);
- *seconds = gmt + tm_for_timezone->tm_gmtoff;
-#else
- *seconds = gmt - timezone;
-#endif
- return true;
-}
-
-std::string HttpAddress(const SocketAddress& address, bool secure) {
- return (address.port() == HttpDefaultPort(secure))
- ? address.hostname() : address.ToString();
-}
-
-//////////////////////////////////////////////////////////////////////
-// HttpData
-//////////////////////////////////////////////////////////////////////
-
-void
-HttpData::clear(bool release_document) {
- // Clear headers first, since releasing a document may have far-reaching
- // effects.
- headers_.clear();
- if (release_document) {
- document.reset();
- }
-}
-
-void
-HttpData::copy(const HttpData& src) {
- headers_ = src.headers_;
-}
-
-void
-HttpData::changeHeader(const std::string& name, const std::string& value,
- HeaderCombine combine) {
- if (combine == HC_AUTO) {
- HttpHeader header;
- // Unrecognized headers are collapsible
- combine = !FromString(header, name) || HttpHeaderIsCollapsible(header)
- ? HC_YES : HC_NO;
- } else if (combine == HC_REPLACE) {
- headers_.erase(name);
- combine = HC_NO;
- }
- // At this point, combine is one of (YES, NO, NEW)
- if (combine != HC_NO) {
- HeaderMap::iterator it = headers_.find(name);
- if (it != headers_.end()) {
- if (combine == HC_YES) {
- it->second.append(",");
- it->second.append(value);
- }
- return;
- }
- }
- headers_.insert(HeaderMap::value_type(name, value));
-}
-
-size_t HttpData::clearHeader(const std::string& name) {
- return headers_.erase(name);
-}
-
-HttpData::iterator HttpData::clearHeader(iterator header) {
- iterator deprecated = header++;
- headers_.erase(deprecated);
- return header;
-}
-
-bool
-HttpData::hasHeader(const std::string& name, std::string* value) const {
- HeaderMap::const_iterator it = headers_.find(name);
- if (it == headers_.end()) {
- return false;
- } else if (value) {
- *value = it->second;
- }
- return true;
-}
-
-void HttpData::setContent(const std::string& content_type,
- StreamInterface* document) {
- setHeader(HH_CONTENT_TYPE, content_type);
- setDocumentAndLength(document);
-}
-
-void HttpData::setDocumentAndLength(StreamInterface* document) {
- // TODO: Consider calling Rewind() here?
- ASSERT(!hasHeader(HH_CONTENT_LENGTH, NULL));
- ASSERT(!hasHeader(HH_TRANSFER_ENCODING, NULL));
- ASSERT(document != NULL);
- this->document.reset(document);
- size_t content_length = 0;
- if (this->document->GetAvailable(&content_length)) {
- char buffer[32];
- sprintfn(buffer, sizeof(buffer), "%d", content_length);
- setHeader(HH_CONTENT_LENGTH, buffer);
- } else {
- setHeader(HH_TRANSFER_ENCODING, "chunked");
- }
-}
-
-//
-// HttpRequestData
-//
-
-void
-HttpRequestData::clear(bool release_document) {
- verb = HV_GET;
- path.clear();
- HttpData::clear(release_document);
-}
-
-void
-HttpRequestData::copy(const HttpRequestData& src) {
- verb = src.verb;
- path = src.path;
- HttpData::copy(src);
-}
-
-size_t
-HttpRequestData::formatLeader(char* buffer, size_t size) const {
- ASSERT(path.find(' ') == std::string::npos);
- return sprintfn(buffer, size, "%s %.*s HTTP/%s", ToString(verb), path.size(),
- path.data(), ToString(version));
-}
-
-HttpError
-HttpRequestData::parseLeader(const char* line, size_t len) {
- unsigned int vmajor, vminor;
- int vend, dstart, dend;
- // sscanf isn't safe with strings that aren't null-terminated, and there is
- // no guarantee that |line| is. Create a local copy that is null-terminated.
- std::string line_str(line, len);
- line = line_str.c_str();
- if ((sscanf(line, "%*s%n %n%*s%n HTTP/%u.%u",
- &vend, &dstart, &dend, &vmajor, &vminor) != 2)
- || (vmajor != 1)) {
- return HE_PROTOCOL;
- }
- if (vminor == 0) {
- version = HVER_1_0;
- } else if (vminor == 1) {
- version = HVER_1_1;
- } else {
- return HE_PROTOCOL;
- }
- std::string sverb(line, vend);
- if (!FromString(verb, sverb.c_str())) {
- return HE_PROTOCOL; // !?! HC_METHOD_NOT_SUPPORTED?
- }
- path.assign(line + dstart, line + dend);
- return HE_NONE;
-}
-
-bool HttpRequestData::getAbsoluteUri(std::string* uri) const {
- if (HV_CONNECT == verb)
- return false;
- Url<char> url(path);
- if (url.valid()) {
- uri->assign(path);
- return true;
- }
- std::string host;
- if (!hasHeader(HH_HOST, &host))
- return false;
- url.set_address(host);
- url.set_full_path(path);
- uri->assign(url.url());
- return url.valid();
-}
-
-bool HttpRequestData::getRelativeUri(std::string* host,
- std::string* path) const
-{
- if (HV_CONNECT == verb)
- return false;
- Url<char> url(this->path);
- if (url.valid()) {
- host->assign(url.address());
- path->assign(url.full_path());
- return true;
- }
- if (!hasHeader(HH_HOST, host))
- return false;
- path->assign(this->path);
- return true;
-}
-
-//
-// HttpResponseData
-//
-
-void
-HttpResponseData::clear(bool release_document) {
- scode = HC_INTERNAL_SERVER_ERROR;
- message.clear();
- HttpData::clear(release_document);
-}
-
-void
-HttpResponseData::copy(const HttpResponseData& src) {
- scode = src.scode;
- message = src.message;
- HttpData::copy(src);
-}
-
-void
-HttpResponseData::set_success(uint32 scode) {
- this->scode = scode;
- message.clear();
- setHeader(HH_CONTENT_LENGTH, "0", false);
-}
-
-void
-HttpResponseData::set_success(const std::string& content_type,
- StreamInterface* document,
- uint32 scode) {
- this->scode = scode;
- message.erase(message.begin(), message.end());
- setContent(content_type, document);
-}
-
-void
-HttpResponseData::set_redirect(const std::string& location, uint32 scode) {
- this->scode = scode;
- message.clear();
- setHeader(HH_LOCATION, location);
- setHeader(HH_CONTENT_LENGTH, "0", false);
-}
-
-void
-HttpResponseData::set_error(uint32 scode) {
- this->scode = scode;
- message.clear();
- setHeader(HH_CONTENT_LENGTH, "0", false);
-}
-
-size_t
-HttpResponseData::formatLeader(char* buffer, size_t size) const {
- size_t len = sprintfn(buffer, size, "HTTP/%s %lu", ToString(version), scode);
- if (!message.empty()) {
- len += sprintfn(buffer + len, size - len, " %.*s",
- message.size(), message.data());
- }
- return len;
-}
-
-HttpError
-HttpResponseData::parseLeader(const char* line, size_t len) {
- size_t pos = 0;
- unsigned int vmajor, vminor, temp_scode;
- int temp_pos;
- // sscanf isn't safe with strings that aren't null-terminated, and there is
- // no guarantee that |line| is. Create a local copy that is null-terminated.
- std::string line_str(line, len);
- line = line_str.c_str();
- if (sscanf(line, "HTTP %u%n",
- &temp_scode, &temp_pos) == 1) {
- // This server's response has no version. :( NOTE: This happens for every
- // response to requests made from Chrome plugins, regardless of the server's
- // behaviour.
- LOG(LS_VERBOSE) << "HTTP version missing from response";
- version = HVER_UNKNOWN;
- } else if ((sscanf(line, "HTTP/%u.%u %u%n",
- &vmajor, &vminor, &temp_scode, &temp_pos) == 3)
- && (vmajor == 1)) {
- // This server's response does have a version.
- if (vminor == 0) {
- version = HVER_1_0;
- } else if (vminor == 1) {
- version = HVER_1_1;
- } else {
- return HE_PROTOCOL;
- }
- } else {
- return HE_PROTOCOL;
- }
- scode = temp_scode;
- pos = static_cast<size_t>(temp_pos);
- while ((pos < len) && isspace(static_cast<unsigned char>(line[pos]))) ++pos;
- message.assign(line + pos, len - pos);
- return HE_NONE;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Http Authentication
-//////////////////////////////////////////////////////////////////////
-
-#define TEST_DIGEST 0
-#if TEST_DIGEST
-/*
-const char * const DIGEST_CHALLENGE =
- "Digest realm=\"testrealm@host.com\","
- " qop=\"auth,auth-int\","
- " nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\","
- " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"";
-const char * const DIGEST_METHOD = "GET";
-const char * const DIGEST_URI =
- "/dir/index.html";;
-const char * const DIGEST_CNONCE =
- "0a4f113b";
-const char * const DIGEST_RESPONSE =
- "6629fae49393a05397450978507c4ef1";
-//user_ = "Mufasa";
-//pass_ = "Circle Of Life";
-*/
-const char * const DIGEST_CHALLENGE =
- "Digest realm=\"Squid proxy-caching web server\","
- " nonce=\"Nny4QuC5PwiSDixJ\","
- " qop=\"auth\","
- " stale=false";
-const char * const DIGEST_URI =
- "/";
-const char * const DIGEST_CNONCE =
- "6501d58e9a21cee1e7b5fec894ded024";
-const char * const DIGEST_RESPONSE =
- "edffcb0829e755838b073a4a42de06bc";
-#endif
-
-std::string quote(const std::string& str) {
- std::string result;
- result.push_back('"');
- for (size_t i=0; i<str.size(); ++i) {
- if ((str[i] == '"') || (str[i] == '\\'))
- result.push_back('\\');
- result.push_back(str[i]);
- }
- result.push_back('"');
- return result;
-}
-
-#ifdef WIN32
-struct NegotiateAuthContext : public HttpAuthContext {
- CredHandle cred;
- CtxtHandle ctx;
- size_t steps;
- bool specified_credentials;
-
- NegotiateAuthContext(const std::string& auth, CredHandle c1, CtxtHandle c2)
- : HttpAuthContext(auth), cred(c1), ctx(c2), steps(0),
- specified_credentials(false)
- { }
-
- virtual ~NegotiateAuthContext() {
- DeleteSecurityContext(&ctx);
- FreeCredentialsHandle(&cred);
- }
-};
-#endif // WIN32
-
-HttpAuthResult HttpAuthenticate(
- const char * challenge, size_t len,
- const SocketAddress& server,
- const std::string& method, const std::string& uri,
- const std::string& username, const CryptString& password,
- HttpAuthContext *& context, std::string& response, std::string& auth_method)
-{
-#if TEST_DIGEST
- challenge = DIGEST_CHALLENGE;
- len = strlen(challenge);
-#endif
-
- HttpAttributeList args;
- HttpParseAttributes(challenge, len, args);
- HttpHasNthAttribute(args, 0, &auth_method, NULL);
-
- if (context && (context->auth_method != auth_method))
- return HAR_IGNORE;
-
- // BASIC
- if (_stricmp(auth_method.c_str(), "basic") == 0) {
- if (context)
- return HAR_CREDENTIALS; // Bad credentials
- if (username.empty())
- return HAR_CREDENTIALS; // Missing credentials
-
- context = new HttpAuthContext(auth_method);
-
- // TODO: convert sensitive to a secure buffer that gets securely deleted
- //std::string decoded = username + ":" + password;
- size_t len = username.size() + password.GetLength() + 2;
- char * sensitive = new char[len];
- size_t pos = strcpyn(sensitive, len, username.data(), username.size());
- pos += strcpyn(sensitive + pos, len - pos, ":");
- password.CopyTo(sensitive + pos, true);
-
- response = auth_method;
- response.append(" ");
- // TODO: create a sensitive-source version of Base64::encode
- response.append(Base64::Encode(sensitive));
- memset(sensitive, 0, len);
- delete [] sensitive;
- return HAR_RESPONSE;
- }
-
- // DIGEST
- if (_stricmp(auth_method.c_str(), "digest") == 0) {
- if (context)
- return HAR_CREDENTIALS; // Bad credentials
- if (username.empty())
- return HAR_CREDENTIALS; // Missing credentials
-
- context = new HttpAuthContext(auth_method);
-
- std::string cnonce, ncount;
-#if TEST_DIGEST
- method = DIGEST_METHOD;
- uri = DIGEST_URI;
- cnonce = DIGEST_CNONCE;
-#else
- char buffer[256];
- sprintf(buffer, "%d", static_cast<int>(time(0)));
- cnonce = MD5(buffer);
-#endif
- ncount = "00000001";
-
- std::string realm, nonce, qop, opaque;
- HttpHasAttribute(args, "realm", &realm);
- HttpHasAttribute(args, "nonce", &nonce);
- bool has_qop = HttpHasAttribute(args, "qop", &qop);
- bool has_opaque = HttpHasAttribute(args, "opaque", &opaque);
-
- // TODO: convert sensitive to be secure buffer
- //std::string A1 = username + ":" + realm + ":" + password;
- size_t len = username.size() + realm.size() + password.GetLength() + 3;
- char * sensitive = new char[len]; // A1
- size_t pos = strcpyn(sensitive, len, username.data(), username.size());
- pos += strcpyn(sensitive + pos, len - pos, ":");
- pos += strcpyn(sensitive + pos, len - pos, realm.c_str());
- pos += strcpyn(sensitive + pos, len - pos, ":");
- password.CopyTo(sensitive + pos, true);
-
- std::string A2 = method + ":" + uri;
- std::string middle;
- if (has_qop) {
- qop = "auth";
- middle = nonce + ":" + ncount + ":" + cnonce + ":" + qop;
- } else {
- middle = nonce;
- }
- std::string HA1 = MD5(sensitive);
- memset(sensitive, 0, len);
- delete [] sensitive;
- std::string HA2 = MD5(A2);
- std::string dig_response = MD5(HA1 + ":" + middle + ":" + HA2);
-
-#if TEST_DIGEST
- ASSERT(strcmp(dig_response.c_str(), DIGEST_RESPONSE) == 0);
-#endif
-
- std::stringstream ss;
- ss << auth_method;
- ss << " username=" << quote(username);
- ss << ", realm=" << quote(realm);
- ss << ", nonce=" << quote(nonce);
- ss << ", uri=" << quote(uri);
- if (has_qop) {
- ss << ", qop=" << qop;
- ss << ", nc=" << ncount;
- ss << ", cnonce=" << quote(cnonce);
- }
- ss << ", response=\"" << dig_response << "\"";
- if (has_opaque) {
- ss << ", opaque=" << quote(opaque);
- }
- response = ss.str();
- return HAR_RESPONSE;
- }
-
-#ifdef WIN32
-#if 1
- bool want_negotiate = (_stricmp(auth_method.c_str(), "negotiate") == 0);
- bool want_ntlm = (_stricmp(auth_method.c_str(), "ntlm") == 0);
- // SPNEGO & NTLM
- if (want_negotiate || want_ntlm) {
- const size_t MAX_MESSAGE = 12000, MAX_SPN = 256;
- char out_buf[MAX_MESSAGE], spn[MAX_SPN];
-
-#if 0 // Requires funky windows versions
- DWORD len = MAX_SPN;
- if (DsMakeSpn("HTTP", server.HostAsURIString().c_str(), NULL,
- server.port(),
- 0, &len, spn) != ERROR_SUCCESS) {
- LOG_F(WARNING) << "(Negotiate) - DsMakeSpn failed";
- return HAR_IGNORE;
- }
-#else
- sprintfn(spn, MAX_SPN, "HTTP/%s", server.ToString().c_str());
-#endif
-
- SecBuffer out_sec;
- out_sec.pvBuffer = out_buf;
- out_sec.cbBuffer = sizeof(out_buf);
- out_sec.BufferType = SECBUFFER_TOKEN;
-
- SecBufferDesc out_buf_desc;
- out_buf_desc.ulVersion = 0;
- out_buf_desc.cBuffers = 1;
- out_buf_desc.pBuffers = &out_sec;
-
- const ULONG NEG_FLAGS_DEFAULT =
- //ISC_REQ_ALLOCATE_MEMORY
- ISC_REQ_CONFIDENTIALITY
- //| ISC_REQ_EXTENDED_ERROR
- //| ISC_REQ_INTEGRITY
- | ISC_REQ_REPLAY_DETECT
- | ISC_REQ_SEQUENCE_DETECT
- //| ISC_REQ_STREAM
- //| ISC_REQ_USE_SUPPLIED_CREDS
- ;
-
- ::TimeStamp lifetime;
- SECURITY_STATUS ret = S_OK;
- ULONG ret_flags = 0, flags = NEG_FLAGS_DEFAULT;
-
- bool specify_credentials = !username.empty();
- size_t steps = 0;
-
- //uint32 now = Time();
-
- NegotiateAuthContext * neg = static_cast<NegotiateAuthContext *>(context);
- if (neg) {
- const size_t max_steps = 10;
- if (++neg->steps >= max_steps) {
- LOG(WARNING) << "AsyncHttpsProxySocket::Authenticate(Negotiate) too many retries";
- return HAR_ERROR;
- }
- steps = neg->steps;
-
- std::string challenge, decoded_challenge;
- if (HttpHasNthAttribute(args, 1, &challenge, NULL)
- && Base64::Decode(challenge, Base64::DO_STRICT,
- &decoded_challenge, NULL)) {
- SecBuffer in_sec;
- in_sec.pvBuffer = const_cast<char *>(decoded_challenge.data());
- in_sec.cbBuffer = static_cast<unsigned long>(decoded_challenge.size());
- in_sec.BufferType = SECBUFFER_TOKEN;
-
- SecBufferDesc in_buf_desc;
- in_buf_desc.ulVersion = 0;
- in_buf_desc.cBuffers = 1;
- in_buf_desc.pBuffers = &in_sec;
-
- ret = InitializeSecurityContextA(&neg->cred, &neg->ctx, spn, flags, 0, SECURITY_NATIVE_DREP, &in_buf_desc, 0, &neg->ctx, &out_buf_desc, &ret_flags, &lifetime);
- //LOG(INFO) << "$$$ InitializeSecurityContext @ " << TimeSince(now);
- if (FAILED(ret)) {
- LOG(LS_ERROR) << "InitializeSecurityContext returned: "
- << ErrorName(ret, SECURITY_ERRORS);
- return HAR_ERROR;
- }
- } else if (neg->specified_credentials) {
- // Try again with default credentials
- specify_credentials = false;
- delete context;
- context = neg = 0;
- } else {
- return HAR_CREDENTIALS;
- }
- }
-
- if (!neg) {
- unsigned char userbuf[256], passbuf[256], domainbuf[16];
- SEC_WINNT_AUTH_IDENTITY_A auth_id, * pauth_id = 0;
- if (specify_credentials) {
- memset(&auth_id, 0, sizeof(auth_id));
- size_t len = password.GetLength()+1;
- char * sensitive = new char[len];
- password.CopyTo(sensitive, true);
- std::string::size_type pos = username.find('\\');
- if (pos == std::string::npos) {
- auth_id.UserLength = static_cast<unsigned long>(
- _min(sizeof(userbuf) - 1, username.size()));
- memcpy(userbuf, username.c_str(), auth_id.UserLength);
- userbuf[auth_id.UserLength] = 0;
- auth_id.DomainLength = 0;
- domainbuf[auth_id.DomainLength] = 0;
- auth_id.PasswordLength = static_cast<unsigned long>(
- _min(sizeof(passbuf) - 1, password.GetLength()));
- memcpy(passbuf, sensitive, auth_id.PasswordLength);
- passbuf[auth_id.PasswordLength] = 0;
- } else {
- auth_id.UserLength = static_cast<unsigned long>(
- _min(sizeof(userbuf) - 1, username.size() - pos - 1));
- memcpy(userbuf, username.c_str() + pos + 1, auth_id.UserLength);
- userbuf[auth_id.UserLength] = 0;
- auth_id.DomainLength = static_cast<unsigned long>(
- _min(sizeof(domainbuf) - 1, pos));
- memcpy(domainbuf, username.c_str(), auth_id.DomainLength);
- domainbuf[auth_id.DomainLength] = 0;
- auth_id.PasswordLength = static_cast<unsigned long>(
- _min(sizeof(passbuf) - 1, password.GetLength()));
- memcpy(passbuf, sensitive, auth_id.PasswordLength);
- passbuf[auth_id.PasswordLength] = 0;
- }
- memset(sensitive, 0, len);
- delete [] sensitive;
- auth_id.User = userbuf;
- auth_id.Domain = domainbuf;
- auth_id.Password = passbuf;
- auth_id.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
- pauth_id = &auth_id;
- LOG(LS_VERBOSE) << "Negotiate protocol: Using specified credentials";
- } else {
- LOG(LS_VERBOSE) << "Negotiate protocol: Using default credentials";
- }
-
- CredHandle cred;
- ret = AcquireCredentialsHandleA(0, want_negotiate ? NEGOSSP_NAME_A : NTLMSP_NAME_A, SECPKG_CRED_OUTBOUND, 0, pauth_id, 0, 0, &cred, &lifetime);
- //LOG(INFO) << "$$$ AcquireCredentialsHandle @ " << TimeSince(now);
- if (ret != SEC_E_OK) {
- LOG(LS_ERROR) << "AcquireCredentialsHandle error: "
- << ErrorName(ret, SECURITY_ERRORS);
- return HAR_IGNORE;
- }
-
- //CSecBufferBundle<5, CSecBufferBase::FreeSSPI> sb_out;
-
- CtxtHandle ctx;
- ret = InitializeSecurityContextA(&cred, 0, spn, flags, 0, SECURITY_NATIVE_DREP, 0, 0, &ctx, &out_buf_desc, &ret_flags, &lifetime);
- //LOG(INFO) << "$$$ InitializeSecurityContext @ " << TimeSince(now);
- if (FAILED(ret)) {
- LOG(LS_ERROR) << "InitializeSecurityContext returned: "
- << ErrorName(ret, SECURITY_ERRORS);
- FreeCredentialsHandle(&cred);
- return HAR_IGNORE;
- }
-
- ASSERT(!context);
- context = neg = new NegotiateAuthContext(auth_method, cred, ctx);
- neg->specified_credentials = specify_credentials;
- neg->steps = steps;
- }
-
- if ((ret == SEC_I_COMPLETE_NEEDED) || (ret == SEC_I_COMPLETE_AND_CONTINUE)) {
- ret = CompleteAuthToken(&neg->ctx, &out_buf_desc);
- //LOG(INFO) << "$$$ CompleteAuthToken @ " << TimeSince(now);
- LOG(LS_VERBOSE) << "CompleteAuthToken returned: "
- << ErrorName(ret, SECURITY_ERRORS);
- if (FAILED(ret)) {
- return HAR_ERROR;
- }
- }
-
- //LOG(INFO) << "$$$ NEGOTIATE took " << TimeSince(now) << "ms";
-
- std::string decoded(out_buf, out_buf + out_sec.cbBuffer);
- response = auth_method;
- response.append(" ");
- response.append(Base64::Encode(decoded));
- return HAR_RESPONSE;
- }
-#endif
-#endif // WIN32
-
- return HAR_IGNORE;
-}
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/httpcommon.h b/base/httpcommon.h
deleted file mode 100644
index 1112f8d..0000000
--- a/base/httpcommon.h
+++ /dev/null
@@ -1,463 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_HTTPCOMMON_H__
-#define TALK_BASE_HTTPCOMMON_H__
-
-#include <map>
-#include <string>
-#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-class CryptString;
-class SocketAddress;
-
-//////////////////////////////////////////////////////////////////////
-// Constants
-//////////////////////////////////////////////////////////////////////
-
-enum HttpCode {
- HC_OK = 200,
- HC_NON_AUTHORITATIVE = 203,
- HC_NO_CONTENT = 204,
- HC_PARTIAL_CONTENT = 206,
-
- HC_MULTIPLE_CHOICES = 300,
- HC_MOVED_PERMANENTLY = 301,
- HC_FOUND = 302,
- HC_SEE_OTHER = 303,
- HC_NOT_MODIFIED = 304,
- HC_MOVED_TEMPORARILY = 307,
-
- HC_BAD_REQUEST = 400,
- HC_UNAUTHORIZED = 401,
- HC_FORBIDDEN = 403,
- HC_NOT_FOUND = 404,
- HC_PROXY_AUTHENTICATION_REQUIRED = 407,
- HC_GONE = 410,
-
- HC_INTERNAL_SERVER_ERROR = 500,
- HC_NOT_IMPLEMENTED = 501,
- HC_SERVICE_UNAVAILABLE = 503,
-};
-
-enum HttpVersion {
- HVER_1_0, HVER_1_1, HVER_UNKNOWN,
- HVER_LAST = HVER_UNKNOWN
-};
-
-enum HttpVerb {
- HV_GET, HV_POST, HV_PUT, HV_DELETE, HV_CONNECT, HV_HEAD,
- HV_LAST = HV_HEAD
-};
-
-enum HttpError {
- HE_NONE,
- HE_PROTOCOL, // Received non-valid HTTP data
- HE_DISCONNECTED, // Connection closed unexpectedly
- HE_OVERFLOW, // Received too much data for internal buffers
- HE_CONNECT_FAILED, // The socket failed to connect.
- HE_SOCKET_ERROR, // An error occurred on a connected socket
- HE_SHUTDOWN, // Http object is being destroyed
- HE_OPERATION_CANCELLED, // Connection aborted locally
- HE_AUTH, // Proxy Authentication Required
- HE_CERTIFICATE_EXPIRED, // During SSL negotiation
- HE_STREAM, // Problem reading or writing to the document
- HE_CACHE, // Problem reading from cache
- HE_DEFAULT
-};
-
-enum HttpHeader {
- HH_AGE,
- HH_CACHE_CONTROL,
- HH_CONNECTION,
- HH_CONTENT_DISPOSITION,
- HH_CONTENT_LENGTH,
- HH_CONTENT_RANGE,
- HH_CONTENT_TYPE,
- HH_COOKIE,
- HH_DATE,
- HH_ETAG,
- HH_EXPIRES,
- HH_HOST,
- HH_IF_MODIFIED_SINCE,
- HH_IF_NONE_MATCH,
- HH_KEEP_ALIVE,
- HH_LAST_MODIFIED,
- HH_LOCATION,
- HH_PROXY_AUTHENTICATE,
- HH_PROXY_AUTHORIZATION,
- HH_PROXY_CONNECTION,
- HH_RANGE,
- HH_SET_COOKIE,
- HH_TE,
- HH_TRAILERS,
- HH_TRANSFER_ENCODING,
- HH_UPGRADE,
- HH_USER_AGENT,
- HH_WWW_AUTHENTICATE,
- HH_LAST = HH_WWW_AUTHENTICATE
-};
-
-const uint16 HTTP_DEFAULT_PORT = 80;
-const uint16 HTTP_SECURE_PORT = 443;
-
-//////////////////////////////////////////////////////////////////////
-// Utility Functions
-//////////////////////////////////////////////////////////////////////
-
-inline HttpError mkerr(HttpError err, HttpError def_err = HE_DEFAULT) {
- return (err != HE_NONE) ? err : def_err;
-}
-
-const char* ToString(HttpVersion version);
-bool FromString(HttpVersion& version, const std::string& str);
-
-const char* ToString(HttpVerb verb);
-bool FromString(HttpVerb& verb, const std::string& str);
-
-const char* ToString(HttpHeader header);
-bool FromString(HttpHeader& header, const std::string& str);
-
-inline bool HttpCodeIsInformational(uint32 code) { return ((code / 100) == 1); }
-inline bool HttpCodeIsSuccessful(uint32 code) { return ((code / 100) == 2); }
-inline bool HttpCodeIsRedirection(uint32 code) { return ((code / 100) == 3); }
-inline bool HttpCodeIsClientError(uint32 code) { return ((code / 100) == 4); }
-inline bool HttpCodeIsServerError(uint32 code) { return ((code / 100) == 5); }
-
-bool HttpCodeHasBody(uint32 code);
-bool HttpCodeIsCacheable(uint32 code);
-bool HttpHeaderIsEndToEnd(HttpHeader header);
-bool HttpHeaderIsCollapsible(HttpHeader header);
-
-struct HttpData;
-bool HttpShouldKeepAlive(const HttpData& data);
-
-typedef std::pair<std::string, std::string> HttpAttribute;
-typedef std::vector<HttpAttribute> HttpAttributeList;
-void HttpComposeAttributes(const HttpAttributeList& attributes, char separator,
- std::string* composed);
-void HttpParseAttributes(const char * data, size_t len,
- HttpAttributeList& attributes);
-bool HttpHasAttribute(const HttpAttributeList& attributes,
- const std::string& name,
- std::string* value);
-bool HttpHasNthAttribute(HttpAttributeList& attributes,
- size_t index,
- std::string* name,
- std::string* value);
-
-// Convert RFC1123 date (DoW, DD Mon YYYY HH:MM:SS TZ) to unix timestamp
-bool HttpDateToSeconds(const std::string& date, time_t* seconds);
-
-inline uint16 HttpDefaultPort(bool secure) {
- return secure ? HTTP_SECURE_PORT : HTTP_DEFAULT_PORT;
-}
-
-// Returns the http server notation for a given address
-std::string HttpAddress(const SocketAddress& address, bool secure);
-
-// functional for insensitive std::string compare
-struct iless {
- bool operator()(const std::string& lhs, const std::string& rhs) const {
- return (::_stricmp(lhs.c_str(), rhs.c_str()) < 0);
- }
-};
-
-// put quotes around a string and escape any quotes inside it
-std::string quote(const std::string& str);
-
-//////////////////////////////////////////////////////////////////////
-// Url
-//////////////////////////////////////////////////////////////////////
-
-template<class CTYPE>
-class Url {
-public:
- typedef typename Traits<CTYPE>::string string;
-
- // TODO: Implement Encode/Decode
- static int Encode(const CTYPE* source, CTYPE* destination, size_t len);
- static int Encode(const string& source, string& destination);
- static int Decode(const CTYPE* source, CTYPE* destination, size_t len);
- static int Decode(const string& source, string& destination);
-
- Url(const string& url) { do_set_url(url.c_str(), url.size()); }
- Url(const string& path, const string& host, uint16 port = HTTP_DEFAULT_PORT)
- : host_(host), port_(port), secure_(HTTP_SECURE_PORT == port)
- { set_full_path(path); }
-
- bool valid() const { return !host_.empty(); }
- void clear() {
- host_.clear();
- port_ = HTTP_DEFAULT_PORT;
- secure_ = false;
- path_.assign(1, static_cast<CTYPE>('/'));
- query_.clear();
- }
-
- void set_url(const string& val) {
- do_set_url(val.c_str(), val.size());
- }
- string url() const {
- string val; do_get_url(&val); return val;
- }
-
- void set_address(const string& val) {
- do_set_address(val.c_str(), val.size());
- }
- string address() const {
- string val; do_get_address(&val); return val;
- }
-
- void set_full_path(const string& val) {
- do_set_full_path(val.c_str(), val.size());
- }
- string full_path() const {
- string val; do_get_full_path(&val); return val;
- }
-
- void set_host(const string& val) { host_ = val; }
- const string& host() const { return host_; }
-
- void set_port(uint16 val) { port_ = val; }
- uint16 port() const { return port_; }
-
- void set_secure(bool val) { secure_ = val; }
- bool secure() const { return secure_; }
-
- void set_path(const string& val) {
- if (val.empty()) {
- path_.assign(1, static_cast<CTYPE>('/'));
- } else {
- ASSERT(val[0] == static_cast<CTYPE>('/'));
- path_ = val;
- }
- }
- const string& path() const { return path_; }
-
- void set_query(const string& val) {
- ASSERT(val.empty() || (val[0] == static_cast<CTYPE>('?')));
- query_ = val;
- }
- const string& query() const { return query_; }
-
- bool get_attribute(const string& name, string* value) const;
-
-private:
- void do_set_url(const CTYPE* val, size_t len);
- void do_set_address(const CTYPE* val, size_t len);
- void do_set_full_path(const CTYPE* val, size_t len);
-
- void do_get_url(string* val) const;
- void do_get_address(string* val) const;
- void do_get_full_path(string* val) const;
-
- string host_, path_, query_;
- uint16 port_;
- bool secure_;
-};
-
-//////////////////////////////////////////////////////////////////////
-// HttpData
-//////////////////////////////////////////////////////////////////////
-
-struct HttpData {
- typedef std::multimap<std::string, std::string, iless> HeaderMap;
- typedef HeaderMap::const_iterator const_iterator;
- typedef HeaderMap::iterator iterator;
-
- HttpVersion version;
- scoped_ptr<StreamInterface> document;
-
- HttpData() : version(HVER_1_1) { }
-
- enum HeaderCombine { HC_YES, HC_NO, HC_AUTO, HC_REPLACE, HC_NEW };
- void changeHeader(const std::string& name, const std::string& value,
- HeaderCombine combine);
- inline void addHeader(const std::string& name, const std::string& value,
- bool append = true) {
- changeHeader(name, value, append ? HC_AUTO : HC_NO);
- }
- inline void setHeader(const std::string& name, const std::string& value,
- bool overwrite = true) {
- changeHeader(name, value, overwrite ? HC_REPLACE : HC_NEW);
- }
- // Returns count of erased headers
- size_t clearHeader(const std::string& name);
- // Returns iterator to next header
- iterator clearHeader(iterator header);
-
- // keep in mind, this may not do what you want in the face of multiple headers
- bool hasHeader(const std::string& name, std::string* value) const;
-
- inline const_iterator begin() const {
- return headers_.begin();
- }
- inline const_iterator end() const {
- return headers_.end();
- }
- inline iterator begin() {
- return headers_.begin();
- }
- inline iterator end() {
- return headers_.end();
- }
- inline const_iterator begin(const std::string& name) const {
- return headers_.lower_bound(name);
- }
- inline const_iterator end(const std::string& name) const {
- return headers_.upper_bound(name);
- }
- inline iterator begin(const std::string& name) {
- return headers_.lower_bound(name);
- }
- inline iterator end(const std::string& name) {
- return headers_.upper_bound(name);
- }
-
- // Convenience methods using HttpHeader
- inline void changeHeader(HttpHeader header, const std::string& value,
- HeaderCombine combine) {
- changeHeader(ToString(header), value, combine);
- }
- inline void addHeader(HttpHeader header, const std::string& value,
- bool append = true) {
- addHeader(ToString(header), value, append);
- }
- inline void setHeader(HttpHeader header, const std::string& value,
- bool overwrite = true) {
- setHeader(ToString(header), value, overwrite);
- }
- inline void clearHeader(HttpHeader header) {
- clearHeader(ToString(header));
- }
- inline bool hasHeader(HttpHeader header, std::string* value) const {
- return hasHeader(ToString(header), value);
- }
- inline const_iterator begin(HttpHeader header) const {
- return headers_.lower_bound(ToString(header));
- }
- inline const_iterator end(HttpHeader header) const {
- return headers_.upper_bound(ToString(header));
- }
- inline iterator begin(HttpHeader header) {
- return headers_.lower_bound(ToString(header));
- }
- inline iterator end(HttpHeader header) {
- return headers_.upper_bound(ToString(header));
- }
-
- void setContent(const std::string& content_type, StreamInterface* document);
- void setDocumentAndLength(StreamInterface* document);
-
- virtual size_t formatLeader(char* buffer, size_t size) const = 0;
- virtual HttpError parseLeader(const char* line, size_t len) = 0;
-
-protected:
- virtual ~HttpData() { }
- void clear(bool release_document);
- void copy(const HttpData& src);
-
-private:
- HeaderMap headers_;
-};
-
-struct HttpRequestData : public HttpData {
- HttpVerb verb;
- std::string path;
-
- HttpRequestData() : verb(HV_GET) { }
-
- void clear(bool release_document);
- void copy(const HttpRequestData& src);
-
- virtual size_t formatLeader(char* buffer, size_t size) const;
- virtual HttpError parseLeader(const char* line, size_t len);
-
- bool getAbsoluteUri(std::string* uri) const;
- bool getRelativeUri(std::string* host, std::string* path) const;
-};
-
-struct HttpResponseData : public HttpData {
- uint32 scode;
- std::string message;
-
- HttpResponseData() : scode(HC_INTERNAL_SERVER_ERROR) { }
- void clear(bool release_document);
- void copy(const HttpResponseData& src);
-
- // Convenience methods
- void set_success(uint32 scode = HC_OK);
- void set_success(const std::string& content_type, StreamInterface* document,
- uint32 scode = HC_OK);
- void set_redirect(const std::string& location,
- uint32 scode = HC_MOVED_TEMPORARILY);
- void set_error(uint32 scode);
-
- virtual size_t formatLeader(char* buffer, size_t size) const;
- virtual HttpError parseLeader(const char* line, size_t len);
-};
-
-struct HttpTransaction {
- HttpRequestData request;
- HttpResponseData response;
-};
-
-//////////////////////////////////////////////////////////////////////
-// Http Authentication
-//////////////////////////////////////////////////////////////////////
-
-struct HttpAuthContext {
- std::string auth_method;
- HttpAuthContext(const std::string& auth) : auth_method(auth) { }
- virtual ~HttpAuthContext() { }
-};
-
-enum HttpAuthResult { HAR_RESPONSE, HAR_IGNORE, HAR_CREDENTIALS, HAR_ERROR };
-
-// 'context' is used by this function to record information between calls.
-// Start by passing a null pointer, then pass the same pointer each additional
-// call. When the authentication attempt is finished, delete the context.
-HttpAuthResult HttpAuthenticate(
- const char * challenge, size_t len,
- const SocketAddress& server,
- const std::string& method, const std::string& uri,
- const std::string& username, const CryptString& password,
- HttpAuthContext *& context, std::string& response, std::string& auth_method);
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_HTTPCOMMON_H__
diff --git a/base/httpcommon_unittest.cc b/base/httpcommon_unittest.cc
deleted file mode 100644
index b60f597..0000000
--- a/base/httpcommon_unittest.cc
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/httpcommon-inl.h"
-#include "talk/base/httpcommon.h"
-
-namespace talk_base {
-
-#define TEST_PROTOCOL "http://"
-#define TEST_HOST "www.google.com"
-#define TEST_PATH "/folder/file.html"
-#define TEST_QUERY "?query=x&attr=y"
-#define TEST_URL TEST_PROTOCOL TEST_HOST TEST_PATH TEST_QUERY
-
-TEST(Url, DecomposesUrls) {
- Url<char> url(TEST_URL);
- EXPECT_TRUE(url.valid());
- EXPECT_FALSE(url.secure());
- EXPECT_STREQ(TEST_HOST, url.host().c_str());
- EXPECT_EQ(80, url.port());
- EXPECT_STREQ(TEST_PATH, url.path().c_str());
- EXPECT_STREQ(TEST_QUERY, url.query().c_str());
- EXPECT_STREQ(TEST_HOST, url.address().c_str());
- EXPECT_STREQ(TEST_PATH TEST_QUERY, url.full_path().c_str());
- EXPECT_STREQ(TEST_URL, url.url().c_str());
-}
-
-TEST(Url, ComposesUrls) {
- // Set in constructor
- Url<char> url(TEST_PATH TEST_QUERY, TEST_HOST, 80);
- EXPECT_TRUE(url.valid());
- EXPECT_FALSE(url.secure());
- EXPECT_STREQ(TEST_HOST, url.host().c_str());
- EXPECT_EQ(80, url.port());
- EXPECT_STREQ(TEST_PATH, url.path().c_str());
- EXPECT_STREQ(TEST_QUERY, url.query().c_str());
- EXPECT_STREQ(TEST_HOST, url.address().c_str());
- EXPECT_STREQ(TEST_PATH TEST_QUERY, url.full_path().c_str());
- EXPECT_STREQ(TEST_URL, url.url().c_str());
-
- url.clear();
- EXPECT_FALSE(url.valid());
- EXPECT_FALSE(url.secure());
- EXPECT_STREQ("", url.host().c_str());
- EXPECT_EQ(80, url.port());
- EXPECT_STREQ("/", url.path().c_str());
- EXPECT_STREQ("", url.query().c_str());
-
- // Set component-wise
- url.set_host(TEST_HOST);
- url.set_port(80);
- url.set_path(TEST_PATH);
- url.set_query(TEST_QUERY);
- EXPECT_TRUE(url.valid());
- EXPECT_FALSE(url.secure());
- EXPECT_STREQ(TEST_HOST, url.host().c_str());
- EXPECT_EQ(80, url.port());
- EXPECT_STREQ(TEST_PATH, url.path().c_str());
- EXPECT_STREQ(TEST_QUERY, url.query().c_str());
- EXPECT_STREQ(TEST_HOST, url.address().c_str());
- EXPECT_STREQ(TEST_PATH TEST_QUERY, url.full_path().c_str());
- EXPECT_STREQ(TEST_URL, url.url().c_str());
-}
-
-TEST(Url, EnsuresNonEmptyPath) {
- Url<char> url(TEST_PROTOCOL TEST_HOST);
- EXPECT_TRUE(url.valid());
- EXPECT_STREQ("/", url.path().c_str());
-
- url.clear();
- EXPECT_STREQ("/", url.path().c_str());
- url.set_path("");
- EXPECT_STREQ("/", url.path().c_str());
-
- url.clear();
- EXPECT_STREQ("/", url.path().c_str());
- url.set_full_path("");
- EXPECT_STREQ("/", url.path().c_str());
-}
-
-TEST(Url, GetQueryAttributes) {
- Url<char> url(TEST_URL);
- std::string value;
- EXPECT_TRUE(url.get_attribute("query", &value));
- EXPECT_STREQ("x", value.c_str());
- value.clear();
- EXPECT_TRUE(url.get_attribute("attr", &value));
- EXPECT_STREQ("y", value.c_str());
- value.clear();
- EXPECT_FALSE(url.get_attribute("Query", &value));
- EXPECT_TRUE(value.empty());
-}
-
-TEST(Url, SkipsUserAndPassword) {
- Url<char> url("https://mail.google.com:pwd@badsite.com:12345/asdf");
- EXPECT_TRUE(url.valid());
- EXPECT_TRUE(url.secure());
- EXPECT_STREQ("badsite.com", url.host().c_str());
- EXPECT_EQ(12345, url.port());
- EXPECT_STREQ("/asdf", url.path().c_str());
- EXPECT_STREQ("badsite.com:12345", url.address().c_str());
-}
-
-TEST(Url, SkipsUser) {
- Url<char> url("https://mail.google.com@badsite.com:12345/asdf");
- EXPECT_TRUE(url.valid());
- EXPECT_TRUE(url.secure());
- EXPECT_STREQ("badsite.com", url.host().c_str());
- EXPECT_EQ(12345, url.port());
- EXPECT_STREQ("/asdf", url.path().c_str());
- EXPECT_STREQ("badsite.com:12345", url.address().c_str());
-}
-
-TEST(HttpResponseData, parseLeaderHttp1_0) {
- static const char kResponseString[] = "HTTP/1.0 200 OK";
- HttpResponseData response;
- EXPECT_EQ(HE_NONE, response.parseLeader(kResponseString,
- sizeof(kResponseString) - 1));
- EXPECT_EQ(HVER_1_0, response.version);
- EXPECT_EQ(200U, response.scode);
-}
-
-TEST(HttpResponseData, parseLeaderHttp1_1) {
- static const char kResponseString[] = "HTTP/1.1 200 OK";
- HttpResponseData response;
- EXPECT_EQ(HE_NONE, response.parseLeader(kResponseString,
- sizeof(kResponseString) - 1));
- EXPECT_EQ(HVER_1_1, response.version);
- EXPECT_EQ(200U, response.scode);
-}
-
-TEST(HttpResponseData, parseLeaderHttpUnknown) {
- static const char kResponseString[] = "HTTP 200 OK";
- HttpResponseData response;
- EXPECT_EQ(HE_NONE, response.parseLeader(kResponseString,
- sizeof(kResponseString) - 1));
- EXPECT_EQ(HVER_UNKNOWN, response.version);
- EXPECT_EQ(200U, response.scode);
-}
-
-TEST(HttpResponseData, parseLeaderHttpFailure) {
- static const char kResponseString[] = "HTTP/1.1 503 Service Unavailable";
- HttpResponseData response;
- EXPECT_EQ(HE_NONE, response.parseLeader(kResponseString,
- sizeof(kResponseString) - 1));
- EXPECT_EQ(HVER_1_1, response.version);
- EXPECT_EQ(503U, response.scode);
-}
-
-TEST(HttpResponseData, parseLeaderHttpInvalid) {
- static const char kResponseString[] = "Durrrrr, what's HTTP?";
- HttpResponseData response;
- EXPECT_EQ(HE_PROTOCOL, response.parseLeader(kResponseString,
- sizeof(kResponseString) - 1));
-}
-
-} // namespace talk_base
diff --git a/base/httprequest.cc b/base/httprequest.cc
deleted file mode 100644
index 48c924e..0000000
--- a/base/httprequest.cc
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/httprequest.h"
-
-#include "talk/base/common.h"
-#include "talk/base/firewallsocketserver.h"
-#include "talk/base/httpclient.h"
-#include "talk/base/logging.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/socketpool.h"
-#include "talk/base/ssladapter.h"
-
-using namespace talk_base;
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpMonitor
-///////////////////////////////////////////////////////////////////////////////
-
-HttpMonitor::HttpMonitor(SocketServer *ss) {
- ASSERT(Thread::Current() != NULL);
- ss_ = ss;
- reset();
-}
-
-void HttpMonitor::Connect(HttpClient *http) {
- http->SignalHttpClientComplete.connect(this,
- &HttpMonitor::OnHttpClientComplete);
-}
-
-void HttpMonitor::OnHttpClientComplete(HttpClient * http, HttpErrorType error) {
- complete_ = true;
- error_ = error;
- ss_->WakeUp();
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpRequest
-///////////////////////////////////////////////////////////////////////////////
-
-const int kDefaultHTTPTimeout = 30 * 1000; // 30 sec
-
-HttpRequest::HttpRequest(const std::string &user_agent)
- : firewall_(0), port_(80), secure_(false),
- timeout_(kDefaultHTTPTimeout), fail_redirect_(false),
- client_(user_agent.c_str(), NULL), error_(HE_NONE) {
-}
-
-void HttpRequest::Send() {
- // TODO: Rewrite this to use the thread's native socket server, and a more
- // natural flow?
-
- PhysicalSocketServer physical;
- SocketServer * ss = &physical;
- if (firewall_) {
- ss = new FirewallSocketServer(ss, firewall_);
- }
-
- SslSocketFactory factory(ss, client_.agent());
- factory.SetProxy(proxy_);
- if (secure_)
- factory.UseSSL(host_.c_str());
-
- //factory.SetLogging("HttpRequest");
-
- ReuseSocketPool pool(&factory);
- client_.set_pool(&pool);
-
- bool transparent_proxy = (port_ == 80) && ((proxy_.type == PROXY_HTTPS) ||
- (proxy_.type == PROXY_UNKNOWN));
-
- if (transparent_proxy) {
- client_.set_proxy(proxy_);
- }
- client_.set_fail_redirect(fail_redirect_);
-
- SocketAddress server(host_, port_);
- client_.set_server(server);
-
- LOG(LS_INFO) << "HttpRequest start: " << host_ + client_.request().path;
-
- HttpMonitor monitor(ss);
- monitor.Connect(&client_);
- client_.start();
- ss->Wait(timeout_, true);
- if (!monitor.done()) {
- LOG(LS_INFO) << "HttpRequest request timed out";
- client_.reset();
- return;
- }
-
- set_error(monitor.error());
- if (error_) {
- LOG(LS_INFO) << "HttpRequest request error: " << error_;
- return;
- }
-
- std::string value;
- if (client_.response().hasHeader(HH_LOCATION, &value)) {
- response_redirect_ = value.c_str();
- }
-}
diff --git a/base/httprequest.h b/base/httprequest.h
deleted file mode 100644
index 2e13c32..0000000
--- a/base/httprequest.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _HTTPREQUEST_H_
-#define _HTTPREQUEST_H_
-
-#include "talk/base/httpclient.h"
-#include "talk/base/logging.h"
-#include "talk/base/proxyinfo.h"
-#include "talk/base/socketserver.h"
-#include "talk/base/thread.h"
-#include "talk/base/sslsocketfactory.h" // Deprecated include
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpRequest
-///////////////////////////////////////////////////////////////////////////////
-
-class FirewallManager;
-class MemoryStream;
-
-class HttpRequest {
-public:
- HttpRequest(const std::string &user_agent);
-
- void Send();
-
- void set_proxy(const ProxyInfo& proxy) {
- proxy_ = proxy;
- }
- void set_firewall(FirewallManager * firewall) {
- firewall_ = firewall;
- }
-
- // The DNS name of the host to connect to.
- const std::string& host() { return host_; }
- void set_host(const std::string& host) { host_ = host; }
-
- // The port to connect to on the target host.
- int port() { return port_; }
- void set_port(int port) { port_ = port; }
-
- // Whether the request should use SSL.
- bool secure() { return secure_; }
- void set_secure(bool secure) { secure_ = secure; }
-
- // Returns the redirect when redirection occurs
- const std::string& response_redirect() { return response_redirect_; }
-
- // Time to wait on the download, in ms. Default is 5000 (5s)
- int timeout() { return timeout_; }
- void set_timeout(int timeout) { timeout_ = timeout; }
-
- // Fail redirects to allow analysis of redirect urls, etc.
- bool fail_redirect() const { return fail_redirect_; }
- void set_fail_redirect(bool fail_redirect) { fail_redirect_ = fail_redirect; }
-
- HttpRequestData& request() { return client_.request(); }
- HttpResponseData& response() { return client_.response(); }
- HttpErrorType error() { return error_; }
-
-protected:
- void set_error(HttpErrorType error) { error_ = error; }
-
-private:
- ProxyInfo proxy_;
- FirewallManager * firewall_;
- std::string host_;
- int port_;
- bool secure_;
- int timeout_;
- bool fail_redirect_;
- HttpClient client_;
- HttpErrorType error_;
- std::string response_redirect_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpMonitor
-///////////////////////////////////////////////////////////////////////////////
-
-class HttpMonitor : public sigslot::has_slots<> {
-public:
- HttpMonitor(SocketServer *ss);
-
- void reset() {
- complete_ = false;
- error_ = HE_DEFAULT;
- }
-
- bool done() const { return complete_; }
- HttpErrorType error() const { return error_; }
-
- void Connect(HttpClient* http);
- void OnHttpClientComplete(HttpClient * http, HttpErrorType error);
-
-private:
- bool complete_;
- HttpErrorType error_;
- SocketServer *ss_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base_
-
-#endif // _HTTPREQUEST_H_
diff --git a/base/httpserver.cc b/base/httpserver.cc
deleted file mode 100644
index 7d467c3..0000000
--- a/base/httpserver.cc
+++ /dev/null
@@ -1,305 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <algorithm>
-
-#include "talk/base/httpcommon-inl.h"
-
-#include "talk/base/asyncsocket.h"
-#include "talk/base/common.h"
-#include "talk/base/httpserver.h"
-#include "talk/base/logging.h"
-#include "talk/base/socketstream.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpServer
-///////////////////////////////////////////////////////////////////////////////
-
-HttpServer::HttpServer() : next_connection_id_(1), closing_(false) {
-}
-
-HttpServer::~HttpServer() {
- if (closing_) {
- LOG(LS_WARNING) << "HttpServer::CloseAll has not completed";
- }
- for (ConnectionMap::iterator it = connections_.begin();
- it != connections_.end();
- ++it) {
- StreamInterface* stream = it->second->EndProcess();
- delete stream;
- delete it->second;
- }
-}
-
-int
-HttpServer::HandleConnection(StreamInterface* stream) {
- int connection_id = next_connection_id_++;
- ASSERT(connection_id != HTTP_INVALID_CONNECTION_ID);
- Connection* connection = new Connection(connection_id, this);
- connections_.insert(ConnectionMap::value_type(connection_id, connection));
- connection->BeginProcess(stream);
- return connection_id;
-}
-
-void
-HttpServer::Respond(HttpServerTransaction* transaction) {
- int connection_id = transaction->connection_id();
- if (Connection* connection = Find(connection_id)) {
- connection->Respond(transaction);
- } else {
- delete transaction;
- // We may be tempted to SignalHttpComplete, but that implies that a
- // connection still exists.
- }
-}
-
-void
-HttpServer::Close(int connection_id, bool force) {
- if (Connection* connection = Find(connection_id)) {
- connection->InitiateClose(force);
- }
-}
-
-void
-HttpServer::CloseAll(bool force) {
- if (connections_.empty()) {
- SignalCloseAllComplete(this);
- return;
- }
- closing_ = true;
- std::list<Connection*> connections;
- for (ConnectionMap::const_iterator it = connections_.begin();
- it != connections_.end(); ++it) {
- connections.push_back(it->second);
- }
- for (std::list<Connection*>::const_iterator it = connections.begin();
- it != connections.end(); ++it) {
- (*it)->InitiateClose(force);
- }
-}
-
-HttpServer::Connection*
-HttpServer::Find(int connection_id) {
- ConnectionMap::iterator it = connections_.find(connection_id);
- if (it == connections_.end())
- return NULL;
- return it->second;
-}
-
-void
-HttpServer::Remove(int connection_id) {
- ConnectionMap::iterator it = connections_.find(connection_id);
- if (it == connections_.end()) {
- ASSERT(false);
- return;
- }
- Connection* connection = it->second;
- connections_.erase(it);
- SignalConnectionClosed(this, connection_id, connection->EndProcess());
- delete connection;
- if (closing_ && connections_.empty()) {
- closing_ = false;
- SignalCloseAllComplete(this);
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpServer::Connection
-///////////////////////////////////////////////////////////////////////////////
-
-HttpServer::Connection::Connection(int connection_id, HttpServer* server)
- : connection_id_(connection_id), server_(server),
- current_(NULL), signalling_(false), close_(false) {
-}
-
-HttpServer::Connection::~Connection() {
- // It's possible that an object hosted inside this transaction signalled
- // an event which caused the connection to close.
- Thread::Current()->Dispose(current_);
-}
-
-void
-HttpServer::Connection::BeginProcess(StreamInterface* stream) {
- base_.notify(this);
- base_.attach(stream);
- current_ = new HttpServerTransaction(connection_id_);
- if (base_.mode() != HM_CONNECT)
- base_.recv(¤t_->request);
-}
-
-StreamInterface*
-HttpServer::Connection::EndProcess() {
- base_.notify(NULL);
- base_.abort(HE_DISCONNECTED);
- return base_.detach();
-}
-
-void
-HttpServer::Connection::Respond(HttpServerTransaction* transaction) {
- ASSERT(current_ == NULL);
- current_ = transaction;
- if (current_->response.begin() == current_->response.end()) {
- current_->response.set_error(HC_INTERNAL_SERVER_ERROR);
- }
- bool keep_alive = HttpShouldKeepAlive(current_->request);
- current_->response.setHeader(HH_CONNECTION,
- keep_alive ? "Keep-Alive" : "Close",
- false);
- close_ = !HttpShouldKeepAlive(current_->response);
- base_.send(¤t_->response);
-}
-
-void
-HttpServer::Connection::InitiateClose(bool force) {
- bool request_in_progress = (HM_SEND == base_.mode()) || (NULL == current_);
- if (!signalling_ && (force || !request_in_progress)) {
- server_->Remove(connection_id_);
- } else {
- close_ = true;
- }
-}
-
-//
-// IHttpNotify Implementation
-//
-
-HttpError
-HttpServer::Connection::onHttpHeaderComplete(bool chunked, size_t& data_size) {
- if (data_size == SIZE_UNKNOWN) {
- data_size = 0;
- }
- ASSERT(current_ != NULL);
- bool custom_document = false;
- server_->SignalHttpRequestHeader(server_, current_, &custom_document);
- if (!custom_document) {
- current_->request.document.reset(new MemoryStream);
- }
- return HE_NONE;
-}
-
-void
-HttpServer::Connection::onHttpComplete(HttpMode mode, HttpError err) {
- if (mode == HM_SEND) {
- ASSERT(current_ != NULL);
- signalling_ = true;
- server_->SignalHttpRequestComplete(server_, current_, err);
- signalling_ = false;
- if (close_) {
- // Force a close
- err = HE_DISCONNECTED;
- }
- }
- if (err != HE_NONE) {
- server_->Remove(connection_id_);
- } else if (mode == HM_CONNECT) {
- base_.recv(¤t_->request);
- } else if (mode == HM_RECV) {
- ASSERT(current_ != NULL);
- // TODO: do we need this?
- //request_.document_->rewind();
- HttpServerTransaction* transaction = current_;
- current_ = NULL;
- server_->SignalHttpRequest(server_, transaction);
- } else if (mode == HM_SEND) {
- Thread::Current()->Dispose(current_->response.document.release());
- current_->request.clear(true);
- current_->response.clear(true);
- base_.recv(¤t_->request);
- } else {
- ASSERT(false);
- }
-}
-
-void
-HttpServer::Connection::onHttpClosed(HttpError err) {
- UNUSED(err);
- server_->Remove(connection_id_);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// HttpListenServer
-///////////////////////////////////////////////////////////////////////////////
-
-HttpListenServer::HttpListenServer() {
- SignalConnectionClosed.connect(this, &HttpListenServer::OnConnectionClosed);
-}
-
-HttpListenServer::~HttpListenServer() {
-}
-
-int HttpListenServer::Listen(const SocketAddress& address) {
- AsyncSocket* sock =
- Thread::Current()->socketserver()->CreateAsyncSocket(address.family(),
- SOCK_STREAM);
- if (!sock) {
- return SOCKET_ERROR;
- }
- listener_.reset(sock);
- listener_->SignalReadEvent.connect(this, &HttpListenServer::OnReadEvent);
- if ((listener_->Bind(address) != SOCKET_ERROR) &&
- (listener_->Listen(5) != SOCKET_ERROR))
- return 0;
- return listener_->GetError();
-}
-
-bool HttpListenServer::GetAddress(SocketAddress* address) const {
- if (!listener_) {
- return false;
- }
- *address = listener_->GetLocalAddress();
- return !address->IsNil();
-}
-
-void HttpListenServer::StopListening() {
- if (listener_) {
- listener_->Close();
- }
-}
-
-void HttpListenServer::OnReadEvent(AsyncSocket* socket) {
- ASSERT(socket == listener_.get());
- ASSERT(listener_);
- AsyncSocket* incoming = listener_->Accept(NULL);
- if (incoming) {
- StreamInterface* stream = new SocketStream(incoming);
- //stream = new LoggingAdapter(stream, LS_VERBOSE, "HttpServer", false);
- HandleConnection(stream);
- }
-}
-
-void HttpListenServer::OnConnectionClosed(HttpServer* server,
- int connection_id,
- StreamInterface* stream) {
- Thread::Current()->Dispose(stream);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/httpserver.h b/base/httpserver.h
deleted file mode 100644
index 67061ee..0000000
--- a/base/httpserver.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_HTTPSERVER_H__
-#define TALK_BASE_HTTPSERVER_H__
-
-#include <map>
-#include "talk/base/httpbase.h"
-
-namespace talk_base {
-
-class AsyncSocket;
-class HttpServer;
-class SocketAddress;
-
-//////////////////////////////////////////////////////////////////////
-// HttpServer
-//////////////////////////////////////////////////////////////////////
-
-const int HTTP_INVALID_CONNECTION_ID = 0;
-
-struct HttpServerTransaction : public HttpTransaction {
-public:
- HttpServerTransaction(int id) : connection_id_(id) { }
- int connection_id() const { return connection_id_; }
-
-private:
- int connection_id_;
-};
-
-class HttpServer {
-public:
- HttpServer();
- virtual ~HttpServer();
-
- int HandleConnection(StreamInterface* stream);
- // Due to sigslot issues, we can't destroy some streams at an arbitrary time.
- sigslot::signal3<HttpServer*, int, StreamInterface*> SignalConnectionClosed;
-
- // This signal occurs when the HTTP request headers have been received, but
- // before the request body is written to the request document. By default,
- // the request document is a MemoryStream. By handling this signal, the
- // document can be overridden, in which case the third signal argument should
- // be set to true. In the case where the request body should be ignored,
- // the document can be set to NULL. Note that the transaction object is still
- // owened by the HttpServer at this point.
- sigslot::signal3<HttpServer*, HttpServerTransaction*, bool*>
- SignalHttpRequestHeader;
-
- // An HTTP request has been made, and is available in the transaction object.
- // Populate the transaction's response, and then return the object via the
- // Respond method. Note that during this time, ownership of the transaction
- // object is transferred, so it may be passed between threads, although
- // respond must be called on the server's active thread.
- sigslot::signal2<HttpServer*, HttpServerTransaction*> SignalHttpRequest;
- void Respond(HttpServerTransaction* transaction);
-
- // If you want to know when a request completes, listen to this event.
- sigslot::signal3<HttpServer*, HttpServerTransaction*, int>
- SignalHttpRequestComplete;
-
- // Stop processing the connection indicated by connection_id.
- // Unless force is true, the server will complete sending a response that is
- // in progress.
- void Close(int connection_id, bool force);
- void CloseAll(bool force);
-
- // After calling CloseAll, this event is signalled to indicate that all
- // outstanding connections have closed.
- sigslot::signal1<HttpServer*> SignalCloseAllComplete;
-
-private:
- class Connection : private IHttpNotify {
- public:
- Connection(int connection_id, HttpServer* server);
- virtual ~Connection();
-
- void BeginProcess(StreamInterface* stream);
- StreamInterface* EndProcess();
-
- void Respond(HttpServerTransaction* transaction);
- void InitiateClose(bool force);
-
- // IHttpNotify Interface
- virtual HttpError onHttpHeaderComplete(bool chunked, size_t& data_size);
- virtual void onHttpComplete(HttpMode mode, HttpError err);
- virtual void onHttpClosed(HttpError err);
-
- int connection_id_;
- HttpServer* server_;
- HttpBase base_;
- HttpServerTransaction* current_;
- bool signalling_, close_;
- };
-
- Connection* Find(int connection_id);
- void Remove(int connection_id);
-
- friend class Connection;
- typedef std::map<int,Connection*> ConnectionMap;
-
- ConnectionMap connections_;
- int next_connection_id_;
- bool closing_;
-};
-
-//////////////////////////////////////////////////////////////////////
-
-class HttpListenServer : public HttpServer, public sigslot::has_slots<> {
-public:
- HttpListenServer();
- virtual ~HttpListenServer();
-
- int Listen(const SocketAddress& address);
- bool GetAddress(SocketAddress* address) const;
- void StopListening();
-
-private:
- void OnReadEvent(AsyncSocket* socket);
- void OnConnectionClosed(HttpServer* server, int connection_id,
- StreamInterface* stream);
-
- scoped_ptr<AsyncSocket> listener_;
-};
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_HTTPSERVER_H__
diff --git a/base/httpserver_unittest.cc b/base/httpserver_unittest.cc
deleted file mode 100644
index 6e12cf5..0000000
--- a/base/httpserver_unittest.cc
+++ /dev/null
@@ -1,124 +0,0 @@
-// Copyright 2007 Google Inc.
-// All Rights Reserved.
-
-
-#include "talk/base/gunit.h"
-#include "talk/base/httpserver.h"
-#include "talk/base/testutils.h"
-
-using namespace testing;
-
-namespace talk_base {
-
-namespace {
- const char* const kRequest =
- "GET /index.html HTTP/1.1\r\n"
- "Host: localhost\r\n"
- "\r\n";
-
- struct HttpServerMonitor : public sigslot::has_slots<> {
- HttpServerTransaction* transaction;
- bool server_closed, connection_closed;
-
- HttpServerMonitor(HttpServer* server)
- : transaction(NULL), server_closed(false), connection_closed(false) {
- server->SignalCloseAllComplete.connect(this,
- &HttpServerMonitor::OnClosed);
- server->SignalHttpRequest.connect(this, &HttpServerMonitor::OnRequest);
- server->SignalHttpRequestComplete.connect(this,
- &HttpServerMonitor::OnRequestComplete);
- server->SignalConnectionClosed.connect(this,
- &HttpServerMonitor::OnConnectionClosed);
- }
- void OnRequest(HttpServer*, HttpServerTransaction* t) {
- ASSERT_FALSE(transaction);
- transaction = t;
- transaction->response.set_success();
- transaction->response.setHeader(HH_CONNECTION, "Close");
- }
- void OnRequestComplete(HttpServer*, HttpServerTransaction* t, int) {
- ASSERT_EQ(transaction, t);
- transaction = NULL;
- }
- void OnClosed(HttpServer*) {
- server_closed = true;
- }
- void OnConnectionClosed(HttpServer*, int, StreamInterface* stream) {
- connection_closed = true;
- delete stream;
- }
- };
-
- void CreateClientConnection(HttpServer& server,
- HttpServerMonitor& monitor,
- bool send_request) {
- StreamSource* client = new StreamSource;
- client->SetState(SS_OPEN);
- server.HandleConnection(client);
- EXPECT_FALSE(monitor.server_closed);
- EXPECT_FALSE(monitor.transaction);
-
- if (send_request) {
- // Simulate a request
- client->QueueString(kRequest);
- EXPECT_FALSE(monitor.server_closed);
- }
- }
-} // anonymous namespace
-
-TEST(HttpServer, DoesNotSignalCloseUnlessCloseAllIsCalled) {
- HttpServer server;
- HttpServerMonitor monitor(&server);
- // Add an active client connection
- CreateClientConnection(server, monitor, true);
- // Simulate a response
- ASSERT_TRUE(NULL != monitor.transaction);
- server.Respond(monitor.transaction);
- EXPECT_FALSE(monitor.transaction);
- // Connection has closed, but no server close signal
- EXPECT_FALSE(monitor.server_closed);
- EXPECT_TRUE(monitor.connection_closed);
-}
-
-TEST(HttpServer, SignalsCloseWhenNoConnectionsAreActive) {
- HttpServer server;
- HttpServerMonitor monitor(&server);
- // Add an idle client connection
- CreateClientConnection(server, monitor, false);
- // Perform graceful close
- server.CloseAll(false);
- // Connections have all closed
- EXPECT_TRUE(monitor.server_closed);
- EXPECT_TRUE(monitor.connection_closed);
-}
-
-TEST(HttpServer, SignalsCloseAfterGracefulCloseAll) {
- HttpServer server;
- HttpServerMonitor monitor(&server);
- // Add an active client connection
- CreateClientConnection(server, monitor, true);
- // Initiate a graceful close
- server.CloseAll(false);
- EXPECT_FALSE(monitor.server_closed);
- // Simulate a response
- ASSERT_TRUE(NULL != monitor.transaction);
- server.Respond(monitor.transaction);
- EXPECT_FALSE(monitor.transaction);
- // Connections have all closed
- EXPECT_TRUE(monitor.server_closed);
- EXPECT_TRUE(monitor.connection_closed);
-}
-
-TEST(HttpServer, SignalsCloseAfterForcedCloseAll) {
- HttpServer server;
- HttpServerMonitor monitor(&server);
- // Add an active client connection
- CreateClientConnection(server, monitor, true);
- // Initiate a forceful close
- server.CloseAll(true);
- // Connections have all closed
- EXPECT_TRUE(monitor.server_closed);
- EXPECT_TRUE(monitor.connection_closed);
-}
-
-} // namespace talk_base
diff --git a/base/ifaddrs-android.cc b/base/ifaddrs-android.cc
deleted file mode 100644
index 7826840..0000000
--- a/base/ifaddrs-android.cc
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if defined(ANDROID)
-#include "talk/base/ifaddrs-android.h"
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/utsname.h>
-#include <sys/ioctl.h>
-#include <netinet/in.h>
-#include <net/if.h>
-#include <unistd.h>
-#include <errno.h>
-#include <linux/netlink.h>
-#include <linux/rtnetlink.h>
-
-struct netlinkrequest {
- nlmsghdr header;
- ifaddrmsg msg;
-};
-
-namespace {
-const int kMaxReadSize = 4096;
-};
-
-int set_ifname(struct ifaddrs* ifaddr, int interface) {
- char buf[IFNAMSIZ] = {0};
- char* name = if_indextoname(interface, buf);
- if (name == NULL) {
- return -1;
- }
- ifaddr->ifa_name = new char[strlen(name) + 1];
- strncpy(ifaddr->ifa_name, name, strlen(name) + 1);
- return 0;
-}
-
-int set_flags(struct ifaddrs* ifaddr) {
- int fd = socket(AF_INET, SOCK_DGRAM, 0);
- if (fd == -1) {
- return -1;
- }
- ifreq ifr;
- memset(&ifr, 0, sizeof(ifr));
- strncpy(ifr.ifr_name, ifaddr->ifa_name, IFNAMSIZ - 1);
- int rc = ioctl(fd, SIOCGIFFLAGS, &ifr);
- close(fd);
- if (rc == -1) {
- return -1;
- }
- ifaddr->ifa_flags = ifr.ifr_flags;
- return 0;
-}
-
-int set_addresses(struct ifaddrs* ifaddr, ifaddrmsg* msg, void* data,
- size_t len) {
- if (msg->ifa_family == AF_INET) {
- sockaddr_in* sa = new sockaddr_in;
- sa->sin_family = AF_INET;
- memcpy(&sa->sin_addr, data, len);
- ifaddr->ifa_addr = reinterpret_cast<sockaddr*>(sa);
- } else if (msg->ifa_family == AF_INET6) {
- sockaddr_in6* sa = new sockaddr_in6;
- sa->sin6_family = AF_INET6;
- sa->sin6_scope_id = msg->ifa_index;
- memcpy(&sa->sin6_addr, data, len);
- ifaddr->ifa_addr = reinterpret_cast<sockaddr*>(sa);
- } else {
- return -1;
- }
- return 0;
-}
-
-int make_prefixes(struct ifaddrs* ifaddr, int family, int prefixlen) {
- char* prefix = NULL;
- if (family == AF_INET) {
- sockaddr_in* mask = new sockaddr_in;
- mask->sin_family = AF_INET;
- memset(&mask->sin_addr, 0, sizeof(in_addr));
- ifaddr->ifa_netmask = reinterpret_cast<sockaddr*>(mask);
- if (prefixlen > 32) {
- prefixlen = 32;
- }
- prefix = reinterpret_cast<char*>(&mask->sin_addr);
- } else if (family == AF_INET6) {
- sockaddr_in6* mask = new sockaddr_in6;
- mask->sin6_family = AF_INET6;
- memset(&mask->sin6_addr, 0, sizeof(in6_addr));
- ifaddr->ifa_netmask = reinterpret_cast<sockaddr*>(mask);
- if (prefixlen > 128) {
- prefixlen = 128;
- }
- prefix = reinterpret_cast<char*>(&mask->sin6_addr);
- } else {
- return -1;
- }
- for (int i = 0; i < (prefixlen / 8); i++) {
- *prefix++ = 0xFF;
- }
- char remainder = 0xff;
- remainder <<= (8 - prefixlen % 8);
- *prefix = remainder;
- return 0;
-}
-
-int populate_ifaddrs(struct ifaddrs* ifaddr, ifaddrmsg* msg, void* bytes,
- size_t len) {
- if (set_ifname(ifaddr, msg->ifa_index) != 0) {
- return -1;
- }
- if (set_flags(ifaddr) != 0) {
- return -1;
- }
- if (set_addresses(ifaddr, msg, bytes, len) != 0) {
- return -1;
- }
- if (make_prefixes(ifaddr, msg->ifa_family, msg->ifa_prefixlen) != 0) {
- return -1;
- }
- return 0;
-}
-
-int getifaddrs(struct ifaddrs** result) {
- int fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
- if (fd < 0) {
- return -1;
- }
-
- netlinkrequest ifaddr_request;
- memset(&ifaddr_request, 0, sizeof(ifaddr_request));
- ifaddr_request.header.nlmsg_flags = NLM_F_ROOT | NLM_F_REQUEST;
- ifaddr_request.header.nlmsg_type = RTM_GETADDR;
- ifaddr_request.header.nlmsg_len = NLMSG_LENGTH(sizeof(ifaddrmsg));
-
- ssize_t count = send(fd, &ifaddr_request, ifaddr_request.header.nlmsg_len, 0);
- if (static_cast<size_t>(count) != ifaddr_request.header.nlmsg_len) {
- close(fd);
- return -1;
- }
- struct ifaddrs* start = NULL;
- struct ifaddrs* current = NULL;
- char buf[kMaxReadSize];
- ssize_t amount_read = recv(fd, &buf, kMaxReadSize, 0);
- while (amount_read > 0) {
- nlmsghdr* header = reinterpret_cast<nlmsghdr*>(&buf[0]);
- size_t header_size = static_cast<size_t>(amount_read);
- for ( ; NLMSG_OK(header, header_size);
- header = NLMSG_NEXT(header, header_size)) {
- switch (header->nlmsg_type) {
- case NLMSG_DONE:
- // Success. Return.
- *result = start;
- close(fd);
- return 0;
- case NLMSG_ERROR:
- close(fd);
- freeifaddrs(start);
- return -1;
- case RTM_NEWADDR: {
- ifaddrmsg* address_msg =
- reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(header));
- rtattr* rta = IFA_RTA(address_msg);
- ssize_t payload_len = IFA_PAYLOAD(header);
- while (RTA_OK(rta, payload_len)) {
- if (rta->rta_type == IFA_ADDRESS) {
- int family = address_msg->ifa_family;
- if (family == AF_INET || family == AF_INET6) {
- ifaddrs* newest = new ifaddrs;
- memset(newest, 0, sizeof(ifaddrs));
- if (current) {
- current->ifa_next = newest;
- } else {
- start = newest;
- }
- if (populate_ifaddrs(newest, address_msg, RTA_DATA(rta),
- RTA_PAYLOAD(rta)) != 0) {
- freeifaddrs(start);
- *result = NULL;
- return -1;
- }
- current = newest;
- }
- }
- rta = RTA_NEXT(rta, payload_len);
- }
- break;
- }
- }
- }
- amount_read = recv(fd, &buf, kMaxReadSize, 0);
- }
- close(fd);
- freeifaddrs(start);
- return -1;
-}
-
-void freeifaddrs(struct ifaddrs* addrs) {
- struct ifaddrs* last = NULL;
- struct ifaddrs* cursor = addrs;
- while (cursor) {
- delete[] cursor->ifa_name;
- delete cursor->ifa_addr;
- delete cursor->ifa_netmask;
- last = cursor;
- cursor = cursor->ifa_next;
- delete last;
- }
-}
-#endif // defined(ANDROID)
diff --git a/base/ifaddrs-android.h b/base/ifaddrs-android.h
deleted file mode 100644
index e7d81e8..0000000
--- a/base/ifaddrs-android.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * libjingle
- * Copyright 2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_IFADDRS_ANDROID_H_
-#define TALK_BASE_IFADDRS_ANDROID_H_
-
-#include <stdio.h>
-#include <sys/socket.h>
-// Implementation of getifaddrs for Android.
-// Fills out a list of ifaddr structs (see below) which contain information
-// about every network interface available on the host.
-// See 'man getifaddrs' on Linux or OS X (nb: it is not a POSIX function).
-struct ifaddrs {
- struct ifaddrs* ifa_next;
- char* ifa_name;
- unsigned int ifa_flags;
- struct sockaddr* ifa_addr;
- struct sockaddr* ifa_netmask;
- // Real ifaddrs has broadcast, point to point and data members.
- // We don't need them (yet?).
-};
-
-int getifaddrs(struct ifaddrs** result);
-void freeifaddrs(struct ifaddrs* addrs);
-
-#endif // TALK_BASE_IFADDRS_ANDROID_H_
diff --git a/base/iosfilesystem.mm b/base/iosfilesystem.mm
deleted file mode 100644
index aaefcb0..0000000
--- a/base/iosfilesystem.mm
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// This file only exists because various iOS system APIs are only
-// available from Objective-C. See unixfilesystem.cc for the only use
-// (enforced by a lack of a header file).
-
-#import <Foundation/NSPathUtilities.h>
-#import <Foundation/NSProcessInfo.h>
-#include <string.h>
-
-#include "talk/base/common.h"
-#include "talk/base/pathutils.h"
-
-// Return a new[]'d |char*| copy of the UTF8 representation of |s|.
-// Caller owns the returned memory and must use delete[] on it.
-static char* copyString(NSString* s) {
- const char* utf8 = [s UTF8String];
- size_t len = strlen(utf8) + 1;
- char* copy = new char[len];
- // This uses a new[] + strcpy (instead of strdup) because the
- // receiver expects to be able to delete[] the returned pointer
- // (instead of free()ing it).
- strcpy(copy, utf8);
- return copy;
-}
-
-// Return a (leaked) copy of a directory name suitable for application data.
-char* IOSDataDirectory() {
- NSArray* paths = NSSearchPathForDirectoriesInDomains(
- NSApplicationSupportDirectory, NSUserDomainMask, YES);
- ASSERT([paths count] == 1);
- return copyString([paths objectAtIndex:0]);
-}
-
-// Return a (leaked) copy of a directory name suitable for use as a $TEMP.
-char* IOSTempDirectory() {
- return copyString(NSTemporaryDirectory());
-}
-
-// Return the binary's path.
-void IOSAppName(talk_base::Pathname* path) {
- NSProcessInfo *pInfo = [NSProcessInfo processInfo];
- NSString* argv0 = [[pInfo arguments] objectAtIndex:0];
- path->SetPathname([argv0 UTF8String]);
-}
diff --git a/base/ipaddress.cc b/base/ipaddress.cc
deleted file mode 100644
index 6c2212b..0000000
--- a/base/ipaddress.cc
+++ /dev/null
@@ -1,466 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef POSIX
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#ifdef OPENBSD
-#include <netinet/in_systm.h>
-#endif
-#ifndef __native_client__
-#include <netinet/ip.h>
-#endif
-#include <arpa/inet.h>
-#include <netdb.h>
-#include <unistd.h>
-#endif
-
-#include <stdio.h>
-
-#include "talk/base/ipaddress.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/win32.h"
-
-namespace talk_base {
-
-// Prefixes used for categorizing IPv6 addresses.
-static const in6_addr kV4MappedPrefix = {{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0xFF, 0xFF, 0}}};
-static const in6_addr k6To4Prefix = {{{0x20, 0x02, 0}}};
-static const in6_addr kTeredoPrefix = {{{0x20, 0x01, 0x00, 0x00}}};
-static const in6_addr kV4CompatibilityPrefix = {{{0}}};
-static const in6_addr k6BonePrefix = {{{0x3f, 0xfe, 0}}};
-
-bool IPAddress::strip_sensitive_ = false;
-
-static bool IsPrivateV4(uint32 ip);
-static in_addr ExtractMappedAddress(const in6_addr& addr);
-
-uint32 IPAddress::v4AddressAsHostOrderInteger() const {
- if (family_ == AF_INET) {
- return NetworkToHost32(u_.ip4.s_addr);
- } else {
- return 0;
- }
-}
-
-size_t IPAddress::Size() const {
- switch (family_) {
- case AF_INET:
- return sizeof(in_addr);
- case AF_INET6:
- return sizeof(in6_addr);
- }
- return 0;
-}
-
-
-bool IPAddress::operator==(const IPAddress &other) const {
- if (family_ != other.family_) {
- return false;
- }
- if (family_ == AF_INET) {
- return memcmp(&u_.ip4, &other.u_.ip4, sizeof(u_.ip4)) == 0;
- }
- if (family_ == AF_INET6) {
- return memcmp(&u_.ip6, &other.u_.ip6, sizeof(u_.ip6)) == 0;
- }
- return family_ == AF_UNSPEC;
-}
-
-bool IPAddress::operator!=(const IPAddress &other) const {
- return !((*this) == other);
-}
-
-bool IPAddress::operator >(const IPAddress &other) const {
- return (*this) != other && !((*this) < other);
-}
-
-bool IPAddress::operator <(const IPAddress &other) const {
- // IPv4 is 'less than' IPv6
- if (family_ != other.family_) {
- if (family_ == AF_UNSPEC) {
- return true;
- }
- if (family_ == AF_INET && other.family_ == AF_INET6) {
- return true;
- }
- return false;
- }
- // Comparing addresses of the same family.
- switch (family_) {
- case AF_INET: {
- return NetworkToHost32(u_.ip4.s_addr) <
- NetworkToHost32(other.u_.ip4.s_addr);
- }
- case AF_INET6: {
- return memcmp(&u_.ip6.s6_addr, &other.u_.ip6.s6_addr, 16) < 0;
- }
- }
- // Catches AF_UNSPEC and invalid addresses.
- return false;
-}
-
-std::ostream& operator<<(std::ostream& os, const IPAddress& ip) {
- os << ip.ToString();
- return os;
-}
-
-in6_addr IPAddress::ipv6_address() const {
- return u_.ip6;
-}
-
-in_addr IPAddress::ipv4_address() const {
- return u_.ip4;
-}
-
-std::string IPAddress::ToString() const {
- if (family_ != AF_INET && family_ != AF_INET6) {
- return std::string();
- }
- char buf[INET6_ADDRSTRLEN] = {0};
- const void* src = &u_.ip4;
- if (family_ == AF_INET6) {
- src = &u_.ip6;
- }
- if (!talk_base::inet_ntop(family_, src, buf, sizeof(buf))) {
- return std::string();
- }
- return std::string(buf);
-}
-
-std::string IPAddress::ToSensitiveString() const {
- if (!strip_sensitive_)
- return ToString();
-
- switch (family_) {
- case AF_INET: {
- std::string address = ToString();
- size_t find_pos = address.rfind('.');
- if (find_pos == std::string::npos)
- return std::string();
- address.resize(find_pos);
- address += ".x";
- return address;
- }
- case AF_INET6: {
- // TODO(grunell): Return a string of format 1:2:3:x:x:x:x:x or such
- // instead of zeroing out.
- return TruncateIP(*this, 128 - 80).ToString();
- }
- }
- return std::string();
-}
-
-IPAddress IPAddress::Normalized() const {
- if (family_ != AF_INET6) {
- return *this;
- }
- if (!IPIsV4Mapped(*this)) {
- return *this;
- }
- in_addr addr = ExtractMappedAddress(u_.ip6);
- return IPAddress(addr);
-}
-
-IPAddress IPAddress::AsIPv6Address() const {
- if (family_ != AF_INET) {
- return *this;
- }
- in6_addr v6addr = kV4MappedPrefix;
- ::memcpy(&v6addr.s6_addr[12], &u_.ip4.s_addr, sizeof(u_.ip4.s_addr));
- return IPAddress(v6addr);
-}
-
-void IPAddress::set_strip_sensitive(bool enable) {
- strip_sensitive_ = enable;
-}
-
-
-bool IsPrivateV4(uint32 ip_in_host_order) {
- return ((ip_in_host_order >> 24) == 127) ||
- ((ip_in_host_order >> 24) == 10) ||
- ((ip_in_host_order >> 20) == ((172 << 4) | 1)) ||
- ((ip_in_host_order >> 16) == ((192 << 8) | 168)) ||
- ((ip_in_host_order >> 16) == ((169 << 8) | 254));
-}
-
-in_addr ExtractMappedAddress(const in6_addr& in6) {
- in_addr ipv4;
- ::memcpy(&ipv4.s_addr, &in6.s6_addr[12], sizeof(ipv4.s_addr));
- return ipv4;
-}
-
-bool IPFromAddrInfo(struct addrinfo* info, IPAddress* out) {
- if (!info || !info->ai_addr) {
- return false;
- }
- if (info->ai_addr->sa_family == AF_INET) {
- sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(info->ai_addr);
- *out = IPAddress(addr->sin_addr);
- return true;
- } else if (info->ai_addr->sa_family == AF_INET6) {
- sockaddr_in6* addr = reinterpret_cast<sockaddr_in6*>(info->ai_addr);
- *out = IPAddress(addr->sin6_addr);
- return true;
- }
- return false;
-}
-
-bool IPFromString(const std::string& str, IPAddress* out) {
- if (!out) {
- return false;
- }
- in_addr addr;
- if (talk_base::inet_pton(AF_INET, str.c_str(), &addr) == 0) {
- in6_addr addr6;
- if (talk_base::inet_pton(AF_INET6, str.c_str(), &addr6) == 0) {
- *out = IPAddress();
- return false;
- }
- *out = IPAddress(addr6);
- } else {
- *out = IPAddress(addr);
- }
- return true;
-}
-
-bool IPIsAny(const IPAddress& ip) {
- switch (ip.family()) {
- case AF_INET:
- return ip == IPAddress(INADDR_ANY);
- case AF_INET6:
- return ip == IPAddress(in6addr_any);
- case AF_UNSPEC:
- return false;
- }
- return false;
-}
-
-bool IPIsLoopback(const IPAddress& ip) {
- switch (ip.family()) {
- case AF_INET: {
- return ip == IPAddress(INADDR_LOOPBACK);
- }
- case AF_INET6: {
- return ip == IPAddress(in6addr_loopback);
- }
- }
- return false;
-}
-
-bool IPIsPrivate(const IPAddress& ip) {
- switch (ip.family()) {
- case AF_INET: {
- return IsPrivateV4(ip.v4AddressAsHostOrderInteger());
- }
- case AF_INET6: {
- in6_addr v6 = ip.ipv6_address();
- return (v6.s6_addr[0] == 0xFE && v6.s6_addr[1] == 0x80) ||
- IPIsLoopback(ip);
- }
- }
- return false;
-}
-
-bool IPIsUnspec(const IPAddress& ip) {
- return ip.family() == AF_UNSPEC;
-}
-
-size_t HashIP(const IPAddress& ip) {
- switch (ip.family()) {
- case AF_INET: {
- return ip.ipv4_address().s_addr;
- }
- case AF_INET6: {
- in6_addr v6addr = ip.ipv6_address();
- const uint32* v6_as_ints =
- reinterpret_cast<const uint32*>(&v6addr.s6_addr);
- return v6_as_ints[0] ^ v6_as_ints[1] ^ v6_as_ints[2] ^ v6_as_ints[3];
- }
- }
- return 0;
-}
-
-IPAddress TruncateIP(const IPAddress& ip, int length) {
- if (length < 0) {
- return IPAddress();
- }
- if (ip.family() == AF_INET) {
- if (length > 31) {
- return ip;
- }
- if (length == 0) {
- return IPAddress(INADDR_ANY);
- }
- int mask = (0xFFFFFFFF << (32 - length));
- uint32 host_order_ip = NetworkToHost32(ip.ipv4_address().s_addr);
- in_addr masked;
- masked.s_addr = HostToNetwork32(host_order_ip & mask);
- return IPAddress(masked);
- } else if (ip.family() == AF_INET6) {
- if (length > 127) {
- return ip;
- }
- if (length == 0) {
- return IPAddress(in6addr_any);
- }
- in6_addr v6addr = ip.ipv6_address();
- int position = length / 32;
- int inner_length = 32 - (length - (position * 32));
- // Note: 64bit mask constant needed to allow possible 32-bit left shift.
- uint32 inner_mask = 0xFFFFFFFFLL << inner_length;
- uint32* v6_as_ints =
- reinterpret_cast<uint32*>(&v6addr.s6_addr);
- for (int i = 0; i < 4; ++i) {
- if (i == position) {
- uint32 host_order_inner = NetworkToHost32(v6_as_ints[i]);
- v6_as_ints[i] = HostToNetwork32(host_order_inner & inner_mask);
- } else if (i > position) {
- v6_as_ints[i] = 0;
- }
- }
- return IPAddress(v6addr);
- }
- return IPAddress();
-}
-
-int CountIPMaskBits(IPAddress mask) {
- uint32 word_to_count = 0;
- int bits = 0;
- switch (mask.family()) {
- case AF_INET: {
- word_to_count = NetworkToHost32(mask.ipv4_address().s_addr);
- break;
- }
- case AF_INET6: {
- in6_addr v6addr = mask.ipv6_address();
- const uint32* v6_as_ints =
- reinterpret_cast<const uint32*>(&v6addr.s6_addr);
- int i = 0;
- for (; i < 4; ++i) {
- if (v6_as_ints[i] != 0xFFFFFFFF) {
- break;
- }
- }
- if (i < 4) {
- word_to_count = NetworkToHost32(v6_as_ints[i]);
- }
- bits = (i * 32);
- break;
- }
- default: {
- return 0;
- }
- }
- if (word_to_count == 0) {
- return bits;
- }
-
- // Public domain bit-twiddling hack from:
- // http://graphics.stanford.edu/~seander/bithacks.html
- // Counts the trailing 0s in the word.
- unsigned int zeroes = 32;
- word_to_count &= -static_cast<int32>(word_to_count);
- if (word_to_count) zeroes--;
- if (word_to_count & 0x0000FFFF) zeroes -= 16;
- if (word_to_count & 0x00FF00FF) zeroes -= 8;
- if (word_to_count & 0x0F0F0F0F) zeroes -= 4;
- if (word_to_count & 0x33333333) zeroes -= 2;
- if (word_to_count & 0x55555555) zeroes -= 1;
-
- return bits + (32 - zeroes);
-}
-
-bool IPIsHelper(const IPAddress& ip, const in6_addr& tomatch, int length) {
- // Helper method for checking IP prefix matches (but only on whole byte
- // lengths). Length is in bits.
- in6_addr addr = ip.ipv6_address();
- return ::memcmp(&addr, &tomatch, (length >> 3)) == 0;
-}
-
-bool IPIs6Bone(const IPAddress& ip) {
- return IPIsHelper(ip, k6BonePrefix, 16);
-}
-
-bool IPIs6To4(const IPAddress& ip) {
- return IPIsHelper(ip, k6To4Prefix, 16);
-}
-
-bool IPIsSiteLocal(const IPAddress& ip) {
- // Can't use the helper because the prefix is 10 bits.
- in6_addr addr = ip.ipv6_address();
- return addr.s6_addr[0] == 0xFE && (addr.s6_addr[1] & 0xC0) == 0xC0;
-}
-
-bool IPIsULA(const IPAddress& ip) {
- // Can't use the helper because the prefix is 7 bits.
- in6_addr addr = ip.ipv6_address();
- return (addr.s6_addr[0] & 0xFE) == 0xFC;
-}
-
-bool IPIsTeredo(const IPAddress& ip) {
- return IPIsHelper(ip, kTeredoPrefix, 32);
-}
-
-bool IPIsV4Compatibility(const IPAddress& ip) {
- return IPIsHelper(ip, kV4CompatibilityPrefix, 96);
-}
-
-bool IPIsV4Mapped(const IPAddress& ip) {
- return IPIsHelper(ip, kV4MappedPrefix, 96);
-}
-
-int IPAddressPrecedence(const IPAddress& ip) {
- // Precedence values from RFC 3484-bis. Prefers native v4 over 6to4/Teredo.
- if (ip.family() == AF_INET) {
- return 30;
- } else if (ip.family() == AF_INET6) {
- if (IPIsLoopback(ip)) {
- return 60;
- } else if (IPIsULA(ip)) {
- return 50;
- } else if (IPIsV4Mapped(ip)) {
- return 30;
- } else if (IPIs6To4(ip)) {
- return 20;
- } else if (IPIsTeredo(ip)) {
- return 10;
- } else if (IPIsV4Compatibility(ip) || IPIsSiteLocal(ip) || IPIs6Bone(ip)) {
- return 1;
- } else {
- // A 'normal' IPv6 address.
- return 40;
- }
- }
- return 0;
-}
-
-} // Namespace talk base
diff --git a/base/ipaddress.h b/base/ipaddress.h
deleted file mode 100644
index b60de8a..0000000
--- a/base/ipaddress.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_IPADDRESS_H_
-#define TALK_BASE_IPADDRESS_H_
-
-#ifdef POSIX
-#include <netinet/in.h>
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-#endif
-#ifdef WIN32
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#endif
-#include <string.h>
-#include <string>
-#include <vector>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/byteorder.h"
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif
-
-namespace talk_base {
-
-// Version-agnostic IP address class, wraps a union of in_addr and in6_addr.
-class IPAddress {
- public:
- IPAddress() : family_(AF_UNSPEC) {
- ::memset(&u_, 0, sizeof(u_));
- }
-
- explicit IPAddress(const in_addr &ip4) : family_(AF_INET) {
- memset(&u_, 0, sizeof(u_));
- u_.ip4 = ip4;
- }
-
- explicit IPAddress(const in6_addr &ip6) : family_(AF_INET6) {
- u_.ip6 = ip6;
- }
-
- explicit IPAddress(uint32 ip_in_host_byte_order) : family_(AF_INET) {
- memset(&u_, 0, sizeof(u_));
- u_.ip4.s_addr = HostToNetwork32(ip_in_host_byte_order);
- }
-
- IPAddress(const IPAddress &other) : family_(other.family_) {
- ::memcpy(&u_, &other.u_, sizeof(u_));
- }
-
- ~IPAddress() {}
-
- const IPAddress & operator=(const IPAddress &other) {
- family_ = other.family_;
- ::memcpy(&u_, &other.u_, sizeof(u_));
- return *this;
- }
-
- bool operator==(const IPAddress &other) const;
- bool operator!=(const IPAddress &other) const;
- bool operator <(const IPAddress &other) const;
- bool operator >(const IPAddress &other) const;
- friend std::ostream& operator<<(std::ostream& os, const IPAddress& addr);
-
- int family() const { return family_; }
- in_addr ipv4_address() const;
- in6_addr ipv6_address() const;
-
- // Returns the number of bytes needed to store the raw address.
- size_t Size() const;
-
- // Wraps inet_ntop.
- std::string ToString() const;
-
- // Same as ToString but anonymizes it by hiding the last part.
- std::string ToSensitiveString() const;
-
- // Returns an unmapped address from a possibly-mapped address.
- // Returns the same address if this isn't a mapped address.
- IPAddress Normalized() const;
-
- // Returns this address as an IPv6 address.
- // Maps v4 addresses (as ::ffff:a.b.c.d), returns v6 addresses unchanged.
- IPAddress AsIPv6Address() const;
-
- // For socketaddress' benefit. Returns the IP in host byte order.
- uint32 v4AddressAsHostOrderInteger() const;
-
- static void set_strip_sensitive(bool enable);
-
- private:
- int family_;
- union {
- in_addr ip4;
- in6_addr ip6;
- } u_;
-
- static bool strip_sensitive_;
-};
-
-bool IPFromAddrInfo(struct addrinfo* info, IPAddress* out);
-bool IPFromString(const std::string& str, IPAddress* out);
-bool IPIsAny(const IPAddress& ip);
-bool IPIsLoopback(const IPAddress& ip);
-bool IPIsPrivate(const IPAddress& ip);
-bool IPIsUnspec(const IPAddress& ip);
-size_t HashIP(const IPAddress& ip);
-
-// These are only really applicable for IPv6 addresses.
-bool IPIs6Bone(const IPAddress& ip);
-bool IPIs6To4(const IPAddress& ip);
-bool IPIsSiteLocal(const IPAddress& ip);
-bool IPIsTeredo(const IPAddress& ip);
-bool IPIsULA(const IPAddress& ip);
-bool IPIsV4Compatibility(const IPAddress& ip);
-bool IPIsV4Mapped(const IPAddress& ip);
-
-// Returns the precedence value for this IP as given in RFC3484.
-int IPAddressPrecedence(const IPAddress& ip);
-
-// Returns 'ip' truncated to be 'length' bits long.
-IPAddress TruncateIP(const IPAddress& ip, int length);
-
-// Returns the number of contiguously set bits, counting from the MSB in network
-// byte order, in this IPAddress. Bits after the first 0 encountered are not
-// counted.
-int CountIPMaskBits(IPAddress mask);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_IPADDRESS_H_
diff --git a/base/ipaddress_unittest.cc b/base/ipaddress_unittest.cc
deleted file mode 100644
index 2c03cbd..0000000
--- a/base/ipaddress_unittest.cc
+++ /dev/null
@@ -1,876 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/ipaddress.h"
-
-namespace talk_base {
-
-static const unsigned int kIPv4AddrSize = 4;
-static const unsigned int kIPv6AddrSize = 16;
-static const unsigned int kIPv4RFC1918Addr = 0xC0A80701;
-static const unsigned int kIPv4PublicAddr = 0x01020304;
-static const in6_addr kIPv6LinkLocalAddr = {{{0xfe, 0x80, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0xbe, 0x30, 0x5b, 0xff,
- 0xfe, 0xe5, 0x00, 0xc3}}};
-static const in6_addr kIPv6PublicAddr = {{{0x24, 0x01, 0xfa, 0x00,
- 0x00, 0x04, 0x10, 0x00,
- 0xbe, 0x30, 0x5b, 0xff,
- 0xfe, 0xe5, 0x00, 0xc3}}};
-static const in6_addr kIPv4MappedAnyAddr = {{{0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0xff, 0xff,
- 0x00, 0x00, 0x00, 0x00}}};
-static const in6_addr kIPv4MappedRFC1918Addr = {{{0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0xff, 0xff,
- 0xc0, 0xa8, 0x07, 0x01}}};
-static const in6_addr kIPv4MappedPublicAddr = {{{0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0xff, 0xff,
- 0x01, 0x02, 0x03, 0x04}}};
-
-static const std::string kIPv4AnyAddrString = "0.0.0.0";
-static const std::string kIPv4LoopbackAddrString = "127.0.0.1";
-static const std::string kIPv4RFC1918AddrString = "192.168.7.1";
-static const std::string kIPv4PublicAddrString = "1.2.3.4";
-static const std::string kIPv4PublicAddrAnonymizedString = "1.2.3.x";
-static const std::string kIPv6AnyAddrString = "::";
-static const std::string kIPv6LoopbackAddrString = "::1";
-static const std::string kIPv6LinkLocalAddrString = "fe80::be30:5bff:fee5:c3";
-static const std::string kIPv6PublicAddrString =
- "2401:fa00:4:1000:be30:5bff:fee5:c3";
-static const std::string kIPv6PublicAddrAnonymizedString = "2401:fa00:4::";
-static const std::string kIPv4MappedAnyAddrString = "::ffff:0:0";
-static const std::string kIPv4MappedRFC1918AddrString = "::ffff:c0a8:701";
-static const std::string kIPv4MappedLoopbackAddrString = "::ffff:7f00:1";
-static const std::string kIPv4MappedPublicAddrString = "::ffff:102:0304";
-static const std::string kIPv4MappedV4StyleAddrString = "::ffff:192.168.7.1";
-
-static const std::string kIPv4BrokenString1 = "192.168.7.";
-static const std::string kIPv4BrokenString2 = "192.168.7.1.1";
-static const std::string kIPv4BrokenString3 = "192.168.7.1:80";
-static const std::string kIPv4BrokenString4 = "192.168.7.ONE";
-static const std::string kIPv4BrokenString5 = "-192.168.7.1";
-static const std::string kIPv4BrokenString6 = "256.168.7.1";
-static const std::string kIPv6BrokenString1 = "2401:fa00:4:1000:be30";
-static const std::string kIPv6BrokenString2 =
- "2401:fa00:4:1000:be30:5bff:fee5:c3:1";
-static const std::string kIPv6BrokenString3 =
- "[2401:fa00:4:1000:be30:5bff:fee5:c3]:1";
-static const std::string kIPv6BrokenString4 =
- "2401::4::be30";
-static const std::string kIPv6BrokenString5 =
- "2401:::4:fee5:be30";
-static const std::string kIPv6BrokenString6 =
- "2401f:fa00:4:1000:be30:5bff:fee5:c3";
-static const std::string kIPv6BrokenString7 =
- "2401:ga00:4:1000:be30:5bff:fee5:c3";
-static const std::string kIPv6BrokenString8 =
- "2401:fa000:4:1000:be30:5bff:fee5:c3";
-static const std::string kIPv6BrokenString9 =
- "2401:fal0:4:1000:be30:5bff:fee5:c3";
-static const std::string kIPv6BrokenString10 =
- "::ffff:192.168.7.";
-static const std::string kIPv6BrokenString11 =
- "::ffff:192.168.7.1.1.1";
-static const std::string kIPv6BrokenString12 =
- "::fffe:192.168.7.1";
-static const std::string kIPv6BrokenString13 =
- "::ffff:192.168.7.ff";
-static const std::string kIPv6BrokenString14 =
- "0x2401:fa00:4:1000:be30:5bff:fee5:c3";
-
-bool AreEqual(const IPAddress& addr,
- const IPAddress& addr2) {
- if ((IPIsAny(addr) != IPIsAny(addr2)) ||
- (IPIsLoopback(addr) != IPIsLoopback(addr2)) ||
- (IPIsPrivate(addr) != IPIsPrivate(addr2)) ||
- (HashIP(addr) != HashIP(addr2)) ||
- (addr.Size() != addr2.Size()) ||
- (addr.family() != addr2.family()) ||
- (addr.ToString() != addr2.ToString())) {
- return false;
- }
- in_addr v4addr, v4addr2;
- v4addr = addr.ipv4_address();
- v4addr2 = addr2.ipv4_address();
- if (0 != memcmp(&v4addr, &v4addr2, sizeof(v4addr))) {
- return false;
- }
- in6_addr v6addr, v6addr2;
- v6addr = addr.ipv6_address();
- v6addr2 = addr2.ipv6_address();
- if (0 != memcmp(&v6addr, &v6addr2, sizeof(v6addr))) {
- return false;
- }
- return true;
-}
-
-bool BrokenIPStringFails(const std::string& broken) {
- IPAddress addr(0); // Intentionally make it v4.
- if (IPFromString(kIPv4BrokenString1, &addr)) {
- return false;
- }
- return addr.family() == AF_UNSPEC;
-}
-
-bool CheckMaskCount(const std::string& mask, int expected_length) {
- IPAddress addr;
- return IPFromString(mask, &addr) &&
- (expected_length == CountIPMaskBits(addr));
-}
-
-bool TryInvalidMaskCount(const std::string& mask) {
- // We don't care about the result at all, but we do want to know if
- // CountIPMaskBits is going to crash or infinite loop or something.
- IPAddress addr;
- if (!IPFromString(mask, &addr)) {
- return false;
- }
- CountIPMaskBits(addr);
- return true;
-}
-
-bool CheckTruncateIP(const std::string& initial, int truncate_length,
- const std::string& expected_result) {
- IPAddress addr, expected;
- IPFromString(initial, &addr);
- IPFromString(expected_result, &expected);
- IPAddress truncated = TruncateIP(addr, truncate_length);
- return truncated == expected;
-}
-
-TEST(IPAddressTest, TestDefaultCtor) {
- IPAddress addr;
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_FALSE(IPIsPrivate(addr));
-
- EXPECT_EQ(0U, addr.Size());
- EXPECT_EQ(AF_UNSPEC, addr.family());
- EXPECT_EQ("", addr.ToString());
-}
-
-TEST(IPAddressTest, TestInAddrCtor) {
- in_addr v4addr;
-
- // Test V4 Any address.
- v4addr.s_addr = INADDR_ANY;
- IPAddress addr(v4addr);
- EXPECT_TRUE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_FALSE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4AnyAddrString, addr.ToString());
-
- // Test a V4 loopback address.
- v4addr.s_addr = htonl(INADDR_LOOPBACK);
- addr = IPAddress(v4addr);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_TRUE(IPIsLoopback(addr));
- EXPECT_TRUE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4LoopbackAddrString, addr.ToString());
-
- // Test an RFC1918 address.
- v4addr.s_addr = htonl(kIPv4RFC1918Addr);
- addr = IPAddress(v4addr);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_TRUE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4RFC1918AddrString, addr.ToString());
-
- // Test a 'normal' v4 address.
- v4addr.s_addr = htonl(kIPv4PublicAddr);
- addr = IPAddress(v4addr);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_FALSE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4PublicAddrString, addr.ToString());
-}
-
-TEST(IPAddressTest, TestInAddr6Ctor) {
- // Test v6 empty.
- IPAddress addr(in6addr_any);
- EXPECT_TRUE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_FALSE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv6AddrSize, addr.Size());
- EXPECT_EQ(kIPv6AnyAddrString, addr.ToString());
-
- // Test v6 loopback.
- addr = IPAddress(in6addr_loopback);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_TRUE(IPIsLoopback(addr));
- EXPECT_TRUE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv6AddrSize, addr.Size());
- EXPECT_EQ(kIPv6LoopbackAddrString, addr.ToString());
-
- // Test v6 link-local.
- addr = IPAddress(kIPv6LinkLocalAddr);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_TRUE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv6AddrSize, addr.Size());
- EXPECT_EQ(kIPv6LinkLocalAddrString, addr.ToString());
-
- // Test v6 global address.
- addr = IPAddress(kIPv6PublicAddr);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_FALSE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv6AddrSize, addr.Size());
- EXPECT_EQ(kIPv6PublicAddrString, addr.ToString());
-}
-
-TEST(IPAddressTest, TestUint32Ctor) {
- // Test V4 Any address.
- IPAddress addr(0);
- EXPECT_TRUE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_FALSE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4AnyAddrString, addr.ToString());
-
- // Test a V4 loopback address.
- addr = IPAddress(INADDR_LOOPBACK);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_TRUE(IPIsLoopback(addr));
- EXPECT_TRUE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4LoopbackAddrString, addr.ToString());
-
- // Test an RFC1918 address.
- addr = IPAddress(kIPv4RFC1918Addr);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_TRUE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4RFC1918AddrString, addr.ToString());
-
- // Test a 'normal' v4 address.
- addr = IPAddress(kIPv4PublicAddr);
- EXPECT_FALSE(IPIsAny(addr));
- EXPECT_FALSE(IPIsLoopback(addr));
- EXPECT_FALSE(IPIsPrivate(addr));
- EXPECT_EQ(kIPv4AddrSize, addr.Size());
- EXPECT_EQ(kIPv4PublicAddrString, addr.ToString());
-}
-
-TEST(IPAddressTest, TestCopyCtor) {
- in_addr v4addr;
- v4addr.s_addr = htonl(kIPv4PublicAddr);
- IPAddress addr(v4addr);
- IPAddress addr2(addr);
-
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(INADDR_ANY);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(INADDR_LOOPBACK);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(kIPv4PublicAddr);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(kIPv4RFC1918Addr);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(in6addr_any);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(in6addr_loopback);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(kIPv6LinkLocalAddr);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr = IPAddress(kIPv6PublicAddr);
- addr2 = IPAddress(addr);
- EXPECT_PRED2(AreEqual, addr, addr2);
-}
-
-TEST(IPAddressTest, TestEquality) {
- // Check v4 equality
- in_addr v4addr, v4addr2;
- v4addr.s_addr = htonl(kIPv4PublicAddr);
- v4addr2.s_addr = htonl(kIPv4PublicAddr + 1);
- IPAddress addr(v4addr);
- IPAddress addr2(v4addr2);
- IPAddress addr3(v4addr);
-
- EXPECT_TRUE(addr == addr);
- EXPECT_TRUE(addr2 == addr2);
- EXPECT_TRUE(addr3 == addr3);
- EXPECT_TRUE(addr == addr3);
- EXPECT_TRUE(addr3 == addr);
- EXPECT_FALSE(addr2 == addr);
- EXPECT_FALSE(addr2 == addr3);
- EXPECT_FALSE(addr == addr2);
- EXPECT_FALSE(addr3 == addr2);
-
- // Check v6 equality
- IPAddress addr4(kIPv6PublicAddr);
- IPAddress addr5(kIPv6LinkLocalAddr);
- IPAddress addr6(kIPv6PublicAddr);
-
- EXPECT_TRUE(addr4 == addr4);
- EXPECT_TRUE(addr5 == addr5);
- EXPECT_TRUE(addr4 == addr6);
- EXPECT_TRUE(addr6 == addr4);
- EXPECT_FALSE(addr4 == addr5);
- EXPECT_FALSE(addr5 == addr4);
- EXPECT_FALSE(addr6 == addr5);
- EXPECT_FALSE(addr5 == addr6);
-
- // Check v4/v6 cross-equality
- EXPECT_FALSE(addr == addr4);
- EXPECT_FALSE(addr == addr5);
- EXPECT_FALSE(addr == addr6);
- EXPECT_FALSE(addr4 == addr);
- EXPECT_FALSE(addr5 == addr);
- EXPECT_FALSE(addr6 == addr);
- EXPECT_FALSE(addr2 == addr4);
- EXPECT_FALSE(addr2 == addr5);
- EXPECT_FALSE(addr2 == addr6);
- EXPECT_FALSE(addr4 == addr2);
- EXPECT_FALSE(addr5 == addr2);
- EXPECT_FALSE(addr6 == addr2);
- EXPECT_FALSE(addr3 == addr4);
- EXPECT_FALSE(addr3 == addr5);
- EXPECT_FALSE(addr3 == addr6);
- EXPECT_FALSE(addr4 == addr3);
- EXPECT_FALSE(addr5 == addr3);
- EXPECT_FALSE(addr6 == addr3);
-
- // Special cases: loopback and any.
- // They're special but they're still not equal.
- IPAddress v4loopback(htonl(INADDR_LOOPBACK));
- IPAddress v6loopback(in6addr_loopback);
- EXPECT_FALSE(v4loopback == v6loopback);
-
- IPAddress v4any(0);
- IPAddress v6any(in6addr_any);
- EXPECT_FALSE(v4any == v6any);
-}
-
-TEST(IPAddressTest, TestComparison) {
- // Defined in 'ascending' order.
- // v6 > v4, and intra-family sorting is purely numerical
- IPAddress addr0; // AF_UNSPEC
- IPAddress addr1(INADDR_ANY); // 0.0.0.0
- IPAddress addr2(kIPv4PublicAddr); // 1.2.3.4
- IPAddress addr3(INADDR_LOOPBACK); // 127.0.0.1
- IPAddress addr4(kIPv4RFC1918Addr); // 192.168.7.1.
- IPAddress addr5(in6addr_any); // ::
- IPAddress addr6(in6addr_loopback); // ::1
- IPAddress addr7(kIPv6PublicAddr); // 2401....
- IPAddress addr8(kIPv6LinkLocalAddr); // fe80....
-
- EXPECT_TRUE(addr0 < addr1);
- EXPECT_TRUE(addr1 < addr2);
- EXPECT_TRUE(addr2 < addr3);
- EXPECT_TRUE(addr3 < addr4);
- EXPECT_TRUE(addr4 < addr5);
- EXPECT_TRUE(addr5 < addr6);
- EXPECT_TRUE(addr6 < addr7);
- EXPECT_TRUE(addr7 < addr8);
-
- EXPECT_FALSE(addr0 > addr1);
- EXPECT_FALSE(addr1 > addr2);
- EXPECT_FALSE(addr2 > addr3);
- EXPECT_FALSE(addr3 > addr4);
- EXPECT_FALSE(addr4 > addr5);
- EXPECT_FALSE(addr5 > addr6);
- EXPECT_FALSE(addr6 > addr7);
- EXPECT_FALSE(addr7 > addr8);
-
- EXPECT_FALSE(addr0 > addr0);
- EXPECT_FALSE(addr1 > addr1);
- EXPECT_FALSE(addr2 > addr2);
- EXPECT_FALSE(addr3 > addr3);
- EXPECT_FALSE(addr4 > addr4);
- EXPECT_FALSE(addr5 > addr5);
- EXPECT_FALSE(addr6 > addr6);
- EXPECT_FALSE(addr7 > addr7);
- EXPECT_FALSE(addr8 > addr8);
-
- EXPECT_FALSE(addr0 < addr0);
- EXPECT_FALSE(addr1 < addr1);
- EXPECT_FALSE(addr2 < addr2);
- EXPECT_FALSE(addr3 < addr3);
- EXPECT_FALSE(addr4 < addr4);
- EXPECT_FALSE(addr5 < addr5);
- EXPECT_FALSE(addr6 < addr6);
- EXPECT_FALSE(addr7 < addr7);
- EXPECT_FALSE(addr8 < addr8);
-}
-
-TEST(IPAddressTest, TestFromString) {
- IPAddress addr;
- IPAddress addr2;
- addr2 = IPAddress(INADDR_ANY);
-
- EXPECT_TRUE(IPFromString(kIPv4AnyAddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv4AnyAddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(INADDR_LOOPBACK);
- EXPECT_TRUE(IPFromString(kIPv4LoopbackAddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv4LoopbackAddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(kIPv4RFC1918Addr);
- EXPECT_TRUE(IPFromString(kIPv4RFC1918AddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv4RFC1918AddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(kIPv4PublicAddr);
- EXPECT_TRUE(IPFromString(kIPv4PublicAddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv4PublicAddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(in6addr_any);
- EXPECT_TRUE(IPFromString(kIPv6AnyAddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv6AnyAddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(in6addr_loopback);
- EXPECT_TRUE(IPFromString(kIPv6LoopbackAddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv6LoopbackAddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(kIPv6LinkLocalAddr);
- EXPECT_TRUE(IPFromString(kIPv6LinkLocalAddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv6LinkLocalAddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(kIPv6PublicAddr);
- EXPECT_TRUE(IPFromString(kIPv6PublicAddrString, &addr));
- EXPECT_EQ(addr.ToString(), kIPv6PublicAddrString);
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- addr2 = IPAddress(kIPv4MappedRFC1918Addr);
- EXPECT_TRUE(IPFromString(kIPv4MappedV4StyleAddrString, &addr));
- EXPECT_PRED2(AreEqual, addr, addr2);
-
- // Broken cases, should set addr to AF_UNSPEC.
- EXPECT_PRED1(BrokenIPStringFails, kIPv4BrokenString1);
- EXPECT_PRED1(BrokenIPStringFails, kIPv4BrokenString2);
- EXPECT_PRED1(BrokenIPStringFails, kIPv4BrokenString3);
- EXPECT_PRED1(BrokenIPStringFails, kIPv4BrokenString4);
- EXPECT_PRED1(BrokenIPStringFails, kIPv4BrokenString5);
- EXPECT_PRED1(BrokenIPStringFails, kIPv4BrokenString6);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString1);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString2);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString3);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString4);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString5);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString6);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString7);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString8);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString9);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString10);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString11);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString12);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString13);
- EXPECT_PRED1(BrokenIPStringFails, kIPv6BrokenString14);
-}
-
-TEST(IPAddressTest, TestIPFromAddrInfo) {
- struct sockaddr_in expected4;
- struct sockaddr_in6 expected6;
- struct addrinfo test_info;
- struct addrinfo next_info;
- memset(&next_info, 'A', sizeof(next_info));
- test_info.ai_next = &next_info;
- // Check that we can get an IPv4 address out.
- test_info.ai_addr = reinterpret_cast<struct sockaddr*>(&expected4);
- expected4.sin_addr.s_addr = HostToNetwork32(kIPv4PublicAddr);
- expected4.sin_family = AF_INET;
- IPAddress expected(kIPv4PublicAddr);
- IPAddress addr;
- EXPECT_TRUE(IPFromAddrInfo(&test_info, &addr));
- EXPECT_EQ(expected, addr);
- // Check that we can get an IPv6 address out.
- expected6.sin6_addr = kIPv6PublicAddr;
- expected6.sin6_family = AF_INET6;
- expected = IPAddress(kIPv6PublicAddr);
- test_info.ai_addr = reinterpret_cast<struct sockaddr*>(&expected6);
- EXPECT_TRUE(IPFromAddrInfo(&test_info, &addr));
- EXPECT_EQ(expected, addr);
- // Check that unspec fails.
- expected6.sin6_family = AF_UNSPEC;
- EXPECT_FALSE(IPFromAddrInfo(&test_info, &addr));
- // Check a zeroed out addrinfo doesn't crash us.
- memset(&next_info, 0, sizeof(next_info));
- EXPECT_FALSE(IPFromAddrInfo(&next_info, &addr));
-}
-
-TEST(IPAddressTest, TestIsPrivate) {
- EXPECT_FALSE(IPIsPrivate(IPAddress(INADDR_ANY)));
- EXPECT_FALSE(IPIsPrivate(IPAddress(kIPv4PublicAddr)));
- EXPECT_FALSE(IPIsPrivate(IPAddress(in6addr_any)));
- EXPECT_FALSE(IPIsPrivate(IPAddress(kIPv6PublicAddr)));
- EXPECT_FALSE(IPIsPrivate(IPAddress(kIPv4MappedAnyAddr)));
- EXPECT_FALSE(IPIsPrivate(IPAddress(kIPv4MappedPublicAddr)));
-
- EXPECT_TRUE(IPIsPrivate(IPAddress(kIPv4RFC1918Addr)));
- EXPECT_TRUE(IPIsPrivate(IPAddress(INADDR_LOOPBACK)));
- EXPECT_TRUE(IPIsPrivate(IPAddress(in6addr_loopback)));
- EXPECT_TRUE(IPIsPrivate(IPAddress(kIPv6LinkLocalAddr)));
-}
-
-TEST(IPAddressTest, TestIsLoopback) {
- EXPECT_FALSE(IPIsLoopback(IPAddress(INADDR_ANY)));
- EXPECT_FALSE(IPIsLoopback(IPAddress(kIPv4PublicAddr)));
- EXPECT_FALSE(IPIsLoopback(IPAddress(in6addr_any)));
- EXPECT_FALSE(IPIsLoopback(IPAddress(kIPv6PublicAddr)));
- EXPECT_FALSE(IPIsLoopback(IPAddress(kIPv4MappedAnyAddr)));
- EXPECT_FALSE(IPIsLoopback(IPAddress(kIPv4MappedPublicAddr)));
-
- EXPECT_TRUE(IPIsLoopback(IPAddress(INADDR_LOOPBACK)));
- EXPECT_TRUE(IPIsLoopback(IPAddress(in6addr_loopback)));
-}
-
-TEST(IPAddressTest, TestNormalized) {
- // Check normalizing a ::ffff:a.b.c.d address.
- IPAddress addr;
- EXPECT_TRUE(IPFromString(kIPv4MappedV4StyleAddrString, &addr));
- IPAddress addr2(kIPv4RFC1918Addr);
- addr = addr.Normalized();
- EXPECT_EQ(addr2, addr);
-
- // Check normalizing a ::ffff:aabb:ccdd address.
- addr = IPAddress(kIPv4MappedPublicAddr);
- addr2 = IPAddress(kIPv4PublicAddr);
- addr = addr.Normalized();
- EXPECT_EQ(addr, addr2);
-
- // Check that a non-mapped v6 addresses isn't altered.
- addr = IPAddress(kIPv6PublicAddr);
- addr2 = IPAddress(kIPv6PublicAddr);
- addr = addr.Normalized();
- EXPECT_EQ(addr, addr2);
-
- // Check that addresses that look a bit like mapped addresses aren't altered
- EXPECT_TRUE(IPFromString("fe80::ffff:0102:0304", &addr));
- addr2 = addr;
- addr = addr.Normalized();
- EXPECT_EQ(addr, addr2);
- EXPECT_TRUE(IPFromString("::0102:0304", &addr));
- addr2 = addr;
- addr = addr.Normalized();
- EXPECT_EQ(addr, addr2);
- // This string should 'work' as an IP address but is not a mapped address,
- // so it shouldn't change on normalization.
- EXPECT_TRUE(IPFromString("::192.168.7.1", &addr));
- addr2 = addr;
- addr = addr.Normalized();
- EXPECT_EQ(addr, addr2);
-
- // Check that v4 addresses aren't altered.
- addr = IPAddress(htonl(kIPv4PublicAddr));
- addr2 = IPAddress(htonl(kIPv4PublicAddr));
- addr = addr.Normalized();
- EXPECT_EQ(addr, addr2);
-}
-
-TEST(IPAddressTest, TestAsIPv6Address) {
- IPAddress addr(kIPv4PublicAddr);
- IPAddress addr2(kIPv4MappedPublicAddr);
- addr = addr.AsIPv6Address();
- EXPECT_EQ(addr, addr2);
-
- addr = IPAddress(kIPv4MappedPublicAddr);
- addr2 = IPAddress(kIPv4MappedPublicAddr);
- addr = addr.AsIPv6Address();
- EXPECT_EQ(addr, addr2);
-
- addr = IPAddress(kIPv6PublicAddr);
- addr2 = IPAddress(kIPv6PublicAddr);
- addr = addr.AsIPv6Address();
- EXPECT_EQ(addr, addr2);
-}
-
-TEST(IPAddressTest, TestCountIPMaskBits) {
- IPAddress mask;
- // IPv4 on byte boundaries
- EXPECT_PRED2(CheckMaskCount, "255.255.255.255", 32);
- EXPECT_PRED2(CheckMaskCount, "255.255.255.0", 24);
- EXPECT_PRED2(CheckMaskCount, "255.255.0.0", 16);
- EXPECT_PRED2(CheckMaskCount, "255.0.0.0", 8);
- EXPECT_PRED2(CheckMaskCount, "0.0.0.0", 0);
-
- // IPv4 not on byte boundaries
- EXPECT_PRED2(CheckMaskCount, "128.0.0.0", 1);
- EXPECT_PRED2(CheckMaskCount, "224.0.0.0", 3);
- EXPECT_PRED2(CheckMaskCount, "255.248.0.0", 13);
- EXPECT_PRED2(CheckMaskCount, "255.255.224.0", 19);
- EXPECT_PRED2(CheckMaskCount, "255.255.255.252", 30);
-
- // V6 on byte boundaries
- EXPECT_PRED2(CheckMaskCount, "::", 0);
- EXPECT_PRED2(CheckMaskCount, "ff00::", 8);
- EXPECT_PRED2(CheckMaskCount, "ffff::", 16);
- EXPECT_PRED2(CheckMaskCount, "ffff:ff00::", 24);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff::", 32);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ff00::", 40);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff::", 48);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ff00::", 56);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff::", 64);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ff00::", 72);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff::", 80);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ff00::", 88);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff::", 96);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ff00:0000", 104);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000", 112);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00", 120);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 128);
-
- // V6 not on byte boundaries.
- EXPECT_PRED2(CheckMaskCount, "8000::", 1);
- EXPECT_PRED2(CheckMaskCount, "ff80::", 9);
- EXPECT_PRED2(CheckMaskCount, "ffff:fe00::", 23);
- EXPECT_PRED2(CheckMaskCount, "ffff:fffe::", 31);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:e000::", 35);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffe0::", 43);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:f800::", 53);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:fff8::", 61);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:fc00::", 70);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:fffc::", 78);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:8000::", 81);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ff80::", 89);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:fe00::", 103);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:fffe:0000", 111);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00", 118);
- EXPECT_PRED2(CheckMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc", 126);
-
- // Non-contiguous ranges. These are invalid but lets test them
- // to make sure they don't crash anything or infinite loop or something.
- EXPECT_PRED1(TryInvalidMaskCount, "217.0.0.0");
- EXPECT_PRED1(TryInvalidMaskCount, "255.185.0.0");
- EXPECT_PRED1(TryInvalidMaskCount, "255.255.251.0");
- EXPECT_PRED1(TryInvalidMaskCount, "255.255.251.255");
- EXPECT_PRED1(TryInvalidMaskCount, "255.255.254.201");
- EXPECT_PRED1(TryInvalidMaskCount, "::1");
- EXPECT_PRED1(TryInvalidMaskCount, "fe80::1");
- EXPECT_PRED1(TryInvalidMaskCount, "ff80::1");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff::1");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ff00:1::1");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff::ffff:1");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ff00:1::");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff::ff00");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ff00:1234::");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:0012::ffff");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:ff01::");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:ffff:7f00::");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:ffff:ff7a::");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:7f00:0000");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ff70:0000");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0211");
- EXPECT_PRED1(TryInvalidMaskCount, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff7f");
-}
-
-TEST(IPAddressTest, TestTruncateIP) {
- EXPECT_PRED3(CheckTruncateIP, "255.255.255.255", 24, "255.255.255.0");
- EXPECT_PRED3(CheckTruncateIP, "255.255.255.255", 16, "255.255.0.0");
- EXPECT_PRED3(CheckTruncateIP, "255.255.255.255", 8, "255.0.0.0");
- EXPECT_PRED3(CheckTruncateIP, "202.67.7.255", 24, "202.67.7.0");
- EXPECT_PRED3(CheckTruncateIP, "202.129.65.205", 16, "202.129.0.0");
- EXPECT_PRED3(CheckTruncateIP, "55.25.2.77", 8, "55.0.0.0");
- EXPECT_PRED3(CheckTruncateIP, "74.128.99.254", 1, "0.0.0.0");
- EXPECT_PRED3(CheckTruncateIP, "106.55.99.254", 3, "96.0.0.0");
- EXPECT_PRED3(CheckTruncateIP, "172.167.53.222", 13, "172.160.0.0");
- EXPECT_PRED3(CheckTruncateIP, "255.255.224.0", 18, "255.255.192.0");
- EXPECT_PRED3(CheckTruncateIP, "255.255.255.252", 28, "255.255.255.240");
-
- EXPECT_PRED3(CheckTruncateIP, "fe80:1111:2222:3333:4444:5555:6666:7777", 1,
- "8000::");
- EXPECT_PRED3(CheckTruncateIP, "fff0:1111:2222:3333:4444:5555:6666:7777", 9,
- "ff80::");
- EXPECT_PRED3(CheckTruncateIP, "ffff:ff80:1111:2222:3333:4444:5555:6666", 23,
- "ffff:fe00::");
- EXPECT_PRED3(CheckTruncateIP, "ffff:ff80:1111:2222:3333:4444:5555:6666", 32,
- "ffff:ff80::");
- EXPECT_PRED3(CheckTruncateIP, "2400:f9af:e456:1111:2222:3333:4444:5555", 35,
- "2400:f9af:e000::");
- EXPECT_PRED3(CheckTruncateIP, "9999:1111:2233:4444:5555:6666:7777:8888", 53,
- "9999:1111:2233:4000::");
- EXPECT_PRED3(CheckTruncateIP, "9999:1111:2233:4567:5555:6666:7777:8888", 64,
- "9999:1111:2233:4567::");
- EXPECT_PRED3(CheckTruncateIP, "1111:2222:3333:4444:5555:6666:7777:8888", 68,
- "1111:2222:3333:4444:5000::");
- EXPECT_PRED3(CheckTruncateIP, "1111:2222:3333:4444:5555:6666:7777:8888", 92,
- "1111:2222:3333:4444:5555:6660::");
- EXPECT_PRED3(CheckTruncateIP, "1111:2222:3333:4444:5555:6666:7777:8888", 96,
- "1111:2222:3333:4444:5555:6666::");
- EXPECT_PRED3(CheckTruncateIP, "1111:2222:3333:4444:5555:6666:7777:8888", 105,
- "1111:2222:3333:4444:5555:6666:7700::");
- EXPECT_PRED3(CheckTruncateIP, "1111:2222:3333:4444:5555:6666:7777:8888", 124,
- "1111:2222:3333:4444:5555:6666:7777:8880");
-
- // Slightly degenerate cases
- EXPECT_PRED3(CheckTruncateIP, "202.165.33.127", 32, "202.165.33.127");
- EXPECT_PRED3(CheckTruncateIP, "235.105.77.12", 0, "0.0.0.0");
- EXPECT_PRED3(CheckTruncateIP, "1111:2222:3333:4444:5555:6666:7777:8888", 128,
- "1111:2222:3333:4444:5555:6666:7777:8888");
- EXPECT_PRED3(CheckTruncateIP, "1111:2222:3333:4444:5555:6666:7777:8888", 0,
- "::");
-}
-
-TEST(IPAddressTest, TestCategorizeIPv6) {
- // Test determining if an IPAddress is 6Bone/6To4/Teredo/etc.
- // IPv4 address, should be none of these (not even v4compat/v4mapped).
- IPAddress v4_addr(kIPv4PublicAddr);
- EXPECT_FALSE(IPIs6Bone(v4_addr));
- EXPECT_FALSE(IPIs6To4(v4_addr));
- EXPECT_FALSE(IPIsSiteLocal(v4_addr));
- EXPECT_FALSE(IPIsTeredo(v4_addr));
- EXPECT_FALSE(IPIsULA(v4_addr));
- EXPECT_FALSE(IPIsV4Compatibility(v4_addr));
- EXPECT_FALSE(IPIsV4Mapped(v4_addr));
- // Linklocal (fe80::/16) adddress; should be none of these.
- IPAddress linklocal_addr(kIPv6LinkLocalAddr);
- EXPECT_FALSE(IPIs6Bone(linklocal_addr));
- EXPECT_FALSE(IPIs6To4(linklocal_addr));
- EXPECT_FALSE(IPIsSiteLocal(linklocal_addr));
- EXPECT_FALSE(IPIsTeredo(linklocal_addr));
- EXPECT_FALSE(IPIsULA(linklocal_addr));
- EXPECT_FALSE(IPIsV4Compatibility(linklocal_addr));
- EXPECT_FALSE(IPIsV4Mapped(linklocal_addr));
- // 'Normal' IPv6 address, should also be none of these.
- IPAddress normal_addr(kIPv6PublicAddr);
- EXPECT_FALSE(IPIs6Bone(normal_addr));
- EXPECT_FALSE(IPIs6To4(normal_addr));
- EXPECT_FALSE(IPIsSiteLocal(normal_addr));
- EXPECT_FALSE(IPIsTeredo(normal_addr));
- EXPECT_FALSE(IPIsULA(normal_addr));
- EXPECT_FALSE(IPIsV4Compatibility(normal_addr));
- EXPECT_FALSE(IPIsV4Mapped(normal_addr));
- // IPv4 mapped address (::ffff:123.123.123.123)
- IPAddress v4mapped_addr(kIPv4MappedPublicAddr);
- EXPECT_TRUE(IPIsV4Mapped(v4mapped_addr));
- EXPECT_FALSE(IPIsV4Compatibility(v4mapped_addr));
- EXPECT_FALSE(IPIs6Bone(v4mapped_addr));
- EXPECT_FALSE(IPIs6To4(v4mapped_addr));
- EXPECT_FALSE(IPIsSiteLocal(v4mapped_addr));
- EXPECT_FALSE(IPIsTeredo(v4mapped_addr));
- EXPECT_FALSE(IPIsULA(v4mapped_addr));
- // IPv4 compatibility address (::123.123.123.123)
- IPAddress v4compat_addr;
- IPFromString("::192.168.7.1", &v4compat_addr);
- EXPECT_TRUE(IPIsV4Compatibility(v4compat_addr));
- EXPECT_FALSE(IPIs6Bone(v4compat_addr));
- EXPECT_FALSE(IPIs6To4(v4compat_addr));
- EXPECT_FALSE(IPIsSiteLocal(v4compat_addr));
- EXPECT_FALSE(IPIsTeredo(v4compat_addr));
- EXPECT_FALSE(IPIsULA(v4compat_addr));
- EXPECT_FALSE(IPIsV4Mapped(v4compat_addr));
- // 6Bone address (3FFE::/16)
- IPAddress sixbone_addr;
- IPFromString("3FFE:123:456::789:123", &sixbone_addr);
- EXPECT_TRUE(IPIs6Bone(sixbone_addr));
- EXPECT_FALSE(IPIs6To4(sixbone_addr));
- EXPECT_FALSE(IPIsSiteLocal(sixbone_addr));
- EXPECT_FALSE(IPIsTeredo(sixbone_addr));
- EXPECT_FALSE(IPIsULA(sixbone_addr));
- EXPECT_FALSE(IPIsV4Mapped(sixbone_addr));
- EXPECT_FALSE(IPIsV4Compatibility(sixbone_addr));
- // Unique Local Address (FC::/7)
- IPAddress ula_addr;
- IPFromString("FC00:123:456::789:123", &ula_addr);
- EXPECT_TRUE(IPIsULA(ula_addr));
- EXPECT_FALSE(IPIs6Bone(ula_addr));
- EXPECT_FALSE(IPIs6To4(ula_addr));
- EXPECT_FALSE(IPIsSiteLocal(ula_addr));
- EXPECT_FALSE(IPIsTeredo(ula_addr));
- EXPECT_FALSE(IPIsV4Mapped(ula_addr));
- EXPECT_FALSE(IPIsV4Compatibility(ula_addr));
- // 6To4 Address (2002::/16)
- IPAddress sixtofour_addr;
- IPFromString("2002:123:456::789:123", &sixtofour_addr);
- EXPECT_TRUE(IPIs6To4(sixtofour_addr));
- EXPECT_FALSE(IPIs6Bone(sixtofour_addr));
- EXPECT_FALSE(IPIsSiteLocal(sixtofour_addr));
- EXPECT_FALSE(IPIsTeredo(sixtofour_addr));
- EXPECT_FALSE(IPIsULA(sixtofour_addr));
- EXPECT_FALSE(IPIsV4Compatibility(sixtofour_addr));
- EXPECT_FALSE(IPIsV4Mapped(sixtofour_addr));
- // Site Local address (FEC0::/10)
- IPAddress sitelocal_addr;
- IPFromString("FEC0:123:456::789:123", &sitelocal_addr);
- EXPECT_TRUE(IPIsSiteLocal(sitelocal_addr));
- EXPECT_FALSE(IPIs6Bone(sitelocal_addr));
- EXPECT_FALSE(IPIs6To4(sitelocal_addr));
- EXPECT_FALSE(IPIsTeredo(sitelocal_addr));
- EXPECT_FALSE(IPIsULA(sitelocal_addr));
- EXPECT_FALSE(IPIsV4Compatibility(sitelocal_addr));
- EXPECT_FALSE(IPIsV4Mapped(sitelocal_addr));
- // Teredo Address (2001:0000::/32)
- IPAddress teredo_addr;
- IPFromString("2001:0000:123:456::789:123", &teredo_addr);
- EXPECT_TRUE(IPIsTeredo(teredo_addr));
- EXPECT_FALSE(IPIsSiteLocal(teredo_addr));
- EXPECT_FALSE(IPIs6Bone(teredo_addr));
- EXPECT_FALSE(IPIs6To4(teredo_addr));
- EXPECT_FALSE(IPIsULA(teredo_addr));
- EXPECT_FALSE(IPIsV4Compatibility(teredo_addr));
- EXPECT_FALSE(IPIsV4Mapped(teredo_addr));
-}
-
-TEST(IPAddressTest, TestToSensitiveString) {
- IPAddress addr_v4 = IPAddress(kIPv4PublicAddr);
- EXPECT_EQ(kIPv4PublicAddrString, addr_v4.ToString());
- EXPECT_EQ(kIPv4PublicAddrString, addr_v4.ToSensitiveString());
- IPAddress::set_strip_sensitive(true);
- EXPECT_EQ(kIPv4PublicAddrString, addr_v4.ToString());
- EXPECT_EQ(kIPv4PublicAddrAnonymizedString, addr_v4.ToSensitiveString());
- IPAddress::set_strip_sensitive(false);
-
- IPAddress addr_v6 = IPAddress(kIPv6PublicAddr);
- EXPECT_EQ(kIPv6PublicAddrString, addr_v6.ToString());
- EXPECT_EQ(kIPv6PublicAddrString, addr_v6.ToSensitiveString());
- IPAddress::set_strip_sensitive(true);
- EXPECT_EQ(kIPv6PublicAddrString, addr_v6.ToString());
- EXPECT_EQ(kIPv6PublicAddrAnonymizedString, addr_v6.ToSensitiveString());
- IPAddress::set_strip_sensitive(false);
-}
-
-} // namespace talk_base
diff --git a/base/json.cc b/base/json.cc
deleted file mode 100644
index 6b9fce1..0000000
--- a/base/json.cc
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/json.h"
-
-#include <errno.h>
-#include <limits.h>
-#include <stdlib.h>
-
-#include <sstream>
-
-bool GetStringFromJson(const Json::Value& in, std::string* out) {
- if (!in.isString()) {
- std::ostringstream s;
- if (in.isBool()) {
- s << std::boolalpha << in.asBool();
- } else if (in.isInt()) {
- s << in.asInt();
- } else if (in.isUInt()) {
- s << in.asUInt();
- } else if (in.isDouble()) {
- s << in.asDouble();
- } else {
- return false;
- }
- *out = s.str();
- } else {
- *out = in.asString();
- }
- return true;
-}
-
-bool GetIntFromJson(const Json::Value& in, int* out) {
- bool ret;
- if (!in.isString()) {
- ret = in.isConvertibleTo(Json::intValue);
- if (ret) {
- *out = in.asInt();
- }
- } else {
- long val; // NOLINT
- const char* c_str = in.asCString();
- char* end_ptr;
- errno = 0;
- val = strtol(c_str, &end_ptr, 10); // NOLINT
- ret = (end_ptr != c_str && *end_ptr == '\0' && !errno &&
- val >= INT_MIN && val <= INT_MAX);
- *out = val;
- }
- return ret;
-}
-
-bool GetUIntFromJson(const Json::Value& in, unsigned int* out) {
- bool ret;
- if (!in.isString()) {
- ret = in.isConvertibleTo(Json::uintValue);
- if (ret) {
- *out = in.asUInt();
- }
- } else {
- unsigned long val; // NOLINT
- const char* c_str = in.asCString();
- char* end_ptr;
- errno = 0;
- val = strtoul(c_str, &end_ptr, 10); // NOLINT
- ret = (end_ptr != c_str && *end_ptr == '\0' && !errno &&
- val <= UINT_MAX);
- *out = val;
- }
- return ret;
-}
-
-bool GetBoolFromJson(const Json::Value& in, bool* out) {
- bool ret;
- if (!in.isString()) {
- ret = in.isConvertibleTo(Json::booleanValue);
- if (ret) {
- *out = in.asBool();
- }
- } else {
- if (in.asString() == "true") {
- *out = true;
- ret = true;
- } else if (in.asString() == "false") {
- *out = false;
- ret = true;
- } else {
- ret = false;
- }
- }
- return ret;
-}
-
-bool GetDoubleFromJson(const Json::Value& in, double* out) {
- bool ret;
- if (!in.isString()) {
- ret = in.isConvertibleTo(Json::realValue);
- if (ret) {
- *out = in.asDouble();
- }
- } else {
- double val;
- const char* c_str = in.asCString();
- char* end_ptr;
- errno = 0;
- val = strtod(c_str, &end_ptr);
- ret = (end_ptr != c_str && *end_ptr == '\0' && !errno);
- *out = val;
- }
- return ret;
-}
-
-namespace {
-template<typename T>
-bool JsonArrayToVector(const Json::Value& value,
- bool (*getter)(const Json::Value& in, T* out),
- std::vector<T> *vec) {
- vec->clear();
- if (!value.isArray()) {
- return false;
- }
-
- for (Json::Value::ArrayIndex i = 0; i < value.size(); ++i) {
- T val;
- if (!getter(value[i], &val)) {
- return false;
- }
- vec->push_back(val);
- }
-
- return true;
-}
-// Trivial getter helper
-bool GetValueFromJson(const Json::Value& in, Json::Value* out) {
- *out = in;
- return true;
-}
-} // unnamed namespace
-
-bool JsonArrayToValueVector(const Json::Value& in,
- std::vector<Json::Value>* out) {
- return JsonArrayToVector(in, GetValueFromJson, out);
-}
-
-bool JsonArrayToIntVector(const Json::Value& in,
- std::vector<int>* out) {
- return JsonArrayToVector(in, GetIntFromJson, out);
-}
-
-bool JsonArrayToUIntVector(const Json::Value& in,
- std::vector<unsigned int>* out) {
- return JsonArrayToVector(in, GetUIntFromJson, out);
-}
-
-bool JsonArrayToStringVector(const Json::Value& in,
- std::vector<std::string>* out) {
- return JsonArrayToVector(in, GetStringFromJson, out);
-}
-
-bool JsonArrayToBoolVector(const Json::Value& in,
- std::vector<bool>* out) {
- return JsonArrayToVector(in, GetBoolFromJson, out);
-}
-
-bool JsonArrayToDoubleVector(const Json::Value& in,
- std::vector<double>* out) {
- return JsonArrayToVector(in, GetDoubleFromJson, out);
-}
-
-namespace {
-template<typename T>
-Json::Value VectorToJsonArray(const std::vector<T>& vec) {
- Json::Value result(Json::arrayValue);
- for (size_t i = 0; i < vec.size(); ++i) {
- result.append(Json::Value(vec[i]));
- }
- return result;
-}
-} // unnamed namespace
-
-Json::Value ValueVectorToJsonArray(const std::vector<Json::Value>& in) {
- return VectorToJsonArray(in);
-}
-
-Json::Value IntVectorToJsonArray(const std::vector<int>& in) {
- return VectorToJsonArray(in);
-}
-
-Json::Value UIntVectorToJsonArray(const std::vector<unsigned int>& in) {
- return VectorToJsonArray(in);
-}
-
-Json::Value StringVectorToJsonArray(const std::vector<std::string>& in) {
- return VectorToJsonArray(in);
-}
-
-Json::Value BoolVectorToJsonArray(const std::vector<bool>& in) {
- return VectorToJsonArray(in);
-}
-
-Json::Value DoubleVectorToJsonArray(const std::vector<double>& in) {
- return VectorToJsonArray(in);
-}
-
-bool GetValueFromJsonArray(const Json::Value& in, size_t n,
- Json::Value* out) {
- if (!in.isArray() || !in.isValidIndex(static_cast<int>(n))) {
- return false;
- }
-
- *out = in[static_cast<Json::Value::ArrayIndex>(n)];
- return true;
-}
-
-bool GetIntFromJsonArray(const Json::Value& in, size_t n,
- int* out) {
- Json::Value x;
- return GetValueFromJsonArray(in, n, &x) && GetIntFromJson(x, out);
-}
-
-bool GetUIntFromJsonArray(const Json::Value& in, size_t n,
- unsigned int* out) {
- Json::Value x;
- return GetValueFromJsonArray(in, n, &x) && GetUIntFromJson(x, out);
-}
-
-bool GetStringFromJsonArray(const Json::Value& in, size_t n,
- std::string* out) {
- Json::Value x;
- return GetValueFromJsonArray(in, n, &x) && GetStringFromJson(x, out);
-}
-
-bool GetBoolFromJsonArray(const Json::Value& in, size_t n,
- bool* out) {
- Json::Value x;
- return GetValueFromJsonArray(in, n, &x) && GetBoolFromJson(x, out);
-}
-
-bool GetDoubleFromJsonArray(const Json::Value& in, size_t n,
- double* out) {
- Json::Value x;
- return GetValueFromJsonArray(in, n, &x) && GetDoubleFromJson(x, out);
-}
-
-bool GetValueFromJsonObject(const Json::Value& in, const std::string& k,
- Json::Value* out) {
- if (!in.isObject() || !in.isMember(k)) {
- return false;
- }
-
- *out = in[k];
- return true;
-}
-
-bool GetIntFromJsonObject(const Json::Value& in, const std::string& k,
- int* out) {
- Json::Value x;
- return GetValueFromJsonObject(in, k, &x) && GetIntFromJson(x, out);
-}
-
-bool GetUIntFromJsonObject(const Json::Value& in, const std::string& k,
- unsigned int* out) {
- Json::Value x;
- return GetValueFromJsonObject(in, k, &x) && GetUIntFromJson(x, out);
-}
-
-bool GetStringFromJsonObject(const Json::Value& in, const std::string& k,
- std::string* out) {
- Json::Value x;
- return GetValueFromJsonObject(in, k, &x) && GetStringFromJson(x, out);
-}
-
-bool GetBoolFromJsonObject(const Json::Value& in, const std::string& k,
- bool* out) {
- Json::Value x;
- return GetValueFromJsonObject(in, k, &x) && GetBoolFromJson(x, out);
-}
-
-bool GetDoubleFromJsonObject(const Json::Value& in, const std::string& k,
- double* out) {
- Json::Value x;
- return GetValueFromJsonObject(in, k, &x) && GetDoubleFromJson(x, out);
-}
-
-std::string JsonValueToString(const Json::Value& json) {
- Json::FastWriter w;
- std::string value = w.write(json);
- return value.substr(0, value.size() - 1); // trim trailing newline
-}
diff --git a/base/json.h b/base/json.h
deleted file mode 100644
index 50a4122..0000000
--- a/base/json.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_JSON_H_
-#define TALK_BASE_JSON_H_
-
-#include <string>
-#include <vector>
-
-#ifdef JSONCPP_RELATIVE_PATH
-#include "json/json.h"
-#else
-#include "third_party/jsoncpp/json.h"
-#endif
-
-// TODO: Move to talk_base namespace
-
-///////////////////////////////////////////////////////////////////////////////
-// JSON Helpers
-///////////////////////////////////////////////////////////////////////////////
-
-// Robust conversion operators, better than the ones in JsonCpp.
-bool GetIntFromJson(const Json::Value& in, int* out);
-bool GetUIntFromJson(const Json::Value& in, unsigned int* out);
-bool GetStringFromJson(const Json::Value& in, std::string* out);
-bool GetBoolFromJson(const Json::Value& in, bool* out);
-bool GetDoubleFromJson(const Json::Value& in, double* out);
-
-// Pull values out of a JSON array.
-bool GetValueFromJsonArray(const Json::Value& in, size_t n,
- Json::Value* out);
-bool GetIntFromJsonArray(const Json::Value& in, size_t n,
- int* out);
-bool GetUIntFromJsonArray(const Json::Value& in, size_t n,
- unsigned int* out);
-bool GetStringFromJsonArray(const Json::Value& in, size_t n,
- std::string* out);
-bool GetBoolFromJsonArray(const Json::Value& in, size_t n,
- bool* out);
-bool GetDoubleFromJsonArray(const Json::Value& in, size_t n,
- double* out);
-
-// Convert json arrays to std::vector
-bool JsonArrayToValueVector(const Json::Value& in,
- std::vector<Json::Value>* out);
-bool JsonArrayToIntVector(const Json::Value& in,
- std::vector<int>* out);
-bool JsonArrayToUIntVector(const Json::Value& in,
- std::vector<unsigned int>* out);
-bool JsonArrayToStringVector(const Json::Value& in,
- std::vector<std::string>* out);
-bool JsonArrayToBoolVector(const Json::Value& in,
- std::vector<bool>* out);
-bool JsonArrayToDoubleVector(const Json::Value& in,
- std::vector<double>* out);
-
-// Convert std::vector to json array
-Json::Value ValueVectorToJsonArray(const std::vector<Json::Value>& in);
-Json::Value IntVectorToJsonArray(const std::vector<int>& in);
-Json::Value UIntVectorToJsonArray(const std::vector<unsigned int>& in);
-Json::Value StringVectorToJsonArray(const std::vector<std::string>& in);
-Json::Value BoolVectorToJsonArray(const std::vector<bool>& in);
-Json::Value DoubleVectorToJsonArray(const std::vector<double>& in);
-
-// Pull values out of a JSON object.
-bool GetValueFromJsonObject(const Json::Value& in, const std::string& k,
- Json::Value* out);
-bool GetIntFromJsonObject(const Json::Value& in, const std::string& k,
- int* out);
-bool GetUIntFromJsonObject(const Json::Value& in, const std::string& k,
- unsigned int* out);
-bool GetStringFromJsonObject(const Json::Value& in, const std::string& k,
- std::string* out);
-bool GetBoolFromJsonObject(const Json::Value& in, const std::string& k,
- bool* out);
-bool GetDoubleFromJsonObject(const Json::Value& in, const std::string& k,
- double* out);
-
-// Writes out a Json value as a string.
-std::string JsonValueToString(const Json::Value& json);
-
-#endif // TALK_BASE_JSON_H_
diff --git a/base/json_unittest.cc b/base/json_unittest.cc
deleted file mode 100644
index 96a7975..0000000
--- a/base/json_unittest.cc
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/json.h"
-
-static Json::Value in_s("foo");
-static Json::Value in_sn("99");
-static Json::Value in_si("-99");
-static Json::Value in_sb("true");
-static Json::Value in_sd("1.2");
-static Json::Value in_n(12);
-static Json::Value in_i(-12);
-static Json::Value in_u(34U);
-static Json::Value in_b(true);
-static Json::Value in_d(1.2);
-static Json::Value big_sn("12345678901234567890");
-static Json::Value big_si("-12345678901234567890");
-static Json::Value big_u(0xFFFFFFFF);
-static Json::Value bad_a(Json::arrayValue);
-static Json::Value bad_o(Json::objectValue);
-
-TEST(JsonTest, GetString) {
- std::string out;
- EXPECT_TRUE(GetStringFromJson(in_s, &out));
- EXPECT_EQ("foo", out);
- EXPECT_TRUE(GetStringFromJson(in_sn, &out));
- EXPECT_EQ("99", out);
- EXPECT_TRUE(GetStringFromJson(in_si, &out));
- EXPECT_EQ("-99", out);
- EXPECT_TRUE(GetStringFromJson(in_i, &out));
- EXPECT_EQ("-12", out);
- EXPECT_TRUE(GetStringFromJson(in_n, &out));
- EXPECT_EQ("12", out);
- EXPECT_TRUE(GetStringFromJson(in_u, &out));
- EXPECT_EQ("34", out);
- EXPECT_TRUE(GetStringFromJson(in_b, &out));
- EXPECT_EQ("true", out);
- // Not supported here yet.
- EXPECT_FALSE(GetStringFromJson(bad_a, &out));
- EXPECT_FALSE(GetStringFromJson(bad_o, &out));
-}
-
-TEST(JsonTest, GetInt) {
- int out;
- EXPECT_TRUE(GetIntFromJson(in_sn, &out));
- EXPECT_EQ(99, out);
- EXPECT_TRUE(GetIntFromJson(in_si, &out));
- EXPECT_EQ(-99, out);
- EXPECT_TRUE(GetIntFromJson(in_n, &out));
- EXPECT_EQ(12, out);
- EXPECT_TRUE(GetIntFromJson(in_i, &out));
- EXPECT_EQ(-12, out);
- EXPECT_TRUE(GetIntFromJson(in_u, &out));
- EXPECT_EQ(34, out);
- EXPECT_TRUE(GetIntFromJson(in_b, &out));
- EXPECT_EQ(1, out);
- EXPECT_FALSE(GetIntFromJson(in_s, &out));
- EXPECT_FALSE(GetIntFromJson(big_sn, &out));
- EXPECT_FALSE(GetIntFromJson(big_si, &out));
- EXPECT_FALSE(GetIntFromJson(big_u, &out));
- EXPECT_FALSE(GetIntFromJson(bad_a, &out));
- EXPECT_FALSE(GetIntFromJson(bad_o, &out));
-}
-
-TEST(JsonTest, GetUInt) {
- unsigned int out;
- EXPECT_TRUE(GetUIntFromJson(in_sn, &out));
- EXPECT_EQ(99U, out);
- EXPECT_TRUE(GetUIntFromJson(in_n, &out));
- EXPECT_EQ(12U, out);
- EXPECT_TRUE(GetUIntFromJson(in_u, &out));
- EXPECT_EQ(34U, out);
- EXPECT_TRUE(GetUIntFromJson(in_b, &out));
- EXPECT_EQ(1U, out);
- EXPECT_TRUE(GetUIntFromJson(big_u, &out));
- EXPECT_EQ(0xFFFFFFFFU, out);
- EXPECT_FALSE(GetUIntFromJson(in_s, &out));
- // TODO: Fail reading negative strings.
- // EXPECT_FALSE(GetUIntFromJson(in_si, &out));
- EXPECT_FALSE(GetUIntFromJson(in_i, &out));
- EXPECT_FALSE(GetUIntFromJson(big_sn, &out));
- EXPECT_FALSE(GetUIntFromJson(big_si, &out));
- EXPECT_FALSE(GetUIntFromJson(bad_a, &out));
- EXPECT_FALSE(GetUIntFromJson(bad_o, &out));
-}
-
-TEST(JsonTest, GetBool) {
- bool out;
- EXPECT_TRUE(GetBoolFromJson(in_sb, &out));
- EXPECT_EQ(true, out);
- EXPECT_TRUE(GetBoolFromJson(in_n, &out));
- EXPECT_EQ(true, out);
- EXPECT_TRUE(GetBoolFromJson(in_i, &out));
- EXPECT_EQ(true, out);
- EXPECT_TRUE(GetBoolFromJson(in_u, &out));
- EXPECT_EQ(true, out);
- EXPECT_TRUE(GetBoolFromJson(in_b, &out));
- EXPECT_EQ(true, out);
- EXPECT_TRUE(GetBoolFromJson(big_u, &out));
- EXPECT_EQ(true, out);
- EXPECT_FALSE(GetBoolFromJson(in_s, &out));
- EXPECT_FALSE(GetBoolFromJson(in_sn, &out));
- EXPECT_FALSE(GetBoolFromJson(in_si, &out));
- EXPECT_FALSE(GetBoolFromJson(big_sn, &out));
- EXPECT_FALSE(GetBoolFromJson(big_si, &out));
- EXPECT_FALSE(GetBoolFromJson(bad_a, &out));
- EXPECT_FALSE(GetBoolFromJson(bad_o, &out));
-}
-
-TEST(JsonTest, GetDouble) {
- double out;
- EXPECT_TRUE(GetDoubleFromJson(in_sn, &out));
- EXPECT_EQ(99, out);
- EXPECT_TRUE(GetDoubleFromJson(in_si, &out));
- EXPECT_EQ(-99, out);
- EXPECT_TRUE(GetDoubleFromJson(in_sd, &out));
- EXPECT_EQ(1.2, out);
- EXPECT_TRUE(GetDoubleFromJson(in_n, &out));
- EXPECT_EQ(12, out);
- EXPECT_TRUE(GetDoubleFromJson(in_i, &out));
- EXPECT_EQ(-12, out);
- EXPECT_TRUE(GetDoubleFromJson(in_u, &out));
- EXPECT_EQ(34, out);
- EXPECT_TRUE(GetDoubleFromJson(in_b, &out));
- EXPECT_EQ(1, out);
- EXPECT_TRUE(GetDoubleFromJson(in_d, &out));
- EXPECT_EQ(1.2, out);
- EXPECT_FALSE(GetDoubleFromJson(in_s, &out));
-}
-
-TEST(JsonTest, GetFromArray) {
- Json::Value a, out;
- a.append(in_s);
- a.append(in_i);
- a.append(in_u);
- a.append(in_b);
- EXPECT_TRUE(GetValueFromJsonArray(a, 0, &out));
- EXPECT_TRUE(GetValueFromJsonArray(a, 3, &out));
- EXPECT_FALSE(GetValueFromJsonArray(a, 99, &out));
- EXPECT_FALSE(GetValueFromJsonArray(a, 0xFFFFFFFF, &out));
-}
-
-TEST(JsonTest, GetFromObject) {
- Json::Value o, out;
- o["string"] = in_s;
- o["int"] = in_i;
- o["uint"] = in_u;
- o["bool"] = in_b;
- EXPECT_TRUE(GetValueFromJsonObject(o, "int", &out));
- EXPECT_TRUE(GetValueFromJsonObject(o, "bool", &out));
- EXPECT_FALSE(GetValueFromJsonObject(o, "foo", &out));
- EXPECT_FALSE(GetValueFromJsonObject(o, "", &out));
-}
-
-namespace {
-template <typename T>
-std::vector<T> VecOf3(const T& a, const T& b, const T& c) {
- std::vector<T> in;
- in.push_back(a);
- in.push_back(b);
- in.push_back(c);
- return in;
-}
-template <typename T>
-Json::Value JsonVecOf3(const T& a, const T& b, const T& c) {
- Json::Value in(Json::arrayValue);
- in.append(a);
- in.append(b);
- in.append(c);
- return in;
-}
-} // unnamed namespace
-
-TEST(JsonTest, ValueVectorToFromArray) {
- std::vector<Json::Value> in = VecOf3<Json::Value>("a", "b", "c");
- Json::Value out = ValueVectorToJsonArray(in);
- EXPECT_EQ(in.size(), out.size());
- for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
- EXPECT_EQ(in[i].asString(), out[i].asString());
- }
- Json::Value inj = JsonVecOf3<Json::Value>("a", "b", "c");
- EXPECT_EQ(inj, out);
- std::vector<Json::Value> outj;
- EXPECT_TRUE(JsonArrayToValueVector(inj, &outj));
- for (Json::Value::ArrayIndex i = 0; i < in.size(); i++) {
- EXPECT_EQ(in[i], outj[i]);
- }
-}
-
-TEST(JsonTest, IntVectorToFromArray) {
- std::vector<int> in = VecOf3<int>(1, 2, 3);
- Json::Value out = IntVectorToJsonArray(in);
- EXPECT_EQ(in.size(), out.size());
- for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
- EXPECT_EQ(in[i], out[i].asInt());
- }
- Json::Value inj = JsonVecOf3<int>(1, 2, 3);
- EXPECT_EQ(inj, out);
- std::vector<int> outj;
- EXPECT_TRUE(JsonArrayToIntVector(inj, &outj));
- for (Json::Value::ArrayIndex i = 0; i < in.size(); i++) {
- EXPECT_EQ(in[i], outj[i]);
- }
-}
-
-TEST(JsonTest, UIntVectorToFromArray) {
- std::vector<unsigned int> in = VecOf3<unsigned int>(1, 2, 3);
- Json::Value out = UIntVectorToJsonArray(in);
- EXPECT_EQ(in.size(), out.size());
- for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
- EXPECT_EQ(in[i], out[i].asUInt());
- }
- Json::Value inj = JsonVecOf3<unsigned int>(1, 2, 3);
- EXPECT_EQ(inj, out);
- std::vector<unsigned int> outj;
- EXPECT_TRUE(JsonArrayToUIntVector(inj, &outj));
- for (Json::Value::ArrayIndex i = 0; i < in.size(); i++) {
- EXPECT_EQ(in[i], outj[i]);
- }
-}
-
-TEST(JsonTest, StringVectorToFromArray) {
- std::vector<std::string> in = VecOf3<std::string>("a", "b", "c");
- Json::Value out = StringVectorToJsonArray(in);
- EXPECT_EQ(in.size(), out.size());
- for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
- EXPECT_EQ(in[i], out[i].asString());
- }
- Json::Value inj = JsonVecOf3<std::string>("a", "b", "c");
- EXPECT_EQ(inj, out);
- std::vector<std::string> outj;
- EXPECT_TRUE(JsonArrayToStringVector(inj, &outj));
- for (Json::Value::ArrayIndex i = 0; i < in.size(); i++) {
- EXPECT_EQ(in[i], outj[i]);
- }
-}
-
-TEST(JsonTest, BoolVectorToFromArray) {
- std::vector<bool> in = VecOf3<bool>(false, true, false);
- Json::Value out = BoolVectorToJsonArray(in);
- EXPECT_EQ(in.size(), out.size());
- for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
- EXPECT_EQ(in[i], out[i].asBool());
- }
- Json::Value inj = JsonVecOf3<bool>(false, true, false);
- EXPECT_EQ(inj, out);
- std::vector<bool> outj;
- EXPECT_TRUE(JsonArrayToBoolVector(inj, &outj));
- for (Json::Value::ArrayIndex i = 0; i < in.size(); i++) {
- EXPECT_EQ(in[i], outj[i]);
- }
-}
-
-TEST(JsonTest, DoubleVectorToFromArray) {
- std::vector<double> in = VecOf3<double>(1.0, 2.0, 3.0);
- Json::Value out = DoubleVectorToJsonArray(in);
- EXPECT_EQ(in.size(), out.size());
- for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
- EXPECT_EQ(in[i], out[i].asDouble());
- }
- Json::Value inj = JsonVecOf3<double>(1.0, 2.0, 3.0);
- EXPECT_EQ(inj, out);
- std::vector<double> outj;
- EXPECT_TRUE(JsonArrayToDoubleVector(inj, &outj));
- for (Json::Value::ArrayIndex i = 0; i < in.size(); i++) {
- EXPECT_EQ(in[i], outj[i]);
- }
-}
diff --git a/base/latebindingsymboltable.cc b/base/latebindingsymboltable.cc
deleted file mode 100644
index 433844e..0000000
--- a/base/latebindingsymboltable.cc
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/latebindingsymboltable.h"
-
-#ifdef POSIX
-#include <dlfcn.h>
-#endif
-
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-#ifdef POSIX
-static const DllHandle kInvalidDllHandle = NULL;
-#else
-#error Not implemented
-#endif
-
-static const char *GetDllError() {
-#ifdef POSIX
- const char *err = dlerror();
- if (err) {
- return err;
- } else {
- return "No error";
- }
-#else
-#error Not implemented
-#endif
-}
-
-static bool LoadSymbol(DllHandle handle,
- const char *symbol_name,
- void **symbol) {
-#ifdef POSIX
- *symbol = dlsym(handle, symbol_name);
- const char *err = dlerror();
- if (err) {
- LOG(LS_ERROR) << "Error loading symbol " << symbol_name << ": " << err;
- return false;
- } else if (!*symbol) {
- // ELF allows for symbols to be NULL, but that should never happen for our
- // usage.
- LOG(LS_ERROR) << "Symbol " << symbol_name << " is NULL";
- return false;
- }
- return true;
-#else
-#error Not implemented
-#endif
-}
-
-LateBindingSymbolTable::LateBindingSymbolTable(const TableInfo *info,
- void **table)
- : info_(info),
- table_(table),
- handle_(kInvalidDllHandle),
- undefined_symbols_(false) {
- ClearSymbols();
-}
-
-LateBindingSymbolTable::~LateBindingSymbolTable() {
- Unload();
-}
-
-bool LateBindingSymbolTable::IsLoaded() const {
- return handle_ != kInvalidDllHandle;
-}
-
-bool LateBindingSymbolTable::Load() {
- ASSERT(info_->dll_name != NULL);
- return LoadFromPath(info_->dll_name);
-}
-
-bool LateBindingSymbolTable::LoadFromPath(const char *dll_path) {
- if (IsLoaded()) {
- return true;
- }
- if (undefined_symbols_) {
- // We do not attempt to load again because repeated attempts are not
- // likely to succeed and DLL loading is costly.
- LOG(LS_ERROR) << "We know there are undefined symbols";
- return false;
- }
-
-#ifdef POSIX
- handle_ = dlopen(dll_path,
- // RTLD_NOW front-loads symbol resolution so that errors are
- // caught early instead of causing a process abort later.
- // RTLD_LOCAL prevents other modules from automatically
- // seeing symbol definitions in the newly-loaded tree. This
- // is necessary for same-named symbols in different ABI
- // versions of the same library to not explode.
- RTLD_NOW|RTLD_LOCAL
-#ifdef LINUX
- // RTLD_DEEPBIND makes symbol dependencies in the
- // newly-loaded tree prefer to resolve to definitions within
- // that tree (the default on OS X). This is necessary for
- // same-named symbols in different ABI versions of the same
- // library to not explode.
- |RTLD_DEEPBIND
-#endif
- ); // NOLINT
-#else
-#error Not implemented
-#endif
-
- if (handle_ == kInvalidDllHandle) {
- LOG(LS_WARNING) << "Can't load " << dll_path << ": "
- << GetDllError();
- return false;
- }
-#ifdef POSIX
- // Clear any old errors.
- dlerror();
-#endif
- for (int i = 0; i < info_->num_symbols; ++i) {
- if (!LoadSymbol(handle_, info_->symbol_names[i], &table_[i])) {
- undefined_symbols_ = true;
- Unload();
- return false;
- }
- }
- return true;
-}
-
-void LateBindingSymbolTable::Unload() {
- if (!IsLoaded()) {
- return;
- }
-
-#ifdef POSIX
- if (dlclose(handle_) != 0) {
- LOG(LS_ERROR) << GetDllError();
- }
-#else
-#error Not implemented
-#endif
-
- handle_ = kInvalidDllHandle;
- ClearSymbols();
-}
-
-void LateBindingSymbolTable::ClearSymbols() {
- memset(table_, 0, sizeof(void *) * info_->num_symbols);
-}
-
-} // namespace talk_base
diff --git a/base/latebindingsymboltable.cc.def b/base/latebindingsymboltable.cc.def
deleted file mode 100644
index 64fc0dc..0000000
--- a/base/latebindingsymboltable.cc.def
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// This file is a supermacro
-// (see http://wanderinghorse.net/computing/papers/supermacros_cpp.html) to
-// expand a definition of a late-binding symbol table class.
-//
-// Arguments:
-// LATE_BINDING_SYMBOL_TABLE_CLASS_NAME: Name of the class to generate.
-// LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST: List of symbols to load from the DLL,
-// as an X-Macro list (see http://www.drdobbs.com/blogs/cpp/228700289).
-// LATE_BINDING_SYMBOL_TABLE_DLL_NAME: String literal for the DLL file name to
-// load.
-//
-// From a .cc file, include the header file containing your call to the .h.def
-// supermacro, and then call this supermacro (optionally from inside the
-// namespace for the class to generate, if any). Example:
-//
-// #include "myclassname.h"
-//
-// namespace foo {
-//
-// #define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME MY_CLASS_NAME
-// #define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST MY_SYMBOLS_LIST
-// #define LATE_BINDING_SYMBOL_TABLE_DLL_NAME "libdll.so.n"
-// #include "talk/base/latebindingsymboltable.cc.def"
-//
-// }
-
-#ifndef LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
-#error You must define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
-#endif
-
-#ifndef LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-#error You must define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-#endif
-
-#ifndef LATE_BINDING_SYMBOL_TABLE_DLL_NAME
-#error You must define LATE_BINDING_SYMBOL_TABLE_DLL_NAME
-#endif
-
-#define X(sym) #sym,
-const char* const LATE_BINDING_SYMBOL_TABLE_CLASS_NAME::kSymbolNames[] = {
- LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-};
-#undef X
-
-const ::talk_base::LateBindingSymbolTable::TableInfo
- LATE_BINDING_SYMBOL_TABLE_CLASS_NAME::kTableInfo = {
- LATE_BINDING_SYMBOL_TABLE_DLL_NAME,
- SYMBOL_TABLE_SIZE,
- LATE_BINDING_SYMBOL_TABLE_CLASS_NAME::kSymbolNames
-};
-
-LATE_BINDING_SYMBOL_TABLE_CLASS_NAME::LATE_BINDING_SYMBOL_TABLE_CLASS_NAME()
- : ::talk_base::LateBindingSymbolTable(&kTableInfo, table_) {}
-
-LATE_BINDING_SYMBOL_TABLE_CLASS_NAME::~LATE_BINDING_SYMBOL_TABLE_CLASS_NAME() {}
-
-#undef LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
-#undef LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-#undef LATE_BINDING_SYMBOL_TABLE_DLL_NAME
diff --git a/base/latebindingsymboltable.h b/base/latebindingsymboltable.h
deleted file mode 100644
index f4ad5a6..0000000
--- a/base/latebindingsymboltable.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_LATEBINDINGSYMBOLTABLE_H_
-#define TALK_BASE_LATEBINDINGSYMBOLTABLE_H_
-
-#include <string.h>
-
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-#ifdef POSIX
-typedef void *DllHandle;
-#else
-#error Not implemented for this platform
-#endif
-
-// This is the base class for "symbol table" classes to simplify the dynamic
-// loading of symbols from DLLs. Currently the implementation only supports
-// Linux and OS X, and pure C symbols (or extern "C" symbols that wrap C++
-// functions). Sub-classes for specific DLLs are generated via the "supermacro"
-// files latebindingsymboltable.h.def and latebindingsymboltable.cc.def. See
-// talk/sound/pulseaudiosymboltable.(h|cc) for an example.
-class LateBindingSymbolTable {
- public:
- struct TableInfo {
- const char *dll_name;
- int num_symbols;
- // Array of size num_symbols.
- const char *const *symbol_names;
- };
-
- LateBindingSymbolTable(const TableInfo *info, void **table);
- ~LateBindingSymbolTable();
-
- bool IsLoaded() const;
- // Loads the DLL and the symbol table. Returns true iff the DLL and symbol
- // table loaded successfully.
- bool Load();
- // Like load, but allows overriding the dll path for when the dll path is
- // dynamic.
- bool LoadFromPath(const char *dll_path);
- void Unload();
-
- // Gets the raw OS handle to the DLL. Be careful what you do with it.
- DllHandle GetDllHandle() const { return handle_; }
-
- private:
- void ClearSymbols();
-
- const TableInfo *info_;
- void **table_;
- DllHandle handle_;
- bool undefined_symbols_;
-
- DISALLOW_COPY_AND_ASSIGN(LateBindingSymbolTable);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_LATEBINDINGSYMBOLTABLE_H_
diff --git a/base/latebindingsymboltable.h.def b/base/latebindingsymboltable.h.def
deleted file mode 100644
index 3e1cdab..0000000
--- a/base/latebindingsymboltable.h.def
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// This file is a supermacro
-// (see http://wanderinghorse.net/computing/papers/supermacros_cpp.html) to
-// expand a declaration of a late-binding symbol table class.
-//
-// Arguments:
-// LATE_BINDING_SYMBOL_TABLE_CLASS_NAME: Name of the class to generate.
-// LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST: List of symbols to load from the DLL,
-// as an X-Macro list (see http://www.drdobbs.com/blogs/cpp/228700289).
-//
-// From a .h file, include the header(s) for the DLL to late-bind and the
-// latebindingsymboltable.h header, and then call this supermacro (optionally
-// from inside the namespace for the class to generate, if any). Example:
-//
-// #include <headerfordll.h>
-//
-// #include "talk/base/latebindingsymboltable.h"
-//
-// namespace foo {
-//
-// #define MY_CLASS_NAME DesiredClassName
-// #define MY_SYMBOLS_LIST X(acos) X(sin) X(tan)
-//
-// #define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME MY_CLASS_NAME
-// #define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST MY_SYMBOLS_LIST
-// #include "talk/base/latebindingsymboltable.h.def"
-//
-// }
-
-#ifndef TALK_BASE_LATEBINDINGSYMBOLTABLE_H_
-#error You must first include latebindingsymboltable.h
-#endif
-
-#ifndef LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
-#error You must define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
-#endif
-
-#ifndef LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-#error You must define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-#endif
-
-class LATE_BINDING_SYMBOL_TABLE_CLASS_NAME :
- public ::talk_base::LateBindingSymbolTable {
- public:
- LATE_BINDING_SYMBOL_TABLE_CLASS_NAME();
- ~LATE_BINDING_SYMBOL_TABLE_CLASS_NAME();
-
-#define X(sym) \
- typeof(&::sym) sym() const { \
- ASSERT(::talk_base::LateBindingSymbolTable::IsLoaded()); \
- return reinterpret_cast<typeof(&::sym)>(table_[SYMBOL_TABLE_INDEX_##sym]); \
- }
-LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-#undef X
-
- private:
- enum {
-#define X(sym) \
- SYMBOL_TABLE_INDEX_##sym,
-LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
-#undef X
- SYMBOL_TABLE_SIZE
- };
-
- static const ::talk_base::LateBindingSymbolTable::TableInfo kTableInfo;
- static const char *const kSymbolNames[];
-
- void *table_[SYMBOL_TABLE_SIZE];
-
- DISALLOW_COPY_AND_ASSIGN(LATE_BINDING_SYMBOL_TABLE_CLASS_NAME);
-};
-
-#undef LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
-#undef LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
diff --git a/base/latebindingsymboltable_unittest.cc b/base/latebindingsymboltable_unittest.cc
deleted file mode 100644
index 58afdcd..0000000
--- a/base/latebindingsymboltable_unittest.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef LINUX
-#include <math.h>
-#endif
-
-#include "talk/base/gunit.h"
-#include "talk/base/latebindingsymboltable.h"
-
-namespace talk_base {
-
-#ifdef LINUX
-
-#define LIBM_SYMBOLS_CLASS_NAME LibmTestSymbolTable
-#define LIBM_SYMBOLS_LIST \
- X(acos) \
- X(sin) \
- X(tan)
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME LIBM_SYMBOLS_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST LIBM_SYMBOLS_LIST
-#include "talk/base/latebindingsymboltable.h.def"
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME LIBM_SYMBOLS_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST LIBM_SYMBOLS_LIST
-#define LATE_BINDING_SYMBOL_TABLE_DLL_NAME "libm.so.6"
-#include "talk/base/latebindingsymboltable.cc.def"
-
-TEST(LateBindingSymbolTable, libm) {
- LibmTestSymbolTable table;
- EXPECT_FALSE(table.IsLoaded());
- ASSERT_TRUE(table.Load());
- EXPECT_TRUE(table.IsLoaded());
- EXPECT_EQ(table.acos()(0.5), acos(0.5));
- EXPECT_EQ(table.sin()(0.5), sin(0.5));
- EXPECT_EQ(table.tan()(0.5), tan(0.5));
- // It would be nice to check that the addresses are the same, but the nature
- // of dynamic linking and relocation makes them actually be different.
- table.Unload();
- EXPECT_FALSE(table.IsLoaded());
-}
-
-#else
-#error Not implemented
-#endif
-
-} // namespace talk_base
diff --git a/base/libdbusglibsymboltable.cc b/base/libdbusglibsymboltable.cc
deleted file mode 100644
index 6a3ebf3..0000000
--- a/base/libdbusglibsymboltable.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_DBUS_GLIB
-
-#include "talk/base/libdbusglibsymboltable.h"
-
-namespace talk_base {
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME LIBDBUS_GLIB_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST LIBDBUS_GLIB_SYMBOLS_LIST
-#define LATE_BINDING_SYMBOL_TABLE_DLL_NAME "libdbus-glib-1.so.2"
-#include "talk/base/latebindingsymboltable.cc.def"
-
-} // namespace talk_base
-
-#endif // HAVE_DBUS_GLIB
diff --git a/base/libdbusglibsymboltable.h b/base/libdbusglibsymboltable.h
deleted file mode 100644
index 8dc140f..0000000
--- a/base/libdbusglibsymboltable.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_LIBDBUSGLIBSYMBOLTABLE_H_
-#define TALK_BASE_LIBDBUSGLIBSYMBOLTABLE_H_
-
-#ifdef HAVE_DBUS_GLIB
-
-#include <dbus/dbus-glib.h>
-#include <dbus/dbus-glib-lowlevel.h>
-
-#include "talk/base/latebindingsymboltable.h"
-
-namespace talk_base {
-
-#define LIBDBUS_GLIB_CLASS_NAME LibDBusGlibSymbolTable
-// The libdbus-glib symbols we need, as an X-Macro list.
-// This list must contain precisely every libdbus-glib function that is used in
-// dbus.cc.
-#define LIBDBUS_GLIB_SYMBOLS_LIST \
- X(dbus_bus_add_match) \
- X(dbus_connection_add_filter) \
- X(dbus_connection_close) \
- X(dbus_connection_remove_filter) \
- X(dbus_connection_set_exit_on_disconnect) \
- X(dbus_g_bus_get) \
- X(dbus_g_bus_get_private) \
- X(dbus_g_connection_get_connection) \
- X(dbus_g_connection_unref) \
- X(dbus_g_thread_init) \
- X(dbus_message_get_interface) \
- X(dbus_message_get_member) \
- X(dbus_message_get_path) \
- X(dbus_message_get_type) \
- X(dbus_message_iter_get_arg_type) \
- X(dbus_message_iter_get_basic) \
- X(dbus_message_iter_init) \
- X(dbus_message_ref) \
- X(dbus_message_unref)
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME LIBDBUS_GLIB_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST LIBDBUS_GLIB_SYMBOLS_LIST
-#include "talk/base/latebindingsymboltable.h.def"
-
-} // namespace talk_base
-
-#endif // HAVE_DBUS_GLIB
-
-#endif // TALK_BASE_LIBDBUSGLIBSYMBOLTABLE_H_
diff --git a/base/linked_ptr.h b/base/linked_ptr.h
deleted file mode 100644
index a98a367..0000000
--- a/base/linked_ptr.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * linked_ptr - simple reference linked pointer
- * (like reference counting, just using a linked list of the references
- * instead of their count.)
- *
- * The implementation stores three pointers for every linked_ptr, but
- * does not allocate anything on the free store.
- */
-
-#ifndef TALK_BASE_LINKED_PTR_H__
-#define TALK_BASE_LINKED_PTR_H__
-
-namespace talk_base {
-
-/* For ANSI-challenged compilers, you may want to #define
- * NO_MEMBER_TEMPLATES, explicit or mutable */
-#define NO_MEMBER_TEMPLATES
-
-template <class X> class linked_ptr
-{
-public:
-
-#ifndef NO_MEMBER_TEMPLATES
-# define TEMPLATE_FUNCTION template <class Y>
- TEMPLATE_FUNCTION friend class linked_ptr<Y>;
-#else
-# define TEMPLATE_FUNCTION
- typedef X Y;
-#endif
-
- typedef X element_type;
-
- explicit linked_ptr(X* p = 0) throw()
- : itsPtr(p) {itsPrev = itsNext = this;}
- ~linked_ptr()
- {release();}
- linked_ptr(const linked_ptr& r) throw()
- {acquire(r);}
- linked_ptr& operator=(const linked_ptr& r)
- {
- if (this != &r) {
- release();
- acquire(r);
- }
- return *this;
- }
-
-#ifndef NO_MEMBER_TEMPLATES
- template <class Y> friend class linked_ptr<Y>;
- template <class Y> linked_ptr(const linked_ptr<Y>& r) throw()
- {acquire(r);}
- template <class Y> linked_ptr& operator=(const linked_ptr<Y>& r)
- {
- if (this != &r) {
- release();
- acquire(r);
- }
- return *this;
- }
-#endif // NO_MEMBER_TEMPLATES
-
- X& operator*() const throw() {return *itsPtr;}
- X* operator->() const throw() {return itsPtr;}
- X* get() const throw() {return itsPtr;}
- bool unique() const throw() {return itsPrev ? itsPrev==this : true;}
-
-private:
- X* itsPtr;
- mutable const linked_ptr* itsPrev;
- mutable const linked_ptr* itsNext;
-
- void acquire(const linked_ptr& r) throw()
- { // insert this to the list
- itsPtr = r.itsPtr;
- itsNext = r.itsNext;
- itsNext->itsPrev = this;
- itsPrev = &r;
-#ifndef mutable
- r.itsNext = this;
-#else // for ANSI-challenged compilers
- (const_cast<linked_ptr<X>*>(&r))->itsNext = this;
-#endif
- }
-
-#ifndef NO_MEMBER_TEMPLATES
- template <class Y> void acquire(const linked_ptr<Y>& r) throw()
- { // insert this to the list
- itsPtr = r.itsPtr;
- itsNext = r.itsNext;
- itsNext->itsPrev = this;
- itsPrev = &r;
-#ifndef mutable
- r.itsNext = this;
-#else // for ANSI-challenged compilers
- (const_cast<linked_ptr<X>*>(&r))->itsNext = this;
-#endif
- }
-#endif // NO_MEMBER_TEMPLATES
-
- void release()
- { // erase this from the list, delete if unique
- if (unique()) delete itsPtr;
- else {
- itsPrev->itsNext = itsNext;
- itsNext->itsPrev = itsPrev;
- itsPrev = itsNext = 0;
- }
- itsPtr = 0;
- }
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_LINKED_PTR_H__
-
diff --git a/base/linux.cc b/base/linux.cc
deleted file mode 100644
index 16666f8..0000000
--- a/base/linux.cc
+++ /dev/null
@@ -1,365 +0,0 @@
-/*
- * libjingle
- * Copyright 2008 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if defined(LINUX) || defined(ANDROID)
-#include "talk/base/linux.h"
-
-#include <ctype.h>
-
-#include <errno.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-
-#include <cstdio>
-#include <set>
-
-#include "talk/base/stringencode.h"
-
-namespace talk_base {
-
-static const char kCpuInfoFile[] = "/proc/cpuinfo";
-static const char kCpuMaxFreqFile[] =
- "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
-
-ProcCpuInfo::ProcCpuInfo() {
-}
-
-ProcCpuInfo::~ProcCpuInfo() {
-}
-
-bool ProcCpuInfo::LoadFromSystem() {
- ConfigParser procfs;
- if (!procfs.Open(kCpuInfoFile)) {
- return false;
- }
- return procfs.Parse(§ions_);
-};
-
-bool ProcCpuInfo::GetSectionCount(size_t* count) {
- if (sections_.empty()) {
- return false;
- }
- if (count) {
- *count = sections_.size();
- }
- return true;
-}
-
-bool ProcCpuInfo::GetNumCpus(int* num) {
- if (sections_.empty()) {
- return false;
- }
- int total_cpus = 0;
-#if defined(__arm__)
- // Count the number of blocks that have a "processor" key defined. On ARM,
- // there may be extra blocks of information that aren't per-processor.
- size_t section_count = sections_.size();
- for (size_t i = 0; i < section_count; ++i) {
- int processor_id;
- if (GetSectionIntValue(i, "processor", &processor_id)) {
- ++total_cpus;
- }
- }
- // Single core ARM systems don't include "processor" keys at all, so return
- // that we have a single core if we didn't find any explicitly above.
- if (total_cpus == 0) {
- total_cpus = 1;
- }
-#else
- // On X86, there is exactly one info section per processor.
- total_cpus = static_cast<int>(sections_.size());
-#endif
- if (num) {
- *num = total_cpus;
- }
- return true;
-}
-
-bool ProcCpuInfo::GetNumPhysicalCpus(int* num) {
- if (sections_.empty()) {
- return false;
- }
- // TODO: /proc/cpuinfo only reports cores that are currently
- // _online_, so this may underreport the number of physical cores.
-#if defined(__arm__)
- // ARM (currently) has no hyperthreading, so just return the same value
- // as GetNumCpus.
- return GetNumCpus(num);
-#else
- int total_cores = 0;
- std::set<int> physical_ids;
- size_t section_count = sections_.size();
- for (size_t i = 0; i < section_count; ++i) {
- int physical_id;
- int cores;
- // Count the cores for the physical id only if we have not counted the id.
- if (GetSectionIntValue(i, "physical id", &physical_id) &&
- GetSectionIntValue(i, "cpu cores", &cores) &&
- physical_ids.find(physical_id) == physical_ids.end()) {
- physical_ids.insert(physical_id);
- total_cores += cores;
- }
- }
-
- if (num) {
- *num = total_cores;
- }
- return true;
-#endif
-}
-
-bool ProcCpuInfo::GetCpuFamily(int* id) {
- int cpu_family = 0;
-
-#if defined(__arm__)
- // On some ARM platforms, there is no 'cpu family' in '/proc/cpuinfo'. But
- // there is 'CPU Architecture' which can be used as 'cpu family'.
- // See http://en.wikipedia.org/wiki/ARM_architecture for a good list of
- // ARM cpu families, architectures, and their mappings.
- // There may be multiple sessions that aren't per-processor. We need to scan
- // through each session until we find the first 'CPU architecture'.
- size_t section_count = sections_.size();
- for (size_t i = 0; i < section_count; ++i) {
- if (GetSectionIntValue(i, "CPU architecture", &cpu_family)) {
- // We returns the first one (if there are multiple entries).
- break;
- };
- }
-#else
- GetSectionIntValue(0, "cpu family", &cpu_family);
-#endif
- if (id) {
- *id = cpu_family;
- }
- return true;
-}
-
-bool ProcCpuInfo::GetSectionStringValue(size_t section_num,
- const std::string& key,
- std::string* result) {
- if (section_num >= sections_.size()) {
- return false;
- }
- ConfigParser::SimpleMap::iterator iter = sections_[section_num].find(key);
- if (iter == sections_[section_num].end()) {
- return false;
- }
- *result = iter->second;
- return true;
-}
-
-bool ProcCpuInfo::GetSectionIntValue(size_t section_num,
- const std::string& key,
- int* result) {
- if (section_num >= sections_.size()) {
- return false;
- }
- ConfigParser::SimpleMap::iterator iter = sections_[section_num].find(key);
- if (iter == sections_[section_num].end()) {
- return false;
- }
- return FromString(iter->second, result);
-}
-
-ConfigParser::ConfigParser() {}
-
-ConfigParser::~ConfigParser() {}
-
-bool ConfigParser::Open(const std::string& filename) {
- FileStream* fs = new FileStream();
- if (!fs->Open(filename, "r", NULL)) {
- return false;
- }
- instream_.reset(fs);
- return true;
-}
-
-void ConfigParser::Attach(StreamInterface* stream) {
- instream_.reset(stream);
-}
-
-bool ConfigParser::Parse(MapVector* key_val_pairs) {
- // Parses the file and places the found key-value pairs into key_val_pairs.
- SimpleMap section;
- while (ParseSection(§ion)) {
- key_val_pairs->push_back(section);
- section.clear();
- }
- return (!key_val_pairs->empty());
-}
-
-bool ConfigParser::ParseSection(SimpleMap* key_val_pair) {
- // Parses the next section in the filestream and places the found key-value
- // pairs into key_val_pair.
- std::string key, value;
- while (ParseLine(&key, &value)) {
- (*key_val_pair)[key] = value;
- }
- return (!key_val_pair->empty());
-}
-
-bool ConfigParser::ParseLine(std::string* key, std::string* value) {
- // Parses the next line in the filestream and places the found key-value
- // pair into key and val.
- std::string line;
- if ((instream_->ReadLine(&line)) == SR_EOS) {
- return false;
- }
- std::vector<std::string> tokens;
- if (2 != split(line, ':', &tokens)) {
- return false;
- }
- // Removes whitespace at the end of Key name
- size_t pos = tokens[0].length() - 1;
- while ((pos > 0) && isspace(tokens[0][pos])) {
- pos--;
- }
- tokens[0].erase(pos + 1);
- // Removes whitespace at the start of value
- pos = 0;
- while (pos < tokens[1].length() && isspace(tokens[1][pos])) {
- pos++;
- }
- tokens[1].erase(0, pos);
- *key = tokens[0];
- *value = tokens[1];
- return true;
-}
-
-#if !defined(GOOGLE_CHROME_BUILD) && !defined(CHROMIUM_BUILD)
-static bool ExpectLineFromStream(FileStream* stream,
- std::string* out) {
- StreamResult res = stream->ReadLine(out);
- if (res != SR_SUCCESS) {
- if (res != SR_EOS) {
- LOG(LS_ERROR) << "Error when reading from stream";
- } else {
- LOG(LS_ERROR) << "Incorrect number of lines in stream";
- }
- return false;
- }
- return true;
-}
-
-static void ExpectEofFromStream(FileStream* stream) {
- std::string unused;
- StreamResult res = stream->ReadLine(&unused);
- if (res == SR_SUCCESS) {
- LOG(LS_WARNING) << "Ignoring unexpected extra lines from stream";
- } else if (res != SR_EOS) {
- LOG(LS_WARNING) << "Error when checking for extra lines from stream";
- }
-}
-
-// For caching the lsb_release output (reading it invokes a sub-process and
-// hence is somewhat expensive).
-static std::string lsb_release_string;
-static CriticalSection lsb_release_string_critsec;
-
-std::string ReadLinuxLsbRelease() {
- CritScope cs(&lsb_release_string_critsec);
- if (!lsb_release_string.empty()) {
- // Have cached result from previous call.
- return lsb_release_string;
- }
- // No cached result. Run lsb_release and parse output.
- POpenStream lsb_release_output;
- if (!lsb_release_output.Open("lsb_release -idrcs", "r", NULL)) {
- LOG_ERR(LS_ERROR) << "Can't run lsb_release";
- return lsb_release_string; // empty
- }
- // Read in the command's output and build the string.
- std::ostringstream sstr;
- std::string line;
- int wait_status;
-
- if (!ExpectLineFromStream(&lsb_release_output, &line)) {
- return lsb_release_string; // empty
- }
- sstr << "DISTRIB_ID=" << line;
-
- if (!ExpectLineFromStream(&lsb_release_output, &line)) {
- return lsb_release_string; // empty
- }
- sstr << " DISTRIB_DESCRIPTION=\"" << line << '"';
-
- if (!ExpectLineFromStream(&lsb_release_output, &line)) {
- return lsb_release_string; // empty
- }
- sstr << " DISTRIB_RELEASE=" << line;
-
- if (!ExpectLineFromStream(&lsb_release_output, &line)) {
- return lsb_release_string; // empty
- }
- sstr << " DISTRIB_CODENAME=" << line;
-
- // Should not be anything left.
- ExpectEofFromStream(&lsb_release_output);
-
- lsb_release_output.Close();
- wait_status = lsb_release_output.GetWaitStatus();
- if (wait_status == -1 ||
- !WIFEXITED(wait_status) ||
- WEXITSTATUS(wait_status) != 0) {
- LOG(LS_WARNING) << "Unexpected exit status from lsb_release";
- }
-
- lsb_release_string = sstr.str();
-
- return lsb_release_string;
-}
-#endif
-
-std::string ReadLinuxUname() {
- struct utsname buf;
- if (uname(&buf) < 0) {
- LOG_ERR(LS_ERROR) << "Can't call uname()";
- return std::string();
- }
- std::ostringstream sstr;
- sstr << buf.sysname << " "
- << buf.release << " "
- << buf.version << " "
- << buf.machine;
- return sstr.str();
-}
-
-int ReadCpuMaxFreq() {
- FileStream fs;
- std::string str;
- int freq = -1;
- if (!fs.Open(kCpuMaxFreqFile, "r", NULL) ||
- SR_SUCCESS != fs.ReadLine(&str) ||
- !FromString(str, &freq)) {
- return -1;
- }
- return freq;
-}
-
-} // namespace talk_base
-
-#endif // defined(LINUX) || defined(ANDROID)
diff --git a/base/linux.h b/base/linux.h
deleted file mode 100644
index 46fa5ed..0000000
--- a/base/linux.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_LINUX_H_
-#define TALK_BASE_LINUX_H_
-
-#if defined(LINUX) || defined(ANDROID)
-#include <string>
-#include <map>
-#include <vector>
-
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////////////
-// ConfigParser parses a FileStream of an ".ini."-type format into a map.
-//////////////////////////////////////////////////////////////////////////////
-
-// Sample Usage:
-// ConfigParser parser;
-// ConfigParser::MapVector key_val_pairs;
-// if (parser.Open(inifile) && parser.Parse(&key_val_pairs)) {
-// for (int section_num=0; i < key_val_pairs.size(); ++section_num) {
-// std::string val1 = key_val_pairs[section_num][key1];
-// std::string val2 = key_val_pairs[section_num][key2];
-// // Do something with valn;
-// }
-// }
-
-class ConfigParser {
- public:
- typedef std::map<std::string, std::string> SimpleMap;
- typedef std::vector<SimpleMap> MapVector;
-
- ConfigParser();
- virtual ~ConfigParser();
-
- virtual bool Open(const std::string& filename);
- virtual void Attach(StreamInterface* stream);
- virtual bool Parse(MapVector* key_val_pairs);
- virtual bool ParseSection(SimpleMap* key_val_pair);
- virtual bool ParseLine(std::string* key, std::string* value);
-
- private:
- scoped_ptr<StreamInterface> instream_;
-};
-
-//////////////////////////////////////////////////////////////////////////////
-// ProcCpuInfo reads CPU info from the /proc subsystem on any *NIX platform.
-//////////////////////////////////////////////////////////////////////////////
-
-// Sample Usage:
-// ProcCpuInfo proc_info;
-// int no_of_cpu;
-// if (proc_info.LoadFromSystem()) {
-// std::string out_str;
-// proc_info.GetNumCpus(&no_of_cpu);
-// proc_info.GetCpuStringValue(0, "vendor_id", &out_str);
-// }
-// }
-
-class ProcCpuInfo {
- public:
- ProcCpuInfo();
- virtual ~ProcCpuInfo();
-
- // Reads the proc subsystem's cpu info into memory. If this fails, this
- // returns false; if it succeeds, it returns true.
- virtual bool LoadFromSystem();
-
- // Obtains the number of logical CPU threads and places the value num.
- virtual bool GetNumCpus(int* num);
-
- // Obtains the number of physical CPU cores and places the value num.
- virtual bool GetNumPhysicalCpus(int* num);
-
- // Obtains the CPU family id.
- virtual bool GetCpuFamily(int* id);
-
- // Obtains the number of sections in /proc/cpuinfo, which may be greater
- // than the number of CPUs (e.g. on ARM)
- virtual bool GetSectionCount(size_t* count);
-
- // Looks for the CPU proc item with the given name for the given section
- // number and places the string value in result.
- virtual bool GetSectionStringValue(size_t section_num, const std::string& key,
- std::string* result);
-
- // Looks for the CPU proc item with the given name for the given section
- // number and places the int value in result.
- virtual bool GetSectionIntValue(size_t section_num, const std::string& key,
- int* result);
-
- private:
- ConfigParser::MapVector sections_;
-};
-
-#if !defined(GOOGLE_CHROME_BUILD) && !defined(CHROMIUM_BUILD)
-// Builds a string containing the info from lsb_release on a single line.
-std::string ReadLinuxLsbRelease();
-#endif
-
-// Returns the output of "uname".
-std::string ReadLinuxUname();
-
-// Returns the content (int) of
-// /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq
-// Returns -1 on error.
-int ReadCpuMaxFreq();
-
-} // namespace talk_base
-
-#endif // defined(LINUX) || defined(ANDROID)
-#endif // TALK_BASE_LINUX_H_
diff --git a/base/linux_unittest.cc b/base/linux_unittest.cc
deleted file mode 100644
index f681514..0000000
--- a/base/linux_unittest.cc
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdio.h>
-#include "talk/base/linux.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/logging.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-// These tests running on ARM are fairly specific to the output of the tegra2
-// ARM processor, and so may fail on other ARM-based systems.
-TEST(ProcCpuInfo, GetProcInfo) {
- ProcCpuInfo proc_info;
- EXPECT_TRUE(proc_info.LoadFromSystem());
-
- int out_cpus = 0;
- EXPECT_TRUE(proc_info.GetNumCpus(&out_cpus));
- LOG(LS_INFO) << "GetNumCpus: " << out_cpus;
- EXPECT_GT(out_cpus, 0);
-
- int out_cpus_phys = 0;
- EXPECT_TRUE(proc_info.GetNumPhysicalCpus(&out_cpus_phys));
- LOG(LS_INFO) << "GetNumPhysicalCpus: " << out_cpus_phys;
- EXPECT_GT(out_cpus_phys, 0);
- EXPECT_LE(out_cpus_phys, out_cpus);
-
- int out_family = 0;
- EXPECT_TRUE(proc_info.GetCpuFamily(&out_family));
- LOG(LS_INFO) << "cpu family: " << out_family;
- EXPECT_GE(out_family, 4);
-
-#if defined(__arm__)
- std::string out_processor;
- EXPECT_TRUE(proc_info.GetSectionStringValue(0, "Processor", &out_processor));
- LOG(LS_INFO) << "Processor: " << out_processor;
- EXPECT_NE(std::string::npos, out_processor.find("ARM"));
-
- // Most other info, such as model, stepping, vendor, etc.
- // is missing on ARM systems.
-#else
- int out_model = 0;
- EXPECT_TRUE(proc_info.GetSectionIntValue(0, "model", &out_model));
- LOG(LS_INFO) << "model: " << out_model;
-
- int out_stepping = 0;
- EXPECT_TRUE(proc_info.GetSectionIntValue(0, "stepping", &out_stepping));
- LOG(LS_INFO) << "stepping: " << out_stepping;
-
- int out_processor = 0;
- EXPECT_TRUE(proc_info.GetSectionIntValue(0, "processor", &out_processor));
- LOG(LS_INFO) << "processor: " << out_processor;
- EXPECT_EQ(0, out_processor);
-
- std::string out_str;
- EXPECT_TRUE(proc_info.GetSectionStringValue(0, "vendor_id", &out_str));
- LOG(LS_INFO) << "vendor_id: " << out_str;
- EXPECT_FALSE(out_str.empty());
-#endif
-}
-
-TEST(ConfigParser, ParseConfig) {
- ConfigParser parser;
- MemoryStream *test_stream = new MemoryStream(
- "Key1: Value1\n"
- "Key2\t: Value2\n"
- "Key3:Value3\n"
- "\n"
- "Key1:Value1\n");
- ConfigParser::MapVector key_val_pairs;
- parser.Attach(test_stream);
- EXPECT_EQ(true, parser.Parse(&key_val_pairs));
- EXPECT_EQ(2U, key_val_pairs.size());
- EXPECT_EQ("Value1", key_val_pairs[0]["Key1"]);
- EXPECT_EQ("Value2", key_val_pairs[0]["Key2"]);
- EXPECT_EQ("Value3", key_val_pairs[0]["Key3"]);
- EXPECT_EQ("Value1", key_val_pairs[1]["Key1"]);
- key_val_pairs.clear();
- EXPECT_EQ(true, parser.Open("/proc/cpuinfo"));
- EXPECT_EQ(true, parser.Parse(&key_val_pairs));
-}
-
-#if !defined(GOOGLE_CHROME_BUILD) && !defined(CHROMIUM_BUILD)
-TEST(ReadLinuxLsbRelease, ReturnsSomething) {
- std::string str = ReadLinuxLsbRelease();
- // ChromeOS don't have lsb_release
- // EXPECT_FALSE(str.empty());
-}
-#endif
-
-TEST(ReadLinuxUname, ReturnsSomething) {
- std::string str = ReadLinuxUname();
- EXPECT_FALSE(str.empty());
-}
-
-} // namespace talk_base
diff --git a/base/linuxfdwalk.c b/base/linuxfdwalk.c
deleted file mode 100644
index 4179f41..0000000
--- a/base/linuxfdwalk.c
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <sys/types.h>
-#include <dirent.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "talk/base/linuxfdwalk.h"
-
-// Parses a file descriptor number in base 10, requiring the strict format used
-// in /proc/*/fd. Returns the value, or -1 if not a valid string.
-static int parse_fd(const char *s) {
- if (!*s) {
- // Empty string is invalid.
- return -1;
- }
- int val = 0;
- do {
- if (*s < '0' || *s > '9') {
- // Non-numeric characters anywhere are invalid.
- return -1;
- }
- int digit = *s++ - '0';
- val = val * 10 + digit;
- } while (*s);
- return val;
-}
-
-int fdwalk(void (*func)(void *, int), void *opaque) {
- DIR *dir = opendir("/proc/self/fd");
- if (!dir) {
- return -1;
- }
- int opendirfd = dirfd(dir);
- int parse_errors = 0;
- struct dirent *ent;
- // Have to clear errno to distinguish readdir() completion from failure.
- while (errno = 0, (ent = readdir(dir)) != NULL) {
- if (strcmp(ent->d_name, ".") == 0 ||
- strcmp(ent->d_name, "..") == 0) {
- continue;
- }
- // We avoid atoi or strtol because those are part of libc and they involve
- // locale stuff, which is probably not safe from a post-fork context in a
- // multi-threaded app.
- int fd = parse_fd(ent->d_name);
- if (fd < 0) {
- parse_errors = 1;
- continue;
- }
- if (fd != opendirfd) {
- (*func)(opaque, fd);
- }
- }
- int saved_errno = errno;
- if (closedir(dir) < 0) {
- if (!saved_errno) {
- // Return the closedir error.
- return -1;
- }
- // Else ignore it because we have a more relevant error to return.
- }
- if (saved_errno) {
- errno = saved_errno;
- return -1;
- } else if (parse_errors) {
- errno = EBADF;
- return -1;
- } else {
- return 0;
- }
-}
diff --git a/base/linuxfdwalk.h b/base/linuxfdwalk.h
deleted file mode 100644
index ea039bf..0000000
--- a/base/linuxfdwalk.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_LINUXFDWALK_H_
-#define TALK_BASE_LINUXFDWALK_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// Linux port of SunOS's fdwalk(3) call. It loops over all open file descriptors
-// and calls func on each one. Additionally, it is safe to use from the child
-// of a fork that hasn't exec'ed yet, so you can use it to close all open file
-// descriptors prior to exec'ing a daemon.
-// The return value is 0 if successful, or else -1 and errno is set. The
-// possible errors include any error that can be returned by opendir(),
-// readdir(), or closedir(), plus EBADF if there are problems parsing the
-// contents of /proc/self/fd.
-// The file descriptors that are enumerated will not include the file descriptor
-// used for the enumeration itself.
-int fdwalk(void (*func)(void *, int), void *opaque);
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-#endif // TALK_BASE_LINUXFDWALK_H_
diff --git a/base/linuxfdwalk_unittest.cc b/base/linuxfdwalk_unittest.cc
deleted file mode 100644
index ff14b66..0000000
--- a/base/linuxfdwalk_unittest.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <set>
-#include <sstream>
-
-#include "talk/base/gunit.h"
-#include "talk/base/linuxfdwalk.h"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-static const int kArbitraryLargeFdNumber = 424;
-
-static void FdCheckVisitor(void *data, int fd) {
- std::set<int> *fds = static_cast<std::set<int> *>(data);
- EXPECT_EQ(1U, fds->erase(fd));
-}
-
-static void FdEnumVisitor(void *data, int fd) {
- std::set<int> *fds = static_cast<std::set<int> *>(data);
- EXPECT_TRUE(fds->insert(fd).second);
-}
-
-// Checks that the set of open fds is exactly the given list.
-static void CheckOpenFdList(std::set<int> fds) {
- EXPECT_EQ(0, fdwalk(&FdCheckVisitor, &fds));
- EXPECT_EQ(0U, fds.size());
-}
-
-static void GetOpenFdList(std::set<int> *fds) {
- fds->clear();
- EXPECT_EQ(0, fdwalk(&FdEnumVisitor, fds));
-}
-
-TEST(LinuxFdWalk, TestFdWalk) {
- std::set<int> fds;
- GetOpenFdList(&fds);
- std::ostringstream str;
- // I have observed that the open set when starting a test is [0, 6]. Leaked
- // fds would change that, but so can (e.g.) running under a debugger, so we
- // can't really do an EXPECT. :(
- str << "File descriptors open in test executable:";
- for (std::set<int>::const_iterator i = fds.begin(); i != fds.end(); ++i) {
- str << " " << *i;
- }
- LOG(LS_INFO) << str.str();
- // Open some files.
- int fd1 = open("/dev/null", O_RDONLY);
- EXPECT_LE(0, fd1);
- int fd2 = open("/dev/null", O_WRONLY);
- EXPECT_LE(0, fd2);
- int fd3 = open("/dev/null", O_RDWR);
- EXPECT_LE(0, fd3);
- int fd4 = dup2(fd3, kArbitraryLargeFdNumber);
- EXPECT_LE(0, fd4);
- EXPECT_TRUE(fds.insert(fd1).second);
- EXPECT_TRUE(fds.insert(fd2).second);
- EXPECT_TRUE(fds.insert(fd3).second);
- EXPECT_TRUE(fds.insert(fd4).second);
- CheckOpenFdList(fds);
- EXPECT_EQ(0, close(fd1));
- EXPECT_EQ(0, close(fd2));
- EXPECT_EQ(0, close(fd3));
- EXPECT_EQ(0, close(fd4));
-}
diff --git a/base/linuxwindowpicker.cc b/base/linuxwindowpicker.cc
deleted file mode 100644
index 75e47d5..0000000
--- a/base/linuxwindowpicker.cc
+++ /dev/null
@@ -1,835 +0,0 @@
-/*
- * libjingle
- * Copyright 2010 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/linuxwindowpicker.h"
-
-#include <math.h>
-#include <string.h>
-
-#include <algorithm>
-#include <string>
-
-#include <X11/Xatom.h>
-#include <X11/extensions/Xcomposite.h>
-#include <X11/extensions/Xrender.h>
-#include <X11/Xutil.h>
-
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-// Convenience wrapper for XGetWindowProperty results.
-template <class PropertyType>
-class XWindowProperty {
- public:
- XWindowProperty(Display* display, Window window, Atom property)
- : data_(NULL) {
- const int kBitsPerByte = 8;
- Atom actual_type;
- int actual_format;
- unsigned long bytes_after; // NOLINT: type required by XGetWindowProperty
- int status = XGetWindowProperty(display, window, property, 0L, ~0L, False,
- AnyPropertyType, &actual_type,
- &actual_format, &size_,
- &bytes_after, &data_);
- succeeded_ = (status == Success);
- if (!succeeded_) {
- data_ = NULL; // Ensure nothing is freed.
- } else if (sizeof(PropertyType) * kBitsPerByte != actual_format) {
- LOG(LS_WARNING) << "Returned type size differs from "
- "requested type size.";
- succeeded_ = false;
- // We still need to call XFree in this case, so leave data_ alone.
- }
- if (!succeeded_) {
- size_ = 0;
- }
- }
-
- ~XWindowProperty() {
- if (data_) {
- XFree(data_);
- }
- }
-
- bool succeeded() const { return succeeded_; }
- size_t size() const { return size_; }
- const PropertyType* data() const {
- return reinterpret_cast<PropertyType*>(data_);
- }
- PropertyType* data() {
- return reinterpret_cast<PropertyType*>(data_);
- }
-
- private:
- bool succeeded_;
- unsigned long size_; // NOLINT: type required by XGetWindowProperty
- unsigned char* data_;
-
- DISALLOW_COPY_AND_ASSIGN(XWindowProperty);
-};
-
-// Stupid X11. It seems none of the synchronous returns codes from X11 calls
-// are meaningful unless an asynchronous error handler is configured. This
-// RAII class registers and unregisters an X11 error handler.
-class XErrorSuppressor {
- public:
- explicit XErrorSuppressor(Display* display)
- : display_(display), original_error_handler_(NULL) {
- SuppressX11Errors();
- }
- ~XErrorSuppressor() {
- UnsuppressX11Errors();
- }
-
- private:
- static int ErrorHandler(Display* display, XErrorEvent* e) {
- char buf[256];
- XGetErrorText(display, e->error_code, buf, sizeof buf);
- LOG(LS_WARNING) << "Received X11 error \"" << buf << "\" for request code "
- << static_cast<unsigned int>(e->request_code);
- return 0;
- }
-
- void SuppressX11Errors() {
- XFlush(display_);
- XSync(display_, False);
- original_error_handler_ = XSetErrorHandler(&ErrorHandler);
- }
-
- void UnsuppressX11Errors() {
- XFlush(display_);
- XSync(display_, False);
- XErrorHandler handler = XSetErrorHandler(original_error_handler_);
- if (handler != &ErrorHandler) {
- LOG(LS_WARNING) << "Unbalanced XSetErrorHandler() calls detected. "
- << "Final error handler may not be what you expect!";
- }
- original_error_handler_ = NULL;
- }
-
- Display* display_;
- XErrorHandler original_error_handler_;
-
- DISALLOW_COPY_AND_ASSIGN(XErrorSuppressor);
-};
-
-// Hiding all X11 specifics inside its own class. This to avoid
-// conflicts between talk and X11 header declarations.
-class XWindowEnumerator {
- public:
- XWindowEnumerator()
- : display_(NULL),
- has_composite_extension_(false),
- has_render_extension_(false) {
- }
-
- ~XWindowEnumerator() {
- if (display_ != NULL) {
- XCloseDisplay(display_);
- }
- }
-
- bool Init() {
- if (display_ != NULL) {
- // Already initialized.
- return true;
- }
- display_ = XOpenDisplay(NULL);
- if (display_ == NULL) {
- LOG(LS_ERROR) << "Failed to open display.";
- return false;
- }
-
- XErrorSuppressor error_suppressor(display_);
-
- wm_state_ = XInternAtom(display_, "WM_STATE", True);
- net_wm_icon_ = XInternAtom(display_, "_NET_WM_ICON", False);
-
- int event_base, error_base, major_version, minor_version;
- if (XCompositeQueryExtension(display_, &event_base, &error_base) &&
- XCompositeQueryVersion(display_, &major_version, &minor_version) &&
- // XCompositeNameWindowPixmap() requires version 0.2
- (major_version > 0 || minor_version >= 2)) {
- has_composite_extension_ = true;
- } else {
- LOG(LS_INFO) << "Xcomposite extension not available or too old.";
- }
-
- if (XRenderQueryExtension(display_, &event_base, &error_base) &&
- XRenderQueryVersion(display_, &major_version, &minor_version) &&
- // XRenderSetPictureTransform() requires version 0.6
- (major_version > 0 || minor_version >= 6)) {
- has_render_extension_ = true;
- } else {
- LOG(LS_INFO) << "Xrender extension not available or too old.";
- }
- return true;
- }
-
- bool EnumerateWindows(WindowDescriptionList* descriptions) {
- if (!Init()) {
- return false;
- }
- XErrorSuppressor error_suppressor(display_);
- int num_screens = XScreenCount(display_);
- bool result = false;
- for (int i = 0; i < num_screens; ++i) {
- if (EnumerateScreenWindows(descriptions, i)) {
- // We know we succeded on at least one screen.
- result = true;
- }
- }
- return result;
- }
-
- bool EnumerateDesktops(DesktopDescriptionList* descriptions) {
- if (!Init()) {
- return false;
- }
- XErrorSuppressor error_suppressor(display_);
- Window default_root_window = XDefaultRootWindow(display_);
- int num_screens = XScreenCount(display_);
- for (int i = 0; i < num_screens; ++i) {
- Window root_window = XRootWindow(display_, i);
- DesktopId id(DesktopId(root_window, i));
- // TODO: Figure out an appropriate desktop title.
- DesktopDescription desc(id, "");
- desc.set_primary(root_window == default_root_window);
- descriptions->push_back(desc);
- }
- return num_screens > 0;
- }
-
- bool IsVisible(const WindowId& id) {
- if (!Init()) {
- return false;
- }
- XErrorSuppressor error_suppressor(display_);
- XWindowAttributes attr;
- if (!XGetWindowAttributes(display_, id.id(), &attr)) {
- LOG(LS_ERROR) << "XGetWindowAttributes() failed";
- return false;
- }
- return attr.map_state == IsViewable;
- }
-
- bool MoveToFront(const WindowId& id) {
- if (!Init()) {
- return false;
- }
- XErrorSuppressor error_suppressor(display_);
- unsigned int num_children;
- Window* children;
- Window parent;
- Window root;
-
- // Find root window to pass event to.
- int status = XQueryTree(display_, id.id(), &root, &parent, &children,
- &num_children);
- if (status == 0) {
- LOG(LS_WARNING) << "Failed to query for child windows.";
- return false;
- }
- if (children != NULL) {
- XFree(children);
- }
-
- // Move the window to front.
- XRaiseWindow(display_, id.id());
-
- // Some window managers (e.g., metacity in GNOME) consider it illegal to
- // raise a window without also giving it input focus with
- // _NET_ACTIVE_WINDOW, so XRaiseWindow() on its own isn't enough.
- Atom atom = XInternAtom(display_, "_NET_ACTIVE_WINDOW", True);
- if (atom != None) {
- XEvent xev;
- long event_mask;
-
- xev.xclient.type = ClientMessage;
- xev.xclient.serial = 0;
- xev.xclient.send_event = True;
- xev.xclient.window = id.id();
- xev.xclient.message_type = atom;
-
- // The format member is set to 8, 16, or 32 and specifies whether the
- // data should be viewed as a list of bytes, shorts, or longs.
- xev.xclient.format = 32;
-
- xev.xclient.data.l[0] = 0;
- xev.xclient.data.l[1] = 0;
- xev.xclient.data.l[2] = 0;
- xev.xclient.data.l[3] = 0;
- xev.xclient.data.l[4] = 0;
-
- event_mask = SubstructureRedirectMask | SubstructureNotifyMask;
-
- XSendEvent(display_, root, False, event_mask, &xev);
- }
- XFlush(display_);
- return true;
- }
-
- uint8* GetWindowIcon(const WindowId& id, int* width, int* height) {
- if (!Init()) {
- return NULL;
- }
- XErrorSuppressor error_suppressor(display_);
- Atom ret_type;
- int format;
- unsigned long length, bytes_after, size;
- unsigned char* data = NULL;
-
- // Find out the size of the icon data.
- if (XGetWindowProperty(
- display_, id.id(), net_wm_icon_, 0, 0, False, XA_CARDINAL,
- &ret_type, &format, &length, &size, &data) == Success &&
- data) {
- XFree(data);
- } else {
- LOG(LS_ERROR) << "Failed to get size of the icon.";
- return NULL;
- }
- // Get the icon data, the format is one uint32 each for width and height,
- // followed by the actual pixel data.
- if (size >= 2 &&
- XGetWindowProperty(
- display_, id.id(), net_wm_icon_, 0, size, False, XA_CARDINAL,
- &ret_type, &format, &length, &bytes_after, &data) == Success &&
- data) {
- uint32* data_ptr = reinterpret_cast<uint32*>(data);
- int w, h;
- w = data_ptr[0];
- h = data_ptr[1];
- if (size < static_cast<unsigned long>(w * h + 2)) {
- XFree(data);
- LOG(LS_ERROR) << "Not a vaild icon.";
- return NULL;
- }
- uint8* rgba =
- ArgbToRgba(&data_ptr[2], 0, 0, w, h, w, h, true);
- XFree(data);
- *width = w;
- *height = h;
- return rgba;
- } else {
- LOG(LS_ERROR) << "Failed to get window icon data.";
- return NULL;
- }
- }
-
- uint8* GetWindowThumbnail(const WindowId& id, int width, int height) {
- if (!Init()) {
- return NULL;
- }
-
- if (!has_composite_extension_) {
- // Without the Xcomposite extension we would only get a good thumbnail if
- // the whole window is visible on screen and not covered by any
- // other window. This is not something we want so instead, just
- // bail out.
- LOG(LS_INFO) << "No Xcomposite extension detected.";
- return NULL;
- }
- XErrorSuppressor error_suppressor(display_);
-
- Window root;
- int x;
- int y;
- unsigned int src_width;
- unsigned int src_height;
- unsigned int border_width;
- unsigned int depth;
-
- // In addition to needing X11 server-side support for Xcomposite, it
- // actually needs to be turned on for this window in order to get a good
- // thumbnail. If the user has modern hardware/drivers but isn't using a
- // compositing window manager, that won't be the case. Here we
- // automatically turn it on for shareable windows so that we can get
- // thumbnails. We used to avoid it because the transition is visually ugly,
- // but recent window managers don't always redirect windows which led to
- // no thumbnails at all, which is a worse experience.
-
- // Redirect drawing to an offscreen buffer (ie, turn on compositing).
- // X11 remembers what has requested this and will turn it off for us when
- // we exit.
- XCompositeRedirectWindow(display_, id.id(), CompositeRedirectAutomatic);
- Pixmap src_pixmap = XCompositeNameWindowPixmap(display_, id.id());
- if (!src_pixmap) {
- // Even if the backing pixmap doesn't exist, this still should have
- // succeeded and returned a valid handle (it just wouldn't be a handle to
- // anything). So this is a real error path.
- LOG(LS_ERROR) << "XCompositeNameWindowPixmap() failed";
- return NULL;
- }
- if (!XGetGeometry(display_, src_pixmap, &root, &x, &y,
- &src_width, &src_height, &border_width,
- &depth)) {
- // If the window does not actually have a backing pixmap, this is the path
- // that will "fail", so it's a warning rather than an error.
- LOG(LS_WARNING) << "XGetGeometry() failed (probably composite is not in "
- << "use)";
- XFreePixmap(display_, src_pixmap);
- return NULL;
- }
-
- // If we get to here, then composite is in use for this window and it has a
- // valid backing pixmap.
-
- XWindowAttributes attr;
- if (!XGetWindowAttributes(display_, id.id(), &attr)) {
- LOG(LS_ERROR) << "XGetWindowAttributes() failed";
- XFreePixmap(display_, src_pixmap);
- return NULL;
- }
-
- uint8* data = GetDrawableThumbnail(src_pixmap,
- attr.visual,
- src_width,
- src_height,
- width,
- height);
- XFreePixmap(display_, src_pixmap);
- return data;
- }
-
- int GetNumDesktops() {
- if (!Init()) {
- return -1;
- }
-
- return XScreenCount(display_);
- }
-
- uint8* GetDesktopThumbnail(const DesktopId& id, int width, int height) {
- if (!Init()) {
- return NULL;
- }
- XErrorSuppressor error_suppressor(display_);
-
- Window root_window = id.id();
- XWindowAttributes attr;
- if (!XGetWindowAttributes(display_, root_window, &attr)) {
- LOG(LS_ERROR) << "XGetWindowAttributes() failed";
- return NULL;
- }
-
- return GetDrawableThumbnail(root_window,
- attr.visual,
- attr.width,
- attr.height,
- width,
- height);
- }
-
- bool GetDesktopDimensions(const DesktopId& id, int* width, int* height) {
- if (!Init()) {
- return false;
- }
- XErrorSuppressor error_suppressor(display_);
- XWindowAttributes attr;
- if (!XGetWindowAttributes(display_, id.id(), &attr)) {
- LOG(LS_ERROR) << "XGetWindowAttributes() failed";
- return false;
- }
- *width = attr.width;
- *height = attr.height;
- return true;
- }
-
- private:
- uint8* GetDrawableThumbnail(Drawable src_drawable,
- Visual* visual,
- int src_width,
- int src_height,
- int dst_width,
- int dst_height) {
- if (!has_render_extension_) {
- // Without the Xrender extension we would have to read the full window and
- // scale it down in our process. Xrender is over a decade old so we aren't
- // going to expend effort to support that situation. We still need to
- // check though because probably some virtual VNC displays are in this
- // category.
- LOG(LS_INFO) << "No Xrender extension detected.";
- return NULL;
- }
-
- XRenderPictFormat* format = XRenderFindVisualFormat(display_,
- visual);
- if (!format) {
- LOG(LS_ERROR) << "XRenderFindVisualFormat() failed";
- return NULL;
- }
-
- // Create a picture to reference the window pixmap.
- XRenderPictureAttributes pa;
- pa.subwindow_mode = IncludeInferiors; // Don't clip child widgets
- Picture src = XRenderCreatePicture(display_,
- src_drawable,
- format,
- CPSubwindowMode,
- &pa);
- if (!src) {
- LOG(LS_ERROR) << "XRenderCreatePicture() failed";
- return NULL;
- }
-
- // Create a picture to reference the destination pixmap.
- Pixmap dst_pixmap = XCreatePixmap(display_,
- src_drawable,
- dst_width,
- dst_height,
- format->depth);
- if (!dst_pixmap) {
- LOG(LS_ERROR) << "XCreatePixmap() failed";
- XRenderFreePicture(display_, src);
- return NULL;
- }
-
- Picture dst = XRenderCreatePicture(display_, dst_pixmap, format, 0, NULL);
- if (!dst) {
- LOG(LS_ERROR) << "XRenderCreatePicture() failed";
- XFreePixmap(display_, dst_pixmap);
- XRenderFreePicture(display_, src);
- return NULL;
- }
-
- // Clear the background.
- XRenderColor transparent = {0};
- XRenderFillRectangle(display_,
- PictOpSrc,
- dst,
- &transparent,
- 0,
- 0,
- dst_width,
- dst_height);
-
- // Calculate how much we need to scale the image.
- double scale_x = static_cast<double>(dst_width) /
- static_cast<double>(src_width);
- double scale_y = static_cast<double>(dst_height) /
- static_cast<double>(src_height);
- double scale = talk_base::_min(scale_y, scale_x);
-
- int scaled_width = round(src_width * scale);
- int scaled_height = round(src_height * scale);
-
- // Render the thumbnail centered on both axis.
- int centered_x = (dst_width - scaled_width) / 2;
- int centered_y = (dst_height - scaled_height) / 2;
-
- // Scaling matrix
- XTransform xform = { {
- { XDoubleToFixed(1), XDoubleToFixed(0), XDoubleToFixed(0) },
- { XDoubleToFixed(0), XDoubleToFixed(1), XDoubleToFixed(0) },
- { XDoubleToFixed(0), XDoubleToFixed(0), XDoubleToFixed(scale) }
- } };
- XRenderSetPictureTransform(display_, src, &xform);
-
- // Apply filter to smooth out the image.
- XRenderSetPictureFilter(display_, src, FilterBest, NULL, 0);
-
- // Render the image to the destination picture.
- XRenderComposite(display_,
- PictOpSrc,
- src,
- None,
- dst,
- 0,
- 0,
- 0,
- 0,
- centered_x,
- centered_y,
- scaled_width,
- scaled_height);
-
- // Get the pixel data from the X server. TODO: XGetImage
- // might be slow here, compare with ShmGetImage.
- XImage* image = XGetImage(display_,
- dst_pixmap,
- 0,
- 0,
- dst_width,
- dst_height,
- AllPlanes, ZPixmap);
- uint8* data = ArgbToRgba(reinterpret_cast<uint32*>(image->data),
- centered_x,
- centered_y,
- scaled_width,
- scaled_height,
- dst_width,
- dst_height,
- false);
- XDestroyImage(image);
- XRenderFreePicture(display_, dst);
- XFreePixmap(display_, dst_pixmap);
- XRenderFreePicture(display_, src);
- return data;
- }
-
- uint8* ArgbToRgba(uint32* argb_data, int x, int y, int w, int h,
- int stride_x, int stride_y, bool has_alpha) {
- uint8* p;
- int len = stride_x * stride_y * 4;
- uint8* data = new uint8[len];
- memset(data, 0, len);
- p = data + 4 * (y * stride_x + x);
- for (int i = 0; i < h; ++i) {
- for (int j = 0; j < w; ++j) {
- uint32 argb;
- uint32 rgba;
- argb = argb_data[stride_x * (y + i) + x + j];
- rgba = (argb << 8) | (argb >> 24);
- *p = rgba >> 24;
- ++p;
- *p = (rgba >> 16) & 0xff;
- ++p;
- *p = (rgba >> 8) & 0xff;
- ++p;
- *p = has_alpha ? rgba & 0xFF : 0xFF;
- ++p;
- }
- p += (stride_x - w) * 4;
- }
- return data;
- }
-
- bool EnumerateScreenWindows(WindowDescriptionList* descriptions, int screen) {
- Window parent;
- Window *children;
- int status;
- unsigned int num_children;
- Window root_window = XRootWindow(display_, screen);
- status = XQueryTree(display_, root_window, &root_window, &parent, &children,
- &num_children);
- if (status == 0) {
- LOG(LS_ERROR) << "Failed to query for child windows.";
- return false;
- }
- for (unsigned int i = 0; i < num_children; ++i) {
- // Iterate in reverse order to display windows from front to back.
-#ifdef CHROMEOS
- // TODO(jhorwich): Short-term fix for crbug.com/120229: Don't need to
- // filter, just return all windows and let the picker scan through them.
- Window app_window = children[num_children - 1 - i];
-#else
- Window app_window = GetApplicationWindow(children[num_children - 1 - i]);
-#endif
- if (app_window &&
- !LinuxWindowPicker::IsDesktopElement(display_, app_window)) {
- std::string title;
- if (GetWindowTitle(app_window, &title)) {
- WindowId id(app_window);
- WindowDescription desc(id, title);
- descriptions->push_back(desc);
- }
- }
- }
- if (children != NULL) {
- XFree(children);
- }
- return true;
- }
-
- bool GetWindowTitle(Window window, std::string* title) {
- int status;
- bool result = false;
- XTextProperty window_name;
- window_name.value = NULL;
- if (window) {
- status = XGetWMName(display_, window, &window_name);
- if (status && window_name.value && window_name.nitems) {
- int cnt;
- char **list = NULL;
- status = Xutf8TextPropertyToTextList(display_, &window_name, &list,
- &cnt);
- if (status >= Success && cnt && *list) {
- if (cnt > 1) {
- LOG(LS_INFO) << "Window has " << cnt
- << " text properties, only using the first one.";
- }
- *title = *list;
- result = true;
- }
- if (list != NULL) {
- XFreeStringList(list);
- }
- }
- if (window_name.value != NULL) {
- XFree(window_name.value);
- }
- }
- return result;
- }
-
- Window GetApplicationWindow(Window window) {
- Window root, parent;
- Window app_window = 0;
- Window *children;
- unsigned int num_children;
- Atom type = None;
- int format;
- unsigned long nitems, after;
- unsigned char *data;
-
- int ret = XGetWindowProperty(display_, window,
- wm_state_, 0L, 2,
- False, wm_state_, &type, &format,
- &nitems, &after, &data);
- if (ret != Success) {
- LOG(LS_ERROR) << "XGetWindowProperty failed with return code " << ret
- << " for window " << window << ".";
- return 0;
- }
- if (type != None) {
- int64 state = static_cast<int64>(*data);
- XFree(data);
- return state == NormalState ? window : 0;
- }
- XFree(data);
- if (!XQueryTree(display_, window, &root, &parent, &children,
- &num_children)) {
- LOG(LS_ERROR) << "Failed to query for child windows although window"
- << "does not have a valid WM_STATE.";
- return 0;
- }
- for (unsigned int i = 0; i < num_children; ++i) {
- app_window = GetApplicationWindow(children[i]);
- if (app_window) {
- break;
- }
- }
- if (children != NULL) {
- XFree(children);
- }
- return app_window;
- }
-
- Atom wm_state_;
- Atom net_wm_icon_;
- Display* display_;
- bool has_composite_extension_;
- bool has_render_extension_;
-};
-
-LinuxWindowPicker::LinuxWindowPicker() : enumerator_(new XWindowEnumerator()) {
-}
-
-LinuxWindowPicker::~LinuxWindowPicker() {
-}
-
-bool LinuxWindowPicker::IsDesktopElement(_XDisplay* display, Window window) {
- if (window == 0) {
- LOG(LS_WARNING) << "Zero is never a valid window.";
- return false;
- }
-
- // First look for _NET_WM_WINDOW_TYPE. The standard
- // (http://standards.freedesktop.org/wm-spec/latest/ar01s05.html#id2760306)
- // says this hint *should* be present on all windows, and we use the existence
- // of _NET_WM_WINDOW_TYPE_NORMAL in the property to indicate a window is not
- // a desktop element (that is, only "normal" windows should be shareable).
- Atom window_type_atom = XInternAtom(display, "_NET_WM_WINDOW_TYPE", True);
- XWindowProperty<uint32_t> window_type(display, window, window_type_atom);
- if (window_type.succeeded() && window_type.size() > 0) {
- Atom normal_window_type_atom = XInternAtom(
- display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
- uint32_t* end = window_type.data() + window_type.size();
- bool is_normal = (end != std::find(
- window_type.data(), end, normal_window_type_atom));
- return !is_normal;
- }
-
- // Fall back on using the hint.
- XClassHint class_hint;
- Status s = XGetClassHint(display, window, &class_hint);
- bool result = false;
- if (s == 0) {
- // No hints, assume this is a normal application window.
- return result;
- }
- static const std::string gnome_panel("gnome-panel");
- static const std::string desktop_window("desktop_window");
-
- if (gnome_panel.compare(class_hint.res_name) == 0 ||
- desktop_window.compare(class_hint.res_name) == 0) {
- result = true;
- }
- XFree(class_hint.res_name);
- XFree(class_hint.res_class);
- return result;
-}
-
-bool LinuxWindowPicker::Init() {
- return enumerator_->Init();
-}
-
-bool LinuxWindowPicker::GetWindowList(WindowDescriptionList* descriptions) {
- return enumerator_->EnumerateWindows(descriptions);
-}
-
-bool LinuxWindowPicker::GetDesktopList(DesktopDescriptionList* descriptions) {
- return enumerator_->EnumerateDesktops(descriptions);
-}
-
-bool LinuxWindowPicker::IsVisible(const WindowId& id) {
- return enumerator_->IsVisible(id);
-}
-
-bool LinuxWindowPicker::MoveToFront(const WindowId& id) {
- return enumerator_->MoveToFront(id);
-}
-
-
-uint8* LinuxWindowPicker::GetWindowIcon(const WindowId& id, int* width,
- int* height) {
- return enumerator_->GetWindowIcon(id, width, height);
-}
-
-uint8* LinuxWindowPicker::GetWindowThumbnail(const WindowId& id, int width,
- int height) {
- return enumerator_->GetWindowThumbnail(id, width, height);
-}
-
-int LinuxWindowPicker::GetNumDesktops() {
- return enumerator_->GetNumDesktops();
-}
-
-uint8* LinuxWindowPicker::GetDesktopThumbnail(const DesktopId& id,
- int width,
- int height) {
- return enumerator_->GetDesktopThumbnail(id, width, height);
-}
-
-bool LinuxWindowPicker::GetDesktopDimensions(const DesktopId& id, int* width,
- int* height) {
- return enumerator_->GetDesktopDimensions(id, width, height);
-}
-
-} // namespace talk_base
diff --git a/base/linuxwindowpicker.h b/base/linuxwindowpicker.h
deleted file mode 100644
index 8e45d8f..0000000
--- a/base/linuxwindowpicker.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * libjingle
- * Copyright 2010 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_LINUXWINDOWPICKER_H_
-#define TALK_BASE_LINUXWINDOWPICKER_H_
-
-#include "talk/base/basictypes.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/windowpicker.h"
-
-// Avoid include <X11/Xlib.h>.
-struct _XDisplay;
-typedef unsigned long Window;
-
-namespace talk_base {
-
-class XWindowEnumerator;
-
-class LinuxWindowPicker : public WindowPicker {
- public:
- LinuxWindowPicker();
- ~LinuxWindowPicker();
-
- static bool IsDesktopElement(_XDisplay* display, Window window);
-
- virtual bool Init();
- virtual bool IsVisible(const WindowId& id);
- virtual bool MoveToFront(const WindowId& id);
- virtual bool GetWindowList(WindowDescriptionList* descriptions);
- virtual bool GetDesktopList(DesktopDescriptionList* descriptions);
- virtual bool GetDesktopDimensions(const DesktopId& id, int* width,
- int* height);
- uint8* GetWindowIcon(const WindowId& id, int* width, int* height);
- uint8* GetWindowThumbnail(const WindowId& id, int width, int height);
- int GetNumDesktops();
- uint8* GetDesktopThumbnail(const DesktopId& id, int width, int height);
-
- private:
- scoped_ptr<XWindowEnumerator> enumerator_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_LINUXWINDOWPICKER_H_
diff --git a/base/linuxwindowpicker_unittest.cc b/base/linuxwindowpicker_unittest.cc
deleted file mode 100644
index c248bba..0000000
--- a/base/linuxwindowpicker_unittest.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * libjingle
- * Copyright 2010 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/linuxwindowpicker.h"
-#include "talk/base/logging.h"
-#include "talk/base/testutils.h"
-#include "talk/base/windowpicker.h"
-
-#ifndef LINUX
-#error Only for Linux
-#endif
-
-namespace talk_base {
-
-TEST(LinuxWindowPickerTest, TestGetWindowList) {
- MAYBE_SKIP_SCREENCAST_TEST();
- LinuxWindowPicker window_picker;
- WindowDescriptionList descriptions;
- window_picker.Init();
- window_picker.GetWindowList(&descriptions);
-}
-
-TEST(LinuxWindowPickerTest, TestGetDesktopList) {
- MAYBE_SKIP_SCREENCAST_TEST();
- LinuxWindowPicker window_picker;
- DesktopDescriptionList descriptions;
- EXPECT_TRUE(window_picker.Init());
- EXPECT_TRUE(window_picker.GetDesktopList(&descriptions));
- EXPECT_TRUE(descriptions.size() > 0);
-}
-
-} // namespace talk_base
diff --git a/base/logging.cc b/base/logging.cc
deleted file mode 100644
index c1d0a53..0000000
--- a/base/logging.cc
+++ /dev/null
@@ -1,635 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#define snprintf _snprintf
-#undef ERROR // wingdi.h
-#endif
-
-#ifdef OSX
-#include <CoreServices/CoreServices.h>
-#elif defined(ANDROID)
-#include <android/log.h>
-static const char kLibjingle[] = "libjingle";
-// Android has a 1024 limit on log inputs. We use 60 chars as an
-// approx for the header/tag portion.
-// See android/system/core/liblog/logd_write.c
-static const int kMaxLogLineSize = 1024 - 60;
-#endif // OSX || ANDROID
-
-#include <time.h>
-
-#include <ostream>
-#include <iomanip>
-#include <limits.h>
-#include <vector>
-
-#include "talk/base/logging.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-/////////////////////////////////////////////////////////////////////////////
-// Constant Labels
-/////////////////////////////////////////////////////////////////////////////
-
-const char * FindLabel(int value, const ConstantLabel entries[]) {
- for (int i = 0; entries[i].label; ++i) {
- if (value == entries[i].value) {
- return entries[i].label;
- }
- }
- return 0;
-}
-
-std::string ErrorName(int err, const ConstantLabel * err_table) {
- if (err == 0)
- return "No error";
-
- if (err_table != 0) {
- if (const char * value = FindLabel(err, err_table))
- return value;
- }
-
- char buffer[16];
- snprintf(buffer, sizeof(buffer), "0x%08x", err);
- return buffer;
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// LogMessage
-/////////////////////////////////////////////////////////////////////////////
-
-const int LogMessage::NO_LOGGING = LS_ERROR + 1;
-
-#if _DEBUG
-static const int LOG_DEFAULT = LS_INFO;
-#else // !_DEBUG
-static const int LOG_DEFAULT = LogMessage::NO_LOGGING;
-#endif // !_DEBUG
-
-// Global lock for log subsystem, only needed to serialize access to streams_.
-CriticalSection LogMessage::crit_;
-
-// By default, release builds don't log, debug builds at info level
-int LogMessage::min_sev_ = LOG_DEFAULT;
-int LogMessage::dbg_sev_ = LOG_DEFAULT;
-
-// Don't bother printing context for the ubiquitous INFO log messages
-int LogMessage::ctx_sev_ = LS_WARNING;
-
-// The list of logging streams currently configured.
-// Note: we explicitly do not clean this up, because of the uncertain ordering
-// of destructors at program exit. Let the person who sets the stream trigger
-// cleanup by setting to NULL, or let it leak (safe at program exit).
-LogMessage::StreamList LogMessage::streams_;
-
-// Boolean options default to false (0)
-bool LogMessage::thread_, LogMessage::timestamp_;
-
-// If we're in diagnostic mode, we'll be explicitly set that way; default=false.
-bool LogMessage::is_diagnostic_mode_ = false;
-
-LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev,
- LogErrorContext err_ctx, int err, const char* module)
- : severity_(sev),
- warn_slow_logs_delay_(WARN_SLOW_LOGS_DELAY) {
- if (timestamp_) {
- uint32 time = TimeSince(LogStartTime());
- // Also ensure WallClockStartTime is initialized, so that it matches
- // LogStartTime.
- WallClockStartTime();
- print_stream_ << "[" << std::setfill('0') << std::setw(3) << (time / 1000)
- << ":" << std::setw(3) << (time % 1000) << std::setfill(' ')
- << "] ";
- }
-
- if (thread_) {
-#ifdef WIN32
- DWORD id = GetCurrentThreadId();
- print_stream_ << "[" << std::hex << id << std::dec << "] ";
-#endif // WIN32
- }
-
- if (severity_ >= ctx_sev_) {
- print_stream_ << Describe(sev) << "(" << DescribeFile(file)
- << ":" << line << "): ";
- }
-
- if (err_ctx != ERRCTX_NONE) {
- std::ostringstream tmp;
- tmp << "[0x" << std::setfill('0') << std::hex << std::setw(8) << err << "]";
- switch (err_ctx) {
- case ERRCTX_ERRNO:
- tmp << " " << strerror(err);
- break;
-#if WIN32
- case ERRCTX_HRESULT: {
- char msgbuf[256];
- DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM;
- HMODULE hmod = GetModuleHandleA(module);
- if (hmod)
- flags |= FORMAT_MESSAGE_FROM_HMODULE;
- if (DWORD len = FormatMessageA(
- flags, hmod, err,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- msgbuf, sizeof(msgbuf) / sizeof(msgbuf[0]), NULL)) {
- while ((len > 0) &&
- isspace(static_cast<unsigned char>(msgbuf[len-1]))) {
- msgbuf[--len] = 0;
- }
- tmp << " " << msgbuf;
- }
- break;
- }
-#endif // WIN32
-#if OSX
- case ERRCTX_OSSTATUS: {
- tmp << " " << nonnull(GetMacOSStatusErrorString(err), "Unknown error");
- if (const char* desc = GetMacOSStatusCommentString(err)) {
- tmp << ": " << desc;
- }
- break;
- }
-#endif // OSX
- default:
- break;
- }
- extra_ = tmp.str();
- }
-}
-
-LogMessage::~LogMessage() {
- if (!extra_.empty())
- print_stream_ << " : " << extra_;
- print_stream_ << std::endl;
-
- const std::string& str = print_stream_.str();
- if (severity_ >= dbg_sev_) {
- OutputToDebug(str, severity_);
- }
-
- uint32 before = Time();
- // Must lock streams_ before accessing
- CritScope cs(&crit_);
- for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
- if (severity_ >= it->second) {
- OutputToStream(it->first, str);
- }
- }
- uint32 delay = TimeSince(before);
- if (delay >= warn_slow_logs_delay_) {
- LogMessage slow_log_warning =
- talk_base::LogMessage(__FILE__, __LINE__, LS_WARNING);
- // If our warning is slow, we don't want to warn about it, because
- // that would lead to inifinite recursion. So, give a really big
- // number for the delay threshold.
- slow_log_warning.warn_slow_logs_delay_ = UINT_MAX;
- slow_log_warning.stream() << "Slow log: took " << delay << "ms to write "
- << str.size() << " bytes.";
- }
-}
-
-uint32 LogMessage::LogStartTime() {
- static const uint32 g_start = Time();
- return g_start;
-}
-
-uint32 LogMessage::WallClockStartTime() {
- static const uint32 g_start_wallclock = time(NULL);
- return g_start_wallclock;
-}
-
-void LogMessage::LogContext(int min_sev) {
- ctx_sev_ = min_sev;
-}
-
-void LogMessage::LogThreads(bool on) {
- thread_ = on;
-}
-
-void LogMessage::LogTimestamps(bool on) {
- timestamp_ = on;
-}
-
-void LogMessage::LogToDebug(int min_sev) {
- dbg_sev_ = min_sev;
- UpdateMinLogSeverity();
-}
-
-void LogMessage::LogToStream(StreamInterface* stream, int min_sev) {
- CritScope cs(&crit_);
- // Discard and delete all previously installed streams
- for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
- delete it->first;
- }
- streams_.clear();
- // Install the new stream, if specified
- if (stream) {
- AddLogToStream(stream, min_sev);
- }
-}
-
-int LogMessage::GetLogToStream(StreamInterface* stream) {
- CritScope cs(&crit_);
- int sev = NO_LOGGING;
- for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
- if (!stream || stream == it->first) {
- sev = _min(sev, it->second);
- }
- }
- return sev;
-}
-
-void LogMessage::AddLogToStream(StreamInterface* stream, int min_sev) {
- CritScope cs(&crit_);
- streams_.push_back(std::make_pair(stream, min_sev));
- UpdateMinLogSeverity();
-}
-
-void LogMessage::RemoveLogToStream(StreamInterface* stream) {
- CritScope cs(&crit_);
- for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
- if (stream == it->first) {
- streams_.erase(it);
- break;
- }
- }
- UpdateMinLogSeverity();
-}
-
-void LogMessage::ConfigureLogging(const char* params, const char* filename) {
- int current_level = LS_VERBOSE;
- int debug_level = GetLogToDebug();
- int file_level = GetLogToStream();
-
- std::vector<std::string> tokens;
- tokenize(params, ' ', &tokens);
-
- for (size_t i = 0; i < tokens.size(); ++i) {
- if (tokens[i].empty())
- continue;
-
- // Logging features
- if (tokens[i] == "tstamp") {
- LogTimestamps();
- } else if (tokens[i] == "thread") {
- LogThreads();
-
- // Logging levels
- } else if (tokens[i] == "sensitive") {
- current_level = LS_SENSITIVE;
- } else if (tokens[i] == "verbose") {
- current_level = LS_VERBOSE;
- } else if (tokens[i] == "info") {
- current_level = LS_INFO;
- } else if (tokens[i] == "warning") {
- current_level = LS_WARNING;
- } else if (tokens[i] == "error") {
- current_level = LS_ERROR;
- } else if (tokens[i] == "none") {
- current_level = NO_LOGGING;
-
- // Logging targets
- } else if (tokens[i] == "file") {
- file_level = current_level;
- } else if (tokens[i] == "debug") {
- debug_level = current_level;
- }
- }
-
-#ifdef WIN32
- if ((NO_LOGGING != debug_level) && !::IsDebuggerPresent()) {
- // First, attempt to attach to our parent's console... so if you invoke
- // from the command line, we'll see the output there. Otherwise, create
- // our own console window.
- // Note: These methods fail if a console already exists, which is fine.
- bool success = false;
- typedef BOOL (WINAPI* PFN_AttachConsole)(DWORD);
- if (HINSTANCE kernel32 = ::LoadLibrary(L"kernel32.dll")) {
- // AttachConsole is defined on WinXP+.
- if (PFN_AttachConsole attach_console = reinterpret_cast<PFN_AttachConsole>
- (::GetProcAddress(kernel32, "AttachConsole"))) {
- success = (FALSE != attach_console(ATTACH_PARENT_PROCESS));
- }
- ::FreeLibrary(kernel32);
- }
- if (!success) {
- ::AllocConsole();
- }
- }
-#endif // WIN32
-
- LogToDebug(debug_level);
-
-#if !defined(__native_client__) // No logging to file in NaCl.
- scoped_ptr<FileStream> stream;
- if (NO_LOGGING != file_level) {
- stream.reset(new FileStream);
- if (!stream->Open(filename, "wb", NULL) || !stream->DisableBuffering()) {
- stream.reset();
- }
- }
-
- LogToStream(stream.release(), file_level);
-#endif
-}
-
-int LogMessage::ParseLogSeverity(const std::string& value) {
- int level = NO_LOGGING;
- if (value == "LS_SENSITIVE") {
- level = LS_SENSITIVE;
- } else if (value == "LS_VERBOSE") {
- level = LS_VERBOSE;
- } else if (value == "LS_INFO") {
- level = LS_INFO;
- } else if (value == "LS_WARNING") {
- level = LS_WARNING;
- } else if (value == "LS_ERROR") {
- level = LS_ERROR;
- } else if (isdigit(value[0])) {
- level = atoi(value.c_str()); // NOLINT
- }
- return level;
-}
-
-void LogMessage::UpdateMinLogSeverity() {
- int min_sev = dbg_sev_;
- for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
- min_sev = _min(dbg_sev_, it->second);
- }
- min_sev_ = min_sev;
-}
-
-const char* LogMessage::Describe(LoggingSeverity sev) {
- switch (sev) {
- case LS_SENSITIVE: return "Sensitive";
- case LS_VERBOSE: return "Verbose";
- case LS_INFO: return "Info";
- case LS_WARNING: return "Warning";
- case LS_ERROR: return "Error";
- default: return "<unknown>";
- }
-}
-
-const char* LogMessage::DescribeFile(const char* file) {
- const char* end1 = ::strrchr(file, '/');
- const char* end2 = ::strrchr(file, '\\');
- if (!end1 && !end2)
- return file;
- else
- return (end1 > end2) ? end1 + 1 : end2 + 1;
-}
-
-void LogMessage::OutputToDebug(const std::string& str,
- LoggingSeverity severity) {
- bool log_to_stderr = true;
-#if defined(OSX) && (!defined(DEBUG) || defined(NDEBUG))
- // On the Mac, all stderr output goes to the Console log and causes clutter.
- // So in opt builds, don't log to stderr unless the user specifically sets
- // a preference to do so.
- CFStringRef key = CFStringCreateWithCString(kCFAllocatorDefault,
- "logToStdErr",
- kCFStringEncodingUTF8);
- CFStringRef domain = CFBundleGetIdentifier(CFBundleGetMainBundle());
- if (key != NULL && domain != NULL) {
- Boolean exists_and_is_valid;
- Boolean should_log =
- CFPreferencesGetAppBooleanValue(key, domain, &exists_and_is_valid);
- // If the key doesn't exist or is invalid or is false, we will not log to
- // stderr.
- log_to_stderr = exists_and_is_valid && should_log;
- }
- if (key != NULL) {
- CFRelease(key);
- }
-#endif
-#ifdef WIN32
- // Always log to the debugger.
- // Perhaps stderr should be controlled by a preference, as on Mac?
- OutputDebugStringA(str.c_str());
- if (log_to_stderr) {
- // This handles dynamically allocated consoles, too.
- if (HANDLE error_handle = ::GetStdHandle(STD_ERROR_HANDLE)) {
- log_to_stderr = false;
- DWORD written = 0;
- ::WriteFile(error_handle, str.data(), static_cast<DWORD>(str.size()),
- &written, 0);
- }
- }
-#endif // WIN32
-#ifdef ANDROID
- // Android's logging facility uses severity to log messages but we
- // need to map libjingle's severity levels to Android ones first.
- // Also write to stderr which maybe available to executable started
- // from the shell.
- int prio;
- switch (severity) {
- case LS_SENSITIVE:
- __android_log_write(ANDROID_LOG_INFO, kLibjingle, "SENSITIVE");
- if (log_to_stderr) {
- fprintf(stderr, "SENSITIVE");
- fflush(stderr);
- }
- return;
- case LS_VERBOSE:
- prio = ANDROID_LOG_VERBOSE;
- break;
- case LS_INFO:
- prio = ANDROID_LOG_INFO;
- break;
- case LS_WARNING:
- prio = ANDROID_LOG_WARN;
- break;
- case LS_ERROR:
- prio = ANDROID_LOG_ERROR;
- break;
- default:
- prio = ANDROID_LOG_UNKNOWN;
- }
-
- int size = str.size();
- int line = 0;
- int idx = 0;
- const int max_lines = size / kMaxLogLineSize + 1;
- if (max_lines == 1) {
- __android_log_print(prio, kLibjingle, "%.*s", size, str.c_str());
- } else {
- while (size > 0) {
- const int len = std::min(size, kMaxLogLineSize);
- // Use the size of the string in the format (str may have \0 in the
- // middle).
- __android_log_print(prio, kLibjingle, "[%d/%d] %.*s",
- line + 1, max_lines,
- len, str.c_str() + idx);
- idx += len;
- size -= len;
- ++line;
- }
- }
-#endif // ANDROID
- if (log_to_stderr) {
- fprintf(stderr, "%s", str.c_str());
- fflush(stderr);
- }
-}
-
-void LogMessage::OutputToStream(StreamInterface* stream,
- const std::string& str) {
- // If write isn't fully successful, what are we going to do, log it? :)
- stream->WriteAll(str.data(), str.size(), NULL, NULL);
-}
-
-//////////////////////////////////////////////////////////////////////
-// Logging Helpers
-//////////////////////////////////////////////////////////////////////
-
-void LogMultiline(LoggingSeverity level, const char* label, bool input,
- const void* data, size_t len, bool hex_mode,
- LogMultilineState* state) {
- if (!LOG_CHECK_LEVEL_V(level))
- return;
-
- const char * direction = (input ? " << " : " >> ");
-
- // NULL data means to flush our count of unprintable characters.
- if (!data) {
- if (state && state->unprintable_count_[input]) {
- LOG_V(level) << label << direction << "## "
- << state->unprintable_count_[input]
- << " consecutive unprintable ##";
- state->unprintable_count_[input] = 0;
- }
- return;
- }
-
- // The ctype classification functions want unsigned chars.
- const unsigned char* udata = static_cast<const unsigned char*>(data);
-
- if (hex_mode) {
- const size_t LINE_SIZE = 24;
- char hex_line[LINE_SIZE * 9 / 4 + 2], asc_line[LINE_SIZE + 1];
- while (len > 0) {
- memset(asc_line, ' ', sizeof(asc_line));
- memset(hex_line, ' ', sizeof(hex_line));
- size_t line_len = _min(len, LINE_SIZE);
- for (size_t i = 0; i < line_len; ++i) {
- unsigned char ch = udata[i];
- asc_line[i] = isprint(ch) ? ch : '.';
- hex_line[i*2 + i/4] = hex_encode(ch >> 4);
- hex_line[i*2 + i/4 + 1] = hex_encode(ch & 0xf);
- }
- asc_line[sizeof(asc_line)-1] = 0;
- hex_line[sizeof(hex_line)-1] = 0;
- LOG_V(level) << label << direction
- << asc_line << " " << hex_line << " ";
- udata += line_len;
- len -= line_len;
- }
- return;
- }
-
- size_t consecutive_unprintable = state ? state->unprintable_count_[input] : 0;
-
- const unsigned char* end = udata + len;
- while (udata < end) {
- const unsigned char* line = udata;
- const unsigned char* end_of_line = strchrn<unsigned char>(udata,
- end - udata,
- '\n');
- if (!end_of_line) {
- udata = end_of_line = end;
- } else {
- udata = end_of_line + 1;
- }
-
- bool is_printable = true;
-
- // If we are in unprintable mode, we need to see a line of at least
- // kMinPrintableLine characters before we'll switch back.
- const ptrdiff_t kMinPrintableLine = 4;
- if (consecutive_unprintable && ((end_of_line - line) < kMinPrintableLine)) {
- is_printable = false;
- } else {
- // Determine if the line contains only whitespace and printable
- // characters.
- bool is_entirely_whitespace = true;
- for (const unsigned char* pos = line; pos < end_of_line; ++pos) {
- if (isspace(*pos))
- continue;
- is_entirely_whitespace = false;
- if (!isprint(*pos)) {
- is_printable = false;
- break;
- }
- }
- // Treat an empty line following unprintable data as unprintable.
- if (consecutive_unprintable && is_entirely_whitespace) {
- is_printable = false;
- }
- }
- if (!is_printable) {
- consecutive_unprintable += (udata - line);
- continue;
- }
- // Print out the current line, but prefix with a count of prior unprintable
- // characters.
- if (consecutive_unprintable) {
- LOG_V(level) << label << direction << "## " << consecutive_unprintable
- << " consecutive unprintable ##";
- consecutive_unprintable = 0;
- }
- // Strip off trailing whitespace.
- while ((end_of_line > line) && isspace(*(end_of_line-1))) {
- --end_of_line;
- }
- // Filter out any private data
- std::string substr(reinterpret_cast<const char*>(line), end_of_line - line);
- std::string::size_type pos_private = substr.find("Email");
- if (pos_private == std::string::npos) {
- pos_private = substr.find("Passwd");
- }
- if (pos_private == std::string::npos) {
- LOG_V(level) << label << direction << substr;
- } else {
- LOG_V(level) << label << direction << "## omitted for privacy ##";
- }
- }
-
- if (state) {
- state->unprintable_count_[input] = consecutive_unprintable;
- }
-}
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/logging.h b/base/logging.h
deleted file mode 100644
index 01636e8..0000000
--- a/base/logging.h
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// LOG(...) an ostream target that can be used to send formatted
-// output to a variety of logging targets, such as debugger console, stderr,
-// file, or any StreamInterface.
-// The severity level passed as the first argument to the LOGging
-// functions is used as a filter, to limit the verbosity of the logging.
-// Static members of LogMessage documented below are used to control the
-// verbosity and target of the output.
-// There are several variations on the LOG macro which facilitate logging
-// of common error conditions, detailed below.
-
-// LOG(sev) logs the given stream at severity "sev", which must be a
-// compile-time constant of the LoggingSeverity type, without the namespace
-// prefix.
-// LOG_V(sev) Like LOG(), but sev is a run-time variable of the LoggingSeverity
-// type (basically, it just doesn't prepend the namespace).
-// LOG_F(sev) Like LOG(), but includes the name of the current function.
-// LOG_T(sev) Like LOG(), but includes the this pointer.
-// LOG_T_F(sev) Like LOG_F(), but includes the this pointer.
-// LOG_GLE(M)(sev [, mod]) attempt to add a string description of the
-// HRESULT returned by GetLastError. The "M" variant allows searching of a
-// DLL's string table for the error description.
-// LOG_ERRNO(sev) attempts to add a string description of an errno-derived
-// error. errno and associated facilities exist on both Windows and POSIX,
-// but on Windows they only apply to the C/C++ runtime.
-// LOG_ERR(sev) is an alias for the platform's normal error system, i.e. _GLE on
-// Windows and _ERRNO on POSIX.
-// (The above three also all have _EX versions that let you specify the error
-// code, rather than using the last one.)
-// LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the
-// specified context.
-// LOG_CHECK_LEVEL(sev) (and LOG_CHECK_LEVEL_V(sev)) can be used as a test
-// before performing expensive or sensitive operations whose sole purpose is
-// to output logging data at the desired level.
-// Lastly, PLOG(sev, err) is an alias for LOG_ERR_EX.
-
-#ifndef TALK_BASE_LOGGING_H_
-#define TALK_BASE_LOGGING_H_
-
-#ifdef HAVE_CONFIG_H
-#include "config.h" // NOLINT
-#endif
-
-#include <list>
-#include <sstream>
-#include <string>
-#include <utility>
-#include "talk/base/basictypes.h"
-#include "talk/base/criticalsection.h"
-
-namespace talk_base {
-
-class StreamInterface;
-
-///////////////////////////////////////////////////////////////////////////////
-// ConstantLabel can be used to easily generate string names from constant
-// values. This can be useful for logging descriptive names of error messages.
-// Usage:
-// const ConstantLabel LIBRARY_ERRORS[] = {
-// KLABEL(SOME_ERROR),
-// KLABEL(SOME_OTHER_ERROR),
-// ...
-// LASTLABEL
-// }
-//
-// int err = LibraryFunc();
-// LOG(LS_ERROR) << "LibraryFunc returned: "
-// << ErrorName(err, LIBRARY_ERRORS);
-
-struct ConstantLabel { int value; const char * label; };
-#define KLABEL(x) { x, #x }
-#define TLABEL(x, y) { x, y }
-#define LASTLABEL { 0, 0 }
-
-const char * FindLabel(int value, const ConstantLabel entries[]);
-std::string ErrorName(int err, const ConstantLabel* err_table);
-
-//////////////////////////////////////////////////////////////////////
-
-// Note that the non-standard LoggingSeverity aliases exist because they are
-// still in broad use. The meanings of the levels are:
-// LS_SENSITIVE: Information which should only be logged with the consent
-// of the user, due to privacy concerns.
-// LS_VERBOSE: This level is for data which we do not want to appear in the
-// normal debug log, but should appear in diagnostic logs.
-// LS_INFO: Chatty level used in debugging for all sorts of things, the default
-// in debug builds.
-// LS_WARNING: Something that may warrant investigation.
-// LS_ERROR: Something that should not have occurred.
-enum LoggingSeverity { LS_SENSITIVE, LS_VERBOSE, LS_INFO, LS_WARNING, LS_ERROR,
- INFO = LS_INFO,
- WARNING = LS_WARNING,
- LERROR = LS_ERROR };
-
-// LogErrorContext assists in interpreting the meaning of an error value.
-enum LogErrorContext {
- ERRCTX_NONE,
- ERRCTX_ERRNO, // System-local errno
- ERRCTX_HRESULT, // Windows HRESULT
- ERRCTX_OSSTATUS, // MacOS OSStatus
-
- // Abbreviations for LOG_E macro
- ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
- ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
- ERRCTX_OS = ERRCTX_OSSTATUS, // LOG_E(sev, OS, x)
-};
-
-class LogMessage {
- public:
- static const int NO_LOGGING;
- static const uint32 WARN_SLOW_LOGS_DELAY = 50; // ms
-
- LogMessage(const char* file, int line, LoggingSeverity sev,
- LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
- const char* module = NULL);
- ~LogMessage();
-
- static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
- std::ostream& stream() { return print_stream_; }
-
- // Returns the time at which this function was called for the first time.
- // The time will be used as the logging start time.
- // If this is not called externally, the LogMessage ctor also calls it, in
- // which case the logging start time will be the time of the first LogMessage
- // instance is created.
- static uint32 LogStartTime();
-
- // Returns the wall clock equivalent of |LogStartTime|, in seconds from the
- // epoch.
- static uint32 WallClockStartTime();
-
- // These are attributes which apply to all logging channels
- // LogContext: Display the file and line number of the message
- static void LogContext(int min_sev);
- // LogThreads: Display the thread identifier of the current thread
- static void LogThreads(bool on = true);
- // LogTimestamps: Display the elapsed time of the program
- static void LogTimestamps(bool on = true);
-
- // These are the available logging channels
- // Debug: Debug console on Windows, otherwise stderr
- static void LogToDebug(int min_sev);
- static int GetLogToDebug() { return dbg_sev_; }
-
- // Stream: Any non-blocking stream interface. LogMessage takes ownership of
- // the stream. Multiple streams may be specified by using AddLogToStream.
- // LogToStream is retained for backwards compatibility; when invoked, it
- // will discard any previously set streams and install the specified stream.
- // GetLogToStream gets the severity for the specified stream, of if none
- // is specified, the minimum stream severity.
- // RemoveLogToStream removes the specified stream, without destroying it.
- static void LogToStream(StreamInterface* stream, int min_sev);
- static int GetLogToStream(StreamInterface* stream = NULL);
- static void AddLogToStream(StreamInterface* stream, int min_sev);
- static void RemoveLogToStream(StreamInterface* stream);
-
- // Testing against MinLogSeverity allows code to avoid potentially expensive
- // logging operations by pre-checking the logging level.
- static int GetMinLogSeverity() { return min_sev_; }
-
- static void SetDiagnosticMode(bool f) { is_diagnostic_mode_ = f; }
- static bool IsDiagnosticMode() { return is_diagnostic_mode_; }
-
- // Parses the provided parameter stream to configure the options above.
- // Useful for configuring logging from the command line. If file logging
- // is enabled, it is output to the specified filename.
- static void ConfigureLogging(const char* params, const char* filename);
-
- // Convert the string to a LS_ value; also accept numeric values.
- static int ParseLogSeverity(const std::string& value);
-
- private:
- typedef std::list<std::pair<StreamInterface*, int> > StreamList;
-
- // Updates min_sev_ appropriately when debug sinks change.
- static void UpdateMinLogSeverity();
-
- // These assist in formatting some parts of the debug output.
- static const char* Describe(LoggingSeverity sev);
- static const char* DescribeFile(const char* file);
-
- // These write out the actual log messages.
- static void OutputToDebug(const std::string& msg, LoggingSeverity severity_);
- static void OutputToStream(StreamInterface* stream, const std::string& msg);
-
- // The ostream that buffers the formatted message before output
- std::ostringstream print_stream_;
-
- // The severity level of this message
- LoggingSeverity severity_;
-
- // String data generated in the constructor, that should be appended to
- // the message before output.
- std::string extra_;
-
- // If time it takes to write to stream is more than this, log one
- // additional warning about it.
- uint32 warn_slow_logs_delay_;
-
- // Global lock for the logging subsystem
- static CriticalSection crit_;
-
- // dbg_sev_ is the thresholds for those output targets
- // min_sev_ is the minimum (most verbose) of those levels, and is used
- // as a short-circuit in the logging macros to identify messages that won't
- // be logged.
- // ctx_sev_ is the minimum level at which file context is displayed
- static int min_sev_, dbg_sev_, ctx_sev_;
-
- // The output streams and their associated severities
- static StreamList streams_;
-
- // Flags for formatting options
- static bool thread_, timestamp_;
-
- // are we in diagnostic mode (as defined by the app)?
- static bool is_diagnostic_mode_;
-
- DISALLOW_EVIL_CONSTRUCTORS(LogMessage);
-};
-
-//////////////////////////////////////////////////////////////////////
-// Logging Helpers
-//////////////////////////////////////////////////////////////////////
-
-class LogMultilineState {
- public:
- size_t unprintable_count_[2];
- LogMultilineState() {
- unprintable_count_[0] = unprintable_count_[1] = 0;
- }
-};
-
-// When possible, pass optional state variable to track various data across
-// multiple calls to LogMultiline. Otherwise, pass NULL.
-void LogMultiline(LoggingSeverity level, const char* label, bool input,
- const void* data, size_t len, bool hex_mode,
- LogMultilineState* state);
-
-//////////////////////////////////////////////////////////////////////
-// Macros which automatically disable logging when LOGGING == 0
-//////////////////////////////////////////////////////////////////////
-
-// If LOGGING is not explicitly defined, default to enabled in debug mode
-#if !defined(LOGGING)
-#if defined(_DEBUG) && !defined(NDEBUG)
-#define LOGGING 1
-#else
-#define LOGGING 0
-#endif
-#endif // !defined(LOGGING)
-
-#ifndef LOG
-#if LOGGING
-
-// The following non-obvious technique for implementation of a
-// conditional log stream was stolen from google3/base/logging.h.
-
-// This class is used to explicitly ignore values in the conditional
-// logging macros. This avoids compiler warnings like "value computed
-// is not used" and "statement has no effect".
-
-class LogMessageVoidify {
- public:
- LogMessageVoidify() { }
- // This has to be an operator with a precedence lower than << but
- // higher than ?:
- void operator&(std::ostream&) { }
-};
-
-#define LOG_SEVERITY_PRECONDITION(sev) \
- !(talk_base::LogMessage::Loggable(sev)) \
- ? (void) 0 \
- : talk_base::LogMessageVoidify() &
-
-#define LOG(sev) \
- LOG_SEVERITY_PRECONDITION(talk_base::sev) \
- talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev).stream()
-
-// The _V version is for when a variable is passed in. It doesn't do the
-// namespace concatination.
-#define LOG_V(sev) \
- LOG_SEVERITY_PRECONDITION(sev) \
- talk_base::LogMessage(__FILE__, __LINE__, sev).stream()
-
-// The _F version prefixes the message with the current function name.
-#if (defined(__GNUC__) && defined(_DEBUG)) || defined(WANT_PRETTY_LOG_F)
-#define LOG_F(sev) LOG(sev) << __PRETTY_FUNCTION__ << ": "
-#define LOG_T_F(sev) LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
-#else
-#define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
-#define LOG_T_F(sev) LOG(sev) << this << ": " << __FUNCTION__ << ": "
-#endif
-
-#define LOG_CHECK_LEVEL(sev) \
- talk_base::LogCheckLevel(talk_base::sev)
-#define LOG_CHECK_LEVEL_V(sev) \
- talk_base::LogCheckLevel(sev)
-inline bool LogCheckLevel(LoggingSeverity sev) {
- return (LogMessage::GetMinLogSeverity() <= sev);
-}
-
-#define LOG_E(sev, ctx, err, ...) \
- LOG_SEVERITY_PRECONDITION(talk_base::sev) \
- talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev, \
- talk_base::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
- .stream()
-
-#define LOG_T(sev) LOG(sev) << this << ": "
-
-#else // !LOGGING
-
-// Hopefully, the compiler will optimize away some of this code.
-// Note: syntax of "1 ? (void)0 : LogMessage" was causing errors in g++,
-// converted to "while (false)"
-#define LOG(sev) \
- while (false)talk_base:: LogMessage(NULL, 0, talk_base::sev).stream()
-#define LOG_V(sev) \
- while (false) talk_base::LogMessage(NULL, 0, sev).stream()
-#define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
-#define LOG_CHECK_LEVEL(sev) \
- false
-#define LOG_CHECK_LEVEL_V(sev) \
- false
-
-#define LOG_E(sev, ctx, err, ...) \
- while (false) talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev, \
- talk_base::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
- .stream()
-
-#define LOG_T(sev) LOG(sev) << this << ": "
-#define LOG_T_F(sev) LOG(sev) << this << ": " << __FUNCTION__ <<
-#endif // !LOGGING
-
-#define LOG_ERRNO_EX(sev, err) \
- LOG_E(sev, ERRNO, err)
-#define LOG_ERRNO(sev) \
- LOG_ERRNO_EX(sev, errno)
-
-#ifdef WIN32
-#define LOG_GLE_EX(sev, err) \
- LOG_E(sev, HRESULT, err)
-#define LOG_GLE(sev) \
- LOG_GLE_EX(sev, GetLastError())
-#define LOG_GLEM(sev, mod) \
- LOG_E(sev, HRESULT, GetLastError(), mod)
-#define LOG_ERR_EX(sev, err) \
- LOG_GLE_EX(sev, err)
-#define LOG_ERR(sev) \
- LOG_GLE(sev)
-#define LAST_SYSTEM_ERROR \
- (::GetLastError())
-#elif __native_client__
-#define LOG_ERR_EX(sev, err) \
- LOG(sev)
-#define LOG_ERR(sev) \
- LOG(sev)
-#define LAST_SYSTEM_ERROR \
- (0)
-#elif POSIX
-#define LOG_ERR_EX(sev, err) \
- LOG_ERRNO_EX(sev, err)
-#define LOG_ERR(sev) \
- LOG_ERRNO(sev)
-#define LAST_SYSTEM_ERROR \
- (errno)
-#endif // WIN32
-
-#define PLOG(sev, err) \
- LOG_ERR_EX(sev, err)
-
-// TODO(?): Add an "assert" wrapper that logs in the same manner.
-
-#endif // LOG
-
-} // namespace talk_base
-
-#endif // TALK_BASE_LOGGING_H_
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc
deleted file mode 100644
index 53cab66..0000000
--- a/base/logging_unittest.cc
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-// Test basic logging operation. We should get the INFO log but not the VERBOSE.
-// We should restore the correct global state at the end.
-TEST(LogTest, SingleStream) {
- int sev = LogMessage::GetLogToStream(NULL);
-
- std::string str;
- StringStream stream(str);
- LogMessage::AddLogToStream(&stream, LS_INFO);
- EXPECT_EQ(LS_INFO, LogMessage::GetLogToStream(&stream));
-
- LOG(LS_INFO) << "INFO";
- LOG(LS_VERBOSE) << "VERBOSE";
- EXPECT_NE(std::string::npos, str.find("INFO"));
- EXPECT_EQ(std::string::npos, str.find("VERBOSE"));
-
- LogMessage::RemoveLogToStream(&stream);
- EXPECT_EQ(LogMessage::NO_LOGGING, LogMessage::GetLogToStream(&stream));
-
- EXPECT_EQ(sev, LogMessage::GetLogToStream(NULL));
-}
-
-// Test using multiple log streams. The INFO stream should get the INFO message,
-// the VERBOSE stream should get the INFO and the VERBOSE.
-// We should restore the correct global state at the end.
-TEST(LogTest, MultipleStreams) {
- int sev = LogMessage::GetLogToStream(NULL);
-
- std::string str1, str2;
- StringStream stream1(str1), stream2(str2);
- LogMessage::AddLogToStream(&stream1, LS_INFO);
- LogMessage::AddLogToStream(&stream2, LS_VERBOSE);
- EXPECT_EQ(LS_INFO, LogMessage::GetLogToStream(&stream1));
- EXPECT_EQ(LS_VERBOSE, LogMessage::GetLogToStream(&stream2));
-
- LOG(LS_INFO) << "INFO";
- LOG(LS_VERBOSE) << "VERBOSE";
-
- EXPECT_NE(std::string::npos, str1.find("INFO"));
- EXPECT_EQ(std::string::npos, str1.find("VERBOSE"));
- EXPECT_NE(std::string::npos, str2.find("INFO"));
- EXPECT_NE(std::string::npos, str2.find("VERBOSE"));
-
- LogMessage::RemoveLogToStream(&stream2);
- LogMessage::RemoveLogToStream(&stream1);
- EXPECT_EQ(LogMessage::NO_LOGGING, LogMessage::GetLogToStream(&stream2));
- EXPECT_EQ(LogMessage::NO_LOGGING, LogMessage::GetLogToStream(&stream1));
-
- EXPECT_EQ(sev, LogMessage::GetLogToStream(NULL));
-}
-
-// Ensure we don't crash when adding/removing streams while threads are going.
-// We should restore the correct global state at the end.
-class LogThread : public Thread {
- public:
- virtual ~LogThread() {
- Stop();
- }
-
- private:
- void Run() {
- // LS_SENSITIVE to avoid cluttering up any real logging going on
- LOG(LS_SENSITIVE) << "LOG";
- }
-};
-
-TEST(LogTest, MultipleThreads) {
- int sev = LogMessage::GetLogToStream(NULL);
-
- LogThread thread1, thread2, thread3;
- thread1.Start();
- thread2.Start();
- thread3.Start();
-
- NullStream stream1, stream2, stream3;
- for (int i = 0; i < 1000; ++i) {
- LogMessage::AddLogToStream(&stream1, LS_INFO);
- LogMessage::AddLogToStream(&stream2, LS_VERBOSE);
- LogMessage::AddLogToStream(&stream3, LS_SENSITIVE);
- LogMessage::RemoveLogToStream(&stream1);
- LogMessage::RemoveLogToStream(&stream2);
- LogMessage::RemoveLogToStream(&stream3);
- }
-
- EXPECT_EQ(sev, LogMessage::GetLogToStream(NULL));
-}
-
-
-TEST(LogTest, WallClockStartTime) {
- uint32 time = LogMessage::WallClockStartTime();
- // Expect the time to be in a sensible range, e.g. > 2012-01-01.
- EXPECT_GT(time, 1325376000u);
-}
-
-// Test the time required to write 1000 80-character logs to an unbuffered file.
-TEST(LogTest, Perf) {
- Pathname path;
- EXPECT_TRUE(Filesystem::GetTemporaryFolder(path, true, NULL));
- path.SetPathname(Filesystem::TempFilename(path, "ut"));
-
- FileStream stream;
- EXPECT_TRUE(stream.Open(path.pathname(), "wb", NULL));
- stream.DisableBuffering();
- LogMessage::AddLogToStream(&stream, LS_SENSITIVE);
-
- uint32 start = Time(), finish;
- std::string message('X', 80);
- for (int i = 0; i < 1000; ++i) {
- LOG(LS_SENSITIVE) << message;
- }
- finish = Time();
-
- LogMessage::RemoveLogToStream(&stream);
- stream.Close();
- Filesystem::DeleteFile(path);
-
- LOG(LS_INFO) << "Average log time: " << TimeDiff(finish, start) << " us";
-}
-
-} // namespace talk_base
diff --git a/base/macasyncsocket.cc b/base/macasyncsocket.cc
deleted file mode 100644
index 7841b4b..0000000
--- a/base/macasyncsocket.cc
+++ /dev/null
@@ -1,471 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved.
-
-// thaloun@google.com (Tim Haloun)
-//
-// MacAsyncSocket is a kind of AsyncSocket. It does not support the SOCK_DGRAM
-// type (yet). It works asynchronously, which means that users of this socket
-// should connect to the various events declared in asyncsocket.h to receive
-// notifications about this socket. It uses CFSockets for signals, but prefers
-// the basic bsd socket operations rather than their CFSocket wrappers when
-// possible.
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <fcntl.h>
-
-#include "talk/base/macasyncsocket.h"
-
-#include "talk/base/logging.h"
-#include "talk/base/macsocketserver.h"
-
-namespace talk_base {
-
-static const int kCallbackFlags = kCFSocketReadCallBack |
- kCFSocketConnectCallBack |
- kCFSocketWriteCallBack;
-
-MacAsyncSocket::MacAsyncSocket(MacBaseSocketServer* ss, int family)
- : ss_(ss),
- socket_(NULL),
- native_socket_(INVALID_SOCKET),
- source_(NULL),
- current_callbacks_(0),
- disabled_(false),
- error_(0),
- state_(CS_CLOSED),
- resolver_(NULL) {
- Initialize(family);
-}
-
-MacAsyncSocket::~MacAsyncSocket() {
- Close();
-}
-
-// Returns the address to which the socket is bound. If the socket is not
-// bound, then the any-address is returned.
-SocketAddress MacAsyncSocket::GetLocalAddress() const {
- SocketAddress address;
-
- // The CFSocket doesn't pick up on implicit binds from the connect call.
- // Calling bind in before connect explicitly causes errors, so just query
- // the underlying bsd socket.
- sockaddr_storage addr;
- socklen_t addrlen = sizeof(addr);
- int result = ::getsockname(native_socket_,
- reinterpret_cast<sockaddr*>(&addr), &addrlen);
- if (result >= 0) {
- SocketAddressFromSockAddrStorage(addr, &address);
- }
- return address;
-}
-
-// Returns the address to which the socket is connected. If the socket is not
-// connected, then the any-address is returned.
-SocketAddress MacAsyncSocket::GetRemoteAddress() const {
- SocketAddress address;
-
- // Use native_socket for consistency with GetLocalAddress.
- sockaddr_storage addr;
- socklen_t addrlen = sizeof(addr);
- int result = ::getpeername(native_socket_,
- reinterpret_cast<sockaddr*>(&addr), &addrlen);
- if (result >= 0) {
- SocketAddressFromSockAddrStorage(addr, &address);
- }
- return address;
-}
-
-// Bind the socket to a local address.
-int MacAsyncSocket::Bind(const SocketAddress& address) {
- sockaddr_storage saddr = {0};
- size_t len = address.ToSockAddrStorage(&saddr);
- int err = ::bind(native_socket_, reinterpret_cast<sockaddr*>(&saddr), len);
- if (err == SOCKET_ERROR) error_ = errno;
- return err;
-}
-
-void MacAsyncSocket::OnResolveResult(SignalThread* thread) {
- if (thread != resolver_) {
- return;
- }
- int error = resolver_->GetError();
- if (error == 0) {
- error = DoConnect(resolver_->address());
- } else {
- Close();
- }
- if (error) {
- error_ = error;
- SignalCloseEvent(this, error_);
- }
-}
-
-// Connect to a remote address.
-int MacAsyncSocket::Connect(const SocketAddress& addr) {
- // TODO(djw): Consolidate all the connect->resolve->doconnect implementations.
- if (state_ != CS_CLOSED) {
- SetError(EALREADY);
- return SOCKET_ERROR;
- }
- if (addr.IsUnresolved()) {
- LOG(LS_VERBOSE) << "Resolving addr in MacAsyncSocket::Connect";
- resolver_ = new AsyncResolver();
- resolver_->SignalWorkDone.connect(this,
- &MacAsyncSocket::OnResolveResult);
- resolver_->Start(addr);
- state_ = CS_CONNECTING;
- return 0;
- }
- return DoConnect(addr);
-}
-
-int MacAsyncSocket::DoConnect(const SocketAddress& addr) {
- if (!valid()) {
- Initialize(addr.family());
- if (!valid())
- return SOCKET_ERROR;
- }
-
- sockaddr_storage saddr;
- size_t len = addr.ToSockAddrStorage(&saddr);
- int result = ::connect(native_socket_, reinterpret_cast<sockaddr*>(&saddr),
- len);
-
- if (result != SOCKET_ERROR) {
- state_ = CS_CONNECTED;
- } else {
- error_ = errno;
- if (error_ == EINPROGRESS) {
- state_ = CS_CONNECTING;
- result = 0;
- }
- }
- return result;
-}
-
-// Send to the remote end we're connected to.
-int MacAsyncSocket::Send(const void* buffer, size_t length) {
- if (!valid()) {
- return SOCKET_ERROR;
- }
-
- int sent = ::send(native_socket_, buffer, length, 0);
-
- if (sent == SOCKET_ERROR) {
- error_ = errno;
-
- if (IsBlocking()) {
- // Reenable the writable callback (once), since we are flow controlled.
- CFSocketEnableCallBacks(socket_, kCallbackFlags);
- current_callbacks_ = kCallbackFlags;
- }
- }
- return sent;
-}
-
-// Send to the given address. We may or may not be connected to anyone.
-int MacAsyncSocket::SendTo(const void* buffer, size_t length,
- const SocketAddress& address) {
- if (!valid()) {
- return SOCKET_ERROR;
- }
-
- sockaddr_storage saddr;
- size_t len = address.ToSockAddrStorage(&saddr);
- int sent = ::sendto(native_socket_, buffer, length, 0,
- reinterpret_cast<sockaddr*>(&saddr), len);
-
- if (sent == SOCKET_ERROR) {
- error_ = errno;
- }
-
- return sent;
-}
-
-// Read data received from the remote end we're connected to.
-int MacAsyncSocket::Recv(void* buffer, size_t length) {
- int received = ::recv(native_socket_, reinterpret_cast<char*>(buffer),
- length, 0);
- if (received == SOCKET_ERROR) error_ = errno;
-
- // Recv should only be called when there is data to read
- ASSERT((received != 0) || (length == 0));
- return received;
-}
-
-// Read data received from any remote party
-int MacAsyncSocket::RecvFrom(void* buffer, size_t length,
- SocketAddress* out_addr) {
- sockaddr_storage saddr;
- socklen_t addr_len = sizeof(saddr);
- int received = ::recvfrom(native_socket_, reinterpret_cast<char*>(buffer),
- length, 0, reinterpret_cast<sockaddr*>(&saddr),
- &addr_len);
- if (received >= 0 && out_addr != NULL) {
- SocketAddressFromSockAddrStorage(saddr, out_addr);
- } else if (received == SOCKET_ERROR) {
- error_ = errno;
- }
- return received;
-}
-
-int MacAsyncSocket::Listen(int backlog) {
- if (!valid()) {
- return SOCKET_ERROR;
- }
-
- int res = ::listen(native_socket_, backlog);
- if (res != SOCKET_ERROR)
- state_ = CS_CONNECTING;
- else
- error_ = errno;
-
- return res;
-}
-
-MacAsyncSocket* MacAsyncSocket::Accept(SocketAddress* out_addr) {
- sockaddr_storage saddr;
- socklen_t addr_len = sizeof(saddr);
-
- int socket_fd = ::accept(native_socket_, reinterpret_cast<sockaddr*>(&saddr),
- &addr_len);
- if (socket_fd == INVALID_SOCKET) {
- error_ = errno;
- return NULL;
- }
-
- MacAsyncSocket* s = new MacAsyncSocket(ss_, saddr.ss_family, socket_fd);
- if (s && s->valid()) {
- s->state_ = CS_CONNECTED;
- if (out_addr)
- SocketAddressFromSockAddrStorage(saddr, out_addr);
- } else {
- delete s;
- s = NULL;
- }
- return s;
-}
-
-int MacAsyncSocket::Close() {
- if (source_ != NULL) {
- CFRunLoopSourceInvalidate(source_);
- CFRelease(source_);
- if (ss_) ss_->UnregisterSocket(this);
- source_ = NULL;
- }
-
- if (socket_ != NULL) {
- CFSocketInvalidate(socket_);
- CFRelease(socket_);
- socket_ = NULL;
- }
-
- if (resolver_) {
- resolver_->Destroy(false);
- resolver_ = NULL;
- }
-
- native_socket_ = INVALID_SOCKET; // invalidates the socket
- error_ = 0;
- state_ = CS_CLOSED;
- return 0;
-}
-
-int MacAsyncSocket::EstimateMTU(uint16* mtu) {
- ASSERT(false && "NYI");
- return -1;
-}
-
-int MacAsyncSocket::GetError() const {
- return error_;
-}
-
-void MacAsyncSocket::SetError(int error) {
- error_ = error;
-}
-
-Socket::ConnState MacAsyncSocket::GetState() const {
- return state_;
-}
-
-int MacAsyncSocket::GetOption(Option opt, int* value) {
- ASSERT(false && "NYI");
- return -1;
-}
-
-int MacAsyncSocket::SetOption(Option opt, int value) {
- ASSERT(false && "NYI");
- return -1;
-}
-
-void MacAsyncSocket::EnableCallbacks() {
- if (valid()) {
- disabled_ = false;
- CFSocketEnableCallBacks(socket_, current_callbacks_);
- }
-}
-
-void MacAsyncSocket::DisableCallbacks() {
- if (valid()) {
- disabled_ = true;
- CFSocketDisableCallBacks(socket_, kCallbackFlags);
- }
-}
-
-MacAsyncSocket::MacAsyncSocket(MacBaseSocketServer* ss, int family,
- int native_socket)
- : ss_(ss),
- socket_(NULL),
- native_socket_(native_socket),
- source_(NULL),
- current_callbacks_(0),
- disabled_(false),
- error_(0),
- state_(CS_CLOSED),
- resolver_(NULL) {
- Initialize(family);
-}
-
-// Create a new socket, wrapping the native socket if provided or creating one
-// otherwise. In case of any failure, consume the native socket. We assume the
-// wrapped socket is in the closed state. If this is not the case you must
-// update the state_ field for this socket yourself.
-void MacAsyncSocket::Initialize(int family) {
- CFSocketContext ctx = { 0 };
- ctx.info = this;
-
- // First create the CFSocket
- CFSocketRef cf_socket = NULL;
- bool res = false;
- if (native_socket_ == INVALID_SOCKET) {
- cf_socket = CFSocketCreate(kCFAllocatorDefault,
- family, SOCK_STREAM, IPPROTO_TCP,
- kCallbackFlags, MacAsyncSocketCallBack, &ctx);
- } else {
- cf_socket = CFSocketCreateWithNative(kCFAllocatorDefault,
- native_socket_, kCallbackFlags,
- MacAsyncSocketCallBack, &ctx);
- }
-
- if (cf_socket) {
- res = true;
- socket_ = cf_socket;
- native_socket_ = CFSocketGetNative(cf_socket);
- current_callbacks_ = kCallbackFlags;
- }
-
- if (res) {
- // Make the underlying socket asynchronous
- res = (-1 != ::fcntl(native_socket_, F_SETFL,
- ::fcntl(native_socket_, F_GETFL, 0) | O_NONBLOCK));
- }
-
- if (res) {
- // Add this socket to the run loop, at priority 1 so that it will be
- // queued behind any pending signals.
- source_ = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 1);
- res = (source_ != NULL);
- if (!res) errno = EINVAL;
- }
-
- if (res) {
- if (ss_) ss_->RegisterSocket(this);
- CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopCommonModes);
- }
-
- if (!res) {
- int error = errno;
- Close(); // Clears error_.
- error_ = error;
- }
-}
-
-// Call CFRelease on the result when done using it
-CFDataRef MacAsyncSocket::CopyCFAddress(const SocketAddress& address) {
- sockaddr_storage saddr;
- size_t len = address.ToSockAddrStorage(&saddr);
-
- const UInt8* bytes = reinterpret_cast<UInt8*>(&saddr);
-
- CFDataRef cf_address = CFDataCreate(kCFAllocatorDefault,
- bytes, len);
-
- ASSERT(cf_address != NULL);
- return cf_address;
-}
-
-void MacAsyncSocket::MacAsyncSocketCallBack(CFSocketRef s,
- CFSocketCallBackType callbackType,
- CFDataRef address,
- const void* data,
- void* info) {
- MacAsyncSocket* this_socket =
- reinterpret_cast<MacAsyncSocket*>(info);
- ASSERT(this_socket != NULL && this_socket->socket_ == s);
-
- // Don't signal any socket messages if the socketserver is not listening on
- // them. When we are reenabled they will be requeued and will fire again.
- if (this_socket->disabled_)
- return;
-
- switch (callbackType) {
- case kCFSocketReadCallBack:
- // This callback is invoked in one of 3 situations:
- // 1. A new connection is waiting to be accepted.
- // 2. The remote end closed the connection (a recv will return 0).
- // 3. Data is available to read.
- // 4. The connection closed unhappily (recv will return -1).
- if (this_socket->state_ == CS_CONNECTING) {
- // Case 1.
- this_socket->SignalReadEvent(this_socket);
- } else {
- char ch, amt;
- amt = ::recv(this_socket->native_socket_, &ch, 1, MSG_PEEK);
- if (amt == 0) {
- // Case 2.
- this_socket->state_ = CS_CLOSED;
-
- // Disable additional callbacks or we will signal close twice.
- CFSocketDisableCallBacks(this_socket->socket_, kCFSocketReadCallBack);
- this_socket->current_callbacks_ &= ~kCFSocketReadCallBack;
- this_socket->SignalCloseEvent(this_socket, 0);
- } else if (amt > 0) {
- // Case 3.
- this_socket->SignalReadEvent(this_socket);
- } else {
- // Case 4.
- int error = errno;
- if (error == EAGAIN) {
- // Observed in practice. Let's hope it's a spurious or out of date
- // signal, since we just eat it.
- } else {
- this_socket->error_ = error;
- this_socket->SignalCloseEvent(this_socket, error);
- }
- }
- }
- break;
-
- case kCFSocketConnectCallBack:
- if (data != NULL) {
- // An error occured in the background while connecting
- this_socket->error_ = errno;
- this_socket->state_ = CS_CLOSED;
- this_socket->SignalCloseEvent(this_socket, this_socket->error_);
- } else {
- this_socket->state_ = CS_CONNECTED;
- this_socket->SignalConnectEvent(this_socket);
- }
- break;
-
- case kCFSocketWriteCallBack:
- // Update our callback tracking. Write doesn't reenable, so it's off now.
- this_socket->current_callbacks_ &= ~kCFSocketWriteCallBack;
- this_socket->SignalWriteEvent(this_socket);
- break;
-
- default:
- ASSERT(false && "Invalid callback type for socket");
- }
-}
-
-} // namespace talk_base
diff --git a/base/macasyncsocket.h b/base/macasyncsocket.h
deleted file mode 100644
index 12d2add..0000000
--- a/base/macasyncsocket.h
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright 2008 Google Inc. All Rights Reserved.
-
-//
-// MacAsyncSocket is a kind of AsyncSocket. It only creates sockets
-// of the TCP type, and does not (yet) support listen and accept. It works
-// asynchronously, which means that users of this socket should connect to
-// the various events declared in asyncsocket.h to receive notifications about
-// this socket.
-
-#ifndef TALK_BASE_MACASYNCSOCKET_H__
-#define TALK_BASE_MACASYNCSOCKET_H__
-
-#include <CoreFoundation/CoreFoundation.h>
-
-#include "talk/base/asyncsocket.h"
-#include "talk/base/nethelpers.h"
-
-namespace talk_base {
-
-class MacBaseSocketServer;
-
-class MacAsyncSocket : public AsyncSocket, public sigslot::has_slots<> {
- public:
- MacAsyncSocket(MacBaseSocketServer* ss, int family);
- virtual ~MacAsyncSocket();
-
- bool valid() const { return source_ != NULL; }
-
- // Socket interface
- virtual SocketAddress GetLocalAddress() const;
- virtual SocketAddress GetRemoteAddress() const;
- virtual int Bind(const SocketAddress& addr);
- virtual int Connect(const SocketAddress& addr);
- virtual int Send(const void* buffer, size_t length);
- virtual int SendTo(const void* buffer, size_t length,
- const SocketAddress& addr);
- virtual int Recv(void* buffer, size_t length);
- virtual int RecvFrom(void* buffer, size_t length, SocketAddress* out_addr);
- virtual int Listen(int backlog);
- virtual MacAsyncSocket* Accept(SocketAddress* out_addr);
- virtual int Close();
- virtual int GetError() const;
- virtual void SetError(int error);
- virtual ConnState GetState() const;
- virtual int EstimateMTU(uint16* mtu);
- virtual int GetOption(Option opt, int* value);
- virtual int SetOption(Option opt, int value);
-
- // For the MacBaseSocketServer to disable callbacks when process_io is false.
- void EnableCallbacks();
- void DisableCallbacks();
-
- protected:
- void OnResolveResult(SignalThread* thread);
- int DoConnect(const SocketAddress& addr);
-
- private:
- // Creates an async socket from an existing bsd socket
- MacAsyncSocket(MacBaseSocketServer* ss, int family, int native_socket);
-
- // Attaches the socket to the CFRunloop and sets the wrapped bsd socket
- // to async mode
- void Initialize(int family);
-
- // Translate the SocketAddress into a CFDataRef to pass to CF socket
- // functions. Caller must call CFRelease on the result when done.
- static CFDataRef CopyCFAddress(const SocketAddress& address);
-
- // Callback for the underlying CFSocketRef.
- static void MacAsyncSocketCallBack(CFSocketRef s,
- CFSocketCallBackType callbackType,
- CFDataRef address,
- const void* data,
- void* info);
-
- MacBaseSocketServer* ss_;
- CFSocketRef socket_;
- int native_socket_;
- CFRunLoopSourceRef source_;
- int current_callbacks_;
- bool disabled_;
- int error_;
- ConnState state_;
- AsyncResolver* resolver_;
-
- DISALLOW_EVIL_CONSTRUCTORS(MacAsyncSocket);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MACASYNCSOCKET_H__
diff --git a/base/maccocoasocketserver.h b/base/maccocoasocketserver.h
deleted file mode 100644
index 51dc749..0000000
--- a/base/maccocoasocketserver.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * libjingle
- * Copyright 2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// A libjingle compatible SocketServer for OSX/iOS/Cocoa.
-
-#ifndef TALK_BASE_MACCOCOASOCKETSERVER_H_
-#define TALK_BASE_MACCOCOASOCKETSERVER_H_
-
-#include "talk/base/macsocketserver.h"
-
-#ifdef __OBJC__
-@class NSTimer, MacCocoaSocketServerHelper;
-#else
-class NSTimer;
-class MacCocoaSocketServerHelper;
-#endif
-
-namespace talk_base {
-
-// A socketserver implementation that wraps the main cocoa
-// application loop accessed through [NSApp run].
-class MacCocoaSocketServer : public MacBaseSocketServer {
- public:
- explicit MacCocoaSocketServer();
- virtual ~MacCocoaSocketServer();
-
- virtual bool Wait(int cms, bool process_io);
- virtual void WakeUp();
-
- private:
- MacCocoaSocketServerHelper* helper_;
- NSTimer* timer_; // Weak.
- // The count of how many times we're inside the NSApplication main loop.
- int run_count_;
-
- DISALLOW_EVIL_CONSTRUCTORS(MacCocoaSocketServer);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MACCOCOASOCKETSERVER_H_
diff --git a/base/maccocoasocketserver.mm b/base/maccocoasocketserver.mm
deleted file mode 100644
index 8257e38..0000000
--- a/base/maccocoasocketserver.mm
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#import "talk/base/maccocoasocketserver.h"
-
-#import <Foundation/Foundation.h>
-#import <AppKit/AppKit.h>
-#include <assert.h>
-
-#include "talk/base/scoped_autorelease_pool.h"
-
-// MacCocoaSocketServerHelper serves as a delegate to NSMachPort or a target for
-// a timeout.
-@interface MacCocoaSocketServerHelper : NSObject {
- // This is a weak reference. This works fine since the
- // talk_base::MacCocoaSocketServer owns this object.
- talk_base::MacCocoaSocketServer* socketServer_; // Weak.
-}
-@end
-
-@implementation MacCocoaSocketServerHelper
-- (id)initWithSocketServer:(talk_base::MacCocoaSocketServer*)ss {
- self = [super init];
- if (self) {
- socketServer_ = ss;
- }
- return self;
-}
-
-- (void)timerFired:(NSTimer*)timer {
- socketServer_->WakeUp();
-}
-
-- (void)breakMainloop {
- [NSApp stop:self];
- // NSApp stop only exits after finishing processing of the
- // current event. Since we're potentially in a timer callback
- // and not an NSEvent handler, we need to trigger a dummy one
- // and turn the loop over. We may be able to skip this if we're
- // on the ss' thread and not inside the app loop already.
- NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
- location:NSMakePoint(0,0)
- modifierFlags:0
- timestamp:0
- windowNumber:0
- context:nil
- subtype:0
- data1:0
- data2:0];
- [NSApp postEvent:event atStart:NO];
-}
-@end
-
-namespace talk_base {
-
-MacCocoaSocketServer::MacCocoaSocketServer() {
- helper_ = [[MacCocoaSocketServerHelper alloc] initWithSocketServer:this];
- timer_ = nil;
- run_count_ = 0;
-
- // Initialize the shared NSApplication
- [NSApplication sharedApplication];
-}
-
-MacCocoaSocketServer::~MacCocoaSocketServer() {
- [timer_ invalidate];
- [timer_ release];
- [helper_ release];
-}
-
-// ::Wait is reentrant, for example when blocking on another thread while
-// responding to I/O. Calls to [NSApp] MUST be made from the main thread
-// only!
-bool MacCocoaSocketServer::Wait(int cms, bool process_io) {
- talk_base::ScopedAutoreleasePool pool;
- if (!process_io && cms == 0) {
- // No op.
- return true;
- }
- if ([NSApp isRunning]) {
- // Only allow reentrant waiting if we're in a blocking send.
- ASSERT(!process_io && cms == kForever);
- }
-
- if (!process_io) {
- // No way to listen to common modes and not get socket events, unless
- // we disable each one's callbacks.
- EnableSocketCallbacks(false);
- }
-
- if (kForever != cms) {
- // Install a timer that fires wakeup after cms has elapsed.
- timer_ =
- [NSTimer scheduledTimerWithTimeInterval:cms / 1000.0
- target:helper_
- selector:@selector(timerFired:)
- userInfo:nil
- repeats:NO];
- [timer_ retain];
- }
-
- // Run until WakeUp is called, which will call stop and exit this loop.
- run_count_++;
- [NSApp run];
- run_count_--;
-
- if (!process_io) {
- // Reenable them. Hopefully this won't cause spurious callbacks or
- // missing ones while they were disabled.
- EnableSocketCallbacks(true);
- }
-
- return true;
-}
-
-// Can be called from any thread. Post a message back to the main thread to
-// break out of the NSApp loop.
-void MacCocoaSocketServer::WakeUp() {
- if (timer_ != nil) {
- [timer_ invalidate];
- [timer_ release];
- timer_ = nil;
- }
-
- // [NSApp isRunning] returns unexpected results when called from another
- // thread. Maintain our own count of how many times to break the main loop.
- if (run_count_ > 0) {
- [helper_ performSelectorOnMainThread:@selector(breakMainloop)
- withObject:nil
- waitUntilDone:false];
- }
-}
-
-} // namespace talk_base
diff --git a/base/maccocoasocketserver_unittest.mm b/base/maccocoasocketserver_unittest.mm
deleted file mode 100644
index 818c30d..0000000
--- a/base/maccocoasocketserver_unittest.mm
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
-#include "talk/base/maccocoasocketserver.h"
-
-namespace talk_base {
-
-class WakeThread : public Thread {
- public:
- WakeThread(SocketServer* ss) : ss_(ss) {
- }
- virtual ~WakeThread() {
- Stop();
- }
- void Run() {
- ss_->WakeUp();
- }
- private:
- SocketServer* ss_;
-};
-
-// Test that MacCocoaSocketServer::Wait works as expected.
-TEST(MacCocoaSocketServer, TestWait) {
- MacCocoaSocketServer server;
- uint32 start = Time();
- server.Wait(1000, true);
- EXPECT_GE(TimeSince(start), 1000);
-}
-
-// Test that MacCocoaSocketServer::Wakeup works as expected.
-TEST(MacCocoaSocketServer, TestWakeup) {
- MacCFSocketServer server;
- WakeThread thread(&server);
- uint32 start = Time();
- thread.Start();
- server.Wait(10000, true);
- EXPECT_LT(TimeSince(start), 10000);
-}
-
-} // namespace talk_base
diff --git a/base/maccocoathreadhelper.h b/base/maccocoathreadhelper.h
deleted file mode 100644
index 336e638..0000000
--- a/base/maccocoathreadhelper.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * libjingle
- * Copyright 2008 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Helper function for using Cocoa with Posix threads. This header should be
-// included from C/C++ files that want to use some Cocoa functionality without
-// using the .mm extension (mostly for files that are compiled on multiple
-// platforms).
-
-#ifndef TALK_BASE_MACCOCOATHREADHELPER_H__
-#define TALK_BASE_MACCOCOATHREADHELPER_H__
-
-namespace talk_base {
-
-// Cocoa must be "put into multithreading mode" before Cocoa functionality can
-// be used on POSIX threads. This function does that.
-void InitCocoaMultiThreading();
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MACCOCOATHREADHELPER_H__
diff --git a/base/maccocoathreadhelper.mm b/base/maccocoathreadhelper.mm
deleted file mode 100644
index fee3972..0000000
--- a/base/maccocoathreadhelper.mm
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * libjingle
- * Copyright 2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-// Helper function for using Cocoa with Posix threading.
-
-#import <assert.h>
-#import <Foundation/Foundation.h>
-
-#import "talk/base/maccocoathreadhelper.h"
-
-namespace talk_base {
-
-// Cocoa must be "put into multithreading mode" before Cocoa functionality can
-// be used on POSIX threads. The way to do that is to spawn one thread that may
-// immediately exit.
-void InitCocoaMultiThreading() {
- if ([NSThread isMultiThreaded] == NO) {
- // The sole purpose of this autorelease pool is to avoid a console
- // message on Leopard that tells us we're autoreleasing the thread
- // with no autorelease pool in place; we can't set up an autorelease
- // pool before this, because this is executed from an initializer,
- // which is run before main. This means we leak an autorelease pool,
- // and one thread, and if other objects are set up in initializers after
- // this they'll be silently added to this pool and never released.
-
- // Doing NSAutoreleasePool* hack = [[NSAutoreleasePool alloc] init];
- // causes unused variable error.
- NSAutoreleasePool* hack;
- hack = [[NSAutoreleasePool alloc] init];
- [NSThread detachNewThreadSelector:@selector(class)
- toTarget:[NSObject class]
- withObject:nil];
- }
-
- assert([NSThread isMultiThreaded]);
-}
-
-} // namespace talk_base
diff --git a/base/macconversion.cc b/base/macconversion.cc
deleted file mode 100644
index 4654e53..0000000
--- a/base/macconversion.cc
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef OSX
-
-#include <CoreFoundation/CoreFoundation.h>
-
-#include "talk/base/logging.h"
-#include "talk/base/macconversion.h"
-
-bool p_convertHostCFStringRefToCPPString(
- const CFStringRef cfstr, std::string& cppstr) {
- bool result = false;
-
- // First this must be non-null,
- if (NULL != cfstr) {
- // it must actually *be* a CFString, and not something just masquerading
- // as one,
- if (CFGetTypeID(cfstr) == CFStringGetTypeID()) {
- // and we must be able to get the characters out of it.
- // (The cfstr owns this buffer; it came from somewhere else,
- // so someone else gets to take care of getting rid of the cfstr,
- // and then this buffer will go away automatically.)
- unsigned length = CFStringGetLength(cfstr);
- char* buf = new char[1 + length];
- if (CFStringGetCString(cfstr, buf, 1 + length, kCFStringEncodingASCII)) {
- if (strlen(buf) == length) {
- cppstr.assign(buf);
- result = true;
- }
- }
- delete [] buf;
- }
- }
-
- return result;
-}
-
-bool p_convertCFNumberToInt(CFNumberRef cfn, int* i) {
- bool converted = false;
-
- // It must not be null.
- if (NULL != cfn) {
- // It must actually *be* a CFNumber and not something just masquerading
- // as one.
- if (CFGetTypeID(cfn) == CFNumberGetTypeID()) {
- CFNumberType ntype = CFNumberGetType(cfn);
- switch (ntype) {
- case kCFNumberSInt8Type:
- SInt8 sint8;
- converted = CFNumberGetValue(cfn, ntype, static_cast<void*>(&sint8));
- if (converted) *i = static_cast<int>(sint8);
- break;
- case kCFNumberSInt16Type:
- SInt16 sint16;
- converted = CFNumberGetValue(cfn, ntype, static_cast<void*>(&sint16));
- if (converted) *i = static_cast<int>(sint16);
- break;
- case kCFNumberSInt32Type:
- SInt32 sint32;
- converted = CFNumberGetValue(cfn, ntype, static_cast<void*>(&sint32));
- if (converted) *i = static_cast<int>(sint32);
- break;
- case kCFNumberSInt64Type:
- SInt64 sint64;
- converted = CFNumberGetValue(cfn, ntype, static_cast<void*>(&sint64));
- if (converted) *i = static_cast<int>(sint64);
- break;
- case kCFNumberFloat32Type:
- Float32 float32;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&float32));
- if (converted) *i = static_cast<int>(float32);
- break;
- case kCFNumberFloat64Type:
- Float64 float64;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&float64));
- if (converted) *i = static_cast<int>(float64);
- break;
- case kCFNumberCharType:
- char charvalue;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&charvalue));
- if (converted) *i = static_cast<int>(charvalue);
- break;
- case kCFNumberShortType:
- short shortvalue;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&shortvalue));
- if (converted) *i = static_cast<int>(shortvalue);
- break;
- case kCFNumberIntType:
- int intvalue;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&intvalue));
- if (converted) *i = static_cast<int>(intvalue);
- break;
- case kCFNumberLongType:
- long longvalue;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&longvalue));
- if (converted) *i = static_cast<int>(longvalue);
- break;
- case kCFNumberLongLongType:
- long long llvalue;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&llvalue));
- if (converted) *i = static_cast<int>(llvalue);
- break;
- case kCFNumberFloatType:
- float floatvalue;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&floatvalue));
- if (converted) *i = static_cast<int>(floatvalue);
- break;
- case kCFNumberDoubleType:
- double doublevalue;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&doublevalue));
- if (converted) *i = static_cast<int>(doublevalue);
- break;
- case kCFNumberCFIndexType:
- CFIndex cfindex;
- converted = CFNumberGetValue(cfn, ntype,
- static_cast<void*>(&cfindex));
- if (converted) *i = static_cast<int>(cfindex);
- break;
- default:
- LOG(LS_ERROR) << "got unknown type.";
- break;
- }
- }
- }
-
- return converted;
-}
-
-bool p_isCFNumberTrue(CFNumberRef cfn) {
- // We assume it's false until proven otherwise.
- bool result = false;
- int asInt;
- bool converted = p_convertCFNumberToInt(cfn, &asInt);
-
- if (converted && (0 != asInt)) {
- result = true;
- }
-
- return result;
-}
-
-#endif // OSX
diff --git a/base/macconversion.h b/base/macconversion.h
deleted file mode 100644
index a401cab..0000000
--- a/base/macconversion.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_MACCONVERSION_H_
-#define TALK_BASE_MACCONVERSION_H_
-
-#ifdef OSX
-
-#include <CoreFoundation/CoreFoundation.h>
-
-#include <string>
-
-// given a CFStringRef, attempt to convert it to a C++ string.
-// returns true if it succeeds, false otherwise.
-// We can safely assume, given our context, that the string is
-// going to be in ASCII, because it will either be an IP address,
-// or a domain name, which is guaranteed to be ASCII-representable.
-bool p_convertHostCFStringRefToCPPString(const CFStringRef cfstr,
- std::string& cppstr);
-
-// Convert the CFNumber to an integer, putting the integer in the location
-// given, and returhing true, if the conversion succeeds.
-// If given a NULL or a non-CFNumber, returns false.
-// This is pretty aggresive about trying to convert to int.
-bool p_convertCFNumberToInt(CFNumberRef cfn, int* i);
-
-// given a CFNumberRef, determine if it represents a true value.
-bool p_isCFNumberTrue(CFNumberRef cfn);
-
-#endif // OSX
-
-#endif // TALK_BASE_MACCONVERSION_H_
diff --git a/base/macsocketserver.cc b/base/macsocketserver.cc
deleted file mode 100644
index 895b0bf..0000000
--- a/base/macsocketserver.cc
+++ /dev/null
@@ -1,369 +0,0 @@
-
-
-#include "talk/base/macsocketserver.h"
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/macasyncsocket.h"
-#include "talk/base/macutils.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// MacBaseSocketServer
-///////////////////////////////////////////////////////////////////////////////
-
-MacBaseSocketServer::MacBaseSocketServer() {
-}
-
-MacBaseSocketServer::~MacBaseSocketServer() {
-}
-
-AsyncSocket* MacBaseSocketServer::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* MacBaseSocketServer::CreateAsyncSocket(int family, int type) {
- if (SOCK_STREAM != type)
- return NULL;
-
- MacAsyncSocket* socket = new MacAsyncSocket(this, family);
- if (!socket->valid()) {
- delete socket;
- return NULL;
- }
- return socket;
-}
-
-void MacBaseSocketServer::RegisterSocket(MacAsyncSocket* s) {
- sockets_.insert(s);
-}
-
-void MacBaseSocketServer::UnregisterSocket(MacAsyncSocket* s) {
- VERIFY(1 == sockets_.erase(s)); // found 1
-}
-
-bool MacBaseSocketServer::SetPosixSignalHandler(int signum,
- void (*handler)(int)) {
- Dispatcher* dispatcher = signal_dispatcher();
- if (!PhysicalSocketServer::SetPosixSignalHandler(signum, handler)) {
- return false;
- }
-
- // Only register the FD once, when the first custom handler is installed.
- if (!dispatcher && (dispatcher = signal_dispatcher())) {
- CFFileDescriptorContext ctx = { 0 };
- ctx.info = this;
-
- CFFileDescriptorRef desc = CFFileDescriptorCreate(
- kCFAllocatorDefault,
- dispatcher->GetDescriptor(),
- false,
- &MacBaseSocketServer::FileDescriptorCallback,
- &ctx);
- if (!desc) {
- return false;
- }
-
- CFFileDescriptorEnableCallBacks(desc, kCFFileDescriptorReadCallBack);
- CFRunLoopSourceRef ref =
- CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, desc, 0);
-
- if (!ref) {
- CFRelease(desc);
- return false;
- }
-
- CFRunLoopAddSource(CFRunLoopGetCurrent(), ref, kCFRunLoopCommonModes);
- CFRelease(desc);
- CFRelease(ref);
- }
-
- return true;
-}
-
-// Used to disable socket events from waking our message queue when
-// process_io is false. Does not disable signal event handling though.
-void MacBaseSocketServer::EnableSocketCallbacks(bool enable) {
- for (std::set<MacAsyncSocket*>::iterator it = sockets().begin();
- it != sockets().end(); ++it) {
- if (enable) {
- (*it)->EnableCallbacks();
- } else {
- (*it)->DisableCallbacks();
- }
- }
-}
-
-void MacBaseSocketServer::FileDescriptorCallback(CFFileDescriptorRef fd,
- CFOptionFlags flags,
- void* context) {
- MacBaseSocketServer* this_ss =
- reinterpret_cast<MacBaseSocketServer*>(context);
- ASSERT(this_ss);
- Dispatcher* signal_dispatcher = this_ss->signal_dispatcher();
- ASSERT(signal_dispatcher);
-
- signal_dispatcher->OnPreEvent(DE_READ);
- signal_dispatcher->OnEvent(DE_READ, 0);
- CFFileDescriptorEnableCallBacks(fd, kCFFileDescriptorReadCallBack);
-}
-
-
-///////////////////////////////////////////////////////////////////////////////
-// MacCFSocketServer
-///////////////////////////////////////////////////////////////////////////////
-
-void WakeUpCallback(void* info) {
- MacCFSocketServer* server = static_cast<MacCFSocketServer*>(info);
- ASSERT(NULL != server);
- server->OnWakeUpCallback();
-}
-
-MacCFSocketServer::MacCFSocketServer()
- : run_loop_(CFRunLoopGetCurrent()),
- wake_up_(NULL) {
- CFRunLoopSourceContext ctx;
- memset(&ctx, 0, sizeof(ctx));
- ctx.info = this;
- ctx.perform = &WakeUpCallback;
- wake_up_ = CFRunLoopSourceCreate(NULL, 0, &ctx);
- ASSERT(NULL != wake_up_);
- if (wake_up_) {
- CFRunLoopAddSource(run_loop_, wake_up_, kCFRunLoopCommonModes);
- }
-}
-
-MacCFSocketServer::~MacCFSocketServer() {
- if (wake_up_) {
- CFRunLoopSourceInvalidate(wake_up_);
- CFRelease(wake_up_);
- }
-}
-
-bool MacCFSocketServer::Wait(int cms, bool process_io) {
- ASSERT(CFRunLoopGetCurrent() == run_loop_);
-
- if (!process_io && cms == 0) {
- // No op.
- return true;
- }
-
- if (!process_io) {
- // No way to listen to common modes and not get socket events, unless
- // we disable each one's callbacks.
- EnableSocketCallbacks(false);
- }
-
- SInt32 result;
- if (kForever == cms) {
- do {
- // Would prefer to run in a custom mode that only listens to wake_up,
- // but we have qtkit sending work to the main thread which is effectively
- // blocked here, causing deadlock. Thus listen to the common modes.
- // TODO: If QTKit becomes thread safe, do the above.
- result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10000000, false);
- } while (result != kCFRunLoopRunFinished && result != kCFRunLoopRunStopped);
- } else {
- // TODO: In the case of 0ms wait, this will only process one event, so we
- // may want to loop until it returns TimedOut.
- CFTimeInterval seconds = cms / 1000.0;
- result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, false);
- }
-
- if (!process_io) {
- // Reenable them. Hopefully this won't cause spurious callbacks or
- // missing ones while they were disabled.
- EnableSocketCallbacks(true);
- }
-
- if (kCFRunLoopRunFinished == result) {
- return false;
- }
- return true;
-}
-
-void MacCFSocketServer::WakeUp() {
- if (wake_up_) {
- CFRunLoopSourceSignal(wake_up_);
- CFRunLoopWakeUp(run_loop_);
- }
-}
-
-void MacCFSocketServer::OnWakeUpCallback() {
- ASSERT(run_loop_ == CFRunLoopGetCurrent());
- CFRunLoopStop(run_loop_);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// MacCarbonSocketServer
-///////////////////////////////////////////////////////////////////////////////
-#ifndef CARBON_DEPRECATED
-
-const UInt32 kEventClassSocketServer = 'MCSS';
-const UInt32 kEventWakeUp = 'WAKE';
-const EventTypeSpec kEventWakeUpSpec[] = {
- { kEventClassSocketServer, kEventWakeUp }
-};
-
-std::string DecodeEvent(EventRef event) {
- std::string str;
- DecodeFourChar(::GetEventClass(event), &str);
- str.push_back(':');
- DecodeFourChar(::GetEventKind(event), &str);
- return str;
-}
-
-MacCarbonSocketServer::MacCarbonSocketServer()
- : event_queue_(GetCurrentEventQueue()), wake_up_(NULL) {
- VERIFY(noErr == CreateEvent(NULL, kEventClassSocketServer, kEventWakeUp, 0,
- kEventAttributeUserEvent, &wake_up_));
-}
-
-MacCarbonSocketServer::~MacCarbonSocketServer() {
- if (wake_up_) {
- ReleaseEvent(wake_up_);
- }
-}
-
-bool MacCarbonSocketServer::Wait(int cms, bool process_io) {
- ASSERT(GetCurrentEventQueue() == event_queue_);
-
- // Listen to all events if we're processing I/O.
- // Only listen for our wakeup event if we're not.
- UInt32 num_types = 0;
- const EventTypeSpec* events = NULL;
- if (!process_io) {
- num_types = GetEventTypeCount(kEventWakeUpSpec);
- events = kEventWakeUpSpec;
- }
-
- EventTargetRef target = GetEventDispatcherTarget();
- EventTimeout timeout =
- (kForever == cms) ? kEventDurationForever : cms / 1000.0;
- EventTimeout end_time = GetCurrentEventTime() + timeout;
-
- bool done = false;
- while (!done) {
- EventRef event;
- OSStatus result = ReceiveNextEvent(num_types, events, timeout, true,
- &event);
- if (noErr == result) {
- if (wake_up_ != event) {
- LOG_F(LS_VERBOSE) << "Dispatching event: " << DecodeEvent(event);
- result = SendEventToEventTarget(event, target);
- if ((noErr != result) && (eventNotHandledErr != result)) {
- LOG_E(LS_ERROR, OS, result) << "SendEventToEventTarget";
- }
- } else {
- done = true;
- }
- ReleaseEvent(event);
- } else if (eventLoopTimedOutErr == result) {
- ASSERT(cms != kForever);
- done = true;
- } else if (eventLoopQuitErr == result) {
- // Ignore this... we get spurious quits for a variety of reasons.
- LOG_E(LS_VERBOSE, OS, result) << "ReceiveNextEvent";
- } else {
- // Some strange error occurred. Log it.
- LOG_E(LS_WARNING, OS, result) << "ReceiveNextEvent";
- return false;
- }
- if (kForever != cms) {
- timeout = end_time - GetCurrentEventTime();
- }
- }
- return true;
-}
-
-void MacCarbonSocketServer::WakeUp() {
- if (!IsEventInQueue(event_queue_, wake_up_)) {
- RetainEvent(wake_up_);
- OSStatus result = PostEventToQueue(event_queue_, wake_up_,
- kEventPriorityStandard);
- if (noErr != result) {
- LOG_E(LS_ERROR, OS, result) << "PostEventToQueue";
- }
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// MacCarbonAppSocketServer
-///////////////////////////////////////////////////////////////////////////////
-
-MacCarbonAppSocketServer::MacCarbonAppSocketServer()
- : event_queue_(GetCurrentEventQueue()) {
- // Install event handler
- VERIFY(noErr == InstallApplicationEventHandler(
- NewEventHandlerUPP(WakeUpEventHandler), 1, kEventWakeUpSpec, this,
- &event_handler_));
-
- // Install a timer and set it idle to begin with.
- VERIFY(noErr == InstallEventLoopTimer(GetMainEventLoop(),
- kEventDurationForever,
- kEventDurationForever,
- NewEventLoopTimerUPP(TimerHandler),
- this,
- &timer_));
-}
-
-MacCarbonAppSocketServer::~MacCarbonAppSocketServer() {
- RemoveEventLoopTimer(timer_);
- RemoveEventHandler(event_handler_);
-}
-
-OSStatus MacCarbonAppSocketServer::WakeUpEventHandler(
- EventHandlerCallRef next, EventRef event, void *data) {
- QuitApplicationEventLoop();
- return noErr;
-}
-
-void MacCarbonAppSocketServer::TimerHandler(
- EventLoopTimerRef timer, void *data) {
- QuitApplicationEventLoop();
-}
-
-bool MacCarbonAppSocketServer::Wait(int cms, bool process_io) {
- if (!process_io && cms == 0) {
- // No op.
- return true;
- }
- if (kForever != cms) {
- // Start a timer.
- OSStatus error =
- SetEventLoopTimerNextFireTime(timer_, cms / 1000.0);
- if (error != noErr) {
- LOG(LS_ERROR) << "Failed setting next fire time.";
- }
- }
- if (!process_io) {
- // No way to listen to common modes and not get socket events, unless
- // we disable each one's callbacks.
- EnableSocketCallbacks(false);
- }
- RunApplicationEventLoop();
- if (!process_io) {
- // Reenable them. Hopefully this won't cause spurious callbacks or
- // missing ones while they were disabled.
- EnableSocketCallbacks(true);
- }
- return true;
-}
-
-void MacCarbonAppSocketServer::WakeUp() {
- // TODO: No-op if there's already a WakeUp in flight.
- EventRef wake_up;
- VERIFY(noErr == CreateEvent(NULL, kEventClassSocketServer, kEventWakeUp, 0,
- kEventAttributeUserEvent, &wake_up));
- OSStatus result = PostEventToQueue(event_queue_, wake_up,
- kEventPriorityStandard);
- if (noErr != result) {
- LOG_E(LS_ERROR, OS, result) << "PostEventToQueue";
- }
- ReleaseEvent(wake_up);
-}
-
-#endif
-} // namespace talk_base
diff --git a/base/macsocketserver.h b/base/macsocketserver.h
deleted file mode 100644
index 2febb7f..0000000
--- a/base/macsocketserver.h
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright 2007, Google Inc.
-
-
-#ifndef TALK_BASE_MACSOCKETSERVER_H__
-#define TALK_BASE_MACSOCKETSERVER_H__
-
-#include <set>
-#ifdef OSX // Invalid on IOS
-#include <Carbon/Carbon.h>
-#endif
-#include "talk/base/physicalsocketserver.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// MacBaseSocketServer
-///////////////////////////////////////////////////////////////////////////////
-class MacAsyncSocket;
-
-class MacBaseSocketServer : public PhysicalSocketServer {
- public:
- MacBaseSocketServer();
- virtual ~MacBaseSocketServer();
-
- // SocketServer Interface
- virtual Socket* CreateSocket(int type) { return NULL; }
- virtual Socket* CreateSocket(int family, int type) { return NULL; }
-
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- virtual bool Wait(int cms, bool process_io) = 0;
- virtual void WakeUp() = 0;
-
- void RegisterSocket(MacAsyncSocket* socket);
- void UnregisterSocket(MacAsyncSocket* socket);
-
- // PhysicalSocketServer Overrides
- virtual bool SetPosixSignalHandler(int signum, void (*handler)(int));
-
- protected:
- void EnableSocketCallbacks(bool enable);
- const std::set<MacAsyncSocket*>& sockets() {
- return sockets_;
- }
-
- private:
- static void FileDescriptorCallback(CFFileDescriptorRef ref,
- CFOptionFlags flags,
- void* context);
-
- std::set<MacAsyncSocket*> sockets_;
-};
-
-// Core Foundation implementation of the socket server. While idle it
-// will run the current CF run loop. When the socket server has work
-// to do the run loop will be paused. Does not support Carbon or Cocoa
-// UI interaction.
-class MacCFSocketServer : public MacBaseSocketServer {
- public:
- MacCFSocketServer();
- virtual ~MacCFSocketServer();
-
- // SocketServer Interface
- virtual bool Wait(int cms, bool process_io);
- virtual void WakeUp();
- void OnWakeUpCallback();
-
- private:
- CFRunLoopRef run_loop_;
- CFRunLoopSourceRef wake_up_;
-};
-
-#ifndef CARBON_DEPRECATED
-
-///////////////////////////////////////////////////////////////////////////////
-// MacCarbonSocketServer
-///////////////////////////////////////////////////////////////////////////////
-
-// Interacts with the Carbon event queue. While idle it will block,
-// waiting for events. When the socket server has work to do, it will
-// post a 'wake up' event to the queue, causing the thread to exit the
-// event loop until the next call to Wait. Other events are dispatched
-// to their target. Supports Carbon and Cocoa UI interaction.
-class MacCarbonSocketServer : public MacBaseSocketServer {
- public:
- MacCarbonSocketServer();
- virtual ~MacCarbonSocketServer();
-
- // SocketServer Interface
- virtual bool Wait(int cms, bool process_io);
- virtual void WakeUp();
-
- private:
- EventQueueRef event_queue_;
- EventRef wake_up_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// MacCarbonAppSocketServer
-///////////////////////////////////////////////////////////////////////////////
-
-// Runs the Carbon application event loop on the current thread while
-// idle. When the socket server has work to do, it will post an event
-// to the queue, causing the thread to exit the event loop until the
-// next call to Wait. Other events are automatically dispatched to
-// their target.
-class MacCarbonAppSocketServer : public MacBaseSocketServer {
- public:
- MacCarbonAppSocketServer();
- virtual ~MacCarbonAppSocketServer();
-
- // SocketServer Interface
- virtual bool Wait(int cms, bool process_io);
- virtual void WakeUp();
-
- private:
- static OSStatus WakeUpEventHandler(EventHandlerCallRef next, EventRef event,
- void *data);
- static void TimerHandler(EventLoopTimerRef timer, void *data);
-
- EventQueueRef event_queue_;
- EventHandlerRef event_handler_;
- EventLoopTimerRef timer_;
-};
-
-#endif
-} // namespace talk_base
-
-#endif // TALK_BASE_MACSOCKETSERVER_H__
diff --git a/base/macsocketserver_unittest.cc b/base/macsocketserver_unittest.cc
deleted file mode 100644
index f10aebc..0000000
--- a/base/macsocketserver_unittest.cc
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socket_unittest.h"
-#include "talk/base/thread.h"
-#include "talk/base/macsocketserver.h"
-
-namespace talk_base {
-
-class WakeThread : public Thread {
- public:
- WakeThread(SocketServer* ss) : ss_(ss) {
- }
- virtual ~WakeThread() {
- Stop();
- }
- void Run() {
- ss_->WakeUp();
- }
- private:
- SocketServer* ss_;
-};
-
-#ifndef CARBON_DEPRECATED
-
-// Test that MacCFSocketServer::Wait works as expected.
-TEST(MacCFSocketServerTest, TestWait) {
- MacCFSocketServer server;
- uint32 start = Time();
- server.Wait(1000, true);
- EXPECT_GE(TimeSince(start), 1000);
-}
-
-// Test that MacCFSocketServer::Wakeup works as expected.
-TEST(MacCFSocketServerTest, TestWakeup) {
- MacCFSocketServer server;
- WakeThread thread(&server);
- uint32 start = Time();
- thread.Start();
- server.Wait(10000, true);
- EXPECT_LT(TimeSince(start), 10000);
-}
-
-// Test that MacCarbonSocketServer::Wait works as expected.
-TEST(MacCarbonSocketServerTest, TestWait) {
- MacCarbonSocketServer server;
- uint32 start = Time();
- server.Wait(1000, true);
- EXPECT_GE(TimeSince(start), 1000);
-}
-
-// Test that MacCarbonSocketServer::Wakeup works as expected.
-TEST(MacCarbonSocketServerTest, TestWakeup) {
- MacCarbonSocketServer server;
- WakeThread thread(&server);
- uint32 start = Time();
- thread.Start();
- server.Wait(10000, true);
- EXPECT_LT(TimeSince(start), 10000);
-}
-
-// Test that MacCarbonAppSocketServer::Wait works as expected.
-TEST(MacCarbonAppSocketServerTest, TestWait) {
- MacCarbonAppSocketServer server;
- uint32 start = Time();
- server.Wait(1000, true);
- EXPECT_GE(TimeSince(start), 1000);
-}
-
-// Test that MacCarbonAppSocketServer::Wakeup works as expected.
-TEST(MacCarbonAppSocketServerTest, TestWakeup) {
- MacCarbonAppSocketServer server;
- WakeThread thread(&server);
- uint32 start = Time();
- thread.Start();
- server.Wait(10000, true);
- EXPECT_LT(TimeSince(start), 10000);
-}
-
-#endif
-
-// Test that MacAsyncSocket passes all the generic Socket tests.
-class MacAsyncSocketTest : public SocketTest {
- protected:
- MacAsyncSocketTest()
- : server_(CreateSocketServer()),
- scope_(server_.get()) {}
- // Override for other implementations of MacBaseSocketServer.
- virtual MacBaseSocketServer* CreateSocketServer() {
- return new MacCFSocketServer();
- };
- talk_base::scoped_ptr<MacBaseSocketServer> server_;
- SocketServerScope scope_;
-};
-
-TEST_F(MacAsyncSocketTest, TestConnectIPv4) {
- SocketTest::TestConnectIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestConnectIPv6) {
- SocketTest::TestConnectIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, TestConnectWithDnsLookupIPv4) {
- SocketTest::TestConnectWithDnsLookupIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestConnectWithDnsLookupIPv6) {
- SocketTest::TestConnectWithDnsLookupIPv6();
-}
-
-// BUG=https://code.google.com/p/webrtc/issues/detail?id=2272
-TEST_F(MacAsyncSocketTest, DISABLED_TestConnectFailIPv4) {
- SocketTest::TestConnectFailIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestConnectFailIPv6) {
- SocketTest::TestConnectFailIPv6();
-}
-
-// Reenable once we have mac async dns
-TEST_F(MacAsyncSocketTest, DISABLED_TestConnectWithDnsLookupFailIPv4) {
- SocketTest::TestConnectWithDnsLookupFailIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, DISABLED_TestConnectWithDnsLookupFailIPv6) {
- SocketTest::TestConnectWithDnsLookupFailIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, TestConnectWithClosedSocketIPv4) {
- SocketTest::TestConnectWithClosedSocketIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestConnectWithClosedSocketIPv6) {
- SocketTest::TestConnectWithClosedSocketIPv6();
-}
-
-// Flaky at the moment (10% failure rate). Seems the client doesn't get
-// signalled in a timely manner...
-TEST_F(MacAsyncSocketTest, DISABLED_TestServerCloseDuringConnectIPv4) {
- SocketTest::TestServerCloseDuringConnectIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, DISABLED_TestServerCloseDuringConnectIPv6) {
- SocketTest::TestServerCloseDuringConnectIPv6();
-}
-// Flaky at the moment (0.5% failure rate). Seems the client doesn't get
-// signalled in a timely manner...
-TEST_F(MacAsyncSocketTest, TestClientCloseDuringConnectIPv4) {
- SocketTest::TestClientCloseDuringConnectIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestClientCloseDuringConnectIPv6) {
- SocketTest::TestClientCloseDuringConnectIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, TestServerCloseIPv4) {
- SocketTest::TestServerCloseIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestServerCloseIPv6) {
- SocketTest::TestServerCloseIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, TestCloseInClosedCallbackIPv4) {
- SocketTest::TestCloseInClosedCallbackIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestCloseInClosedCallbackIPv6) {
- SocketTest::TestCloseInClosedCallbackIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, TestSocketServerWaitIPv4) {
- SocketTest::TestSocketServerWaitIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestSocketServerWaitIPv6) {
- SocketTest::TestSocketServerWaitIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, TestTcpIPv4) {
- SocketTest::TestTcpIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestTcpIPv6) {
- SocketTest::TestTcpIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, TestSingleFlowControlCallbackIPv4) {
- SocketTest::TestSingleFlowControlCallbackIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, TestSingleFlowControlCallbackIPv6) {
- SocketTest::TestSingleFlowControlCallbackIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, DISABLED_TestUdpIPv4) {
- SocketTest::TestUdpIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, DISABLED_TestUdpIPv6) {
- SocketTest::TestUdpIPv6();
-}
-
-TEST_F(MacAsyncSocketTest, DISABLED_TestGetSetOptionsIPv4) {
- SocketTest::TestGetSetOptionsIPv4();
-}
-
-TEST_F(MacAsyncSocketTest, DISABLED_TestGetSetOptionsIPv6) {
- SocketTest::TestGetSetOptionsIPv6();
-}
-
-#ifndef CARBON_DEPRECATED
-class MacCarbonAppAsyncSocketTest : public MacAsyncSocketTest {
- virtual MacBaseSocketServer* CreateSocketServer() {
- return new MacCarbonAppSocketServer();
- };
-};
-
-TEST_F(MacCarbonAppAsyncSocketTest, TestSocketServerWaitIPv4) {
- SocketTest::TestSocketServerWaitIPv4();
-}
-
-TEST_F(MacCarbonAppAsyncSocketTest, TestSocketServerWaitIPv6) {
- SocketTest::TestSocketServerWaitIPv6();
-}
-#endif
-} // namespace talk_base
diff --git a/base/macutils.cc b/base/macutils.cc
deleted file mode 100644
index a1dcc04..0000000
--- a/base/macutils.cc
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * libjingle
- * Copyright 2007 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <sstream>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/macutils.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-bool ToUtf8(const CFStringRef str16, std::string* str8) {
- if ((NULL == str16) || (NULL == str8)) {
- return false;
- }
- size_t maxlen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str16),
- kCFStringEncodingUTF8) + 1;
- scoped_ptr<char[]> buffer(new char[maxlen]);
- if (!buffer || !CFStringGetCString(str16, buffer.get(), maxlen,
- kCFStringEncodingUTF8)) {
- return false;
- }
- str8->assign(buffer.get());
- return true;
-}
-
-bool ToUtf16(const std::string& str8, CFStringRef* str16) {
- if (NULL == str16) {
- return false;
- }
- *str16 = CFStringCreateWithBytes(kCFAllocatorDefault,
- reinterpret_cast<const UInt8*>(str8.data()),
- str8.length(), kCFStringEncodingUTF8,
- false);
- return NULL != *str16;
-}
-
-#ifdef OSX
-void DecodeFourChar(UInt32 fc, std::string* out) {
- std::stringstream ss;
- ss << '\'';
- bool printable = true;
- for (int i = 3; i >= 0; --i) {
- char ch = (fc >> (8 * i)) & 0xFF;
- if (isprint(static_cast<unsigned char>(ch))) {
- ss << ch;
- } else {
- printable = false;
- break;
- }
- }
- if (printable) {
- ss << '\'';
- } else {
- ss.str("");
- ss << "0x" << std::hex << fc;
- }
- out->append(ss.str());
-}
-
-static bool GetGestalt(OSType ostype, int* value) {
- ASSERT(NULL != value);
- SInt32 native_value;
- OSStatus result = Gestalt(ostype, &native_value);
- if (noErr == result) {
- *value = native_value;
- return true;
- }
- std::string str;
- DecodeFourChar(ostype, &str);
- LOG_E(LS_ERROR, OS, result) << "Gestalt(" << str << ")";
- return false;
-}
-
-bool GetOSVersion(int* major, int* minor, int* bugfix) {
- ASSERT(major && minor && bugfix);
- if (!GetGestalt(gestaltSystemVersion, major)) {
- return false;
- }
- if (*major < 0x1040) {
- *bugfix = *major & 0xF;
- *minor = (*major >> 4) & 0xF;
- *major = (*major >> 8);
- return true;
- }
- return GetGestalt(gestaltSystemVersionMajor, major) &&
- GetGestalt(gestaltSystemVersionMinor, minor) &&
- GetGestalt(gestaltSystemVersionBugFix, bugfix);
-}
-
-MacOSVersionName GetOSVersionName() {
- int major = 0, minor = 0, bugfix = 0;
- if (!GetOSVersion(&major, &minor, &bugfix)) {
- return kMacOSUnknown;
- }
- if (major > 10) {
- return kMacOSNewer;
- }
- if ((major < 10) || (minor < 3)) {
- return kMacOSOlder;
- }
- switch (minor) {
- case 3:
- return kMacOSPanther;
- case 4:
- return kMacOSTiger;
- case 5:
- return kMacOSLeopard;
- case 6:
- return kMacOSSnowLeopard;
- case 7:
- return kMacOSLion;
- case 8:
- return kMacOSMountainLion;
- case 9:
- return kMacOSMavericks;
- }
- return kMacOSNewer;
-}
-
-bool GetQuickTimeVersion(std::string* out) {
- int ver;
- if (!GetGestalt(gestaltQuickTimeVersion, &ver)) {
- return false;
- }
-
- std::stringstream ss;
- ss << std::hex << ver;
- *out = ss.str();
- return true;
-}
-
-bool RunAppleScript(const std::string& script) {
- // TODO(thaloun): Add a .mm file that contains something like this:
- // NSString source from script
- // NSAppleScript* appleScript = [[NSAppleScript alloc] initWithSource:&source]
- // if (appleScript != nil) {
- // [appleScript executeAndReturnError:nil]
- // [appleScript release]
-#ifndef CARBON_DEPRECATED
- ComponentInstance component = NULL;
- AEDesc script_desc;
- AEDesc result_data;
- OSStatus err;
- OSAID script_id, result_id;
-
- AECreateDesc(typeNull, NULL, 0, &script_desc);
- AECreateDesc(typeNull, NULL, 0, &result_data);
- script_id = kOSANullScript;
- result_id = kOSANullScript;
-
- component = OpenDefaultComponent(kOSAComponentType, typeAppleScript);
- if (component == NULL) {
- LOG(LS_ERROR) << "Failed opening Apple Script component";
- return false;
- }
- err = AECreateDesc(typeUTF8Text, script.data(), script.size(), &script_desc);
- if (err != noErr) {
- CloseComponent(component);
- LOG(LS_ERROR) << "Failed creating Apple Script description";
- return false;
- }
-
- err = OSACompile(component, &script_desc, kOSAModeCanInteract, &script_id);
- if (err != noErr) {
- AEDisposeDesc(&script_desc);
- if (script_id != kOSANullScript) {
- OSADispose(component, script_id);
- }
- CloseComponent(component);
- LOG(LS_ERROR) << "Error compiling Apple Script";
- return false;
- }
-
- err = OSAExecute(component, script_id, kOSANullScript, kOSAModeCanInteract,
- &result_id);
-
- if (err == errOSAScriptError) {
- LOG(LS_ERROR) << "Error when executing Apple Script: " << script;
- AECreateDesc(typeNull, NULL, 0, &result_data);
- OSAScriptError(component, kOSAErrorMessage, typeChar, &result_data);
- int len = AEGetDescDataSize(&result_data);
- char* data = (char*) malloc(len);
- if (data != NULL) {
- err = AEGetDescData(&result_data, data, len);
- LOG(LS_ERROR) << "Script error: " << data;
- }
- AEDisposeDesc(&script_desc);
- AEDisposeDesc(&result_data);
- return false;
- }
- AEDisposeDesc(&script_desc);
- if (script_id != kOSANullScript) {
- OSADispose(component, script_id);
- }
- if (result_id != kOSANullScript) {
- OSADispose(component, result_id);
- }
- CloseComponent(component);
- return true;
-#else
- // TODO(thaloun): Support applescripts with the NSAppleScript API.
- return false;
-#endif // CARBON_DEPRECATED
-}
-#endif // OSX
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/macutils.h b/base/macutils.h
deleted file mode 100644
index 17c09ed..0000000
--- a/base/macutils.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * libjingle
- * Copyright 2007 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_MACUTILS_H__
-#define TALK_BASE_MACUTILS_H__
-
-#include <CoreFoundation/CoreFoundation.h>
-#ifdef OSX
-#include <Carbon/Carbon.h>
-#endif
-#include <string>
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Note that some of these functions work for both iOS and Mac OS X. The ones
-// that are specific to Mac are #ifdef'ed as such.
-
-bool ToUtf8(const CFStringRef str16, std::string* str8);
-bool ToUtf16(const std::string& str8, CFStringRef* str16);
-
-#ifdef OSX
-void DecodeFourChar(UInt32 fc, std::string* out);
-
-enum MacOSVersionName {
- kMacOSUnknown, // ???
- kMacOSOlder, // 10.2-
- kMacOSPanther, // 10.3
- kMacOSTiger, // 10.4
- kMacOSLeopard, // 10.5
- kMacOSSnowLeopard, // 10.6
- kMacOSLion, // 10.7
- kMacOSMountainLion, // 10.8
- kMacOSMavericks, // 10.9
- kMacOSNewer, // 10.10+
-};
-
-bool GetOSVersion(int* major, int* minor, int* bugfix);
-MacOSVersionName GetOSVersionName();
-bool GetQuickTimeVersion(std::string* version);
-
-// Runs the given apple script. Only supports scripts that does not
-// require user interaction.
-bool RunAppleScript(const std::string& script);
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MACUTILS_H__
diff --git a/base/macutils_unittest.cc b/base/macutils_unittest.cc
deleted file mode 100644
index dfc211a..0000000
--- a/base/macutils_unittest.cc
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/macutils.h"
-
-TEST(MacUtilsTest, GetOsVersionName) {
- talk_base::MacOSVersionName ver = talk_base::GetOSVersionName();
- LOG(LS_INFO) << "GetOsVersionName " << ver;
- EXPECT_NE(talk_base::kMacOSUnknown, ver);
-}
-
-TEST(MacUtilsTest, GetQuickTimeVersion) {
- std::string version;
- EXPECT_TRUE(talk_base::GetQuickTimeVersion(&version));
- LOG(LS_INFO) << "GetQuickTimeVersion " << version;
-}
-
-TEST(MacUtilsTest, RunAppleScriptCompileError) {
- std::string script("set value to to 5");
- EXPECT_FALSE(talk_base::RunAppleScript(script));
-}
-
-TEST(MacUtilsTest, RunAppleScriptRuntimeError) {
- std::string script("set value to 5 / 0");
- EXPECT_FALSE(talk_base::RunAppleScript(script));
-}
-
-#ifdef CARBON_DEPRECATED
-TEST(MacUtilsTest, DISABLED_RunAppleScriptSuccess) {
-#else
-TEST(MacUtilsTest, RunAppleScriptSuccess) {
-#endif
- std::string script("set value to 5");
- EXPECT_TRUE(talk_base::RunAppleScript(script));
-}
diff --git a/base/macwindowpicker.cc b/base/macwindowpicker.cc
deleted file mode 100644
index 209b4ab..0000000
--- a/base/macwindowpicker.cc
+++ /dev/null
@@ -1,250 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved
-
-
-#include "talk/base/macwindowpicker.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-#include <CoreFoundation/CoreFoundation.h>
-#include <dlfcn.h>
-
-#include "talk/base/logging.h"
-#include "talk/base/macutils.h"
-
-namespace talk_base {
-
-static const char* kCoreGraphicsName =
- "/System/Library/Frameworks/ApplicationServices.framework/Frameworks/"
- "CoreGraphics.framework/CoreGraphics";
-
-static const char* kWindowListCopyWindowInfo = "CGWindowListCopyWindowInfo";
-static const char* kWindowListCreateDescriptionFromArray =
- "CGWindowListCreateDescriptionFromArray";
-
-// Function pointer for holding the CGWindowListCopyWindowInfo function.
-typedef CFArrayRef(*CGWindowListCopyWindowInfoProc)(CGWindowListOption,
- CGWindowID);
-
-// Function pointer for holding the CGWindowListCreateDescriptionFromArray
-// function.
-typedef CFArrayRef(*CGWindowListCreateDescriptionFromArrayProc)(CFArrayRef);
-
-MacWindowPicker::MacWindowPicker() : lib_handle_(NULL), get_window_list_(NULL),
- get_window_list_desc_(NULL) {
-}
-
-MacWindowPicker::~MacWindowPicker() {
- if (lib_handle_ != NULL) {
- dlclose(lib_handle_);
- }
-}
-
-bool MacWindowPicker::Init() {
- // TODO: If this class grows to use more dynamically functions
- // from the CoreGraphics framework, consider using
- // talk/base/latebindingsymboltable.h.
- lib_handle_ = dlopen(kCoreGraphicsName, RTLD_NOW);
- if (lib_handle_ == NULL) {
- LOG(LS_ERROR) << "Could not load CoreGraphics";
- return false;
- }
-
- get_window_list_ = dlsym(lib_handle_, kWindowListCopyWindowInfo);
- get_window_list_desc_ =
- dlsym(lib_handle_, kWindowListCreateDescriptionFromArray);
- if (get_window_list_ == NULL || get_window_list_desc_ == NULL) {
- // The CGWindowListCopyWindowInfo and the
- // CGWindowListCreateDescriptionFromArray functions was introduced
- // in Leopard(10.5) so this is a normal failure on Tiger.
- LOG(LS_INFO) << "Failed to load Core Graphics symbols";
- dlclose(lib_handle_);
- lib_handle_ = NULL;
- return false;
- }
-
- return true;
-}
-
-bool MacWindowPicker::IsVisible(const WindowId& id) {
- // Init if we're not already inited.
- if (get_window_list_desc_ == NULL && !Init()) {
- return false;
- }
- CGWindowID ids[1];
- ids[0] = id.id();
- CFArrayRef window_id_array =
- CFArrayCreate(NULL, reinterpret_cast<const void **>(&ids), 1, NULL);
-
- CFArrayRef window_array =
- reinterpret_cast<CGWindowListCreateDescriptionFromArrayProc>(
- get_window_list_desc_)(window_id_array);
- if (window_array == NULL || 0 == CFArrayGetCount(window_array)) {
- // Could not find the window. It might have been closed.
- LOG(LS_INFO) << "Window not found";
- CFRelease(window_id_array);
- return false;
- }
-
- CFDictionaryRef window = reinterpret_cast<CFDictionaryRef>(
- CFArrayGetValueAtIndex(window_array, 0));
- CFBooleanRef is_visible = reinterpret_cast<CFBooleanRef>(
- CFDictionaryGetValue(window, kCGWindowIsOnscreen));
-
- // Check that the window is visible. If not we might crash.
- bool visible = false;
- if (is_visible != NULL) {
- visible = CFBooleanGetValue(is_visible);
- }
- CFRelease(window_id_array);
- CFRelease(window_array);
- return visible;
-}
-
-bool MacWindowPicker::MoveToFront(const WindowId& id) {
- // Init if we're not already initialized.
- if (get_window_list_desc_ == NULL && !Init()) {
- return false;
- }
- CGWindowID ids[1];
- ids[0] = id.id();
- CFArrayRef window_id_array =
- CFArrayCreate(NULL, reinterpret_cast<const void **>(&ids), 1, NULL);
-
- CFArrayRef window_array =
- reinterpret_cast<CGWindowListCreateDescriptionFromArrayProc>(
- get_window_list_desc_)(window_id_array);
- if (window_array == NULL || 0 == CFArrayGetCount(window_array)) {
- // Could not find the window. It might have been closed.
- LOG(LS_INFO) << "Window not found";
- CFRelease(window_id_array);
- return false;
- }
-
- CFDictionaryRef window = reinterpret_cast<CFDictionaryRef>(
- CFArrayGetValueAtIndex(window_array, 0));
- CFStringRef window_name_ref = reinterpret_cast<CFStringRef>(
- CFDictionaryGetValue(window, kCGWindowName));
- CFNumberRef application_pid = reinterpret_cast<CFNumberRef>(
- CFDictionaryGetValue(window, kCGWindowOwnerPID));
-
- int pid_val;
- CFNumberGetValue(application_pid, kCFNumberIntType, &pid_val);
- std::string window_name;
- ToUtf8(window_name_ref, &window_name);
-
- // Build an applescript that sets the selected window to front
- // within the application. Then set the application to front.
- bool result = true;
- std::stringstream ss;
- ss << "tell application \"System Events\"\n"
- << "set proc to the first item of (every process whose unix id is "
- << pid_val
- << ")\n"
- << "tell proc to perform action \"AXRaise\" of window \""
- << window_name
- << "\"\n"
- << "set the frontmost of proc to true\n"
- << "end tell";
- if (!RunAppleScript(ss.str())) {
- // This might happen to for example X applications where the X
- // server spawns of processes with their own PID but the X server
- // is still registered as owner to the application windows. As a
- // workaround, we put the X server process to front, meaning that
- // all X applications will show up. The drawback with this
- // workaround is that the application that we really wanted to set
- // to front might be behind another X application.
- ProcessSerialNumber psn;
- pid_t pid = pid_val;
- int res = GetProcessForPID(pid, &psn);
- if (res != 0) {
- LOG(LS_ERROR) << "Failed getting process for pid";
- result = false;
- }
- res = SetFrontProcess(&psn);
- if (res != 0) {
- LOG(LS_ERROR) << "Failed setting process to front";
- result = false;
- }
- }
- CFRelease(window_id_array);
- CFRelease(window_array);
- return result;
-}
-
-bool MacWindowPicker::GetDesktopList(DesktopDescriptionList* descriptions) {
- const uint32_t kMaxDisplays = 128;
- CGDirectDisplayID active_displays[kMaxDisplays];
- uint32_t display_count = 0;
-
- CGError err = CGGetActiveDisplayList(kMaxDisplays,
- active_displays,
- &display_count);
- if (err != kCGErrorSuccess) {
- LOG_E(LS_ERROR, OS, err) << "Failed to enumerate the active displays.";
- return false;
- }
- for (uint32_t i = 0; i < display_count; ++i) {
- DesktopId id(active_displays[i], static_cast<int>(i));
- // TODO: Figure out an appropriate desktop title.
- DesktopDescription desc(id, "");
- desc.set_primary(CGDisplayIsMain(id.id()));
- descriptions->push_back(desc);
- }
- return display_count > 0;
-}
-
-bool MacWindowPicker::GetDesktopDimensions(const DesktopId& id,
- int* width,
- int* height) {
- *width = CGDisplayPixelsWide(id.id());
- *height = CGDisplayPixelsHigh(id.id());
- return true;
-}
-
-bool MacWindowPicker::GetWindowList(WindowDescriptionList* descriptions) {
- // Init if we're not already inited.
- if (get_window_list_ == NULL && !Init()) {
- return false;
- }
-
- // Only get onscreen, non-desktop windows.
- CFArrayRef window_array =
- reinterpret_cast<CGWindowListCopyWindowInfoProc>(get_window_list_)(
- kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
- kCGNullWindowID);
- if (window_array == NULL) {
- return false;
- }
-
- // Check windows to make sure they have an id, title, and use window layer 0.
- CFIndex i;
- CFIndex count = CFArrayGetCount(window_array);
- for (i = 0; i < count; ++i) {
- CFDictionaryRef window = reinterpret_cast<CFDictionaryRef>(
- CFArrayGetValueAtIndex(window_array, i));
- CFStringRef window_title = reinterpret_cast<CFStringRef>(
- CFDictionaryGetValue(window, kCGWindowName));
- CFNumberRef window_id = reinterpret_cast<CFNumberRef>(
- CFDictionaryGetValue(window, kCGWindowNumber));
- CFNumberRef window_layer = reinterpret_cast<CFNumberRef>(
- CFDictionaryGetValue(window, kCGWindowLayer));
- if (window_title != NULL && window_id != NULL && window_layer != NULL) {
- std::string title_str;
- int id_val, layer_val;
- ToUtf8(window_title, &title_str);
- CFNumberGetValue(window_id, kCFNumberIntType, &id_val);
- CFNumberGetValue(window_layer, kCFNumberIntType, &layer_val);
-
- // Discard windows without a title.
- if (layer_val == 0 && title_str.length() > 0) {
- WindowId id(static_cast<CGWindowID>(id_val));
- WindowDescription desc(id, title_str);
- descriptions->push_back(desc);
- }
- }
- }
-
- CFRelease(window_array);
- return true;
-}
-
-} // namespace talk_base
diff --git a/base/macwindowpicker.h b/base/macwindowpicker.h
deleted file mode 100644
index 85fcc36..0000000
--- a/base/macwindowpicker.h
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved
-
-
-#ifndef TALK_BASE_MACWINDOWPICKER_H_
-#define TALK_BASE_MACWINDOWPICKER_H_
-
-#include "talk/base/windowpicker.h"
-
-namespace talk_base {
-
-class MacWindowPicker : public WindowPicker {
- public:
- MacWindowPicker();
- ~MacWindowPicker();
- virtual bool Init();
- virtual bool IsVisible(const WindowId& id);
- virtual bool MoveToFront(const WindowId& id);
- virtual bool GetWindowList(WindowDescriptionList* descriptions);
- virtual bool GetDesktopList(DesktopDescriptionList* descriptions);
- virtual bool GetDesktopDimensions(const DesktopId& id, int* width,
- int* height);
-
- private:
- void* lib_handle_;
- void* get_window_list_;
- void* get_window_list_desc_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MACWINDOWPICKER_H_
diff --git a/base/macwindowpicker_unittest.cc b/base/macwindowpicker_unittest.cc
deleted file mode 100644
index 9cb67db..0000000
--- a/base/macwindowpicker_unittest.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved
-
-
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/macutils.h"
-#include "talk/base/macwindowpicker.h"
-#include "talk/base/windowpicker.h"
-
-#ifndef OSX
-#error Only for Mac OSX
-#endif
-
-namespace talk_base {
-
-bool IsLeopardOrLater() {
- return GetOSVersionName() >= kMacOSLeopard;
-}
-
-// Test that this works on new versions and fails acceptably on old versions.
-TEST(MacWindowPickerTest, TestGetWindowList) {
- MacWindowPicker picker, picker2;
- WindowDescriptionList descriptions;
- if (IsLeopardOrLater()) {
- EXPECT_TRUE(picker.Init());
- EXPECT_TRUE(picker.GetWindowList(&descriptions));
- EXPECT_TRUE(picker2.GetWindowList(&descriptions)); // Init is optional
- } else {
- EXPECT_FALSE(picker.Init());
- EXPECT_FALSE(picker.GetWindowList(&descriptions));
- EXPECT_FALSE(picker2.GetWindowList(&descriptions));
- }
-}
-
-// TODO: Add verification of the actual parsing, ie, add
-// functionality to inject a fake get_window_array function which
-// provide a pre-constructed list of windows.
-
-} // namespace talk_base
diff --git a/base/mathutils.h b/base/mathutils.h
deleted file mode 100644
index eeb110a..0000000
--- a/base/mathutils.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * libjingle
- * Copyright 2005 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_MATHUTILS_H_
-#define TALK_BASE_MATHUTILS_H_
-
-#include <math.h>
-
-#ifndef M_PI
-#define M_PI 3.14159265359f
-#endif
-
-#endif // TALK_BASE_MATHUTILS_H_
diff --git a/base/md5.cc b/base/md5.cc
deleted file mode 100644
index 7adb12d..0000000
--- a/base/md5.cc
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * This code implements the MD5 message-digest algorithm.
- * The algorithm is due to Ron Rivest. This code was
- * written by Colin Plumb in 1993, no copyright is claimed.
- * This code is in the public domain; do with it what you wish.
- *
- * Equivalent code is available from RSA Data Security, Inc.
- * This code has been tested against that, and is equivalent,
- * except that you don't need to include two pages of legalese
- * with every copy.
- *
- * To compute the message digest of a chunk of bytes, declare an
- * MD5Context structure, pass it to MD5Init, call MD5Update as
- * needed on buffers full of bytes, and then call MD5Final, which
- * will fill a supplied 16-byte array with the digest.
- */
-
-// Changes from original C code:
-// Ported to C++, type casting, Google code style.
-
-#include "talk/base/md5.h"
-
-// TODO: Avoid memcmpy - hash directly from memory.
-#include <string.h> // for memcpy().
-
-#include "talk/base/byteorder.h" // for ARCH_CPU_LITTLE_ENDIAN.
-
-#ifdef ARCH_CPU_LITTLE_ENDIAN
-#define ByteReverse(buf, len) // Nothing.
-#else // ARCH_CPU_BIG_ENDIAN
-static void ByteReverse(uint32* buf, int len) {
- for (int i = 0; i < len; ++i) {
- buf[i] = talk_base::GetLE32(&buf[i]);
- }
-}
-#endif
-
-// Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
-// initialization constants.
-void MD5Init(MD5Context* ctx) {
- ctx->buf[0] = 0x67452301;
- ctx->buf[1] = 0xefcdab89;
- ctx->buf[2] = 0x98badcfe;
- ctx->buf[3] = 0x10325476;
- ctx->bits[0] = 0;
- ctx->bits[1] = 0;
-}
-
-// Update context to reflect the concatenation of another buffer full of bytes.
-void MD5Update(MD5Context* ctx, const uint8* buf, size_t len) {
- // Update bitcount.
- uint32 t = ctx->bits[0];
- if ((ctx->bits[0] = t + (static_cast<uint32>(len) << 3)) < t) {
- ctx->bits[1]++; // Carry from low to high.
- }
- ctx->bits[1] += static_cast<uint32>(len >> 29);
- t = (t >> 3) & 0x3f; // Bytes already in shsInfo->data.
-
- // Handle any leading odd-sized chunks.
- if (t) {
- uint8* p = reinterpret_cast<uint8*>(ctx->in) + t;
-
- t = 64-t;
- if (len < t) {
- memcpy(p, buf, len);
- return;
- }
- memcpy(p, buf, t);
- ByteReverse(ctx->in, 16);
- MD5Transform(ctx->buf, ctx->in);
- buf += t;
- len -= t;
- }
-
- // Process data in 64-byte chunks.
- while (len >= 64) {
- memcpy(ctx->in, buf, 64);
- ByteReverse(ctx->in, 16);
- MD5Transform(ctx->buf, ctx->in);
- buf += 64;
- len -= 64;
- }
-
- // Handle any remaining bytes of data.
- memcpy(ctx->in, buf, len);
-}
-
-// Final wrapup - pad to 64-byte boundary with the bit pattern.
-// 1 0* (64-bit count of bits processed, MSB-first)
-void MD5Final(MD5Context* ctx, uint8 digest[16]) {
- // Compute number of bytes mod 64.
- uint32 count = (ctx->bits[0] >> 3) & 0x3F;
-
- // Set the first char of padding to 0x80. This is safe since there is
- // always at least one byte free.
- uint8* p = reinterpret_cast<uint8*>(ctx->in) + count;
- *p++ = 0x80;
-
- // Bytes of padding needed to make 64 bytes.
- count = 64 - 1 - count;
-
- // Pad out to 56 mod 64.
- if (count < 8) {
- // Two lots of padding: Pad the first block to 64 bytes.
- memset(p, 0, count);
- ByteReverse(ctx->in, 16);
- MD5Transform(ctx->buf, ctx->in);
-
- // Now fill the next block with 56 bytes.
- memset(ctx->in, 0, 56);
- } else {
- // Pad block to 56 bytes.
- memset(p, 0, count - 8);
- }
- ByteReverse(ctx->in, 14);
-
- // Append length in bits and transform.
- ctx->in[14] = ctx->bits[0];
- ctx->in[15] = ctx->bits[1];
-
- MD5Transform(ctx->buf, ctx->in);
- ByteReverse(ctx->buf, 4);
- memcpy(digest, ctx->buf, 16);
- memset(ctx, 0, sizeof(*ctx)); // In case it's sensitive.
-}
-
-// The four core functions - F1 is optimized somewhat.
-// #define F1(x, y, z) (x & y | ~x & z)
-#define F1(x, y, z) (z ^ (x & (y ^ z)))
-#define F2(x, y, z) F1(z, x, y)
-#define F3(x, y, z) (x ^ y ^ z)
-#define F4(x, y, z) (y ^ (x | ~z))
-
-// This is the central step in the MD5 algorithm.
-#define MD5STEP(f, w, x, y, z, data, s) \
- (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
-
-// The core of the MD5 algorithm, this alters an existing MD5 hash to
-// reflect the addition of 16 longwords of new data. MD5Update blocks
-// the data and converts bytes into longwords for this routine.
-void MD5Transform(uint32 buf[4], const uint32 in[16]) {
- uint32 a = buf[0];
- uint32 b = buf[1];
- uint32 c = buf[2];
- uint32 d = buf[3];
-
- MD5STEP(F1, a, b, c, d, in[ 0] + 0xd76aa478, 7);
- MD5STEP(F1, d, a, b, c, in[ 1] + 0xe8c7b756, 12);
- MD5STEP(F1, c, d, a, b, in[ 2] + 0x242070db, 17);
- MD5STEP(F1, b, c, d, a, in[ 3] + 0xc1bdceee, 22);
- MD5STEP(F1, a, b, c, d, in[ 4] + 0xf57c0faf, 7);
- MD5STEP(F1, d, a, b, c, in[ 5] + 0x4787c62a, 12);
- MD5STEP(F1, c, d, a, b, in[ 6] + 0xa8304613, 17);
- MD5STEP(F1, b, c, d, a, in[ 7] + 0xfd469501, 22);
- MD5STEP(F1, a, b, c, d, in[ 8] + 0x698098d8, 7);
- MD5STEP(F1, d, a, b, c, in[ 9] + 0x8b44f7af, 12);
- MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
- MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
- MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
- MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
- MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
- MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
-
- MD5STEP(F2, a, b, c, d, in[ 1] + 0xf61e2562, 5);
- MD5STEP(F2, d, a, b, c, in[ 6] + 0xc040b340, 9);
- MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
- MD5STEP(F2, b, c, d, a, in[ 0] + 0xe9b6c7aa, 20);
- MD5STEP(F2, a, b, c, d, in[ 5] + 0xd62f105d, 5);
- MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
- MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
- MD5STEP(F2, b, c, d, a, in[ 4] + 0xe7d3fbc8, 20);
- MD5STEP(F2, a, b, c, d, in[ 9] + 0x21e1cde6, 5);
- MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
- MD5STEP(F2, c, d, a, b, in[ 3] + 0xf4d50d87, 14);
- MD5STEP(F2, b, c, d, a, in[ 8] + 0x455a14ed, 20);
- MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
- MD5STEP(F2, d, a, b, c, in[ 2] + 0xfcefa3f8, 9);
- MD5STEP(F2, c, d, a, b, in[ 7] + 0x676f02d9, 14);
- MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
-
- MD5STEP(F3, a, b, c, d, in[ 5] + 0xfffa3942, 4);
- MD5STEP(F3, d, a, b, c, in[ 8] + 0x8771f681, 11);
- MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
- MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
- MD5STEP(F3, a, b, c, d, in[ 1] + 0xa4beea44, 4);
- MD5STEP(F3, d, a, b, c, in[ 4] + 0x4bdecfa9, 11);
- MD5STEP(F3, c, d, a, b, in[ 7] + 0xf6bb4b60, 16);
- MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
- MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
- MD5STEP(F3, d, a, b, c, in[ 0] + 0xeaa127fa, 11);
- MD5STEP(F3, c, d, a, b, in[ 3] + 0xd4ef3085, 16);
- MD5STEP(F3, b, c, d, a, in[ 6] + 0x04881d05, 23);
- MD5STEP(F3, a, b, c, d, in[ 9] + 0xd9d4d039, 4);
- MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
- MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
- MD5STEP(F3, b, c, d, a, in[ 2] + 0xc4ac5665, 23);
-
- MD5STEP(F4, a, b, c, d, in[ 0] + 0xf4292244, 6);
- MD5STEP(F4, d, a, b, c, in[ 7] + 0x432aff97, 10);
- MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
- MD5STEP(F4, b, c, d, a, in[ 5] + 0xfc93a039, 21);
- MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
- MD5STEP(F4, d, a, b, c, in[ 3] + 0x8f0ccc92, 10);
- MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
- MD5STEP(F4, b, c, d, a, in[ 1] + 0x85845dd1, 21);
- MD5STEP(F4, a, b, c, d, in[ 8] + 0x6fa87e4f, 6);
- MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
- MD5STEP(F4, c, d, a, b, in[ 6] + 0xa3014314, 15);
- MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
- MD5STEP(F4, a, b, c, d, in[ 4] + 0xf7537e82, 6);
- MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
- MD5STEP(F4, c, d, a, b, in[ 2] + 0x2ad7d2bb, 15);
- MD5STEP(F4, b, c, d, a, in[ 9] + 0xeb86d391, 21);
- buf[0] += a;
- buf[1] += b;
- buf[2] += c;
- buf[3] += d;
-}
diff --git a/base/md5.h b/base/md5.h
deleted file mode 100644
index 3aba3d2..0000000
--- a/base/md5.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * This is the header file for the MD5 message-digest algorithm.
- * The algorithm is due to Ron Rivest. This code was
- * written by Colin Plumb in 1993, no copyright is claimed.
- * This code is in the public domain; do with it what you wish.
- *
- * Equivalent code is available from RSA Data Security, Inc.
- * This code has been tested against that, and is equivalent,
- * except that you don't need to include two pages of legalese
- * with every copy.
- * To compute the message digest of a chunk of bytes, declare an
- * MD5Context structure, pass it to MD5Init, call MD5Update as
- * needed on buffers full of bytes, and then call MD5Final, which
- * will fill a supplied 16-byte array with the digest.
- *
- */
-
-// Changes(fbarchard): Ported to C++ and Google style guide.
-// Made context first parameter in MD5Final for consistency with Sha1.
-
-#ifndef TALK_BASE_MD5_H_
-#define TALK_BASE_MD5_H_
-
-#include "talk/base/basictypes.h"
-
-// Canonical name for a MD5 context structure, used in many crypto libs.
-typedef struct MD5Context MD5_CTX;
-
-struct MD5Context {
- uint32 buf[4];
- uint32 bits[2];
- uint32 in[16];
-};
-
-void MD5Init(MD5Context* context);
-void MD5Update(MD5Context* context, const uint8* data, size_t len);
-void MD5Final(MD5Context* context, uint8 digest[16]);
-void MD5Transform(uint32 buf[4], const uint32 in[16]);
-
-#endif // TALK_BASE_MD5_H_
diff --git a/base/md5digest.h b/base/md5digest.h
deleted file mode 100644
index a6c2ea9..0000000
--- a/base/md5digest.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_MD5DIGEST_H_
-#define TALK_BASE_MD5DIGEST_H_
-
-#include "talk/base/md5.h"
-#include "talk/base/messagedigest.h"
-
-namespace talk_base {
-
-// A simple wrapper for our MD5 implementation.
-class Md5Digest : public MessageDigest {
- public:
- enum { kSize = 16 };
- Md5Digest() {
- MD5Init(&ctx_);
- }
- virtual size_t Size() const {
- return kSize;
- }
- virtual void Update(const void* buf, size_t len) {
- MD5Update(&ctx_, static_cast<const uint8*>(buf), len);
- }
- virtual size_t Finish(void* buf, size_t len) {
- if (len < kSize) {
- return 0;
- }
- MD5Final(&ctx_, static_cast<uint8*>(buf));
- MD5Init(&ctx_); // Reset for next use.
- return kSize;
- }
- private:
- MD5_CTX ctx_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MD5DIGEST_H_
diff --git a/base/md5digest_unittest.cc b/base/md5digest_unittest.cc
deleted file mode 100644
index 9232b40..0000000
--- a/base/md5digest_unittest.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/md5digest.h"
-#include "talk/base/gunit.h"
-#include "talk/base/stringencode.h"
-
-namespace talk_base {
-
-std::string Md5(const std::string& input) {
- Md5Digest md5;
- return ComputeDigest(&md5, input);
-}
-
-TEST(Md5DigestTest, TestSize) {
- Md5Digest md5;
- EXPECT_EQ(16, static_cast<int>(Md5Digest::kSize));
- EXPECT_EQ(16U, md5.Size());
-}
-
-TEST(Md5DigestTest, TestBasic) {
- // These are the standard MD5 test vectors from RFC 1321.
- EXPECT_EQ("d41d8cd98f00b204e9800998ecf8427e", Md5(""));
- EXPECT_EQ("0cc175b9c0f1b6a831c399e269772661", Md5("a"));
- EXPECT_EQ("900150983cd24fb0d6963f7d28e17f72", Md5("abc"));
- EXPECT_EQ("f96b697d7cb7938d525a2f31aaf161d0", Md5("message digest"));
- EXPECT_EQ("c3fcd3d76192e4007dfb496cca67e13b",
- Md5("abcdefghijklmnopqrstuvwxyz"));
-}
-
-TEST(Md5DigestTest, TestMultipleUpdates) {
- Md5Digest md5;
- std::string input = "abcdefghijklmnopqrstuvwxyz";
- char output[Md5Digest::kSize];
- for (size_t i = 0; i < input.size(); ++i) {
- md5.Update(&input[i], 1);
- }
- EXPECT_EQ(md5.Size(), md5.Finish(output, sizeof(output)));
- EXPECT_EQ("c3fcd3d76192e4007dfb496cca67e13b",
- hex_encode(output, sizeof(output)));
-}
-
-TEST(Md5DigestTest, TestReuse) {
- Md5Digest md5;
- std::string input = "message digest";
- EXPECT_EQ("f96b697d7cb7938d525a2f31aaf161d0", ComputeDigest(&md5, input));
- input = "abcdefghijklmnopqrstuvwxyz";
- EXPECT_EQ("c3fcd3d76192e4007dfb496cca67e13b", ComputeDigest(&md5, input));
-}
-
-TEST(Md5DigestTest, TestBufferTooSmall) {
- Md5Digest md5;
- std::string input = "abcdefghijklmnopqrstuvwxyz";
- char output[Md5Digest::kSize - 1];
- md5.Update(input.c_str(), input.size());
- EXPECT_EQ(0U, md5.Finish(output, sizeof(output)));
-}
-
-TEST(Md5DigestTest, TestBufferConst) {
- Md5Digest md5;
- const int kLongSize = 1000000;
- std::string input(kLongSize, '\0');
- for (int i = 0; i < kLongSize; ++i) {
- input[i] = static_cast<char>(i);
- }
- md5.Update(input.c_str(), input.size());
- for (int i = 0; i < kLongSize; ++i) {
- EXPECT_EQ(static_cast<char>(i), input[i]);
- }
-}
-
-} // namespace talk_base
diff --git a/base/messagedigest.cc b/base/messagedigest.cc
deleted file mode 100644
index 975991d..0000000
--- a/base/messagedigest.cc
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/messagedigest.h"
-
-#include <string.h>
-
-#include "talk/base/sslconfig.h"
-#if SSL_USE_OPENSSL
-#include "talk/base/openssldigest.h"
-#else
-#include "talk/base/md5digest.h"
-#include "talk/base/sha1digest.h"
-#endif
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringencode.h"
-
-namespace talk_base {
-
-// From RFC 4572.
-const char DIGEST_MD5[] = "md5";
-const char DIGEST_SHA_1[] = "sha-1";
-const char DIGEST_SHA_224[] = "sha-224";
-const char DIGEST_SHA_256[] = "sha-256";
-const char DIGEST_SHA_384[] = "sha-384";
-const char DIGEST_SHA_512[] = "sha-512";
-
-static const size_t kBlockSize = 64; // valid for SHA-256 and down
-
-MessageDigest* MessageDigestFactory::Create(const std::string& alg) {
-#if SSL_USE_OPENSSL
- MessageDigest* digest = new OpenSSLDigest(alg);
- if (digest->Size() == 0) { // invalid algorithm
- delete digest;
- digest = NULL;
- }
- return digest;
-#else
- MessageDigest* digest = NULL;
- if (alg == DIGEST_MD5) {
- digest = new Md5Digest();
- } else if (alg == DIGEST_SHA_1) {
- digest = new Sha1Digest();
- }
- return digest;
-#endif
-}
-
-bool IsFips180DigestAlgorithm(const std::string& alg) {
- // These are the FIPS 180 algorithms. According to RFC 4572 Section 5,
- // "Self-signed certificates (for which legacy certificates are not a
- // consideration) MUST use one of the FIPS 180 algorithms (SHA-1,
- // SHA-224, SHA-256, SHA-384, or SHA-512) as their signature algorithm,
- // and thus also MUST use it to calculate certificate fingerprints."
- return alg == DIGEST_SHA_1 ||
- alg == DIGEST_SHA_224 ||
- alg == DIGEST_SHA_256 ||
- alg == DIGEST_SHA_384 ||
- alg == DIGEST_SHA_512;
-}
-
-size_t ComputeDigest(MessageDigest* digest, const void* input, size_t in_len,
- void* output, size_t out_len) {
- digest->Update(input, in_len);
- return digest->Finish(output, out_len);
-}
-
-size_t ComputeDigest(const std::string& alg, const void* input, size_t in_len,
- void* output, size_t out_len) {
- scoped_ptr<MessageDigest> digest(MessageDigestFactory::Create(alg));
- return (digest) ?
- ComputeDigest(digest.get(), input, in_len, output, out_len) :
- 0;
-}
-
-std::string ComputeDigest(MessageDigest* digest, const std::string& input) {
- scoped_ptr<char[]> output(new char[digest->Size()]);
- ComputeDigest(digest, input.data(), input.size(),
- output.get(), digest->Size());
- return hex_encode(output.get(), digest->Size());
-}
-
-bool ComputeDigest(const std::string& alg, const std::string& input,
- std::string* output) {
- scoped_ptr<MessageDigest> digest(MessageDigestFactory::Create(alg));
- if (!digest) {
- return false;
- }
- *output = ComputeDigest(digest.get(), input);
- return true;
-}
-
-std::string ComputeDigest(const std::string& alg, const std::string& input) {
- std::string output;
- ComputeDigest(alg, input, &output);
- return output;
-}
-
-// Compute a RFC 2104 HMAC: H(K XOR opad, H(K XOR ipad, text))
-size_t ComputeHmac(MessageDigest* digest,
- const void* key, size_t key_len,
- const void* input, size_t in_len,
- void* output, size_t out_len) {
- // We only handle algorithms with a 64-byte blocksize.
- // TODO: Add BlockSize() method to MessageDigest.
- size_t block_len = kBlockSize;
- if (digest->Size() > 32) {
- return 0;
- }
- // Copy the key to a block-sized buffer to simplify padding.
- // If the key is longer than a block, hash it and use the result instead.
- scoped_ptr<uint8[]> new_key(new uint8[block_len]);
- if (key_len > block_len) {
- ComputeDigest(digest, key, key_len, new_key.get(), block_len);
- memset(new_key.get() + digest->Size(), 0, block_len - digest->Size());
- } else {
- memcpy(new_key.get(), key, key_len);
- memset(new_key.get() + key_len, 0, block_len - key_len);
- }
- // Set up the padding from the key, salting appropriately for each padding.
- scoped_ptr<uint8[]> o_pad(new uint8[block_len]), i_pad(new uint8[block_len]);
- for (size_t i = 0; i < block_len; ++i) {
- o_pad[i] = 0x5c ^ new_key[i];
- i_pad[i] = 0x36 ^ new_key[i];
- }
- // Inner hash; hash the inner padding, and then the input buffer.
- scoped_ptr<uint8[]> inner(new uint8[digest->Size()]);
- digest->Update(i_pad.get(), block_len);
- digest->Update(input, in_len);
- digest->Finish(inner.get(), digest->Size());
- // Outer hash; hash the outer padding, and then the result of the inner hash.
- digest->Update(o_pad.get(), block_len);
- digest->Update(inner.get(), digest->Size());
- return digest->Finish(output, out_len);
-}
-
-size_t ComputeHmac(const std::string& alg, const void* key, size_t key_len,
- const void* input, size_t in_len,
- void* output, size_t out_len) {
- scoped_ptr<MessageDigest> digest(MessageDigestFactory::Create(alg));
- if (!digest) {
- return 0;
- }
- return ComputeHmac(digest.get(), key, key_len,
- input, in_len, output, out_len);
-}
-
-std::string ComputeHmac(MessageDigest* digest, const std::string& key,
- const std::string& input) {
- scoped_ptr<char[]> output(new char[digest->Size()]);
- ComputeHmac(digest, key.data(), key.size(),
- input.data(), input.size(), output.get(), digest->Size());
- return hex_encode(output.get(), digest->Size());
-}
-
-bool ComputeHmac(const std::string& alg, const std::string& key,
- const std::string& input, std::string* output) {
- scoped_ptr<MessageDigest> digest(MessageDigestFactory::Create(alg));
- if (!digest) {
- return false;
- }
- *output = ComputeHmac(digest.get(), key, input);
- return true;
-}
-
-std::string ComputeHmac(const std::string& alg, const std::string& key,
- const std::string& input) {
- std::string output;
- ComputeHmac(alg, key, input, &output);
- return output;
-}
-
-} // namespace talk_base
diff --git a/base/messagedigest.h b/base/messagedigest.h
deleted file mode 100644
index e8f303f..0000000
--- a/base/messagedigest.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_MESSAGEDIGEST_H_
-#define TALK_BASE_MESSAGEDIGEST_H_
-
-#include <string>
-
-namespace talk_base {
-
-// Definitions for the digest algorithms.
-extern const char DIGEST_MD5[];
-extern const char DIGEST_SHA_1[];
-extern const char DIGEST_SHA_224[];
-extern const char DIGEST_SHA_256[];
-extern const char DIGEST_SHA_384[];
-extern const char DIGEST_SHA_512[];
-
-// A general class for computing hashes.
-class MessageDigest {
- public:
- enum { kMaxSize = 64 }; // Maximum known size (SHA-512)
- virtual ~MessageDigest() {}
- // Returns the digest output size (e.g. 16 bytes for MD5).
- virtual size_t Size() const = 0;
- // Updates the digest with |len| bytes from |buf|.
- virtual void Update(const void* buf, size_t len) = 0;
- // Outputs the digest value to |buf| with length |len|.
- // Returns the number of bytes written, i.e., Size().
- virtual size_t Finish(void* buf, size_t len) = 0;
-};
-
-// A factory class for creating digest objects.
-class MessageDigestFactory {
- public:
- static MessageDigest* Create(const std::string& alg);
-};
-
-// A whitelist of approved digest algorithms from RFC 4572 (FIPS 180).
-bool IsFips180DigestAlgorithm(const std::string& alg);
-
-// Functions to create hashes.
-
-// Computes the hash of |in_len| bytes of |input|, using the |digest| hash
-// implementation, and outputs the hash to the buffer |output|, which is
-// |out_len| bytes long. Returns the number of bytes written to |output| if
-// successful, or 0 if |out_len| was too small.
-size_t ComputeDigest(MessageDigest* digest, const void* input, size_t in_len,
- void* output, size_t out_len);
-// Like the previous function, but creates a digest implementation based on
-// the desired digest name |alg|, e.g. DIGEST_SHA_1. Returns 0 if there is no
-// digest with the given name.
-size_t ComputeDigest(const std::string& alg, const void* input, size_t in_len,
- void* output, size_t out_len);
-// Computes the hash of |input| using the |digest| hash implementation, and
-// returns it as a hex-encoded string.
-std::string ComputeDigest(MessageDigest* digest, const std::string& input);
-// Like the previous function, but creates a digest implementation based on
-// the desired digest name |alg|, e.g. DIGEST_SHA_1. Returns empty string if
-// there is no digest with the given name.
-std::string ComputeDigest(const std::string& alg, const std::string& input);
-// Like the previous function, but returns an explicit result code.
-bool ComputeDigest(const std::string& alg, const std::string& input,
- std::string* output);
-
-// Shorthand way to compute a hex-encoded hash using MD5.
-inline std::string MD5(const std::string& input) {
- return ComputeDigest(DIGEST_MD5, input);
-}
-
-// Functions to compute RFC 2104 HMACs.
-
-// Computes the HMAC of |in_len| bytes of |input|, using the |digest| hash
-// implementation and |key_len| bytes of |key| to key the HMAC, and outputs
-// the HMAC to the buffer |output|, which is |out_len| bytes long. Returns the
-// number of bytes written to |output| if successful, or 0 if |out_len| was too
-// small.
-size_t ComputeHmac(MessageDigest* digest, const void* key, size_t key_len,
- const void* input, size_t in_len,
- void* output, size_t out_len);
-// Like the previous function, but creates a digest implementation based on
-// the desired digest name |alg|, e.g. DIGEST_SHA_1. Returns 0 if there is no
-// digest with the given name.
-size_t ComputeHmac(const std::string& alg, const void* key, size_t key_len,
- const void* input, size_t in_len,
- void* output, size_t out_len);
-// Computes the HMAC of |input| using the |digest| hash implementation and |key|
-// to key the HMAC, and returns it as a hex-encoded string.
-std::string ComputeHmac(MessageDigest* digest, const std::string& key,
- const std::string& input);
-// Like the previous function, but creates a digest implementation based on
-// the desired digest name |alg|, e.g. DIGEST_SHA_1. Returns empty string if
-// there is no digest with the given name.
-std::string ComputeHmac(const std::string& alg, const std::string& key,
- const std::string& input);
-// Like the previous function, but returns an explicit result code.
-bool ComputeHmac(const std::string& alg, const std::string& key,
- const std::string& input, std::string* output);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MESSAGEDIGEST_H_
diff --git a/base/messagedigest_unittest.cc b/base/messagedigest_unittest.cc
deleted file mode 100644
index cd68e86..0000000
--- a/base/messagedigest_unittest.cc
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/stringencode.h"
-
-namespace talk_base {
-
-// Test vectors from RFC 1321.
-TEST(MessageDigestTest, TestMd5Digest) {
- // Test the string versions of the APIs.
- EXPECT_EQ("d41d8cd98f00b204e9800998ecf8427e",
- ComputeDigest(DIGEST_MD5, ""));
- EXPECT_EQ("900150983cd24fb0d6963f7d28e17f72",
- ComputeDigest(DIGEST_MD5, "abc"));
- EXPECT_EQ("c3fcd3d76192e4007dfb496cca67e13b",
- ComputeDigest(DIGEST_MD5, "abcdefghijklmnopqrstuvwxyz"));
-
- // Test the raw buffer versions of the APIs; also check output buffer size.
- char output[16];
- EXPECT_EQ(sizeof(output),
- ComputeDigest(DIGEST_MD5, "abc", 3, output, sizeof(output)));
- EXPECT_EQ("900150983cd24fb0d6963f7d28e17f72",
- hex_encode(output, sizeof(output)));
- EXPECT_EQ(0U,
- ComputeDigest(DIGEST_MD5, "abc", 3, output, sizeof(output) - 1));
-}
-
-// Test vectors from RFC 3174.
-TEST(MessageDigestTest, TestSha1Digest) {
- // Test the string versions of the APIs.
- EXPECT_EQ("da39a3ee5e6b4b0d3255bfef95601890afd80709",
- ComputeDigest(DIGEST_SHA_1, ""));
- EXPECT_EQ("a9993e364706816aba3e25717850c26c9cd0d89d",
- ComputeDigest(DIGEST_SHA_1, "abc"));
- EXPECT_EQ("84983e441c3bd26ebaae4aa1f95129e5e54670f1",
- ComputeDigest(DIGEST_SHA_1,
- "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"));
-
- // Test the raw buffer versions of the APIs; also check output buffer size.
- char output[20];
- EXPECT_EQ(sizeof(output),
- ComputeDigest(DIGEST_SHA_1, "abc", 3, output, sizeof(output)));
- EXPECT_EQ("a9993e364706816aba3e25717850c26c9cd0d89d",
- hex_encode(output, sizeof(output)));
- EXPECT_EQ(0U,
- ComputeDigest(DIGEST_SHA_1, "abc", 3, output, sizeof(output) - 1));
-}
-
-// Test that we fail properly if a bad digest algorithm is specified.
-TEST(MessageDigestTest, TestBadDigest) {
- std::string output;
- EXPECT_FALSE(ComputeDigest("sha-9000", "abc", &output));
- EXPECT_EQ("", ComputeDigest("sha-9000", "abc"));
-}
-
-// Test vectors from RFC 2202.
-TEST(MessageDigestTest, TestMd5Hmac) {
- // Test the string versions of the APIs.
- EXPECT_EQ("9294727a3638bb1c13f48ef8158bfc9d",
- ComputeHmac(DIGEST_MD5, std::string(16, '\x0b'), "Hi There"));
- EXPECT_EQ("750c783e6ab0b503eaa86e310a5db738",
- ComputeHmac(DIGEST_MD5, "Jefe", "what do ya want for nothing?"));
- EXPECT_EQ("56be34521d144c88dbb8c733f0e8b3f6",
- ComputeHmac(DIGEST_MD5, std::string(16, '\xaa'),
- std::string(50, '\xdd')));
- EXPECT_EQ("697eaf0aca3a3aea3a75164746ffaa79",
- ComputeHmac(DIGEST_MD5,
- "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
- "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19",
- std::string(50, '\xcd')));
- EXPECT_EQ("56461ef2342edc00f9bab995690efd4c",
- ComputeHmac(DIGEST_MD5, std::string(16, '\x0c'),
- "Test With Truncation"));
- EXPECT_EQ("6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd",
- ComputeHmac(DIGEST_MD5, std::string(80, '\xaa'),
- "Test Using Larger Than Block-Size Key - Hash Key First"));
- EXPECT_EQ("6f630fad67cda0ee1fb1f562db3aa53e",
- ComputeHmac(DIGEST_MD5, std::string(80, '\xaa'),
- "Test Using Larger Than Block-Size Key and Larger "
- "Than One Block-Size Data"));
-
- // Test the raw buffer versions of the APIs; also check output buffer size.
- std::string key(16, '\x0b');
- std::string input("Hi There");
- char output[16];
- EXPECT_EQ(sizeof(output),
- ComputeHmac(DIGEST_MD5, key.c_str(), key.size(),
- input.c_str(), input.size(), output, sizeof(output)));
- EXPECT_EQ("9294727a3638bb1c13f48ef8158bfc9d",
- hex_encode(output, sizeof(output)));
- EXPECT_EQ(0U,
- ComputeHmac(DIGEST_MD5, key.c_str(), key.size(),
- input.c_str(), input.size(), output, sizeof(output) - 1));
-}
-
-// Test vectors from RFC 2202.
-TEST(MessageDigestTest, TestSha1Hmac) {
- // Test the string versions of the APIs.
- EXPECT_EQ("b617318655057264e28bc0b6fb378c8ef146be00",
- ComputeHmac(DIGEST_SHA_1, std::string(20, '\x0b'), "Hi There"));
- EXPECT_EQ("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
- ComputeHmac(DIGEST_SHA_1, "Jefe", "what do ya want for nothing?"));
- EXPECT_EQ("125d7342b9ac11cd91a39af48aa17b4f63f175d3",
- ComputeHmac(DIGEST_SHA_1, std::string(20, '\xaa'),
- std::string(50, '\xdd')));
- EXPECT_EQ("4c9007f4026250c6bc8414f9bf50c86c2d7235da",
- ComputeHmac(DIGEST_SHA_1,
- "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
- "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19",
- std::string(50, '\xcd')));
- EXPECT_EQ("4c1a03424b55e07fe7f27be1d58bb9324a9a5a04",
- ComputeHmac(DIGEST_SHA_1, std::string(20, '\x0c'),
- "Test With Truncation"));
- EXPECT_EQ("aa4ae5e15272d00e95705637ce8a3b55ed402112",
- ComputeHmac(DIGEST_SHA_1, std::string(80, '\xaa'),
- "Test Using Larger Than Block-Size Key - Hash Key First"));
- EXPECT_EQ("e8e99d0f45237d786d6bbaa7965c7808bbff1a91",
- ComputeHmac(DIGEST_SHA_1, std::string(80, '\xaa'),
- "Test Using Larger Than Block-Size Key and Larger "
- "Than One Block-Size Data"));
-
- // Test the raw buffer versions of the APIs; also check output buffer size.
- std::string key(20, '\x0b');
- std::string input("Hi There");
- char output[20];
- EXPECT_EQ(sizeof(output),
- ComputeHmac(DIGEST_SHA_1, key.c_str(), key.size(),
- input.c_str(), input.size(), output, sizeof(output)));
- EXPECT_EQ("b617318655057264e28bc0b6fb378c8ef146be00",
- hex_encode(output, sizeof(output)));
- EXPECT_EQ(0U,
- ComputeHmac(DIGEST_SHA_1, key.c_str(), key.size(),
- input.c_str(), input.size(), output, sizeof(output) - 1));
-}
-
-TEST(MessageDigestTest, TestBadHmac) {
- std::string output;
- EXPECT_FALSE(ComputeHmac("sha-9000", "key", "abc", &output));
- EXPECT_EQ("", ComputeHmac("sha-9000", "key", "abc"));
-}
-
-} // namespace talk_base
diff --git a/base/messagehandler.cc b/base/messagehandler.cc
deleted file mode 100644
index 16f9a21..0000000
--- a/base/messagehandler.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/messagehandler.h"
-#include "talk/base/messagequeue.h"
-
-namespace talk_base {
-
-MessageHandler::~MessageHandler() {
- MessageQueueManager::Clear(this);
-}
-
-} // namespace talk_base
diff --git a/base/messagehandler.h b/base/messagehandler.h
deleted file mode 100644
index 6494f2b..0000000
--- a/base/messagehandler.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_MESSAGEHANDLER_H_
-#define TALK_BASE_MESSAGEHANDLER_H_
-
-#include "talk/base/constructormagic.h"
-
-namespace talk_base {
-
-struct Message;
-
-// Messages get dispatched to a MessageHandler
-
-class MessageHandler {
- public:
- virtual ~MessageHandler();
- virtual void OnMessage(Message* msg) = 0;
-
- protected:
- MessageHandler() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(MessageHandler);
-};
-
-// Helper class to facilitate executing a functor on a thread.
-template <class ReturnT, class FunctorT>
-class FunctorMessageHandler : public MessageHandler {
- public:
- explicit FunctorMessageHandler(const FunctorT& functor)
- : functor_(functor) {}
- virtual void OnMessage(Message* msg) {
- result_ = functor_();
- }
- const ReturnT& result() const { return result_; }
-
- private:
- FunctorT functor_;
- ReturnT result_;
-};
-
-// Specialization for ReturnT of void.
-template <class FunctorT>
-class FunctorMessageHandler<void, FunctorT> : public MessageHandler {
- public:
- explicit FunctorMessageHandler(const FunctorT& functor)
- : functor_(functor) {}
- virtual void OnMessage(Message* msg) {
- functor_();
- }
- void result() const {}
-
- private:
- FunctorT functor_;
-};
-
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MESSAGEHANDLER_H_
diff --git a/base/messagequeue.cc b/base/messagequeue.cc
deleted file mode 100644
index 7bda924..0000000
--- a/base/messagequeue.cc
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef POSIX
-#include <sys/time.h>
-#endif
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagequeue.h"
-#if defined(__native_client__)
-#include "talk/base/nullsocketserver.h"
-typedef talk_base::NullSocketServer DefaultSocketServer;
-#else
-#include "talk/base/physicalsocketserver.h"
-typedef talk_base::PhysicalSocketServer DefaultSocketServer;
-#endif
-
-namespace talk_base {
-
-const uint32 kMaxMsgLatency = 150; // 150 ms
-
-//------------------------------------------------------------------
-// MessageQueueManager
-
-MessageQueueManager* MessageQueueManager::instance_ = NULL;
-
-MessageQueueManager* MessageQueueManager::Instance() {
- // Note: This is not thread safe, but it is first called before threads are
- // spawned.
- if (!instance_)
- instance_ = new MessageQueueManager;
- return instance_;
-}
-
-bool MessageQueueManager::IsInitialized() {
- return instance_ != NULL;
-}
-
-MessageQueueManager::MessageQueueManager() {
-}
-
-MessageQueueManager::~MessageQueueManager() {
-}
-
-void MessageQueueManager::Add(MessageQueue *message_queue) {
- return Instance()->AddInternal(message_queue);
-}
-void MessageQueueManager::AddInternal(MessageQueue *message_queue) {
- // MessageQueueManager methods should be non-reentrant, so we
- // ASSERT that is the case. If any of these ASSERT, please
- // contact bpm or jbeda.
- ASSERT(!crit_.CurrentThreadIsOwner());
- CritScope cs(&crit_);
- message_queues_.push_back(message_queue);
-}
-
-void MessageQueueManager::Remove(MessageQueue *message_queue) {
- // If there isn't a message queue manager instance, then there isn't a queue
- // to remove.
- if (!instance_) return;
- return Instance()->RemoveInternal(message_queue);
-}
-void MessageQueueManager::RemoveInternal(MessageQueue *message_queue) {
- ASSERT(!crit_.CurrentThreadIsOwner()); // See note above.
- // If this is the last MessageQueue, destroy the manager as well so that
- // we don't leak this object at program shutdown. As mentioned above, this is
- // not thread-safe, but this should only happen at program termination (when
- // the ThreadManager is destroyed, and threads are no longer active).
- bool destroy = false;
- {
- CritScope cs(&crit_);
- std::vector<MessageQueue *>::iterator iter;
- iter = std::find(message_queues_.begin(), message_queues_.end(),
- message_queue);
- if (iter != message_queues_.end()) {
- message_queues_.erase(iter);
- }
- destroy = message_queues_.empty();
- }
- if (destroy) {
- instance_ = NULL;
- delete this;
- }
-}
-
-void MessageQueueManager::Clear(MessageHandler *handler) {
- // If there isn't a message queue manager instance, then there aren't any
- // queues to remove this handler from.
- if (!instance_) return;
- return Instance()->ClearInternal(handler);
-}
-void MessageQueueManager::ClearInternal(MessageHandler *handler) {
- ASSERT(!crit_.CurrentThreadIsOwner()); // See note above.
- CritScope cs(&crit_);
- std::vector<MessageQueue *>::iterator iter;
- for (iter = message_queues_.begin(); iter != message_queues_.end(); iter++)
- (*iter)->Clear(handler);
-}
-
-//------------------------------------------------------------------
-// MessageQueue
-
-MessageQueue::MessageQueue(SocketServer* ss)
- : ss_(ss), fStop_(false), fPeekKeep_(false),
- dmsgq_next_num_(0) {
- if (!ss_) {
- // Currently, MessageQueue holds a socket server, and is the base class for
- // Thread. It seems like it makes more sense for Thread to hold the socket
- // server, and provide it to the MessageQueue, since the Thread controls
- // the I/O model, and MQ is agnostic to those details. Anyway, this causes
- // messagequeue_unittest to depend on network libraries... yuck.
- default_ss_.reset(new DefaultSocketServer());
- ss_ = default_ss_.get();
- }
- ss_->SetMessageQueue(this);
- MessageQueueManager::Add(this);
-}
-
-MessageQueue::~MessageQueue() {
- // The signal is done from here to ensure
- // that it always gets called when the queue
- // is going away.
- SignalQueueDestroyed();
- MessageQueueManager::Remove(this);
- Clear(NULL);
- if (ss_) {
- ss_->SetMessageQueue(NULL);
- }
-}
-
-void MessageQueue::set_socketserver(SocketServer* ss) {
- ss_ = ss ? ss : default_ss_.get();
- ss_->SetMessageQueue(this);
-}
-
-void MessageQueue::Quit() {
- fStop_ = true;
- ss_->WakeUp();
-}
-
-bool MessageQueue::IsQuitting() {
- return fStop_;
-}
-
-void MessageQueue::Restart() {
- fStop_ = false;
-}
-
-bool MessageQueue::Peek(Message *pmsg, int cmsWait) {
- if (fPeekKeep_) {
- *pmsg = msgPeek_;
- return true;
- }
- if (!Get(pmsg, cmsWait))
- return false;
- msgPeek_ = *pmsg;
- fPeekKeep_ = true;
- return true;
-}
-
-bool MessageQueue::Get(Message *pmsg, int cmsWait, bool process_io) {
- // Return and clear peek if present
- // Always return the peek if it exists so there is Peek/Get symmetry
-
- if (fPeekKeep_) {
- *pmsg = msgPeek_;
- fPeekKeep_ = false;
- return true;
- }
-
- // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
-
- int cmsTotal = cmsWait;
- int cmsElapsed = 0;
- uint32 msStart = Time();
- uint32 msCurrent = msStart;
- while (true) {
- // Check for sent messages
- ReceiveSends();
-
- // Check for posted events
- int cmsDelayNext = kForever;
- bool first_pass = true;
- while (true) {
- // All queue operations need to be locked, but nothing else in this loop
- // (specifically handling disposed message) can happen inside the crit.
- // Otherwise, disposed MessageHandlers will cause deadlocks.
- {
- CritScope cs(&crit_);
- // On the first pass, check for delayed messages that have been
- // triggered and calculate the next trigger time.
- if (first_pass) {
- first_pass = false;
- while (!dmsgq_.empty()) {
- if (TimeIsLater(msCurrent, dmsgq_.top().msTrigger_)) {
- cmsDelayNext = TimeDiff(dmsgq_.top().msTrigger_, msCurrent);
- break;
- }
- msgq_.push_back(dmsgq_.top().msg_);
- dmsgq_.pop();
- }
- }
- // Pull a message off the message queue, if available.
- if (msgq_.empty()) {
- break;
- } else {
- *pmsg = msgq_.front();
- msgq_.pop_front();
- }
- } // crit_ is released here.
-
- // Log a warning for time-sensitive messages that we're late to deliver.
- if (pmsg->ts_sensitive) {
- int32 delay = TimeDiff(msCurrent, pmsg->ts_sensitive);
- if (delay > 0) {
- LOG_F(LS_WARNING) << "id: " << pmsg->message_id << " delay: "
- << (delay + kMaxMsgLatency) << "ms";
- }
- }
- // If this was a dispose message, delete it and skip it.
- if (MQID_DISPOSE == pmsg->message_id) {
- ASSERT(NULL == pmsg->phandler);
- delete pmsg->pdata;
- *pmsg = Message();
- continue;
- }
- return true;
- }
-
- if (fStop_)
- break;
-
- // Which is shorter, the delay wait or the asked wait?
-
- int cmsNext;
- if (cmsWait == kForever) {
- cmsNext = cmsDelayNext;
- } else {
- cmsNext = _max(0, cmsTotal - cmsElapsed);
- if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
- cmsNext = cmsDelayNext;
- }
-
- // Wait and multiplex in the meantime
- if (!ss_->Wait(cmsNext, process_io))
- return false;
-
- // If the specified timeout expired, return
-
- msCurrent = Time();
- cmsElapsed = TimeDiff(msCurrent, msStart);
- if (cmsWait != kForever) {
- if (cmsElapsed >= cmsWait)
- return false;
- }
- }
- return false;
-}
-
-void MessageQueue::ReceiveSends() {
-}
-
-void MessageQueue::Post(MessageHandler *phandler, uint32 id,
- MessageData *pdata, bool time_sensitive) {
- if (fStop_)
- return;
-
- // Keep thread safe
- // Add the message to the end of the queue
- // Signal for the multiplexer to return
-
- CritScope cs(&crit_);
- Message msg;
- msg.phandler = phandler;
- msg.message_id = id;
- msg.pdata = pdata;
- if (time_sensitive) {
- msg.ts_sensitive = Time() + kMaxMsgLatency;
- }
- msgq_.push_back(msg);
- ss_->WakeUp();
-}
-
-void MessageQueue::DoDelayPost(int cmsDelay, uint32 tstamp,
- MessageHandler *phandler, uint32 id, MessageData* pdata) {
- if (fStop_)
- return;
-
- // Keep thread safe
- // Add to the priority queue. Gets sorted soonest first.
- // Signal for the multiplexer to return.
-
- CritScope cs(&crit_);
- Message msg;
- msg.phandler = phandler;
- msg.message_id = id;
- msg.pdata = pdata;
- DelayedMessage dmsg(cmsDelay, tstamp, dmsgq_next_num_, msg);
- dmsgq_.push(dmsg);
- // If this message queue processes 1 message every millisecond for 50 days,
- // we will wrap this number. Even then, only messages with identical times
- // will be misordered, and then only briefly. This is probably ok.
- VERIFY(0 != ++dmsgq_next_num_);
- ss_->WakeUp();
-}
-
-int MessageQueue::GetDelay() {
- CritScope cs(&crit_);
-
- if (!msgq_.empty())
- return 0;
-
- if (!dmsgq_.empty()) {
- int delay = TimeUntil(dmsgq_.top().msTrigger_);
- if (delay < 0)
- delay = 0;
- return delay;
- }
-
- return kForever;
-}
-
-void MessageQueue::Clear(MessageHandler *phandler, uint32 id,
- MessageList* removed) {
- CritScope cs(&crit_);
-
- // Remove messages with phandler
-
- if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
- if (removed) {
- removed->push_back(msgPeek_);
- } else {
- delete msgPeek_.pdata;
- }
- fPeekKeep_ = false;
- }
-
- // Remove from ordered message queue
-
- for (MessageList::iterator it = msgq_.begin(); it != msgq_.end();) {
- if (it->Match(phandler, id)) {
- if (removed) {
- removed->push_back(*it);
- } else {
- delete it->pdata;
- }
- it = msgq_.erase(it);
- } else {
- ++it;
- }
- }
-
- // Remove from priority queue. Not directly iterable, so use this approach
-
- PriorityQueue::container_type::iterator new_end = dmsgq_.container().begin();
- for (PriorityQueue::container_type::iterator it = new_end;
- it != dmsgq_.container().end(); ++it) {
- if (it->msg_.Match(phandler, id)) {
- if (removed) {
- removed->push_back(it->msg_);
- } else {
- delete it->msg_.pdata;
- }
- } else {
- *new_end++ = *it;
- }
- }
- dmsgq_.container().erase(new_end, dmsgq_.container().end());
- dmsgq_.reheap();
-}
-
-void MessageQueue::Dispatch(Message *pmsg) {
- pmsg->phandler->OnMessage(pmsg);
-}
-
-} // namespace talk_base
diff --git a/base/messagequeue.h b/base/messagequeue.h
deleted file mode 100644
index dc2b5a8..0000000
--- a/base/messagequeue.h
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_MESSAGEQUEUE_H_
-#define TALK_BASE_MESSAGEQUEUE_H_
-
-#include <string.h>
-
-#include <algorithm>
-#include <list>
-#include <queue>
-#include <vector>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/constructormagic.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/scoped_ref_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socketserver.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-struct Message;
-class MessageQueue;
-
-// MessageQueueManager does cleanup of of message queues
-
-class MessageQueueManager {
- public:
- static void Add(MessageQueue *message_queue);
- static void Remove(MessageQueue *message_queue);
- static void Clear(MessageHandler *handler);
-
- // For testing purposes, we expose whether or not the MessageQueueManager
- // instance has been initialized. It has no other use relative to the rest of
- // the functions of this class, which auto-initialize the underlying
- // MessageQueueManager instance when necessary.
- static bool IsInitialized();
-
- private:
- static MessageQueueManager* Instance();
-
- MessageQueueManager();
- ~MessageQueueManager();
-
- void AddInternal(MessageQueue *message_queue);
- void RemoveInternal(MessageQueue *message_queue);
- void ClearInternal(MessageHandler *handler);
-
- static MessageQueueManager* instance_;
- // This list contains all live MessageQueues.
- std::vector<MessageQueue *> message_queues_;
- CriticalSection crit_;
-};
-
-// Derive from this for specialized data
-// App manages lifetime, except when messages are purged
-
-class MessageData {
- public:
- MessageData() {}
- virtual ~MessageData() {}
-};
-
-template <class T>
-class TypedMessageData : public MessageData {
- public:
- explicit TypedMessageData(const T& data) : data_(data) { }
- const T& data() const { return data_; }
- T& data() { return data_; }
- private:
- T data_;
-};
-
-// Like TypedMessageData, but for pointers that require a delete.
-template <class T>
-class ScopedMessageData : public MessageData {
- public:
- explicit ScopedMessageData(T* data) : data_(data) { }
- const scoped_ptr<T>& data() const { return data_; }
- scoped_ptr<T>& data() { return data_; }
- private:
- scoped_ptr<T> data_;
-};
-
-// Like ScopedMessageData, but for reference counted pointers.
-template <class T>
-class ScopedRefMessageData : public MessageData {
- public:
- explicit ScopedRefMessageData(T* data) : data_(data) { }
- const scoped_refptr<T>& data() const { return data_; }
- scoped_refptr<T>& data() { return data_; }
- private:
- scoped_refptr<T> data_;
-};
-
-template<class T>
-inline MessageData* WrapMessageData(const T& data) {
- return new TypedMessageData<T>(data);
-}
-
-template<class T>
-inline const T& UseMessageData(MessageData* data) {
- return static_cast< TypedMessageData<T>* >(data)->data();
-}
-
-template<class T>
-class DisposeData : public MessageData {
- public:
- explicit DisposeData(T* data) : data_(data) { }
- virtual ~DisposeData() { delete data_; }
- private:
- T* data_;
-};
-
-const uint32 MQID_ANY = static_cast<uint32>(-1);
-const uint32 MQID_DISPOSE = static_cast<uint32>(-2);
-
-// No destructor
-
-struct Message {
- Message() {
- memset(this, 0, sizeof(*this));
- }
- inline bool Match(MessageHandler* handler, uint32 id) const {
- return (handler == NULL || handler == phandler)
- && (id == MQID_ANY || id == message_id);
- }
- MessageHandler *phandler;
- uint32 message_id;
- MessageData *pdata;
- uint32 ts_sensitive;
-};
-
-typedef std::list<Message> MessageList;
-
-// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
-// with the same trigger time are processed in num_ (FIFO) order.
-
-class DelayedMessage {
- public:
- DelayedMessage(int delay, uint32 trigger, uint32 num, const Message& msg)
- : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) { }
-
- bool operator< (const DelayedMessage& dmsg) const {
- return (dmsg.msTrigger_ < msTrigger_)
- || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
- }
-
- int cmsDelay_; // for debugging
- uint32 msTrigger_;
- uint32 num_;
- Message msg_;
-};
-
-class MessageQueue {
- public:
- explicit MessageQueue(SocketServer* ss = NULL);
- virtual ~MessageQueue();
-
- SocketServer* socketserver() { return ss_; }
- void set_socketserver(SocketServer* ss);
-
- // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
- // futher Posts and Sends will fail. However, any pending Sends and *ready*
- // Posts (as opposed to unexpired delayed Posts) will be delivered before
- // Get (or Peek) returns false. By guaranteeing delivery of those messages,
- // we eliminate the race condition when an MessageHandler and MessageQueue
- // may be destroyed independently of each other.
- virtual void Quit();
- virtual bool IsQuitting();
- virtual void Restart();
-
- // Get() will process I/O until:
- // 1) A message is available (returns true)
- // 2) cmsWait seconds have elapsed (returns false)
- // 3) Stop() is called (returns false)
- virtual bool Get(Message *pmsg, int cmsWait = kForever,
- bool process_io = true);
- virtual bool Peek(Message *pmsg, int cmsWait = 0);
- virtual void Post(MessageHandler *phandler, uint32 id = 0,
- MessageData *pdata = NULL, bool time_sensitive = false);
- virtual void PostDelayed(int cmsDelay, MessageHandler *phandler,
- uint32 id = 0, MessageData *pdata = NULL) {
- return DoDelayPost(cmsDelay, TimeAfter(cmsDelay), phandler, id, pdata);
- }
- virtual void PostAt(uint32 tstamp, MessageHandler *phandler,
- uint32 id = 0, MessageData *pdata = NULL) {
- return DoDelayPost(TimeUntil(tstamp), tstamp, phandler, id, pdata);
- }
- virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY,
- MessageList* removed = NULL);
- virtual void Dispatch(Message *pmsg);
- virtual void ReceiveSends();
-
- // Amount of time until the next message can be retrieved
- virtual int GetDelay();
-
- bool empty() const { return size() == 0u; }
- size_t size() const {
- CritScope cs(&crit_); // msgq_.size() is not thread safe.
- return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
- }
-
- // Internally posts a message which causes the doomed object to be deleted
- template<class T> void Dispose(T* doomed) {
- if (doomed) {
- Post(NULL, MQID_DISPOSE, new DisposeData<T>(doomed));
- }
- }
-
- // When this signal is sent out, any references to this queue should
- // no longer be used.
- sigslot::signal0<> SignalQueueDestroyed;
-
- protected:
- class PriorityQueue : public std::priority_queue<DelayedMessage> {
- public:
- container_type& container() { return c; }
- void reheap() { make_heap(c.begin(), c.end(), comp); }
- };
-
- void DoDelayPost(int cmsDelay, uint32 tstamp, MessageHandler *phandler,
- uint32 id, MessageData* pdata);
-
- // The SocketServer is not owned by MessageQueue.
- SocketServer* ss_;
- // If a server isn't supplied in the constructor, use this one.
- scoped_ptr<SocketServer> default_ss_;
- bool fStop_;
- bool fPeekKeep_;
- Message msgPeek_;
- MessageList msgq_;
- PriorityQueue dmsgq_;
- uint32 dmsgq_next_num_;
- mutable CriticalSection crit_;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(MessageQueue);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MESSAGEQUEUE_H_
diff --git a/base/messagequeue_unittest.cc b/base/messagequeue_unittest.cc
deleted file mode 100644
index 9ce524e..0000000
--- a/base/messagequeue_unittest.cc
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/messagequeue.h"
-
-#include "talk/base/bind.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-#include "talk/base/nullsocketserver.h"
-
-using namespace talk_base;
-
-class MessageQueueTest: public testing::Test, public MessageQueue {
- public:
- bool IsLocked_Worker() {
- if (!crit_.TryEnter()) {
- return true;
- }
- crit_.Leave();
- return false;
- }
- bool IsLocked() {
- // We have to do this on a worker thread, or else the TryEnter will
- // succeed, since our critical sections are reentrant.
- Thread worker;
- worker.Start();
- return worker.Invoke<bool>(
- talk_base::Bind(&MessageQueueTest::IsLocked_Worker, this));
- }
-};
-
-struct DeletedLockChecker {
- DeletedLockChecker(MessageQueueTest* test, bool* was_locked, bool* deleted)
- : test(test), was_locked(was_locked), deleted(deleted) { }
- ~DeletedLockChecker() {
- *deleted = true;
- *was_locked = test->IsLocked();
- }
- MessageQueueTest* test;
- bool* was_locked;
- bool* deleted;
-};
-
-static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(
- MessageQueue* q) {
- EXPECT_TRUE(q != NULL);
- TimeStamp now = Time();
- q->PostAt(now, NULL, 3);
- q->PostAt(now - 2, NULL, 0);
- q->PostAt(now - 1, NULL, 1);
- q->PostAt(now, NULL, 4);
- q->PostAt(now - 1, NULL, 2);
-
- Message msg;
- for (size_t i=0; i<5; ++i) {
- memset(&msg, 0, sizeof(msg));
- EXPECT_TRUE(q->Get(&msg, 0));
- EXPECT_EQ(i, msg.message_id);
- }
-
- EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
-}
-
-TEST_F(MessageQueueTest,
- DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
- MessageQueue q;
- DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
- NullSocketServer nullss;
- MessageQueue q_nullss(&nullss);
- DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
-}
-
-TEST_F(MessageQueueTest, DisposeNotLocked) {
- bool was_locked = true;
- bool deleted = false;
- DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
- Dispose(d);
- Message msg;
- EXPECT_FALSE(Get(&msg, 0));
- EXPECT_TRUE(deleted);
- EXPECT_FALSE(was_locked);
-}
-
-class DeletedMessageHandler : public MessageHandler {
- public:
- explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) { }
- ~DeletedMessageHandler() {
- *deleted_ = true;
- }
- void OnMessage(Message* msg) { }
- private:
- bool* deleted_;
-};
-
-TEST_F(MessageQueueTest, DiposeHandlerWithPostedMessagePending) {
- bool deleted = false;
- DeletedMessageHandler *handler = new DeletedMessageHandler(&deleted);
- // First, post a dispose.
- Dispose(handler);
- // Now, post a message, which should *not* be returned by Get().
- Post(handler, 1);
- Message msg;
- EXPECT_FALSE(Get(&msg, 0));
- EXPECT_TRUE(deleted);
-}
-
-struct UnwrapMainThreadScope {
- UnwrapMainThreadScope() : rewrap_(Thread::Current() != NULL) {
- if (rewrap_) ThreadManager::Instance()->UnwrapCurrentThread();
- }
- ~UnwrapMainThreadScope() {
- if (rewrap_) ThreadManager::Instance()->WrapCurrentThread();
- }
- private:
- bool rewrap_;
-};
-
-TEST(MessageQueueManager, Clear) {
- UnwrapMainThreadScope s;
- if (MessageQueueManager::IsInitialized()) {
- LOG(LS_INFO) << "Unable to run MessageQueueManager::Clear test, since the "
- << "MessageQueueManager was already initialized by some "
- << "other test in this run.";
- return;
- }
- bool deleted = false;
- DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
- delete handler;
- EXPECT_TRUE(deleted);
- EXPECT_FALSE(MessageQueueManager::IsInitialized());
-}
diff --git a/base/move.h b/base/move.h
deleted file mode 100644
index a04b7c8..0000000
--- a/base/move.h
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_WEBRTC_FILES_TALK_BASE_MOVE_H_
-#define THIRD_PARTY_WEBRTC_FILES_TALK_BASE_MOVE_H_
-
-// Macro with the boilerplate that makes a type move-only in C++03.
-//
-// USAGE
-//
-// This macro should be used instead of DISALLOW_COPY_AND_ASSIGN to create
-// a "move-only" type. Unlike DISALLOW_COPY_AND_ASSIGN, this macro should be
-// the first line in a class declaration.
-//
-// A class using this macro must call .Pass() (or somehow be an r-value already)
-// before it can be:
-//
-// * Passed as a function argument
-// * Used as the right-hand side of an assignment
-// * Returned from a function
-//
-// Each class will still need to define their own "move constructor" and "move
-// operator=" to make this useful. Here's an example of the macro, the move
-// constructor, and the move operator= from the scoped_ptr class:
-//
-// template <typename T>
-// class scoped_ptr {
-// TALK_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
-// public:
-// scoped_ptr(RValue& other) : ptr_(other.release()) { }
-// scoped_ptr& operator=(RValue& other) {
-// swap(other);
-// return *this;
-// }
-// };
-//
-// Note that the constructor must NOT be marked explicit.
-//
-// For consistency, the second parameter to the macro should always be RValue
-// unless you have a strong reason to do otherwise. It is only exposed as a
-// macro parameter so that the move constructor and move operator= don't look
-// like they're using a phantom type.
-//
-//
-// HOW THIS WORKS
-//
-// For a thorough explanation of this technique, see:
-//
-// http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Move_Constructor
-//
-// The summary is that we take advantage of 2 properties:
-//
-// 1) non-const references will not bind to r-values.
-// 2) C++ can apply one user-defined conversion when initializing a
-// variable.
-//
-// The first lets us disable the copy constructor and assignment operator
-// by declaring private version of them with a non-const reference parameter.
-//
-// For l-values, direct initialization still fails like in
-// DISALLOW_COPY_AND_ASSIGN because the copy constructor and assignment
-// operators are private.
-//
-// For r-values, the situation is different. The copy constructor and
-// assignment operator are not viable due to (1), so we are trying to call
-// a non-existent constructor and non-existing operator= rather than a private
-// one. Since we have not committed an error quite yet, we can provide an
-// alternate conversion sequence and a constructor. We add
-//
-// * a private struct named "RValue"
-// * a user-defined conversion "operator RValue()"
-// * a "move constructor" and "move operator=" that take the RValue& as
-// their sole parameter.
-//
-// Only r-values will trigger this sequence and execute our "move constructor"
-// or "move operator=." L-values will match the private copy constructor and
-// operator= first giving a "private in this context" error. This combination
-// gives us a move-only type.
-//
-// For signaling a destructive transfer of data from an l-value, we provide a
-// method named Pass() which creates an r-value for the current instance
-// triggering the move constructor or move operator=.
-//
-// Other ways to get r-values is to use the result of an expression like a
-// function call.
-//
-// Here's an example with comments explaining what gets triggered where:
-//
-// class Foo {
-// TALK_MOVE_ONLY_TYPE_FOR_CPP_03(Foo, RValue);
-//
-// public:
-// ... API ...
-// Foo(RValue other); // Move constructor.
-// Foo& operator=(RValue rhs); // Move operator=
-// };
-//
-// Foo MakeFoo(); // Function that returns a Foo.
-//
-// Foo f;
-// Foo f_copy(f); // ERROR: Foo(Foo&) is private in this context.
-// Foo f_assign;
-// f_assign = f; // ERROR: operator=(Foo&) is private in this context.
-//
-//
-// Foo f(MakeFoo()); // R-value so alternate conversion executed.
-// Foo f_copy(f.Pass()); // R-value so alternate conversion executed.
-// f = f_copy.Pass(); // R-value so alternate conversion executed.
-//
-//
-// IMPLEMENTATION SUBTLETIES WITH RValue
-//
-// The RValue struct is just a container for a pointer back to the original
-// object. It should only ever be created as a temporary, and no external
-// class should ever declare it or use it in a parameter.
-//
-// It is tempting to want to use the RValue type in function parameters, but
-// excluding the limited usage here for the move constructor and move
-// operator=, doing so would mean that the function could take both r-values
-// and l-values equially which is unexpected. See COMPARED To Boost.Move for
-// more details.
-//
-// An alternate, and incorrect, implementation of the RValue class used by
-// Boost.Move makes RValue a fieldless child of the move-only type. RValue&
-// is then used in place of RValue in the various operators. The RValue& is
-// "created" by doing *reinterpret_cast<RValue*>(this). This has the appeal
-// of never creating a temporary RValue struct even with optimizations
-// disabled. Also, by virtue of inheritance you can treat the RValue
-// reference as if it were the move-only type itself. Unfortunately,
-// using the result of this reinterpret_cast<> is actually undefined behavior
-// due to C++98 5.2.10.7. In certain compilers (e.g., NaCl) the optimizer
-// will generate non-working code.
-//
-// In optimized builds, both implementations generate the same assembly so we
-// choose the one that adheres to the standard.
-//
-//
-// COMPARED TO C++11
-//
-// In C++11, you would implement this functionality using an r-value reference
-// and our .Pass() method would be replaced with a call to std::move().
-//
-// This emulation also has a deficiency where it uses up the single
-// user-defined conversion allowed by C++ during initialization. This can
-// cause problems in some API edge cases. For instance, in scoped_ptr, it is
-// impossible to make a function "void Foo(scoped_ptr<Parent> p)" accept a
-// value of type scoped_ptr<Child> even if you add a constructor to
-// scoped_ptr<> that would make it look like it should work. C++11 does not
-// have this deficiency.
-//
-//
-// COMPARED TO Boost.Move
-//
-// Our implementation similar to Boost.Move, but we keep the RValue struct
-// private to the move-only type, and we don't use the reinterpret_cast<> hack.
-//
-// In Boost.Move, RValue is the boost::rv<> template. This type can be used
-// when writing APIs like:
-//
-// void MyFunc(boost::rv<Foo>& f)
-//
-// that can take advantage of rv<> to avoid extra copies of a type. However you
-// would still be able to call this version of MyFunc with an l-value:
-//
-// Foo f;
-// MyFunc(f); // Uh oh, we probably just destroyed |f| w/o calling Pass().
-//
-// unless someone is very careful to also declare a parallel override like:
-//
-// void MyFunc(const Foo& f)
-//
-// that would catch the l-values first. This was declared unsafe in C++11 and
-// a C++11 compiler will explicitly fail MyFunc(f). Unfortunately, we cannot
-// ensure this in C++03.
-//
-// Since we have no need for writing such APIs yet, our implementation keeps
-// RValue private and uses a .Pass() method to do the conversion instead of
-// trying to write a version of "std::move()." Writing an API like std::move()
-// would require the RValue struct to be public.
-//
-//
-// CAVEATS
-//
-// If you include a move-only type as a field inside a class that does not
-// explicitly declare a copy constructor, the containing class's implicit
-// copy constructor will change from Containing(const Containing&) to
-// Containing(Containing&). This can cause some unexpected errors.
-//
-// http://llvm.org/bugs/show_bug.cgi?id=11528
-//
-// The workaround is to explicitly declare your copy constructor.
-//
-#define TALK_MOVE_ONLY_TYPE_FOR_CPP_03(type, rvalue_type) \
- private: \
- struct rvalue_type { \
- explicit rvalue_type(type* object) : object(object) {} \
- type* object; \
- }; \
- type(type&); \
- void operator=(type&); \
- public: \
- operator rvalue_type() { return rvalue_type(this); } \
- type Pass() { return type(rvalue_type(this)); } \
- private:
-
-#endif // THIRD_PARTY_WEBRTC_FILES_TALK_BASE_MOVE_H_
diff --git a/base/multipart.cc b/base/multipart.cc
deleted file mode 100644
index d280ff3..0000000
--- a/base/multipart.cc
+++ /dev/null
@@ -1,268 +0,0 @@
-// libjingle
-// Copyright 2004--2010, Google Inc.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-// 2. Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following disclaimer in the documentation
-// and/or other materials provided with the distribution.
-// 3. The name of the author may not be used to endorse or promote products
-// derived from this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
-// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-#include "talk/base/common.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/multipart.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// MultipartStream
-///////////////////////////////////////////////////////////////////////////////
-
-MultipartStream::MultipartStream(const std::string& type,
- const std::string& boundary)
- : type_(type),
- boundary_(boundary),
- adding_(true),
- current_(0),
- position_(0) {
- // The content type should be multipart/*.
- ASSERT(0 == strncmp(type_.c_str(), "multipart/", 10));
-}
-
-MultipartStream::~MultipartStream() {
- Close();
-}
-
-void MultipartStream::GetContentType(std::string* content_type) {
- ASSERT(NULL != content_type);
- content_type->assign(type_);
- content_type->append("; boundary=");
- content_type->append(boundary_);
-}
-
-bool MultipartStream::AddPart(StreamInterface* data_stream,
- const std::string& content_disposition,
- const std::string& content_type) {
- if (!AddPart("", content_disposition, content_type))
- return false;
- parts_.push_back(data_stream);
- data_stream->SignalEvent.connect(this, &MultipartStream::OnEvent);
- return true;
-}
-
-bool MultipartStream::AddPart(const std::string& data,
- const std::string& content_disposition,
- const std::string& content_type) {
- ASSERT(adding_);
- if (!adding_)
- return false;
- std::stringstream ss;
- if (!parts_.empty()) {
- ss << "\r\n";
- }
- ss << "--" << boundary_ << "\r\n";
- if (!content_disposition.empty()) {
- ss << ToString(HH_CONTENT_DISPOSITION) << ": "
- << content_disposition << "\r\n";
- }
- if (!content_type.empty()) {
- ss << ToString(HH_CONTENT_TYPE) << ": "
- << content_type << "\r\n";
- }
- ss << "\r\n" << data;
- parts_.push_back(new MemoryStream(ss.str().data(), ss.str().size()));
- return true;
-}
-
-void MultipartStream::EndParts() {
- ASSERT(adding_);
- if (!adding_)
- return;
-
- std::stringstream ss;
- if (!parts_.empty()) {
- ss << "\r\n";
- }
- ss << "--" << boundary_ << "--" << "\r\n";
- parts_.push_back(new MemoryStream(ss.str().data(), ss.str().size()));
-
- ASSERT(0 == current_);
- ASSERT(0 == position_);
- adding_ = false;
- SignalEvent(this, SE_OPEN | SE_READ, 0);
-}
-
-size_t MultipartStream::GetPartSize(const std::string& data,
- const std::string& content_disposition,
- const std::string& content_type) const {
- size_t size = 0;
- if (!parts_.empty()) {
- size += 2; // for "\r\n";
- }
- size += boundary_.size() + 4; // for "--boundary_\r\n";
- if (!content_disposition.empty()) {
- // for ToString(HH_CONTENT_DISPOSITION): content_disposition\r\n
- size += std::string(ToString(HH_CONTENT_DISPOSITION)).size() + 2 +
- content_disposition.size() + 2;
- }
- if (!content_type.empty()) {
- // for ToString(HH_CONTENT_TYPE): content_type\r\n
- size += std::string(ToString(HH_CONTENT_TYPE)).size() + 2 +
- content_type.size() + 2;
- }
- size += 2 + data.size(); // for \r\ndata
- return size;
-}
-
-size_t MultipartStream::GetEndPartSize() const {
- size_t size = 0;
- if (!parts_.empty()) {
- size += 2; // for "\r\n";
- }
- size += boundary_.size() + 6; // for "--boundary_--\r\n";
- return size;
-}
-
-//
-// StreamInterface
-//
-
-StreamState MultipartStream::GetState() const {
- if (adding_) {
- return SS_OPENING;
- }
- return (current_ < parts_.size()) ? SS_OPEN : SS_CLOSED;
-}
-
-StreamResult MultipartStream::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- if (adding_) {
- return SR_BLOCK;
- }
- size_t local_read;
- if (!read) read = &local_read;
- while (current_ < parts_.size()) {
- StreamResult result = parts_[current_]->Read(buffer, buffer_len, read,
- error);
- if (SR_EOS != result) {
- if (SR_SUCCESS == result) {
- position_ += *read;
- }
- return result;
- }
- ++current_;
- }
- return SR_EOS;
-}
-
-StreamResult MultipartStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (error) {
- *error = -1;
- }
- return SR_ERROR;
-}
-
-void MultipartStream::Close() {
- for (size_t i = 0; i < parts_.size(); ++i) {
- delete parts_[i];
- }
- parts_.clear();
- adding_ = false;
- current_ = 0;
- position_ = 0;
-}
-
-bool MultipartStream::SetPosition(size_t position) {
- if (adding_) {
- return false;
- }
- size_t part_size, part_offset = 0;
- for (size_t i = 0; i < parts_.size(); ++i) {
- if (!parts_[i]->GetSize(&part_size)) {
- return false;
- }
- if (part_offset + part_size > position) {
- for (size_t j = i+1; j < _min(parts_.size(), current_+1); ++j) {
- if (!parts_[j]->Rewind()) {
- return false;
- }
- }
- if (!parts_[i]->SetPosition(position - part_offset)) {
- return false;
- }
- current_ = i;
- position_ = position;
- return true;
- }
- part_offset += part_size;
- }
- return false;
-}
-
-bool MultipartStream::GetPosition(size_t* position) const {
- if (position) {
- *position = position_;
- }
- return true;
-}
-
-bool MultipartStream::GetSize(size_t* size) const {
- size_t part_size, total_size = 0;
- for (size_t i = 0; i < parts_.size(); ++i) {
- if (!parts_[i]->GetSize(&part_size)) {
- return false;
- }
- total_size += part_size;
- }
- if (size) {
- *size = total_size;
- }
- return true;
-}
-
-bool MultipartStream::GetAvailable(size_t* size) const {
- if (adding_) {
- return false;
- }
- size_t part_size, total_size = 0;
- for (size_t i = current_; i < parts_.size(); ++i) {
- if (!parts_[i]->GetAvailable(&part_size)) {
- return false;
- }
- total_size += part_size;
- }
- if (size) {
- *size = total_size;
- }
- return true;
-}
-
-//
-// StreamInterface Slots
-//
-
-void MultipartStream::OnEvent(StreamInterface* stream, int events, int error) {
- if (adding_ || (current_ >= parts_.size()) || (parts_[current_] != stream)) {
- return;
- }
- SignalEvent(this, events, error);
-}
-
-} // namespace talk_base
diff --git a/base/multipart.h b/base/multipart.h
deleted file mode 100644
index cce592b..0000000
--- a/base/multipart.h
+++ /dev/null
@@ -1,94 +0,0 @@
-// libjingle
-// Copyright 2004--2010, Google Inc.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-// 2. Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following disclaimer in the documentation
-// and/or other materials provided with the distribution.
-// 3. The name of the author may not be used to endorse or promote products
-// derived from this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
-// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef TALK_BASE_MULTIPART_H__
-#define TALK_BASE_MULTIPART_H__
-
-#include <string>
-#include <vector>
-
-#include "talk/base/sigslot.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// MultipartStream - Implements an RFC2046 multipart stream by concatenating
-// the supplied parts together, and adding the correct boundaries.
-///////////////////////////////////////////////////////////////////////////////
-
-class MultipartStream : public StreamInterface, public sigslot::has_slots<> {
- public:
- MultipartStream(const std::string& type, const std::string& boundary);
- virtual ~MultipartStream();
-
- void GetContentType(std::string* content_type);
-
- // Note: If content_disposition and/or content_type are the empty string,
- // they will be omitted.
- bool AddPart(StreamInterface* data_stream,
- const std::string& content_disposition,
- const std::string& content_type);
- bool AddPart(const std::string& data,
- const std::string& content_disposition,
- const std::string& content_type);
- void EndParts();
-
- // Calculates the size of a part before actually adding the part.
- size_t GetPartSize(const std::string& data,
- const std::string& content_disposition,
- const std::string& content_type) const;
- size_t GetEndPartSize() const;
-
- // StreamInterface
- virtual StreamState GetState() const;
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- virtual void Close();
- virtual bool SetPosition(size_t position);
- virtual bool GetPosition(size_t* position) const;
- virtual bool GetSize(size_t* size) const;
- virtual bool GetAvailable(size_t* size) const;
-
- private:
- typedef std::vector<StreamInterface*> PartList;
-
- // StreamInterface Slots
- void OnEvent(StreamInterface* stream, int events, int error);
-
- std::string type_, boundary_;
- PartList parts_;
- bool adding_;
- size_t current_; // The index into parts_ of the current read position.
- size_t position_; // The current read position in bytes.
-
- DISALLOW_COPY_AND_ASSIGN(MultipartStream);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_MULTIPART_H__
diff --git a/base/multipart_unittest.cc b/base/multipart_unittest.cc
deleted file mode 100644
index 7266ed5..0000000
--- a/base/multipart_unittest.cc
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/multipart.h"
-
-namespace talk_base {
-
-static const std::string kTestMultipartBoundary = "123456789987654321";
-static const std::string kTestContentType =
- "multipart/form-data; boundary=123456789987654321";
-static const char kTestData[] = "This is a test.";
-static const char kTestStreamContent[] = "This is a test stream.";
-
-TEST(MultipartTest, TestBasicOperations) {
- MultipartStream multipart("multipart/form-data", kTestMultipartBoundary);
- std::string content_type;
- multipart.GetContentType(&content_type);
- EXPECT_EQ(kTestContentType, content_type);
-
- EXPECT_EQ(talk_base::SS_OPENING, multipart.GetState());
-
- // The multipart stream contains only --boundary--\r\n
- size_t end_part_size = multipart.GetEndPartSize();
- multipart.EndParts();
- EXPECT_EQ(talk_base::SS_OPEN, multipart.GetState());
- size_t size;
- EXPECT_TRUE(multipart.GetSize(&size));
- EXPECT_EQ(end_part_size, size);
-
- // Write is not supported.
- EXPECT_EQ(talk_base::SR_ERROR,
- multipart.Write(kTestData, sizeof(kTestData), NULL, NULL));
-
- multipart.Close();
- EXPECT_EQ(talk_base::SS_CLOSED, multipart.GetState());
- EXPECT_TRUE(multipart.GetSize(&size));
- EXPECT_EQ(0U, size);
-}
-
-TEST(MultipartTest, TestAddAndRead) {
- MultipartStream multipart("multipart/form-data", kTestMultipartBoundary);
-
- size_t part_size =
- multipart.GetPartSize(kTestData, "form-data; name=\"text\"", "text");
- EXPECT_TRUE(multipart.AddPart(kTestData, "form-data; name=\"text\"", "text"));
- size_t size;
- EXPECT_TRUE(multipart.GetSize(&size));
- EXPECT_EQ(part_size, size);
-
- talk_base::scoped_ptr<talk_base::MemoryStream> stream(
- new talk_base::MemoryStream(kTestStreamContent));
- size_t stream_size = 0;
- EXPECT_TRUE(stream->GetSize(&stream_size));
- part_size +=
- multipart.GetPartSize("", "form-data; name=\"stream\"", "stream");
- part_size += stream_size;
-
- EXPECT_TRUE(multipart.AddPart(
- new talk_base::MemoryStream(kTestStreamContent),
- "form-data; name=\"stream\"",
- "stream"));
- EXPECT_TRUE(multipart.GetSize(&size));
- EXPECT_EQ(part_size, size);
-
- // In adding state, block read.
- char buffer[1024];
- EXPECT_EQ(talk_base::SR_BLOCK,
- multipart.Read(buffer, sizeof(buffer), NULL, NULL));
- // Write is not supported.
- EXPECT_EQ(talk_base::SR_ERROR,
- multipart.Write(buffer, sizeof(buffer), NULL, NULL));
-
- part_size += multipart.GetEndPartSize();
- multipart.EndParts();
- EXPECT_TRUE(multipart.GetSize(&size));
- EXPECT_EQ(part_size, size);
-
- // Read the multipart stream into StringStream
- std::string str;
- talk_base::StringStream str_stream(str);
- EXPECT_EQ(talk_base::SR_SUCCESS,
- Flow(&multipart, buffer, sizeof(buffer), &str_stream));
- EXPECT_EQ(size, str.length());
-
- // Search three boundaries and two parts in the order.
- size_t pos = 0;
- pos = str.find(kTestMultipartBoundary);
- EXPECT_NE(std::string::npos, pos);
- pos += kTestMultipartBoundary.length();
-
- pos = str.find(kTestData, pos);
- EXPECT_NE(std::string::npos, pos);
- pos += sizeof(kTestData);
-
- pos = str.find(kTestMultipartBoundary, pos);
- EXPECT_NE(std::string::npos, pos);
- pos += kTestMultipartBoundary.length();
-
- pos = str.find(kTestStreamContent, pos);
- EXPECT_NE(std::string::npos, pos);
- pos += sizeof(kTestStreamContent);
-
- pos = str.find(kTestMultipartBoundary, pos);
- EXPECT_NE(std::string::npos, pos);
- pos += kTestMultipartBoundary.length();
-
- pos = str.find(kTestMultipartBoundary, pos);
- EXPECT_EQ(std::string::npos, pos);
-}
-
-} // namespace talk_base
diff --git a/base/nat_unittest.cc b/base/nat_unittest.cc
deleted file mode 100644
index 9771235..0000000
--- a/base/nat_unittest.cc
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/natserver.h"
-#include "talk/base/natsocketfactory.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/network.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/testclient.h"
-#include "talk/base/virtualsocketserver.h"
-
-using namespace talk_base;
-
-bool CheckReceive(
- TestClient* client, bool should_receive, const char* buf, size_t size) {
- return (should_receive) ?
- client->CheckNextPacket(buf, size, 0) :
- client->CheckNoPacket();
-}
-
-TestClient* CreateTestClient(
- SocketFactory* factory, const SocketAddress& local_addr) {
- AsyncUDPSocket* socket = AsyncUDPSocket::Create(factory, local_addr);
- return new TestClient(socket);
-}
-
-// Tests that when sending from internal_addr to external_addrs through the
-// NAT type specified by nat_type, all external addrs receive the sent packet
-// and, if exp_same is true, all use the same mapped-address on the NAT.
-void TestSend(
- SocketServer* internal, const SocketAddress& internal_addr,
- SocketServer* external, const SocketAddress external_addrs[4],
- NATType nat_type, bool exp_same) {
- Thread th_int(internal);
- Thread th_ext(external);
-
- SocketAddress server_addr = internal_addr;
- server_addr.SetPort(0); // Auto-select a port
- NATServer* nat = new NATServer(
- nat_type, internal, server_addr, external, external_addrs[0]);
- NATSocketFactory* natsf = new NATSocketFactory(internal,
- nat->internal_address());
-
- TestClient* in = CreateTestClient(natsf, internal_addr);
- TestClient* out[4];
- for (int i = 0; i < 4; i++)
- out[i] = CreateTestClient(external, external_addrs[i]);
-
- th_int.Start();
- th_ext.Start();
-
- const char* buf = "filter_test";
- size_t len = strlen(buf);
-
- in->SendTo(buf, len, out[0]->address());
- SocketAddress trans_addr;
- EXPECT_TRUE(out[0]->CheckNextPacket(buf, len, &trans_addr));
-
- for (int i = 1; i < 4; i++) {
- in->SendTo(buf, len, out[i]->address());
- SocketAddress trans_addr2;
- EXPECT_TRUE(out[i]->CheckNextPacket(buf, len, &trans_addr2));
- bool are_same = (trans_addr == trans_addr2);
- ASSERT_EQ(are_same, exp_same) << "same translated address";
- ASSERT_NE(AF_UNSPEC, trans_addr.family());
- ASSERT_NE(AF_UNSPEC, trans_addr2.family());
- }
-
- th_int.Stop();
- th_ext.Stop();
-
- delete nat;
- delete natsf;
- delete in;
- for (int i = 0; i < 4; i++)
- delete out[i];
-}
-
-// Tests that when sending from external_addrs to internal_addr, the packet
-// is delivered according to the specified filter_ip and filter_port rules.
-void TestRecv(
- SocketServer* internal, const SocketAddress& internal_addr,
- SocketServer* external, const SocketAddress external_addrs[4],
- NATType nat_type, bool filter_ip, bool filter_port) {
- Thread th_int(internal);
- Thread th_ext(external);
-
- SocketAddress server_addr = internal_addr;
- server_addr.SetPort(0); // Auto-select a port
- NATServer* nat = new NATServer(
- nat_type, internal, server_addr, external, external_addrs[0]);
- NATSocketFactory* natsf = new NATSocketFactory(internal,
- nat->internal_address());
-
- TestClient* in = CreateTestClient(natsf, internal_addr);
- TestClient* out[4];
- for (int i = 0; i < 4; i++)
- out[i] = CreateTestClient(external, external_addrs[i]);
-
- th_int.Start();
- th_ext.Start();
-
- const char* buf = "filter_test";
- size_t len = strlen(buf);
-
- in->SendTo(buf, len, out[0]->address());
- SocketAddress trans_addr;
- EXPECT_TRUE(out[0]->CheckNextPacket(buf, len, &trans_addr));
-
- out[1]->SendTo(buf, len, trans_addr);
- EXPECT_TRUE(CheckReceive(in, !filter_ip, buf, len));
-
- out[2]->SendTo(buf, len, trans_addr);
- EXPECT_TRUE(CheckReceive(in, !filter_port, buf, len));
-
- out[3]->SendTo(buf, len, trans_addr);
- EXPECT_TRUE(CheckReceive(in, !filter_ip && !filter_port, buf, len));
-
- th_int.Stop();
- th_ext.Stop();
-
- delete nat;
- delete natsf;
- delete in;
- for (int i = 0; i < 4; i++)
- delete out[i];
-}
-
-// Tests that NATServer allocates bindings properly.
-void TestBindings(
- SocketServer* internal, const SocketAddress& internal_addr,
- SocketServer* external, const SocketAddress external_addrs[4]) {
- TestSend(internal, internal_addr, external, external_addrs,
- NAT_OPEN_CONE, true);
- TestSend(internal, internal_addr, external, external_addrs,
- NAT_ADDR_RESTRICTED, true);
- TestSend(internal, internal_addr, external, external_addrs,
- NAT_PORT_RESTRICTED, true);
- TestSend(internal, internal_addr, external, external_addrs,
- NAT_SYMMETRIC, false);
-}
-
-// Tests that NATServer filters packets properly.
-void TestFilters(
- SocketServer* internal, const SocketAddress& internal_addr,
- SocketServer* external, const SocketAddress external_addrs[4]) {
- TestRecv(internal, internal_addr, external, external_addrs,
- NAT_OPEN_CONE, false, false);
- TestRecv(internal, internal_addr, external, external_addrs,
- NAT_ADDR_RESTRICTED, true, false);
- TestRecv(internal, internal_addr, external, external_addrs,
- NAT_PORT_RESTRICTED, true, true);
- TestRecv(internal, internal_addr, external, external_addrs,
- NAT_SYMMETRIC, true, true);
-}
-
-bool TestConnectivity(const SocketAddress& src, const IPAddress& dst) {
- // The physical NAT tests require connectivity to the selected ip from the
- // internal address used for the NAT. Things like firewalls can break that, so
- // check to see if it's worth even trying with this ip.
- scoped_ptr<PhysicalSocketServer> pss(new PhysicalSocketServer());
- scoped_ptr<AsyncSocket> client(pss->CreateAsyncSocket(src.family(),
- SOCK_DGRAM));
- scoped_ptr<AsyncSocket> server(pss->CreateAsyncSocket(src.family(),
- SOCK_DGRAM));
- if (client->Bind(SocketAddress(src.ipaddr(), 0)) != 0 ||
- server->Bind(SocketAddress(dst, 0)) != 0) {
- return false;
- }
- const char* buf = "hello other socket";
- size_t len = strlen(buf);
- int sent = client->SendTo(buf, len, server->GetLocalAddress());
- SocketAddress addr;
- const size_t kRecvBufSize = 64;
- char recvbuf[kRecvBufSize];
- Thread::Current()->SleepMs(100);
- int received = server->RecvFrom(recvbuf, kRecvBufSize, &addr);
- return received == sent && ::memcmp(buf, recvbuf, len) == 0;
-}
-
-void TestPhysicalInternal(const SocketAddress& int_addr) {
- BasicNetworkManager network_manager;
- network_manager.set_ipv6_enabled(true);
- network_manager.StartUpdating();
- // Process pending messages so the network list is updated.
- Thread::Current()->ProcessMessages(0);
-
- std::vector<Network*> networks;
- network_manager.GetNetworks(&networks);
- if (networks.empty()) {
- LOG(LS_WARNING) << "Not enough network adapters for test.";
- return;
- }
-
- SocketAddress ext_addr1(int_addr);
- SocketAddress ext_addr2;
- // Find an available IP with matching family. The test breaks if int_addr
- // can't talk to ip, so check for connectivity as well.
- for (std::vector<Network*>::iterator it = networks.begin();
- it != networks.end(); ++it) {
- const IPAddress& ip = (*it)->ip();
- if (ip.family() == int_addr.family() && TestConnectivity(int_addr, ip)) {
- ext_addr2.SetIP(ip);
- break;
- }
- }
- if (ext_addr2.IsNil()) {
- LOG(LS_WARNING) << "No available IP of same family as " << int_addr;
- return;
- }
-
- LOG(LS_INFO) << "selected ip " << ext_addr2.ipaddr();
-
- SocketAddress ext_addrs[4] = {
- SocketAddress(ext_addr1),
- SocketAddress(ext_addr2),
- SocketAddress(ext_addr1),
- SocketAddress(ext_addr2)
- };
-
- scoped_ptr<PhysicalSocketServer> int_pss(new PhysicalSocketServer());
- scoped_ptr<PhysicalSocketServer> ext_pss(new PhysicalSocketServer());
-
- TestBindings(int_pss.get(), int_addr, ext_pss.get(), ext_addrs);
- TestFilters(int_pss.get(), int_addr, ext_pss.get(), ext_addrs);
-}
-
-TEST(NatTest, TestPhysicalIPv4) {
- TestPhysicalInternal(SocketAddress("127.0.0.1", 0));
-}
-
-TEST(NatTest, TestPhysicalIPv6) {
- if (HasIPv6Enabled()) {
- TestPhysicalInternal(SocketAddress("::1", 0));
- } else {
- LOG(LS_WARNING) << "No IPv6, skipping";
- }
-}
-
-class TestVirtualSocketServer : public VirtualSocketServer {
- public:
- explicit TestVirtualSocketServer(SocketServer* ss)
- : VirtualSocketServer(ss),
- ss_(ss) {}
- // Expose this publicly
- IPAddress GetNextIP(int af) { return VirtualSocketServer::GetNextIP(af); }
-
- private:
- scoped_ptr<SocketServer> ss_;
-};
-
-void TestVirtualInternal(int family) {
- scoped_ptr<TestVirtualSocketServer> int_vss(new TestVirtualSocketServer(
- new PhysicalSocketServer()));
- scoped_ptr<TestVirtualSocketServer> ext_vss(new TestVirtualSocketServer(
- new PhysicalSocketServer()));
-
- SocketAddress int_addr;
- SocketAddress ext_addrs[4];
- int_addr.SetIP(int_vss->GetNextIP(family));
- ext_addrs[0].SetIP(ext_vss->GetNextIP(int_addr.family()));
- ext_addrs[1].SetIP(ext_vss->GetNextIP(int_addr.family()));
- ext_addrs[2].SetIP(ext_addrs[0].ipaddr());
- ext_addrs[3].SetIP(ext_addrs[1].ipaddr());
-
- TestBindings(int_vss.get(), int_addr, ext_vss.get(), ext_addrs);
- TestFilters(int_vss.get(), int_addr, ext_vss.get(), ext_addrs);
-}
-
-TEST(NatTest, TestVirtualIPv4) {
- TestVirtualInternal(AF_INET);
-}
-
-TEST(NatTest, TestVirtualIPv6) {
- if (HasIPv6Enabled()) {
- TestVirtualInternal(AF_INET6);
- } else {
- LOG(LS_WARNING) << "No IPv6, skipping";
- }
-}
-
-// TODO: Finish this test
-class NatTcpTest : public testing::Test, public sigslot::has_slots<> {
- public:
- NatTcpTest() : connected_(false) {}
- virtual void SetUp() {
- int_vss_ = new TestVirtualSocketServer(new PhysicalSocketServer());
- ext_vss_ = new TestVirtualSocketServer(new PhysicalSocketServer());
- nat_ = new NATServer(NAT_OPEN_CONE, int_vss_, SocketAddress(),
- ext_vss_, SocketAddress());
- natsf_ = new NATSocketFactory(int_vss_, nat_->internal_address());
- }
- void OnConnectEvent(AsyncSocket* socket) {
- connected_ = true;
- }
- void OnAcceptEvent(AsyncSocket* socket) {
- accepted_ = server_->Accept(NULL);
- }
- void OnCloseEvent(AsyncSocket* socket, int error) {
- }
- void ConnectEvents() {
- server_->SignalReadEvent.connect(this, &NatTcpTest::OnAcceptEvent);
- client_->SignalConnectEvent.connect(this, &NatTcpTest::OnConnectEvent);
- }
- TestVirtualSocketServer* int_vss_;
- TestVirtualSocketServer* ext_vss_;
- NATServer* nat_;
- NATSocketFactory* natsf_;
- AsyncSocket* client_;
- AsyncSocket* server_;
- AsyncSocket* accepted_;
- bool connected_;
-};
-
-TEST_F(NatTcpTest, DISABLED_TestConnectOut) {
- server_ = ext_vss_->CreateAsyncSocket(SOCK_STREAM);
- server_->Bind(SocketAddress());
- server_->Listen(5);
-
- client_ = int_vss_->CreateAsyncSocket(SOCK_STREAM);
- EXPECT_GE(0, client_->Bind(SocketAddress()));
- EXPECT_GE(0, client_->Connect(server_->GetLocalAddress()));
-
-
- ConnectEvents();
-
- EXPECT_TRUE_WAIT(connected_, 1000);
- EXPECT_EQ(client_->GetRemoteAddress(), server_->GetLocalAddress());
- EXPECT_EQ(client_->GetRemoteAddress(), accepted_->GetLocalAddress());
- EXPECT_EQ(client_->GetLocalAddress(), accepted_->GetRemoteAddress());
-
- client_->Close();
-}
-//#endif
diff --git a/base/natserver.cc b/base/natserver.cc
deleted file mode 100644
index f69baa0..0000000
--- a/base/natserver.cc
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/natsocketfactory.h"
-#include "talk/base/natserver.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-RouteCmp::RouteCmp(NAT* nat) : symmetric(nat->IsSymmetric()) {
-}
-
-size_t RouteCmp::operator()(const SocketAddressPair& r) const {
- size_t h = r.source().Hash();
- if (symmetric)
- h ^= r.destination().Hash();
- return h;
-}
-
-bool RouteCmp::operator()(
- const SocketAddressPair& r1, const SocketAddressPair& r2) const {
- if (r1.source() < r2.source())
- return true;
- if (r2.source() < r1.source())
- return false;
- if (symmetric && (r1.destination() < r2.destination()))
- return true;
- if (symmetric && (r2.destination() < r1.destination()))
- return false;
- return false;
-}
-
-AddrCmp::AddrCmp(NAT* nat)
- : use_ip(nat->FiltersIP()), use_port(nat->FiltersPort()) {
-}
-
-size_t AddrCmp::operator()(const SocketAddress& a) const {
- size_t h = 0;
- if (use_ip)
- h ^= HashIP(a.ipaddr());
- if (use_port)
- h ^= a.port() | (a.port() << 16);
- return h;
-}
-
-bool AddrCmp::operator()(
- const SocketAddress& a1, const SocketAddress& a2) const {
- if (use_ip && (a1.ipaddr() < a2.ipaddr()))
- return true;
- if (use_ip && (a2.ipaddr() < a1.ipaddr()))
- return false;
- if (use_port && (a1.port() < a2.port()))
- return true;
- if (use_port && (a2.port() < a1.port()))
- return false;
- return false;
-}
-
-NATServer::NATServer(
- NATType type, SocketFactory* internal, const SocketAddress& internal_addr,
- SocketFactory* external, const SocketAddress& external_ip)
- : external_(external), external_ip_(external_ip.ipaddr(), 0) {
- nat_ = NAT::Create(type);
-
- server_socket_ = AsyncUDPSocket::Create(internal, internal_addr);
- server_socket_->SignalReadPacket.connect(this, &NATServer::OnInternalPacket);
-
- int_map_ = new InternalMap(RouteCmp(nat_));
- ext_map_ = new ExternalMap();
-}
-
-NATServer::~NATServer() {
- for (InternalMap::iterator iter = int_map_->begin();
- iter != int_map_->end();
- iter++)
- delete iter->second;
-
- delete nat_;
- delete server_socket_;
- delete int_map_;
- delete ext_map_;
-}
-
-void NATServer::OnInternalPacket(
- AsyncPacketSocket* socket, const char* buf, size_t size,
- const SocketAddress& addr, const PacketTime& packet_time) {
-
- // Read the intended destination from the wire.
- SocketAddress dest_addr;
- size_t length = UnpackAddressFromNAT(buf, size, &dest_addr);
-
- // Find the translation for these addresses (allocating one if necessary).
- SocketAddressPair route(addr, dest_addr);
- InternalMap::iterator iter = int_map_->find(route);
- if (iter == int_map_->end()) {
- Translate(route);
- iter = int_map_->find(route);
- }
- ASSERT(iter != int_map_->end());
-
- // Allow the destination to send packets back to the source.
- iter->second->WhitelistInsert(dest_addr);
-
- // Send the packet to its intended destination.
- talk_base::PacketOptions options;
- iter->second->socket->SendTo(buf + length, size - length, dest_addr, options);
-}
-
-void NATServer::OnExternalPacket(
- AsyncPacketSocket* socket, const char* buf, size_t size,
- const SocketAddress& remote_addr, const PacketTime& packet_time) {
-
- SocketAddress local_addr = socket->GetLocalAddress();
-
- // Find the translation for this addresses.
- ExternalMap::iterator iter = ext_map_->find(local_addr);
- ASSERT(iter != ext_map_->end());
-
- // Allow the NAT to reject this packet.
- if (ShouldFilterOut(iter->second, remote_addr)) {
- LOG(LS_INFO) << "Packet from " << remote_addr.ToSensitiveString()
- << " was filtered out by the NAT.";
- return;
- }
-
- // Forward this packet to the internal address.
- // First prepend the address in a quasi-STUN format.
- scoped_ptr<char[]> real_buf(new char[size + kNATEncodedIPv6AddressSize]);
- size_t addrlength = PackAddressForNAT(real_buf.get(),
- size + kNATEncodedIPv6AddressSize,
- remote_addr);
- // Copy the data part after the address.
- talk_base::PacketOptions options;
- memcpy(real_buf.get() + addrlength, buf, size);
- server_socket_->SendTo(real_buf.get(), size + addrlength,
- iter->second->route.source(), options);
-}
-
-void NATServer::Translate(const SocketAddressPair& route) {
- AsyncUDPSocket* socket = AsyncUDPSocket::Create(external_, external_ip_);
-
- if (!socket) {
- LOG(LS_ERROR) << "Couldn't find a free port!";
- return;
- }
-
- TransEntry* entry = new TransEntry(route, socket, nat_);
- (*int_map_)[route] = entry;
- (*ext_map_)[socket->GetLocalAddress()] = entry;
- socket->SignalReadPacket.connect(this, &NATServer::OnExternalPacket);
-}
-
-bool NATServer::ShouldFilterOut(TransEntry* entry,
- const SocketAddress& ext_addr) {
- return entry->WhitelistContains(ext_addr);
-}
-
-NATServer::TransEntry::TransEntry(
- const SocketAddressPair& r, AsyncUDPSocket* s, NAT* nat)
- : route(r), socket(s) {
- whitelist = new AddressSet(AddrCmp(nat));
-}
-
-NATServer::TransEntry::~TransEntry() {
- delete whitelist;
- delete socket;
-}
-
-void NATServer::TransEntry::WhitelistInsert(const SocketAddress& addr) {
- CritScope cs(&crit_);
- whitelist->insert(addr);
-}
-
-bool NATServer::TransEntry::WhitelistContains(const SocketAddress& ext_addr) {
- CritScope cs(&crit_);
- return whitelist->find(ext_addr) == whitelist->end();
-}
-
-} // namespace talk_base
diff --git a/base/natserver.h b/base/natserver.h
deleted file mode 100644
index 05d3475..0000000
--- a/base/natserver.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NATSERVER_H_
-#define TALK_BASE_NATSERVER_H_
-
-#include <map>
-#include <set>
-
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/socketaddresspair.h"
-#include "talk/base/thread.h"
-#include "talk/base/socketfactory.h"
-#include "talk/base/nattypes.h"
-
-namespace talk_base {
-
-// Change how routes (socketaddress pairs) are compared based on the type of
-// NAT. The NAT server maintains a hashtable of the routes that it knows
-// about. So these affect which routes are treated the same.
-struct RouteCmp {
- explicit RouteCmp(NAT* nat);
- size_t operator()(const SocketAddressPair& r) const;
- bool operator()(
- const SocketAddressPair& r1, const SocketAddressPair& r2) const;
-
- bool symmetric;
-};
-
-// Changes how addresses are compared based on the filtering rules of the NAT.
-struct AddrCmp {
- explicit AddrCmp(NAT* nat);
- size_t operator()(const SocketAddress& r) const;
- bool operator()(const SocketAddress& r1, const SocketAddress& r2) const;
-
- bool use_ip;
- bool use_port;
-};
-
-// Implements the NAT device. It listens for packets on the internal network,
-// translates them, and sends them out over the external network.
-
-const int NAT_SERVER_PORT = 4237;
-
-class NATServer : public sigslot::has_slots<> {
- public:
- NATServer(
- NATType type, SocketFactory* internal, const SocketAddress& internal_addr,
- SocketFactory* external, const SocketAddress& external_ip);
- ~NATServer();
-
- SocketAddress internal_address() const {
- return server_socket_->GetLocalAddress();
- }
-
- // Packets received on one of the networks.
- void OnInternalPacket(AsyncPacketSocket* socket, const char* buf,
- size_t size, const SocketAddress& addr,
- const PacketTime& packet_time);
- void OnExternalPacket(AsyncPacketSocket* socket, const char* buf,
- size_t size, const SocketAddress& remote_addr,
- const PacketTime& packet_time);
-
- private:
- typedef std::set<SocketAddress, AddrCmp> AddressSet;
-
- /* Records a translation and the associated external socket. */
- struct TransEntry {
- TransEntry(const SocketAddressPair& r, AsyncUDPSocket* s, NAT* nat);
- ~TransEntry();
-
- void WhitelistInsert(const SocketAddress& addr);
- bool WhitelistContains(const SocketAddress& ext_addr);
-
- SocketAddressPair route;
- AsyncUDPSocket* socket;
- AddressSet* whitelist;
- CriticalSection crit_;
- };
-
- typedef std::map<SocketAddressPair, TransEntry*, RouteCmp> InternalMap;
- typedef std::map<SocketAddress, TransEntry*> ExternalMap;
-
- /* Creates a new entry that translates the given route. */
- void Translate(const SocketAddressPair& route);
-
- /* Determines whether the NAT would filter out a packet from this address. */
- bool ShouldFilterOut(TransEntry* entry, const SocketAddress& ext_addr);
-
- NAT* nat_;
- SocketFactory* internal_;
- SocketFactory* external_;
- SocketAddress external_ip_;
- AsyncUDPSocket* server_socket_;
- AsyncSocket* tcp_server_socket_;
- InternalMap* int_map_;
- ExternalMap* ext_map_;
- DISALLOW_EVIL_CONSTRUCTORS(NATServer);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_NATSERVER_H_
diff --git a/base/natserver_main.cc b/base/natserver_main.cc
deleted file mode 100644
index a748108..0000000
--- a/base/natserver_main.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <iostream>
-
-#include "talk/base/natserver.h"
-#include "talk/base/host.h"
-#include "talk/base/physicalsocketserver.h"
-
-using namespace talk_base;
-
-int main(int argc, char* argv[]) {
- if (argc != 3) {
- std::cerr << "usage: natserver <internal-ip> <external-ip>" << std::endl;
- exit(1);
- }
-
- SocketAddress internal = SocketAddress(argv[1]);
- SocketAddress external = SocketAddress(argv[2]);
- if (internal.EqualIPs(external)) {
- std::cerr << "internal and external IPs must differ" << std::endl;
- exit(1);
- }
-
- Thread* pthMain = Thread::Current();
- PhysicalSocketServer* ss = new PhysicalSocketServer();
- pthMain->set_socketserver(ss);
- NATServer* server = new NATServer(NAT_OPEN_CONE, ss, internal, ss, external);
- server = server;
-
- pthMain->Run();
- return 0;
-}
diff --git a/base/natsocketfactory.cc b/base/natsocketfactory.cc
deleted file mode 100644
index 6ce09fd..0000000
--- a/base/natsocketfactory.cc
+++ /dev/null
@@ -1,504 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/natsocketfactory.h"
-
-#include "talk/base/logging.h"
-#include "talk/base/natserver.h"
-#include "talk/base/virtualsocketserver.h"
-
-namespace talk_base {
-
-// Packs the given socketaddress into the buffer in buf, in the quasi-STUN
-// format that the natserver uses.
-// Returns 0 if an invalid address is passed.
-size_t PackAddressForNAT(char* buf, size_t buf_size,
- const SocketAddress& remote_addr) {
- const IPAddress& ip = remote_addr.ipaddr();
- int family = ip.family();
- buf[0] = 0;
- buf[1] = family;
- // Writes the port.
- *(reinterpret_cast<uint16*>(&buf[2])) = HostToNetwork16(remote_addr.port());
- if (family == AF_INET) {
- ASSERT(buf_size >= kNATEncodedIPv4AddressSize);
- in_addr v4addr = ip.ipv4_address();
- memcpy(&buf[4], &v4addr, kNATEncodedIPv4AddressSize - 4);
- return kNATEncodedIPv4AddressSize;
- } else if (family == AF_INET6) {
- ASSERT(buf_size >= kNATEncodedIPv6AddressSize);
- in6_addr v6addr = ip.ipv6_address();
- memcpy(&buf[4], &v6addr, kNATEncodedIPv6AddressSize - 4);
- return kNATEncodedIPv6AddressSize;
- }
- return 0U;
-}
-
-// Decodes the remote address from a packet that has been encoded with the nat's
-// quasi-STUN format. Returns the length of the address (i.e., the offset into
-// data where the original packet starts).
-size_t UnpackAddressFromNAT(const char* buf, size_t buf_size,
- SocketAddress* remote_addr) {
- ASSERT(buf_size >= 8);
- ASSERT(buf[0] == 0);
- int family = buf[1];
- uint16 port = NetworkToHost16(*(reinterpret_cast<const uint16*>(&buf[2])));
- if (family == AF_INET) {
- const in_addr* v4addr = reinterpret_cast<const in_addr*>(&buf[4]);
- *remote_addr = SocketAddress(IPAddress(*v4addr), port);
- return kNATEncodedIPv4AddressSize;
- } else if (family == AF_INET6) {
- ASSERT(buf_size >= 20);
- const in6_addr* v6addr = reinterpret_cast<const in6_addr*>(&buf[4]);
- *remote_addr = SocketAddress(IPAddress(*v6addr), port);
- return kNATEncodedIPv6AddressSize;
- }
- return 0U;
-}
-
-
-// NATSocket
-class NATSocket : public AsyncSocket, public sigslot::has_slots<> {
- public:
- explicit NATSocket(NATInternalSocketFactory* sf, int family, int type)
- : sf_(sf), family_(family), type_(type), connected_(false),
- socket_(NULL), buf_(NULL), size_(0) {
- }
-
- virtual ~NATSocket() {
- delete socket_;
- delete[] buf_;
- }
-
- virtual SocketAddress GetLocalAddress() const {
- return (socket_) ? socket_->GetLocalAddress() : SocketAddress();
- }
-
- virtual SocketAddress GetRemoteAddress() const {
- return remote_addr_; // will be NIL if not connected
- }
-
- virtual int Bind(const SocketAddress& addr) {
- if (socket_) { // already bound, bubble up error
- return -1;
- }
-
- int result;
- socket_ = sf_->CreateInternalSocket(family_, type_, addr, &server_addr_);
- result = (socket_) ? socket_->Bind(addr) : -1;
- if (result >= 0) {
- socket_->SignalConnectEvent.connect(this, &NATSocket::OnConnectEvent);
- socket_->SignalReadEvent.connect(this, &NATSocket::OnReadEvent);
- socket_->SignalWriteEvent.connect(this, &NATSocket::OnWriteEvent);
- socket_->SignalCloseEvent.connect(this, &NATSocket::OnCloseEvent);
- } else {
- server_addr_.Clear();
- delete socket_;
- socket_ = NULL;
- }
-
- return result;
- }
-
- virtual int Connect(const SocketAddress& addr) {
- if (!socket_) { // socket must be bound, for now
- return -1;
- }
-
- int result = 0;
- if (type_ == SOCK_STREAM) {
- result = socket_->Connect(server_addr_.IsNil() ? addr : server_addr_);
- } else {
- connected_ = true;
- }
-
- if (result >= 0) {
- remote_addr_ = addr;
- }
-
- return result;
- }
-
- virtual int Send(const void* data, size_t size) {
- ASSERT(connected_);
- return SendTo(data, size, remote_addr_);
- }
-
- virtual int SendTo(const void* data, size_t size, const SocketAddress& addr) {
- ASSERT(!connected_ || addr == remote_addr_);
- if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
- return socket_->SendTo(data, size, addr);
- }
- // This array will be too large for IPv4 packets, but only by 12 bytes.
- scoped_ptr<char[]> buf(new char[size + kNATEncodedIPv6AddressSize]);
- size_t addrlength = PackAddressForNAT(buf.get(),
- size + kNATEncodedIPv6AddressSize,
- addr);
- size_t encoded_size = size + addrlength;
- memcpy(buf.get() + addrlength, data, size);
- int result = socket_->SendTo(buf.get(), encoded_size, server_addr_);
- if (result >= 0) {
- ASSERT(result == static_cast<int>(encoded_size));
- result = result - static_cast<int>(addrlength);
- }
- return result;
- }
-
- virtual int Recv(void* data, size_t size) {
- SocketAddress addr;
- return RecvFrom(data, size, &addr);
- }
-
- virtual int RecvFrom(void* data, size_t size, SocketAddress *out_addr) {
- if (server_addr_.IsNil() || type_ == SOCK_STREAM) {
- return socket_->RecvFrom(data, size, out_addr);
- }
- // Make sure we have enough room to read the requested amount plus the
- // largest possible header address.
- SocketAddress remote_addr;
- Grow(size + kNATEncodedIPv6AddressSize);
-
- // Read the packet from the socket.
- int result = socket_->RecvFrom(buf_, size_, &remote_addr);
- if (result >= 0) {
- ASSERT(remote_addr == server_addr_);
-
- // TODO: we need better framing so we know how many bytes we can
- // return before we need to read the next address. For UDP, this will be
- // fine as long as the reader always reads everything in the packet.
- ASSERT((size_t)result < size_);
-
- // Decode the wire packet into the actual results.
- SocketAddress real_remote_addr;
- size_t addrlength =
- UnpackAddressFromNAT(buf_, result, &real_remote_addr);
- memcpy(data, buf_ + addrlength, result - addrlength);
-
- // Make sure this packet should be delivered before returning it.
- if (!connected_ || (real_remote_addr == remote_addr_)) {
- if (out_addr)
- *out_addr = real_remote_addr;
- result = result - static_cast<int>(addrlength);
- } else {
- LOG(LS_ERROR) << "Dropping packet from unknown remote address: "
- << real_remote_addr.ToString();
- result = 0; // Tell the caller we didn't read anything
- }
- }
-
- return result;
- }
-
- virtual int Close() {
- int result = 0;
- if (socket_) {
- result = socket_->Close();
- if (result >= 0) {
- connected_ = false;
- remote_addr_ = SocketAddress();
- delete socket_;
- socket_ = NULL;
- }
- }
- return result;
- }
-
- virtual int Listen(int backlog) {
- return socket_->Listen(backlog);
- }
- virtual AsyncSocket* Accept(SocketAddress *paddr) {
- return socket_->Accept(paddr);
- }
- virtual int GetError() const {
- return socket_->GetError();
- }
- virtual void SetError(int error) {
- socket_->SetError(error);
- }
- virtual ConnState GetState() const {
- return connected_ ? CS_CONNECTED : CS_CLOSED;
- }
- virtual int EstimateMTU(uint16* mtu) {
- return socket_->EstimateMTU(mtu);
- }
- virtual int GetOption(Option opt, int* value) {
- return socket_->GetOption(opt, value);
- }
- virtual int SetOption(Option opt, int value) {
- return socket_->SetOption(opt, value);
- }
-
- void OnConnectEvent(AsyncSocket* socket) {
- // If we're NATed, we need to send a request with the real addr to use.
- ASSERT(socket == socket_);
- if (server_addr_.IsNil()) {
- connected_ = true;
- SignalConnectEvent(this);
- } else {
- SendConnectRequest();
- }
- }
- void OnReadEvent(AsyncSocket* socket) {
- // If we're NATed, we need to process the connect reply.
- ASSERT(socket == socket_);
- if (type_ == SOCK_STREAM && !server_addr_.IsNil() && !connected_) {
- HandleConnectReply();
- } else {
- SignalReadEvent(this);
- }
- }
- void OnWriteEvent(AsyncSocket* socket) {
- ASSERT(socket == socket_);
- SignalWriteEvent(this);
- }
- void OnCloseEvent(AsyncSocket* socket, int error) {
- ASSERT(socket == socket_);
- SignalCloseEvent(this, error);
- }
-
- private:
- // Makes sure the buffer is at least the given size.
- void Grow(size_t new_size) {
- if (size_ < new_size) {
- delete[] buf_;
- size_ = new_size;
- buf_ = new char[size_];
- }
- }
-
- // Sends the destination address to the server to tell it to connect.
- void SendConnectRequest() {
- char buf[256];
- size_t length = PackAddressForNAT(buf, ARRAY_SIZE(buf), remote_addr_);
- socket_->Send(buf, length);
- }
-
- // Handles the byte sent back from the server and fires the appropriate event.
- void HandleConnectReply() {
- char code;
- socket_->Recv(&code, sizeof(code));
- if (code == 0) {
- SignalConnectEvent(this);
- } else {
- Close();
- SignalCloseEvent(this, code);
- }
- }
-
- NATInternalSocketFactory* sf_;
- int family_;
- int type_;
- bool connected_;
- SocketAddress remote_addr_;
- SocketAddress server_addr_; // address of the NAT server
- AsyncSocket* socket_;
- char* buf_;
- size_t size_;
-};
-
-// NATSocketFactory
-NATSocketFactory::NATSocketFactory(SocketFactory* factory,
- const SocketAddress& nat_addr)
- : factory_(factory), nat_addr_(nat_addr) {
-}
-
-Socket* NATSocketFactory::CreateSocket(int type) {
- return CreateSocket(AF_INET, type);
-}
-
-Socket* NATSocketFactory::CreateSocket(int family, int type) {
- return new NATSocket(this, family, type);
-}
-
-AsyncSocket* NATSocketFactory::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* NATSocketFactory::CreateAsyncSocket(int family, int type) {
- return new NATSocket(this, family, type);
-}
-
-AsyncSocket* NATSocketFactory::CreateInternalSocket(int family, int type,
- const SocketAddress& local_addr, SocketAddress* nat_addr) {
- *nat_addr = nat_addr_;
- return factory_->CreateAsyncSocket(family, type);
-}
-
-// NATSocketServer
-NATSocketServer::NATSocketServer(SocketServer* server)
- : server_(server), msg_queue_(NULL) {
-}
-
-NATSocketServer::Translator* NATSocketServer::GetTranslator(
- const SocketAddress& ext_ip) {
- return nats_.Get(ext_ip);
-}
-
-NATSocketServer::Translator* NATSocketServer::AddTranslator(
- const SocketAddress& ext_ip, const SocketAddress& int_ip, NATType type) {
- // Fail if a translator already exists with this extternal address.
- if (nats_.Get(ext_ip))
- return NULL;
-
- return nats_.Add(ext_ip, new Translator(this, type, int_ip, server_, ext_ip));
-}
-
-void NATSocketServer::RemoveTranslator(
- const SocketAddress& ext_ip) {
- nats_.Remove(ext_ip);
-}
-
-Socket* NATSocketServer::CreateSocket(int type) {
- return CreateSocket(AF_INET, type);
-}
-
-Socket* NATSocketServer::CreateSocket(int family, int type) {
- return new NATSocket(this, family, type);
-}
-
-AsyncSocket* NATSocketServer::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* NATSocketServer::CreateAsyncSocket(int family, int type) {
- return new NATSocket(this, family, type);
-}
-
-AsyncSocket* NATSocketServer::CreateInternalSocket(int family, int type,
- const SocketAddress& local_addr, SocketAddress* nat_addr) {
- AsyncSocket* socket = NULL;
- Translator* nat = nats_.FindClient(local_addr);
- if (nat) {
- socket = nat->internal_factory()->CreateAsyncSocket(family, type);
- *nat_addr = (type == SOCK_STREAM) ?
- nat->internal_tcp_address() : nat->internal_address();
- } else {
- socket = server_->CreateAsyncSocket(family, type);
- }
- return socket;
-}
-
-// NATSocketServer::Translator
-NATSocketServer::Translator::Translator(
- NATSocketServer* server, NATType type, const SocketAddress& int_ip,
- SocketFactory* ext_factory, const SocketAddress& ext_ip)
- : server_(server) {
- // Create a new private network, and a NATServer running on the private
- // network that bridges to the external network. Also tell the private
- // network to use the same message queue as us.
- VirtualSocketServer* internal_server = new VirtualSocketServer(server_);
- internal_server->SetMessageQueue(server_->queue());
- internal_factory_.reset(internal_server);
- nat_server_.reset(new NATServer(type, internal_server, int_ip,
- ext_factory, ext_ip));
-}
-
-
-NATSocketServer::Translator* NATSocketServer::Translator::GetTranslator(
- const SocketAddress& ext_ip) {
- return nats_.Get(ext_ip);
-}
-
-NATSocketServer::Translator* NATSocketServer::Translator::AddTranslator(
- const SocketAddress& ext_ip, const SocketAddress& int_ip, NATType type) {
- // Fail if a translator already exists with this extternal address.
- if (nats_.Get(ext_ip))
- return NULL;
-
- AddClient(ext_ip);
- return nats_.Add(ext_ip,
- new Translator(server_, type, int_ip, server_, ext_ip));
-}
-void NATSocketServer::Translator::RemoveTranslator(
- const SocketAddress& ext_ip) {
- nats_.Remove(ext_ip);
- RemoveClient(ext_ip);
-}
-
-bool NATSocketServer::Translator::AddClient(
- const SocketAddress& int_ip) {
- // Fail if a client already exists with this internal address.
- if (clients_.find(int_ip) != clients_.end())
- return false;
-
- clients_.insert(int_ip);
- return true;
-}
-
-void NATSocketServer::Translator::RemoveClient(
- const SocketAddress& int_ip) {
- std::set<SocketAddress>::iterator it = clients_.find(int_ip);
- if (it != clients_.end()) {
- clients_.erase(it);
- }
-}
-
-NATSocketServer::Translator* NATSocketServer::Translator::FindClient(
- const SocketAddress& int_ip) {
- // See if we have the requested IP, or any of our children do.
- return (clients_.find(int_ip) != clients_.end()) ?
- this : nats_.FindClient(int_ip);
-}
-
-// NATSocketServer::TranslatorMap
-NATSocketServer::TranslatorMap::~TranslatorMap() {
- for (TranslatorMap::iterator it = begin(); it != end(); ++it) {
- delete it->second;
- }
-}
-
-NATSocketServer::Translator* NATSocketServer::TranslatorMap::Get(
- const SocketAddress& ext_ip) {
- TranslatorMap::iterator it = find(ext_ip);
- return (it != end()) ? it->second : NULL;
-}
-
-NATSocketServer::Translator* NATSocketServer::TranslatorMap::Add(
- const SocketAddress& ext_ip, Translator* nat) {
- (*this)[ext_ip] = nat;
- return nat;
-}
-
-void NATSocketServer::TranslatorMap::Remove(
- const SocketAddress& ext_ip) {
- TranslatorMap::iterator it = find(ext_ip);
- if (it != end()) {
- delete it->second;
- erase(it);
- }
-}
-
-NATSocketServer::Translator* NATSocketServer::TranslatorMap::FindClient(
- const SocketAddress& int_ip) {
- Translator* nat = NULL;
- for (TranslatorMap::iterator it = begin(); it != end() && !nat; ++it) {
- nat = it->second->FindClient(int_ip);
- }
- return nat;
-}
-
-} // namespace talk_base
diff --git a/base/natsocketfactory.h b/base/natsocketfactory.h
deleted file mode 100644
index d02503f..0000000
--- a/base/natsocketfactory.h
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NATSOCKETFACTORY_H_
-#define TALK_BASE_NATSOCKETFACTORY_H_
-
-#include <string>
-#include <map>
-#include <set>
-
-#include "talk/base/natserver.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/socketserver.h"
-
-namespace talk_base {
-
-const size_t kNATEncodedIPv4AddressSize = 8U;
-const size_t kNATEncodedIPv6AddressSize = 20U;
-
-// Used by the NAT socket implementation.
-class NATInternalSocketFactory {
- public:
- virtual ~NATInternalSocketFactory() {}
- virtual AsyncSocket* CreateInternalSocket(int family, int type,
- const SocketAddress& local_addr, SocketAddress* nat_addr) = 0;
-};
-
-// Creates sockets that will send all traffic through a NAT, using an existing
-// NATServer instance running at nat_addr. The actual data is sent using sockets
-// from a socket factory, given to the constructor.
-class NATSocketFactory : public SocketFactory, public NATInternalSocketFactory {
- public:
- NATSocketFactory(SocketFactory* factory, const SocketAddress& nat_addr);
-
- // SocketFactory implementation
- virtual Socket* CreateSocket(int type);
- virtual Socket* CreateSocket(int family, int type);
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- // NATInternalSocketFactory implementation
- virtual AsyncSocket* CreateInternalSocket(int family, int type,
- const SocketAddress& local_addr, SocketAddress* nat_addr);
-
- private:
- SocketFactory* factory_;
- SocketAddress nat_addr_;
- DISALLOW_EVIL_CONSTRUCTORS(NATSocketFactory);
-};
-
-// Creates sockets that will send traffic through a NAT depending on what
-// address they bind to. This can be used to simulate a client on a NAT sending
-// to a client that is not behind a NAT.
-// Note that the internal addresses of clients must be unique. This is because
-// there is only one socketserver per thread, and the Bind() address is used to
-// figure out which NAT (if any) the socket should talk to.
-//
-// Example with 3 NATs (2 cascaded), and 3 clients.
-// ss->AddTranslator("1.2.3.4", "192.168.0.1", NAT_ADDR_RESTRICTED);
-// ss->AddTranslator("99.99.99.99", "10.0.0.1", NAT_SYMMETRIC)->
-// AddTranslator("10.0.0.2", "192.168.1.1", NAT_OPEN_CONE);
-// ss->GetTranslator("1.2.3.4")->AddClient("1.2.3.4", "192.168.0.2");
-// ss->GetTranslator("99.99.99.99")->AddClient("10.0.0.3");
-// ss->GetTranslator("99.99.99.99")->GetTranslator("10.0.0.2")->
-// AddClient("192.168.1.2");
-class NATSocketServer : public SocketServer, public NATInternalSocketFactory {
- public:
- class Translator;
- // holds a list of NATs
- class TranslatorMap : private std::map<SocketAddress, Translator*> {
- public:
- ~TranslatorMap();
- Translator* Get(const SocketAddress& ext_ip);
- Translator* Add(const SocketAddress& ext_ip, Translator*);
- void Remove(const SocketAddress& ext_ip);
- Translator* FindClient(const SocketAddress& int_ip);
- };
-
- // a specific NAT
- class Translator {
- public:
- Translator(NATSocketServer* server, NATType type,
- const SocketAddress& int_addr, SocketFactory* ext_factory,
- const SocketAddress& ext_addr);
-
- SocketFactory* internal_factory() { return internal_factory_.get(); }
- SocketAddress internal_address() const {
- return nat_server_->internal_address();
- }
- SocketAddress internal_tcp_address() const {
- return SocketAddress(); // nat_server_->internal_tcp_address();
- }
-
- Translator* GetTranslator(const SocketAddress& ext_ip);
- Translator* AddTranslator(const SocketAddress& ext_ip,
- const SocketAddress& int_ip, NATType type);
- void RemoveTranslator(const SocketAddress& ext_ip);
-
- bool AddClient(const SocketAddress& int_ip);
- void RemoveClient(const SocketAddress& int_ip);
-
- // Looks for the specified client in this or a child NAT.
- Translator* FindClient(const SocketAddress& int_ip);
-
- private:
- NATSocketServer* server_;
- scoped_ptr<SocketFactory> internal_factory_;
- scoped_ptr<NATServer> nat_server_;
- TranslatorMap nats_;
- std::set<SocketAddress> clients_;
- };
-
- explicit NATSocketServer(SocketServer* ss);
-
- SocketServer* socketserver() { return server_; }
- MessageQueue* queue() { return msg_queue_; }
-
- Translator* GetTranslator(const SocketAddress& ext_ip);
- Translator* AddTranslator(const SocketAddress& ext_ip,
- const SocketAddress& int_ip, NATType type);
- void RemoveTranslator(const SocketAddress& ext_ip);
-
- // SocketServer implementation
- virtual Socket* CreateSocket(int type);
- virtual Socket* CreateSocket(int family, int type);
-
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- virtual void SetMessageQueue(MessageQueue* queue) {
- msg_queue_ = queue;
- server_->SetMessageQueue(queue);
- }
- virtual bool Wait(int cms, bool process_io) {
- return server_->Wait(cms, process_io);
- }
- virtual void WakeUp() {
- server_->WakeUp();
- }
-
- // NATInternalSocketFactory implementation
- virtual AsyncSocket* CreateInternalSocket(int family, int type,
- const SocketAddress& local_addr, SocketAddress* nat_addr);
-
- private:
- SocketServer* server_;
- MessageQueue* msg_queue_;
- TranslatorMap nats_;
- DISALLOW_EVIL_CONSTRUCTORS(NATSocketServer);
-};
-
-// Free-standing NAT helper functions.
-size_t PackAddressForNAT(char* buf, size_t buf_size,
- const SocketAddress& remote_addr);
-size_t UnpackAddressFromNAT(const char* buf, size_t buf_size,
- SocketAddress* remote_addr);
-} // namespace talk_base
-
-#endif // TALK_BASE_NATSOCKETFACTORY_H_
diff --git a/base/nattypes.cc b/base/nattypes.cc
deleted file mode 100644
index da1d011..0000000
--- a/base/nattypes.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <assert.h>
-
-#include "talk/base/nattypes.h"
-
-namespace talk_base {
-
-class SymmetricNAT : public NAT {
-public:
- bool IsSymmetric() { return true; }
- bool FiltersIP() { return true; }
- bool FiltersPort() { return true; }
-};
-
-class OpenConeNAT : public NAT {
-public:
- bool IsSymmetric() { return false; }
- bool FiltersIP() { return false; }
- bool FiltersPort() { return false; }
-};
-
-class AddressRestrictedNAT : public NAT {
-public:
- bool IsSymmetric() { return false; }
- bool FiltersIP() { return true; }
- bool FiltersPort() { return false; }
-};
-
-class PortRestrictedNAT : public NAT {
-public:
- bool IsSymmetric() { return false; }
- bool FiltersIP() { return true; }
- bool FiltersPort() { return true; }
-};
-
-NAT* NAT::Create(NATType type) {
- switch (type) {
- case NAT_OPEN_CONE: return new OpenConeNAT();
- case NAT_ADDR_RESTRICTED: return new AddressRestrictedNAT();
- case NAT_PORT_RESTRICTED: return new PortRestrictedNAT();
- case NAT_SYMMETRIC: return new SymmetricNAT();
- default: assert(0); return 0;
- }
-}
-
-} // namespace talk_base
diff --git a/base/nattypes.h b/base/nattypes.h
deleted file mode 100644
index e9602c7..0000000
--- a/base/nattypes.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NATTYPE_H__
-#define TALK_BASE_NATTYPE_H__
-
-namespace talk_base {
-
-/* Identifies each type of NAT that can be simulated. */
-enum NATType {
- NAT_OPEN_CONE,
- NAT_ADDR_RESTRICTED,
- NAT_PORT_RESTRICTED,
- NAT_SYMMETRIC
-};
-
-// Implements the rules for each specific type of NAT.
-class NAT {
-public:
- virtual ~NAT() { }
-
- // Determines whether this NAT uses both source and destination address when
- // checking whether a mapping already exists.
- virtual bool IsSymmetric() = 0;
-
- // Determines whether this NAT drops packets received from a different IP
- // the one last sent to.
- virtual bool FiltersIP() = 0;
-
- // Determines whether this NAT drops packets received from a different port
- // the one last sent to.
- virtual bool FiltersPort() = 0;
-
- // Returns an implementation of the given type of NAT.
- static NAT* Create(NATType type);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_NATTYPE_H__
diff --git a/base/nethelpers.cc b/base/nethelpers.cc
deleted file mode 100644
index 057f34d..0000000
--- a/base/nethelpers.cc
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/nethelpers.h"
-
-#if defined(WIN32)
-#include <ws2spi.h>
-#include <ws2tcpip.h>
-#include "talk/base/win32.h"
-#endif
-
-#include "talk/base/byteorder.h"
-#include "talk/base/logging.h"
-#include "talk/base/signalthread.h"
-
-namespace talk_base {
-
-int ResolveHostname(const std::string& hostname, int family,
- std::vector<IPAddress>* addresses) {
-#ifdef __native_client__
- ASSERT(false);
- LOG(LS_WARNING) << "ResolveHostname() is not implemented for NaCl";
- return -1;
-#else // __native_client__
- if (!addresses) {
- return -1;
- }
- addresses->clear();
- struct addrinfo* result = NULL;
- struct addrinfo hints = {0};
- // TODO(djw): For now this is IPv4 only so existing users remain unaffected.
- hints.ai_family = AF_INET;
- hints.ai_flags = AI_ADDRCONFIG;
- int ret = getaddrinfo(hostname.c_str(), NULL, &hints, &result);
- if (ret != 0) {
- return ret;
- }
- struct addrinfo* cursor = result;
- for (; cursor; cursor = cursor->ai_next) {
- if (family == AF_UNSPEC || cursor->ai_family == family) {
- IPAddress ip;
- if (IPFromAddrInfo(cursor, &ip)) {
- addresses->push_back(ip);
- }
- }
- }
- freeaddrinfo(result);
- return 0;
-#endif // !__native_client__
-}
-
-// AsyncResolver
-AsyncResolver::AsyncResolver() : error_(-1) {
-}
-
-void AsyncResolver::Start(const SocketAddress& addr) {
- addr_ = addr;
- // SignalThred Start will kickoff the resolve process.
- SignalThread::Start();
-}
-
-bool AsyncResolver::GetResolvedAddress(int family, SocketAddress* addr) const {
- if (error_ != 0 || addresses_.empty())
- return false;
-
- *addr = addr_;
- for (size_t i = 0; i < addresses_.size(); ++i) {
- if (family == addresses_[i].family()) {
- addr->SetResolvedIP(addresses_[i]);
- return true;
- }
- }
- return false;
-}
-
-void AsyncResolver::DoWork() {
- error_ = ResolveHostname(addr_.hostname().c_str(), addr_.family(),
- &addresses_);
-}
-
-void AsyncResolver::OnWorkDone() {
- SignalDone(this);
-}
-
-const char* inet_ntop(int af, const void *src, char* dst, socklen_t size) {
-#ifdef WIN32
- return win32_inet_ntop(af, src, dst, size);
-#else
- return ::inet_ntop(af, src, dst, size);
-#endif
-}
-
-int inet_pton(int af, const char* src, void *dst) {
-#ifdef WIN32
- return win32_inet_pton(af, src, dst);
-#else
- return ::inet_pton(af, src, dst);
-#endif
-}
-
-bool HasIPv6Enabled() {
-#ifndef WIN32
- // We only need to check this for Windows XP (so far).
- return true;
-#else
- if (IsWindowsVistaOrLater()) {
- return true;
- }
- if (!IsWindowsXpOrLater()) {
- return false;
- }
- DWORD protbuff_size = 4096;
- scoped_ptr<char[]> protocols;
- LPWSAPROTOCOL_INFOW protocol_infos = NULL;
- int requested_protocols[2] = {AF_INET6, 0};
-
- int err = 0;
- int ret = 0;
- // Check for protocols in a do-while loop until we provide a buffer large
- // enough. (WSCEnumProtocols sets protbuff_size to its desired value).
- // It is extremely unlikely that this will loop more than once.
- do {
- protocols.reset(new char[protbuff_size]);
- protocol_infos = reinterpret_cast<LPWSAPROTOCOL_INFOW>(protocols.get());
- ret = WSCEnumProtocols(requested_protocols, protocol_infos,
- &protbuff_size, &err);
- } while (ret == SOCKET_ERROR && err == WSAENOBUFS);
-
- if (ret == SOCKET_ERROR) {
- return false;
- }
-
- // Even if ret is positive, check specifically for IPv6.
- // Non-IPv6 enabled WinXP will still return a RAW protocol.
- for (int i = 0; i < ret; ++i) {
- if (protocol_infos[i].iAddressFamily == AF_INET6) {
- return true;
- }
- }
- return false;
-#endif
-}
-} // namespace talk_base
diff --git a/base/nethelpers.h b/base/nethelpers.h
deleted file mode 100644
index 5b385bb..0000000
--- a/base/nethelpers.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NETHELPERS_H_
-#define TALK_BASE_NETHELPERS_H_
-
-#ifdef POSIX
-#include <netdb.h>
-#include <stddef.h>
-#elif WIN32
-#include <winsock2.h> // NOLINT
-#endif
-
-#include <list>
-
-#include "talk/base/asyncresolverinterface.h"
-#include "talk/base/signalthread.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socketaddress.h"
-
-namespace talk_base {
-
-class AsyncResolverTest;
-
-// AsyncResolver will perform async DNS resolution, signaling the result on
-// the SignalDone from AsyncResolverInterface when the operation completes.
-class AsyncResolver : public SignalThread, public AsyncResolverInterface {
- public:
- AsyncResolver();
- virtual ~AsyncResolver() {}
-
- virtual void Start(const SocketAddress& addr);
- virtual bool GetResolvedAddress(int family, SocketAddress* addr) const;
- virtual int GetError() const { return error_; }
- virtual void Destroy(bool wait) { SignalThread::Destroy(wait); }
-
- const std::vector<IPAddress>& addresses() const { return addresses_; }
- void set_error(int error) { error_ = error; }
-
- protected:
- virtual void DoWork();
- virtual void OnWorkDone();
-
- private:
- SocketAddress addr_;
- std::vector<IPAddress> addresses_;
- int error_;
-};
-
-// talk_base namespaced wrappers for inet_ntop and inet_pton so we can avoid
-// the windows-native versions of these.
-const char* inet_ntop(int af, const void *src, char* dst, socklen_t size);
-int inet_pton(int af, const char* src, void *dst);
-
-bool HasIPv6Enabled();
-} // namespace talk_base
-
-#endif // TALK_BASE_NETHELPERS_H_
diff --git a/base/network.cc b/base/network.cc
deleted file mode 100644
index 829507a..0000000
--- a/base/network.cc
+++ /dev/null
@@ -1,675 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include "talk/base/network.h"
-
-#ifdef POSIX
-// linux/if.h can't be included at the same time as the posix sys/if.h, and
-// it's transitively required by linux/route.h, so include that version on
-// linux instead of the standard posix one.
-#if defined(ANDROID) || defined(LINUX)
-#include <linux/if.h>
-#include <linux/route.h>
-#elif !defined(__native_client__)
-#include <net/if.h>
-#endif
-#include <sys/socket.h>
-#include <sys/utsname.h>
-#include <sys/ioctl.h>
-#include <unistd.h>
-#include <errno.h>
-
-#ifdef ANDROID
-#include "talk/base/ifaddrs-android.h"
-#elif !defined(__native_client__)
-#include <ifaddrs.h>
-#endif
-
-#endif // POSIX
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#include <Iphlpapi.h>
-#endif
-
-#include <stdio.h>
-
-#include <algorithm>
-
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socket.h" // includes something that makes windows happy
-#include "talk/base/stream.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-namespace {
-
-const uint32 kUpdateNetworksMessage = 1;
-const uint32 kSignalNetworksMessage = 2;
-
-// Fetch list of networks every two seconds.
-const int kNetworksUpdateIntervalMs = 2000;
-
-const int kHighestNetworkPreference = 127;
-
-bool CompareNetworks(const Network* a, const Network* b) {
- if (a->prefix_length() == b->prefix_length()) {
- if (a->name() == b->name()) {
- return a->prefix() < b->prefix();
- }
- }
- return a->name() < b->name();
-}
-
-bool SortNetworks(const Network* a, const Network* b) {
- // Network types will be preferred above everything else while sorting
- // Networks.
-
- // Networks are sorted first by type.
- if (a->type() != b->type()) {
- return a->type() < b->type();
- }
-
- // After type, networks are sorted by IP address precedence values
- // from RFC 3484-bis
- if (IPAddressPrecedence(a->ip()) != IPAddressPrecedence(b->ip())) {
- return IPAddressPrecedence(a->ip()) > IPAddressPrecedence(b->ip());
- }
-
- // TODO(mallinath) - Add VPN and Link speed conditions while sorting.
-
- // Networks are sorted last by key.
- return a->key() > b->key();
-}
-
-std::string AdapterTypeToString(AdapterType type) {
- switch (type) {
- case ADAPTER_TYPE_UNKNOWN:
- return "Unknown";
- case ADAPTER_TYPE_ETHERNET:
- return "Ethernet";
- case ADAPTER_TYPE_WIFI:
- return "Wifi";
- case ADAPTER_TYPE_CELLULAR:
- return "Cellular";
- case ADAPTER_TYPE_VPN:
- return "VPN";
- default:
- ASSERT(false);
- return std::string();
- }
-}
-
-} // namespace
-
-std::string MakeNetworkKey(const std::string& name, const IPAddress& prefix,
- int prefix_length) {
- std::ostringstream ost;
- ost << name << "%" << prefix.ToString() << "/" << prefix_length;
- return ost.str();
-}
-
-NetworkManager::NetworkManager() {
-}
-
-NetworkManager::~NetworkManager() {
-}
-
-NetworkManagerBase::NetworkManagerBase() : ipv6_enabled_(true) {
-}
-
-NetworkManagerBase::~NetworkManagerBase() {
- for (NetworkMap::iterator i = networks_map_.begin();
- i != networks_map_.end(); ++i) {
- delete i->second;
- }
-}
-
-void NetworkManagerBase::GetNetworks(NetworkList* result) const {
- *result = networks_;
-}
-
-void NetworkManagerBase::MergeNetworkList(const NetworkList& new_networks,
- bool* changed) {
- // Sort the list so that we can detect when it changes.
- typedef std::pair<Network*, std::vector<IPAddress> > address_list;
- std::map<std::string, address_list> address_map;
- NetworkList list(new_networks);
- NetworkList merged_list;
- std::sort(list.begin(), list.end(), CompareNetworks);
-
- *changed = false;
-
- if (networks_.size() != list.size())
- *changed = true;
-
- // First, build a set of network-keys to the ipaddresses.
- for (uint32 i = 0; i < list.size(); ++i) {
- bool might_add_to_merged_list = false;
- std::string key = MakeNetworkKey(list[i]->name(),
- list[i]->prefix(),
- list[i]->prefix_length());
- if (address_map.find(key) == address_map.end()) {
- address_map[key] = address_list(list[i], std::vector<IPAddress>());
- might_add_to_merged_list = true;
- }
- const std::vector<IPAddress>& addresses = list[i]->GetIPs();
- address_list& current_list = address_map[key];
- for (std::vector<IPAddress>::const_iterator it = addresses.begin();
- it != addresses.end();
- ++it) {
- current_list.second.push_back(*it);
- }
- if (!might_add_to_merged_list) {
- delete list[i];
- }
- }
-
- // Next, look for existing network objects to re-use.
- for (std::map<std::string, address_list >::iterator it = address_map.begin();
- it != address_map.end();
- ++it) {
- const std::string& key = it->first;
- Network* net = it->second.first;
- NetworkMap::iterator existing = networks_map_.find(key);
- if (existing == networks_map_.end()) {
- // This network is new. Place it in the network map.
- merged_list.push_back(net);
- networks_map_[key] = net;
- *changed = true;
- } else {
- // This network exists in the map already. Reset its IP addresses.
- *changed = existing->second->SetIPs(it->second.second, *changed);
- merged_list.push_back(existing->second);
- if (existing->second != net) {
- delete net;
- }
- }
- }
- networks_ = merged_list;
-
- // If the network lists changes, we resort it.
- if (changed) {
- std::sort(networks_.begin(), networks_.end(), SortNetworks);
- // Now network interfaces are sorted, we should set the preference value
- // for each of the interfaces we are planning to use.
- // Preference order of network interfaces might have changed from previous
- // sorting due to addition of higher preference network interface.
- // Since we have already sorted the network interfaces based on our
- // requirements, we will just assign a preference value starting with 127,
- // in decreasing order.
- int pref = kHighestNetworkPreference;
- for (NetworkList::const_iterator iter = networks_.begin();
- iter != networks_.end(); ++iter) {
- (*iter)->set_preference(pref);
- if (pref > 0) {
- --pref;
- } else {
- LOG(LS_ERROR) << "Too many network interfaces to handle!";
- break;
- }
- }
- }
-}
-
-BasicNetworkManager::BasicNetworkManager()
- : thread_(NULL), sent_first_update_(false), start_count_(0),
- ignore_non_default_routes_(false) {
-}
-
-BasicNetworkManager::~BasicNetworkManager() {
-}
-
-#if defined(__native_client__)
-
-bool BasicNetworkManager::CreateNetworks(bool include_ignored,
- NetworkList* networks) const {
- ASSERT(false);
- LOG(LS_WARNING) << "BasicNetworkManager doesn't work on NaCl yet";
- return false;
-}
-
-#elif defined(POSIX)
-void BasicNetworkManager::ConvertIfAddrs(struct ifaddrs* interfaces,
- bool include_ignored,
- NetworkList* networks) const {
- NetworkMap current_networks;
- for (struct ifaddrs* cursor = interfaces;
- cursor != NULL; cursor = cursor->ifa_next) {
- IPAddress prefix;
- IPAddress mask;
- IPAddress ip;
- int scope_id = 0;
-
- // Some interfaces may not have address assigned.
- if (!cursor->ifa_addr || !cursor->ifa_netmask)
- continue;
-
- switch (cursor->ifa_addr->sa_family) {
- case AF_INET: {
- ip = IPAddress(
- reinterpret_cast<sockaddr_in*>(cursor->ifa_addr)->sin_addr);
- mask = IPAddress(
- reinterpret_cast<sockaddr_in*>(cursor->ifa_netmask)->sin_addr);
- break;
- }
- case AF_INET6: {
- if (ipv6_enabled()) {
- ip = IPAddress(
- reinterpret_cast<sockaddr_in6*>(cursor->ifa_addr)->sin6_addr);
- mask = IPAddress(
- reinterpret_cast<sockaddr_in6*>(cursor->ifa_netmask)->sin6_addr);
- scope_id =
- reinterpret_cast<sockaddr_in6*>(cursor->ifa_addr)->sin6_scope_id;
- break;
- } else {
- continue;
- }
- }
- default: {
- continue;
- }
- }
-
- int prefix_length = CountIPMaskBits(mask);
- prefix = TruncateIP(ip, prefix_length);
- std::string key = MakeNetworkKey(std::string(cursor->ifa_name),
- prefix, prefix_length);
- NetworkMap::iterator existing_network = current_networks.find(key);
- if (existing_network == current_networks.end()) {
- scoped_ptr<Network> network(new Network(cursor->ifa_name,
- cursor->ifa_name,
- prefix,
- prefix_length));
- network->set_scope_id(scope_id);
- network->AddIP(ip);
- bool ignored = ((cursor->ifa_flags & IFF_LOOPBACK) ||
- IsIgnoredNetwork(*network));
- network->set_ignored(ignored);
- if (include_ignored || !network->ignored()) {
- networks->push_back(network.release());
- }
- } else {
- (*existing_network).second->AddIP(ip);
- }
- }
-}
-
-bool BasicNetworkManager::CreateNetworks(bool include_ignored,
- NetworkList* networks) const {
- struct ifaddrs* interfaces;
- int error = getifaddrs(&interfaces);
- if (error != 0) {
- LOG_ERR(LERROR) << "getifaddrs failed to gather interface data: " << error;
- return false;
- }
-
- ConvertIfAddrs(interfaces, include_ignored, networks);
-
- freeifaddrs(interfaces);
- return true;
-}
-
-#elif defined(WIN32)
-
-unsigned int GetPrefix(PIP_ADAPTER_PREFIX prefixlist,
- const IPAddress& ip, IPAddress* prefix) {
- IPAddress current_prefix;
- IPAddress best_prefix;
- unsigned int best_length = 0;
- while (prefixlist) {
- // Look for the longest matching prefix in the prefixlist.
- if (prefixlist->Address.lpSockaddr == NULL ||
- prefixlist->Address.lpSockaddr->sa_family != ip.family()) {
- prefixlist = prefixlist->Next;
- continue;
- }
- switch (prefixlist->Address.lpSockaddr->sa_family) {
- case AF_INET: {
- sockaddr_in* v4_addr =
- reinterpret_cast<sockaddr_in*>(prefixlist->Address.lpSockaddr);
- current_prefix = IPAddress(v4_addr->sin_addr);
- break;
- }
- case AF_INET6: {
- sockaddr_in6* v6_addr =
- reinterpret_cast<sockaddr_in6*>(prefixlist->Address.lpSockaddr);
- current_prefix = IPAddress(v6_addr->sin6_addr);
- break;
- }
- default: {
- prefixlist = prefixlist->Next;
- continue;
- }
- }
- if (TruncateIP(ip, prefixlist->PrefixLength) == current_prefix &&
- prefixlist->PrefixLength > best_length) {
- best_prefix = current_prefix;
- best_length = prefixlist->PrefixLength;
- }
- prefixlist = prefixlist->Next;
- }
- *prefix = best_prefix;
- return best_length;
-}
-
-bool BasicNetworkManager::CreateNetworks(bool include_ignored,
- NetworkList* networks) const {
- NetworkMap current_networks;
- // MSDN recommends a 15KB buffer for the first try at GetAdaptersAddresses.
- size_t buffer_size = 16384;
- scoped_ptr<char[]> adapter_info(new char[buffer_size]);
- PIP_ADAPTER_ADDRESSES adapter_addrs =
- reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get());
- int adapter_flags = (GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_ANYCAST |
- GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_INCLUDE_PREFIX);
- int ret = 0;
- do {
- adapter_info.reset(new char[buffer_size]);
- adapter_addrs = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(adapter_info.get());
- ret = GetAdaptersAddresses(AF_UNSPEC, adapter_flags,
- 0, adapter_addrs,
- reinterpret_cast<PULONG>(&buffer_size));
- } while (ret == ERROR_BUFFER_OVERFLOW);
- if (ret != ERROR_SUCCESS) {
- return false;
- }
- int count = 0;
- while (adapter_addrs) {
- if (adapter_addrs->OperStatus == IfOperStatusUp) {
- PIP_ADAPTER_UNICAST_ADDRESS address = adapter_addrs->FirstUnicastAddress;
- PIP_ADAPTER_PREFIX prefixlist = adapter_addrs->FirstPrefix;
- std::string name;
- std::string description;
-#ifdef _DEBUG
- name = ToUtf8(adapter_addrs->FriendlyName,
- wcslen(adapter_addrs->FriendlyName));
-#endif
- description = ToUtf8(adapter_addrs->Description,
- wcslen(adapter_addrs->Description));
- for (; address; address = address->Next) {
-#ifndef _DEBUG
- name = talk_base::ToString(count);
-#endif
-
- IPAddress ip;
- int scope_id = 0;
- scoped_ptr<Network> network;
- switch (address->Address.lpSockaddr->sa_family) {
- case AF_INET: {
- sockaddr_in* v4_addr =
- reinterpret_cast<sockaddr_in*>(address->Address.lpSockaddr);
- ip = IPAddress(v4_addr->sin_addr);
- break;
- }
- case AF_INET6: {
- if (ipv6_enabled()) {
- sockaddr_in6* v6_addr =
- reinterpret_cast<sockaddr_in6*>(address->Address.lpSockaddr);
- scope_id = v6_addr->sin6_scope_id;
- ip = IPAddress(v6_addr->sin6_addr);
- break;
- } else {
- continue;
- }
- }
- default: {
- continue;
- }
- }
-
- IPAddress prefix;
- int prefix_length = GetPrefix(prefixlist, ip, &prefix);
- std::string key = MakeNetworkKey(name, prefix, prefix_length);
- NetworkMap::iterator existing_network = current_networks.find(key);
- if (existing_network == current_networks.end()) {
- scoped_ptr<Network> network(new Network(name,
- description,
- prefix,
- prefix_length));
- network->set_scope_id(scope_id);
- network->AddIP(ip);
- bool ignore = ((adapter_addrs->IfType == IF_TYPE_SOFTWARE_LOOPBACK) ||
- IsIgnoredNetwork(*network));
- network->set_ignored(ignore);
- if (include_ignored || !network->ignored()) {
- networks->push_back(network.release());
- }
- } else {
- (*existing_network).second->AddIP(ip);
- }
- }
- // Count is per-adapter - all 'Networks' created from the same
- // adapter need to have the same name.
- ++count;
- }
- adapter_addrs = adapter_addrs->Next;
- }
- return true;
-}
-#endif // WIN32
-
-#if defined(ANDROID) || defined(LINUX)
-bool IsDefaultRoute(const std::string& network_name) {
- FileStream fs;
- if (!fs.Open("/proc/net/route", "r", NULL)) {
- LOG(LS_WARNING) << "Couldn't read /proc/net/route, skipping default "
- << "route check (assuming everything is a default route).";
- return true;
- } else {
- std::string line;
- while (fs.ReadLine(&line) == SR_SUCCESS) {
- char iface_name[256];
- unsigned int iface_ip, iface_gw, iface_mask, iface_flags;
- if (sscanf(line.c_str(),
- "%255s %8X %8X %4X %*d %*u %*d %8X",
- iface_name, &iface_ip, &iface_gw,
- &iface_flags, &iface_mask) == 5 &&
- network_name == iface_name &&
- iface_mask == 0 &&
- (iface_flags & (RTF_UP | RTF_HOST)) == RTF_UP) {
- return true;
- }
- }
- }
- return false;
-}
-#endif
-
-bool BasicNetworkManager::IsIgnoredNetwork(const Network& network) const {
- // Ignore networks on the explicit ignore list.
- for (size_t i = 0; i < network_ignore_list_.size(); ++i) {
- if (network.name() == network_ignore_list_[i]) {
- return true;
- }
- }
-#ifdef POSIX
- // Filter out VMware interfaces, typically named vmnet1 and vmnet8
- if (strncmp(network.name().c_str(), "vmnet", 5) == 0 ||
- strncmp(network.name().c_str(), "vnic", 4) == 0) {
- return true;
- }
-#if defined(ANDROID) || defined(LINUX)
- // Make sure this is a default route, if we're ignoring non-defaults.
- if (ignore_non_default_routes_ && !IsDefaultRoute(network.name())) {
- return true;
- }
-#endif
-#elif defined(WIN32)
- // Ignore any HOST side vmware adapters with a description like:
- // VMware Virtual Ethernet Adapter for VMnet1
- // but don't ignore any GUEST side adapters with a description like:
- // VMware Accelerated AMD PCNet Adapter #2
- if (strstr(network.description().c_str(), "VMnet") != NULL) {
- return true;
- }
-#endif
-
- // Ignore any networks with a 0.x.y.z IP
- if (network.prefix().family() == AF_INET) {
- return (network.prefix().v4AddressAsHostOrderInteger() < 0x01000000);
- }
- return false;
-}
-
-void BasicNetworkManager::StartUpdating() {
- thread_ = Thread::Current();
- if (start_count_) {
- // If network interfaces are already discovered and signal is sent,
- // we should trigger network signal immediately for the new clients
- // to start allocating ports.
- if (sent_first_update_)
- thread_->Post(this, kSignalNetworksMessage);
- } else {
- thread_->Post(this, kUpdateNetworksMessage);
- }
- ++start_count_;
-}
-
-void BasicNetworkManager::StopUpdating() {
- ASSERT(Thread::Current() == thread_);
- if (!start_count_)
- return;
-
- --start_count_;
- if (!start_count_) {
- thread_->Clear(this);
- sent_first_update_ = false;
- }
-}
-
-void BasicNetworkManager::OnMessage(Message* msg) {
- switch (msg->message_id) {
- case kUpdateNetworksMessage: {
- DoUpdateNetworks();
- break;
- }
- case kSignalNetworksMessage: {
- SignalNetworksChanged();
- break;
- }
- default:
- ASSERT(false);
- }
-}
-
-void BasicNetworkManager::DoUpdateNetworks() {
- if (!start_count_)
- return;
-
- ASSERT(Thread::Current() == thread_);
-
- NetworkList list;
- if (!CreateNetworks(false, &list)) {
- SignalError();
- } else {
- bool changed;
- MergeNetworkList(list, &changed);
- if (changed || !sent_first_update_) {
- SignalNetworksChanged();
- sent_first_update_ = true;
- }
- }
-
- thread_->PostDelayed(kNetworksUpdateIntervalMs, this, kUpdateNetworksMessage);
-}
-
-void BasicNetworkManager::DumpNetworks(bool include_ignored) {
- NetworkList list;
- CreateNetworks(include_ignored, &list);
- LOG(LS_INFO) << "NetworkManager detected " << list.size() << " networks:";
- for (size_t i = 0; i < list.size(); ++i) {
- const Network* network = list[i];
- if (!network->ignored() || include_ignored) {
- LOG(LS_INFO) << network->ToString() << ": "
- << network->description()
- << ((network->ignored()) ? ", Ignored" : "");
- }
- }
- // Release the network list created previously.
- // Do this in a seperated for loop for better readability.
- for (size_t i = 0; i < list.size(); ++i) {
- delete list[i];
- }
-}
-
-Network::Network(const std::string& name, const std::string& desc,
- const IPAddress& prefix, int prefix_length)
- : name_(name), description_(desc), prefix_(prefix),
- prefix_length_(prefix_length),
- key_(MakeNetworkKey(name, prefix, prefix_length)), scope_id_(0),
- ignored_(false), type_(ADAPTER_TYPE_UNKNOWN), preference_(0) {
-}
-
-Network::Network(const std::string& name, const std::string& desc,
- const IPAddress& prefix, int prefix_length, AdapterType type)
- : name_(name), description_(desc), prefix_(prefix),
- prefix_length_(prefix_length),
- key_(MakeNetworkKey(name, prefix, prefix_length)), scope_id_(0),
- ignored_(false), type_(type), preference_(0) {
-}
-
-std::string Network::ToString() const {
- std::stringstream ss;
- // Print out the first space-terminated token of the network desc, plus
- // the IP address.
- ss << "Net[" << description_.substr(0, description_.find(' '))
- << ":" << prefix_.ToSensitiveString() << "/" << prefix_length_
- << ":" << AdapterTypeToString(type_) << "]";
- return ss.str();
-}
-
-// Sets the addresses of this network. Returns true if the address set changed.
-// Change detection is short circuited if the changed argument is true.
-bool Network::SetIPs(const std::vector<IPAddress>& ips, bool changed) {
- changed = changed || ips.size() != ips_.size();
- // Detect changes with a nested loop; n-squared but we expect on the order
- // of 2-3 addresses per network.
- for (std::vector<IPAddress>::const_iterator it = ips.begin();
- !changed && it != ips.end();
- ++it) {
- bool found = false;
- for (std::vector<IPAddress>::iterator inner_it = ips_.begin();
- !found && inner_it != ips_.end();
- ++inner_it) {
- if (*it == *inner_it) {
- found = true;
- }
- }
- changed = !found;
- }
- ips_ = ips;
- return changed;
-}
-
-} // namespace talk_base
diff --git a/base/network.h b/base/network.h
deleted file mode 100644
index 2be81bb..0000000
--- a/base/network.h
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NETWORK_H_
-#define TALK_BASE_NETWORK_H_
-
-#include <deque>
-#include <map>
-#include <string>
-#include <vector>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/ipaddress.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/sigslot.h"
-
-#if defined(POSIX)
-struct ifaddrs;
-#endif // defined(POSIX)
-
-namespace talk_base {
-
-class Network;
-class Thread;
-
-enum AdapterType {
- // This enum resembles the one in Chromium net::ConnectionType.
- ADAPTER_TYPE_UNKNOWN = 0,
- ADAPTER_TYPE_ETHERNET = 1,
- ADAPTER_TYPE_WIFI = 2,
- ADAPTER_TYPE_CELLULAR = 3,
- ADAPTER_TYPE_VPN = 4
-};
-
-// Makes a string key for this network. Used in the network manager's maps.
-// Network objects are keyed on interface name, network prefix and the
-// length of that prefix.
-std::string MakeNetworkKey(const std::string& name, const IPAddress& prefix,
- int prefix_length);
-
-// Generic network manager interface. It provides list of local
-// networks.
-class NetworkManager {
- public:
- typedef std::vector<Network*> NetworkList;
-
- NetworkManager();
- virtual ~NetworkManager();
-
- // Called when network list is updated.
- sigslot::signal0<> SignalNetworksChanged;
-
- // Indicates a failure when getting list of network interfaces.
- sigslot::signal0<> SignalError;
-
- // Start/Stop monitoring of network interfaces
- // list. SignalNetworksChanged or SignalError is emitted immidiately
- // after StartUpdating() is called. After that SignalNetworksChanged
- // is emitted wheneven list of networks changes.
- virtual void StartUpdating() = 0;
- virtual void StopUpdating() = 0;
-
- // Returns the current list of networks available on this machine.
- // UpdateNetworks() must be called before this method is called.
- // It makes sure that repeated calls return the same object for a
- // given network, so that quality is tracked appropriately. Does not
- // include ignored networks.
- virtual void GetNetworks(NetworkList* networks) const = 0;
-
- // Dumps a list of networks available to LS_INFO.
- virtual void DumpNetworks(bool include_ignored) {}
-};
-
-// Base class for NetworkManager implementations.
-class NetworkManagerBase : public NetworkManager {
- public:
- NetworkManagerBase();
- virtual ~NetworkManagerBase();
-
- virtual void GetNetworks(std::vector<Network*>* networks) const;
- bool ipv6_enabled() const { return ipv6_enabled_; }
- void set_ipv6_enabled(bool enabled) { ipv6_enabled_ = enabled; }
-
- protected:
- typedef std::map<std::string, Network*> NetworkMap;
- // Updates |networks_| with the networks listed in |list|. If
- // |network_map_| already has a Network object for a network listed
- // in the |list| then it is reused. Accept ownership of the Network
- // objects in the |list|. |changed| will be set to true if there is
- // any change in the network list.
- void MergeNetworkList(const NetworkList& list, bool* changed);
-
- private:
- friend class NetworkTest;
- void DoUpdateNetworks();
-
- NetworkList networks_;
- NetworkMap networks_map_;
- bool ipv6_enabled_;
-};
-
-// Basic implementation of the NetworkManager interface that gets list
-// of networks using OS APIs.
-class BasicNetworkManager : public NetworkManagerBase,
- public MessageHandler {
- public:
- BasicNetworkManager();
- virtual ~BasicNetworkManager();
-
- virtual void StartUpdating();
- virtual void StopUpdating();
-
- // Logs the available networks.
- virtual void DumpNetworks(bool include_ignored);
-
- // MessageHandler interface.
- virtual void OnMessage(Message* msg);
- bool started() { return start_count_ > 0; }
-
- // Sets the network ignore list, which is empty by default. Any network on
- // the ignore list will be filtered from network enumeration results.
- void set_network_ignore_list(const std::vector<std::string>& list) {
- network_ignore_list_ = list;
- }
-#if defined(ANDROID) || defined(LINUX)
- // Sets the flag for ignoring non-default routes.
- void set_ignore_non_default_routes(bool value) {
- ignore_non_default_routes_ = true;
- }
-#endif
-
- protected:
-#if defined(POSIX)
- // Separated from CreateNetworks for tests.
- void ConvertIfAddrs(ifaddrs* interfaces,
- bool include_ignored,
- NetworkList* networks) const;
-#endif // defined(POSIX)
-
- // Creates a network object for each network available on the machine.
- bool CreateNetworks(bool include_ignored, NetworkList* networks) const;
-
- // Determines if a network should be ignored.
- bool IsIgnoredNetwork(const Network& network) const;
-
- private:
- friend class NetworkTest;
-
- void DoUpdateNetworks();
-
- Thread* thread_;
- bool sent_first_update_;
- int start_count_;
- std::vector<std::string> network_ignore_list_;
- bool ignore_non_default_routes_;
-};
-
-// Represents a Unix-type network interface, with a name and single address.
-class Network {
- public:
- Network(const std::string& name, const std::string& description,
- const IPAddress& prefix, int prefix_length);
-
- Network(const std::string& name, const std::string& description,
- const IPAddress& prefix, int prefix_length, AdapterType type);
-
- // Returns the name of the interface this network is associated wtih.
- const std::string& name() const { return name_; }
-
- // Returns the OS-assigned name for this network. This is useful for
- // debugging but should not be sent over the wire (for privacy reasons).
- const std::string& description() const { return description_; }
-
- // Returns the prefix for this network.
- const IPAddress& prefix() const { return prefix_; }
- // Returns the length, in bits, of this network's prefix.
- int prefix_length() const { return prefix_length_; }
-
- // |key_| has unique value per network interface. Used in sorting network
- // interfaces. Key is derived from interface name and it's prefix.
- std::string key() const { return key_; }
-
- // Returns the Network's current idea of the 'best' IP it has.
- // 'Best' currently means the first one added.
- // TODO: We should be preferring temporary addresses.
- // Returns an unset IP if this network has no active addresses.
- IPAddress ip() const {
- if (ips_.size() == 0) {
- return IPAddress();
- }
- return ips_.at(0);
- }
- // Adds an active IP address to this network. Does not check for duplicates.
- void AddIP(const IPAddress& ip) { ips_.push_back(ip); }
-
- // Sets the network's IP address list. Returns true if new IP addresses were
- // detected. Passing true to already_changed skips this check.
- bool SetIPs(const std::vector<IPAddress>& ips, bool already_changed);
- // Get the list of IP Addresses associated with this network.
- const std::vector<IPAddress>& GetIPs() { return ips_;}
- // Clear the network's list of addresses.
- void ClearIPs() { ips_.clear(); }
-
- // Returns the scope-id of the network's address.
- // Should only be relevant for link-local IPv6 addresses.
- int scope_id() const { return scope_id_; }
- void set_scope_id(int id) { scope_id_ = id; }
-
- // Indicates whether this network should be ignored, perhaps because
- // the IP is 0, or the interface is one we know is invalid.
- bool ignored() const { return ignored_; }
- void set_ignored(bool ignored) { ignored_ = ignored; }
-
- AdapterType type() const { return type_; }
- int preference() const { return preference_; }
- void set_preference(int preference) { preference_ = preference; }
-
- // Debugging description of this network
- std::string ToString() const;
-
- private:
- std::string name_;
- std::string description_;
- IPAddress prefix_;
- int prefix_length_;
- std::string key_;
- std::vector<IPAddress> ips_;
- int scope_id_;
- bool ignored_;
- AdapterType type_;
- int preference_;
-
- friend class NetworkManager;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_NETWORK_H_
diff --git a/base/network_unittest.cc b/base/network_unittest.cc
deleted file mode 100644
index 56b11c6..0000000
--- a/base/network_unittest.cc
+++ /dev/null
@@ -1,634 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/network.h"
-
-#include <vector>
-#if defined(POSIX)
-#include <sys/types.h>
-#ifndef ANDROID
-#include <ifaddrs.h>
-#else
-#include "talk/base/ifaddrs-android.h"
-#endif
-#endif
-#include "talk/base/gunit.h"
-#ifdef WIN32
-#include "talk/base/logging.h" // For LOG_GLE
-#endif
-
-namespace talk_base {
-
-class NetworkTest : public testing::Test, public sigslot::has_slots<> {
- public:
- NetworkTest() : callback_called_(false) {}
-
- void OnNetworksChanged() {
- callback_called_ = true;
- }
-
- void MergeNetworkList(BasicNetworkManager& network_manager,
- const NetworkManager::NetworkList& list,
- bool* changed ) {
- network_manager.MergeNetworkList(list, changed);
- }
-
- bool IsIgnoredNetwork(BasicNetworkManager& network_manager,
- const Network& network) {
- return network_manager.IsIgnoredNetwork(network);
- }
-
- NetworkManager::NetworkList GetNetworks(
- const BasicNetworkManager& network_manager, bool include_ignored) {
- NetworkManager::NetworkList list;
- network_manager.CreateNetworks(include_ignored, &list);
- return list;
- }
-
-#if defined(POSIX)
- // Separated from CreateNetworks for tests.
- static void CallConvertIfAddrs(const BasicNetworkManager& network_manager,
- struct ifaddrs* interfaces,
- bool include_ignored,
- NetworkManager::NetworkList* networks) {
- network_manager.ConvertIfAddrs(interfaces, include_ignored, networks);
- }
-#endif // defined(POSIX)
-
- protected:
- bool callback_called_;
-};
-
-// Test that the Network ctor works properly.
-TEST_F(NetworkTest, TestNetworkConstruct) {
- Network ipv4_network1("test_eth0", "Test Network Adapter 1",
- IPAddress(0x12345600U), 24);
- EXPECT_EQ("test_eth0", ipv4_network1.name());
- EXPECT_EQ("Test Network Adapter 1", ipv4_network1.description());
- EXPECT_EQ(IPAddress(0x12345600U), ipv4_network1.prefix());
- EXPECT_EQ(24, ipv4_network1.prefix_length());
- EXPECT_FALSE(ipv4_network1.ignored());
-}
-
-// Tests that our ignore function works properly.
-TEST_F(NetworkTest, TestNetworkIgnore) {
- Network ipv4_network1("test_eth0", "Test Network Adapter 1",
- IPAddress(0x12345600U), 24);
- Network ipv4_network2("test_eth1", "Test Network Adapter 2",
- IPAddress(0x00010000U), 16);
- BasicNetworkManager network_manager;
- EXPECT_FALSE(IsIgnoredNetwork(network_manager, ipv4_network1));
- EXPECT_TRUE(IsIgnoredNetwork(network_manager, ipv4_network2));
-}
-
-TEST_F(NetworkTest, TestIgnoreList) {
- Network ignore_me("ignore_me", "Ignore me please!",
- IPAddress(0x12345600U), 24);
- Network include_me("include_me", "Include me please!",
- IPAddress(0x12345600U), 24);
- BasicNetworkManager network_manager;
- EXPECT_FALSE(IsIgnoredNetwork(network_manager, ignore_me));
- EXPECT_FALSE(IsIgnoredNetwork(network_manager, include_me));
- std::vector<std::string> ignore_list;
- ignore_list.push_back("ignore_me");
- network_manager.set_network_ignore_list(ignore_list);
- EXPECT_TRUE(IsIgnoredNetwork(network_manager, ignore_me));
- EXPECT_FALSE(IsIgnoredNetwork(network_manager, include_me));
-}
-
-// Test is failing on Windows opt: b/11288214
-TEST_F(NetworkTest, DISABLED_TestCreateNetworks) {
- BasicNetworkManager manager;
- NetworkManager::NetworkList result = GetNetworks(manager, true);
- // We should be able to bind to any addresses we find.
- NetworkManager::NetworkList::iterator it;
- for (it = result.begin();
- it != result.end();
- ++it) {
- sockaddr_storage storage;
- memset(&storage, 0, sizeof(storage));
- IPAddress ip = (*it)->ip();
- SocketAddress bindaddress(ip, 0);
- bindaddress.SetScopeID((*it)->scope_id());
- // TODO(thaloun): Use talk_base::AsyncSocket once it supports IPv6.
- int fd = static_cast<int>(socket(ip.family(), SOCK_STREAM, IPPROTO_TCP));
- if (fd > 0) {
- size_t ipsize = bindaddress.ToSockAddrStorage(&storage);
- EXPECT_GE(ipsize, 0U);
- int success = ::bind(fd,
- reinterpret_cast<sockaddr*>(&storage),
- static_cast<int>(ipsize));
-#ifdef WIN32
- if (success) LOG_GLE(LS_ERROR) << "Socket bind failed.";
-#endif
- EXPECT_EQ(0, success);
-#ifdef WIN32
- closesocket(fd);
-#else
- close(fd);
-#endif
- }
- delete (*it);
- }
-}
-
-// Test that UpdateNetworks succeeds.
-TEST_F(NetworkTest, TestUpdateNetworks) {
- BasicNetworkManager manager;
- manager.SignalNetworksChanged.connect(
- static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
- manager.StartUpdating();
- Thread::Current()->ProcessMessages(0);
- EXPECT_TRUE(callback_called_);
- callback_called_ = false;
- // Callback should be triggered immediately when StartUpdating
- // is called, after network update signal is already sent.
- manager.StartUpdating();
- EXPECT_TRUE(manager.started());
- Thread::Current()->ProcessMessages(0);
- EXPECT_TRUE(callback_called_);
- manager.StopUpdating();
- EXPECT_TRUE(manager.started());
- manager.StopUpdating();
- EXPECT_FALSE(manager.started());
- manager.StopUpdating();
- EXPECT_FALSE(manager.started());
- callback_called_ = false;
- // Callback should be triggered immediately after StartUpdating is called
- // when start_count_ is reset to 0.
- manager.StartUpdating();
- Thread::Current()->ProcessMessages(0);
- EXPECT_TRUE(callback_called_);
-}
-
-// Verify that MergeNetworkList() merges network lists properly.
-TEST_F(NetworkTest, TestBasicMergeNetworkList) {
- Network ipv4_network1("test_eth0", "Test Network Adapter 1",
- IPAddress(0x12345600U), 24);
- Network ipv4_network2("test_eth1", "Test Network Adapter 2",
- IPAddress(0x00010000U), 16);
- ipv4_network1.AddIP(IPAddress(0x12345678));
- ipv4_network2.AddIP(IPAddress(0x00010004));
- BasicNetworkManager manager;
-
- // Add ipv4_network1 to the list of networks.
- NetworkManager::NetworkList list;
- list.push_back(new Network(ipv4_network1));
- bool changed;
- MergeNetworkList(manager, list, &changed);
- EXPECT_TRUE(changed);
- list.clear();
-
- manager.GetNetworks(&list);
- EXPECT_EQ(1U, list.size());
- EXPECT_EQ(ipv4_network1.ToString(), list[0]->ToString());
- Network* net1 = list[0];
- list.clear();
-
- // Replace ipv4_network1 with ipv4_network2.
- list.push_back(new Network(ipv4_network2));
- MergeNetworkList(manager, list, &changed);
- EXPECT_TRUE(changed);
- list.clear();
-
- manager.GetNetworks(&list);
- EXPECT_EQ(1U, list.size());
- EXPECT_EQ(ipv4_network2.ToString(), list[0]->ToString());
- Network* net2 = list[0];
- list.clear();
-
- // Add Network2 back.
- list.push_back(new Network(ipv4_network1));
- list.push_back(new Network(ipv4_network2));
- MergeNetworkList(manager, list, &changed);
- EXPECT_TRUE(changed);
- list.clear();
-
- // Verify that we get previous instances of Network objects.
- manager.GetNetworks(&list);
- EXPECT_EQ(2U, list.size());
- EXPECT_TRUE((net1 == list[0] && net2 == list[1]) ||
- (net1 == list[1] && net2 == list[0]));
- list.clear();
-
- // Call MergeNetworkList() again and verify that we don't get update
- // notification.
- list.push_back(new Network(ipv4_network2));
- list.push_back(new Network(ipv4_network1));
- MergeNetworkList(manager, list, &changed);
- EXPECT_FALSE(changed);
- list.clear();
-
- // Verify that we get previous instances of Network objects.
- manager.GetNetworks(&list);
- EXPECT_EQ(2U, list.size());
- EXPECT_TRUE((net1 == list[0] && net2 == list[1]) ||
- (net1 == list[1] && net2 == list[0]));
- list.clear();
-}
-
-// Sets up some test IPv6 networks and appends them to list.
-// Four networks are added - public and link local, for two interfaces.
-void SetupNetworks(NetworkManager::NetworkList* list) {
- IPAddress ip;
- IPAddress prefix;
- EXPECT_TRUE(IPFromString("fe80::1234:5678:abcd:ef12", &ip));
- EXPECT_TRUE(IPFromString("fe80::", &prefix));
- // First, fake link-locals.
- Network ipv6_eth0_linklocalnetwork("test_eth0", "Test NetworkAdapter 1",
- prefix, 64);
- ipv6_eth0_linklocalnetwork.AddIP(ip);
- EXPECT_TRUE(IPFromString("fe80::5678:abcd:ef12:3456", &ip));
- Network ipv6_eth1_linklocalnetwork("test_eth1", "Test NetworkAdapter 2",
- prefix, 64);
- ipv6_eth1_linklocalnetwork.AddIP(ip);
- // Public networks:
- EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c3", &ip));
- prefix = TruncateIP(ip, 64);
- Network ipv6_eth0_publicnetwork1_ip1("test_eth0", "Test NetworkAdapter 1",
- prefix, 64);
- ipv6_eth0_publicnetwork1_ip1.AddIP(ip);
- EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:abcd:efab:cdef", &ip));
- prefix = TruncateIP(ip, 64);
- Network ipv6_eth1_publicnetwork1_ip1("test_eth1", "Test NetworkAdapter 1",
- prefix, 64);
- ipv6_eth1_publicnetwork1_ip1.AddIP(ip);
- list->push_back(new Network(ipv6_eth0_linklocalnetwork));
- list->push_back(new Network(ipv6_eth1_linklocalnetwork));
- list->push_back(new Network(ipv6_eth0_publicnetwork1_ip1));
- list->push_back(new Network(ipv6_eth1_publicnetwork1_ip1));
-}
-
-// Test that the basic network merging case works.
-TEST_F(NetworkTest, TestIPv6MergeNetworkList) {
- BasicNetworkManager manager;
- manager.SignalNetworksChanged.connect(
- static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
- NetworkManager::NetworkList original_list;
- SetupNetworks(&original_list);
- bool changed = false;
- MergeNetworkList(manager, original_list, &changed);
- EXPECT_TRUE(changed);
- NetworkManager::NetworkList list;
- manager.GetNetworks(&list);
- EXPECT_EQ(original_list.size(), list.size());
- // Verify that the original members are in the merged list.
- for (NetworkManager::NetworkList::iterator it = original_list.begin();
- it != original_list.end(); ++it) {
- EXPECT_NE(list.end(), std::find(list.begin(), list.end(), *it));
- }
-}
-
-// Tests that when two network lists that describe the same set of networks are
-// merged, that the changed callback is not called, and that the original
-// objects remain in the result list.
-TEST_F(NetworkTest, TestNoChangeMerge) {
- BasicNetworkManager manager;
- manager.SignalNetworksChanged.connect(
- static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
- NetworkManager::NetworkList original_list;
- SetupNetworks(&original_list);
- bool changed = false;
- MergeNetworkList(manager, original_list, &changed);
- EXPECT_TRUE(changed);
- // Second list that describes the same networks but with new objects.
- NetworkManager::NetworkList second_list;
- SetupNetworks(&second_list);
- changed = false;
- MergeNetworkList(manager, second_list, &changed);
- EXPECT_FALSE(changed);
- NetworkManager::NetworkList resulting_list;
- manager.GetNetworks(&resulting_list);
- EXPECT_EQ(original_list.size(), resulting_list.size());
- // Verify that the original members are in the merged list.
- for (NetworkManager::NetworkList::iterator it = original_list.begin();
- it != original_list.end(); ++it) {
- EXPECT_NE(resulting_list.end(),
- std::find(resulting_list.begin(), resulting_list.end(), *it));
- }
- // Doublecheck that the new networks aren't in the list.
- for (NetworkManager::NetworkList::iterator it = second_list.begin();
- it != second_list.end(); ++it) {
- EXPECT_EQ(resulting_list.end(),
- std::find(resulting_list.begin(), resulting_list.end(), *it));
- }
-}
-
-// Test that we can merge a network that is the same as another network but with
-// a different IP. The original network should remain in the list, but have its
-// IP changed.
-TEST_F(NetworkTest, MergeWithChangedIP) {
- BasicNetworkManager manager;
- manager.SignalNetworksChanged.connect(
- static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
- NetworkManager::NetworkList original_list;
- SetupNetworks(&original_list);
- // Make a network that we're going to change.
- IPAddress ip;
- EXPECT_TRUE(IPFromString("2401:fa01:4:1000:be30:faa:fee:faa", &ip));
- IPAddress prefix = TruncateIP(ip, 64);
- Network* network_to_change = new Network("test_eth0",
- "Test Network Adapter 1",
- prefix, 64);
- Network* changed_network = new Network(*network_to_change);
- network_to_change->AddIP(ip);
- IPAddress changed_ip;
- EXPECT_TRUE(IPFromString("2401:fa01:4:1000:be30:f00:f00:f00", &changed_ip));
- changed_network->AddIP(changed_ip);
- original_list.push_back(network_to_change);
- bool changed = false;
- MergeNetworkList(manager, original_list, &changed);
- NetworkManager::NetworkList second_list;
- SetupNetworks(&second_list);
- second_list.push_back(changed_network);
- changed = false;
- MergeNetworkList(manager, second_list, &changed);
- EXPECT_TRUE(changed);
- NetworkManager::NetworkList list;
- manager.GetNetworks(&list);
- EXPECT_EQ(original_list.size(), list.size());
- // Make sure the original network is still in the merged list.
- EXPECT_NE(list.end(),
- std::find(list.begin(), list.end(), network_to_change));
- EXPECT_EQ(changed_ip, network_to_change->GetIPs().at(0));
-}
-
-// Testing a similar case to above, but checking that a network can be updated
-// with additional IPs (not just a replacement).
-TEST_F(NetworkTest, TestMultipleIPMergeNetworkList) {
- BasicNetworkManager manager;
- manager.SignalNetworksChanged.connect(
- static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
- NetworkManager::NetworkList original_list;
- SetupNetworks(&original_list);
- bool changed = false;
- MergeNetworkList(manager, original_list, &changed);
- EXPECT_TRUE(changed);
- IPAddress ip;
- IPAddress check_ip;
- IPAddress prefix;
- // Add a second IP to the public network on eth0 (2401:fa00:4:1000/64).
- EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c6", &ip));
- prefix = TruncateIP(ip, 64);
- Network ipv6_eth0_publicnetwork1_ip2("test_eth0", "Test NetworkAdapter 1",
- prefix, 64);
- // This is the IP that already existed in the public network on eth0.
- EXPECT_TRUE(IPFromString("2401:fa00:4:1000:be30:5bff:fee5:c3", &check_ip));
- ipv6_eth0_publicnetwork1_ip2.AddIP(ip);
- original_list.push_back(new Network(ipv6_eth0_publicnetwork1_ip2));
- changed = false;
- MergeNetworkList(manager, original_list, &changed);
- EXPECT_TRUE(changed);
- // There should still be four networks.
- NetworkManager::NetworkList list;
- manager.GetNetworks(&list);
- EXPECT_EQ(4U, list.size());
- // Check the gathered IPs.
- int matchcount = 0;
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- if ((*it)->ToString() == original_list[2]->ToString()) {
- ++matchcount;
- EXPECT_EQ(1, matchcount);
- // This should be the same network object as before.
- EXPECT_EQ((*it), original_list[2]);
- // But with two addresses now.
- EXPECT_EQ(2U, (*it)->GetIPs().size());
- EXPECT_NE((*it)->GetIPs().end(),
- std::find((*it)->GetIPs().begin(),
- (*it)->GetIPs().end(),
- check_ip));
- EXPECT_NE((*it)->GetIPs().end(),
- std::find((*it)->GetIPs().begin(),
- (*it)->GetIPs().end(),
- ip));
- } else {
- // Check the IP didn't get added anywhere it wasn't supposed to.
- EXPECT_EQ((*it)->GetIPs().end(),
- std::find((*it)->GetIPs().begin(),
- (*it)->GetIPs().end(),
- ip));
- }
- }
-}
-
-// Test that merge correctly distinguishes multiple networks on an interface.
-TEST_F(NetworkTest, TestMultiplePublicNetworksOnOneInterfaceMerge) {
- BasicNetworkManager manager;
- manager.SignalNetworksChanged.connect(
- static_cast<NetworkTest*>(this), &NetworkTest::OnNetworksChanged);
- NetworkManager::NetworkList original_list;
- SetupNetworks(&original_list);
- bool changed = false;
- MergeNetworkList(manager, original_list, &changed);
- EXPECT_TRUE(changed);
- IPAddress ip;
- IPAddress prefix;
- // A second network for eth0.
- EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:5bff:fee5:c3", &ip));
- prefix = TruncateIP(ip, 64);
- Network ipv6_eth0_publicnetwork2_ip1("test_eth0", "Test NetworkAdapter 1",
- prefix, 64);
- ipv6_eth0_publicnetwork2_ip1.AddIP(ip);
- original_list.push_back(new Network(ipv6_eth0_publicnetwork2_ip1));
- changed = false;
- MergeNetworkList(manager, original_list, &changed);
- EXPECT_TRUE(changed);
- // There should be five networks now.
- NetworkManager::NetworkList list;
- manager.GetNetworks(&list);
- EXPECT_EQ(5U, list.size());
- // Check the resulting addresses.
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- if ((*it)->prefix() == ipv6_eth0_publicnetwork2_ip1.prefix() &&
- (*it)->name() == ipv6_eth0_publicnetwork2_ip1.name()) {
- // Check the new network has 1 IP and that it's the correct one.
- EXPECT_EQ(1U, (*it)->GetIPs().size());
- EXPECT_EQ(ip, (*it)->GetIPs().at(0));
- } else {
- // Check the IP didn't get added anywhere it wasn't supposed to.
- EXPECT_EQ((*it)->GetIPs().end(),
- std::find((*it)->GetIPs().begin(),
- (*it)->GetIPs().end(),
- ip));
- }
- }
-}
-
-// Test that DumpNetworks works.
-TEST_F(NetworkTest, TestDumpNetworks) {
- BasicNetworkManager manager;
- manager.DumpNetworks(true);
-}
-
-// Test that we can toggle IPv6 on and off.
-TEST_F(NetworkTest, TestIPv6Toggle) {
- BasicNetworkManager manager;
- bool ipv6_found = false;
- NetworkManager::NetworkList list;
-#ifndef WIN32
- // There should be at least one IPv6 network (fe80::/64 should be in there).
- // TODO(thaloun): Disabling this test on windows for the moment as the test
- // machines don't seem to have IPv6 installed on them at all.
- manager.set_ipv6_enabled(true);
- list = GetNetworks(manager, true);
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- if ((*it)->prefix().family() == AF_INET6) {
- ipv6_found = true;
- break;
- }
- }
- EXPECT_TRUE(ipv6_found);
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- delete (*it);
- }
-#endif
- ipv6_found = false;
- manager.set_ipv6_enabled(false);
- list = GetNetworks(manager, true);
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- if ((*it)->prefix().family() == AF_INET6) {
- ipv6_found = true;
- break;
- }
- }
- EXPECT_FALSE(ipv6_found);
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- delete (*it);
- }
-}
-
-TEST_F(NetworkTest, TestNetworkListSorting) {
- BasicNetworkManager manager;
- Network ipv4_network1("test_eth0", "Test Network Adapter 1",
- IPAddress(0x12345600U), 24);
- ipv4_network1.AddIP(IPAddress(0x12345600U));
-
- IPAddress ip;
- IPAddress prefix;
- EXPECT_TRUE(IPFromString("2400:4030:1:2c00:be30:abcd:efab:cdef", &ip));
- prefix = TruncateIP(ip, 64);
- Network ipv6_eth1_publicnetwork1_ip1("test_eth1", "Test NetworkAdapter 2",
- prefix, 64);
- ipv6_eth1_publicnetwork1_ip1.AddIP(ip);
-
- NetworkManager::NetworkList list;
- list.push_back(new Network(ipv4_network1));
- list.push_back(new Network(ipv6_eth1_publicnetwork1_ip1));
- Network* net1 = list[0];
- Network* net2 = list[1];
-
- bool changed = false;
- MergeNetworkList(manager, list, &changed);
- ASSERT_TRUE(changed);
- // After sorting IPv6 network should be higher order than IPv4 networks.
- EXPECT_TRUE(net1->preference() < net2->preference());
-}
-
-TEST_F(NetworkTest, TestNetworkAdapterTypes) {
- Network wifi("wlan0", "Wireless Adapter", IPAddress(0x12345600U), 24,
- ADAPTER_TYPE_WIFI);
- EXPECT_EQ(ADAPTER_TYPE_WIFI, wifi.type());
- Network ethernet("eth0", "Ethernet", IPAddress(0x12345600U), 24,
- ADAPTER_TYPE_ETHERNET);
- EXPECT_EQ(ADAPTER_TYPE_ETHERNET, ethernet.type());
- Network cellular("test_cell", "Cellular Adapter", IPAddress(0x12345600U), 24,
- ADAPTER_TYPE_CELLULAR);
- EXPECT_EQ(ADAPTER_TYPE_CELLULAR, cellular.type());
- Network vpn("bridge_test", "VPN Adapter", IPAddress(0x12345600U), 24,
- ADAPTER_TYPE_VPN);
- EXPECT_EQ(ADAPTER_TYPE_VPN, vpn.type());
- Network unknown("test", "Test Adapter", IPAddress(0x12345600U), 24,
- ADAPTER_TYPE_UNKNOWN);
- EXPECT_EQ(ADAPTER_TYPE_UNKNOWN, unknown.type());
-}
-
-#if defined(POSIX)
-// Verify that we correctly handle interfaces with no address.
-TEST_F(NetworkTest, TestConvertIfAddrsNoAddress) {
- ifaddrs list;
- memset(&list, 0, sizeof(list));
- list.ifa_name = const_cast<char*>("test_iface");
-
- NetworkManager::NetworkList result;
- BasicNetworkManager manager;
- CallConvertIfAddrs(manager, &list, true, &result);
- EXPECT_TRUE(result.empty());
-}
-#endif // defined(POSIX)
-
-#if defined(LINUX)
-// If you want to test non-default routes, you can do the following on a linux
-// machine:
-// 1) Load the dummy network driver:
-// sudo modprobe dummy
-// sudo ifconfig dummy0 127.0.0.1
-// 2) Run this test and confirm the output says it found a dummy route (and
-// passes).
-// 3) When done:
-// sudo rmmmod dummy
-TEST_F(NetworkTest, TestIgnoreNonDefaultRoutes) {
- BasicNetworkManager manager;
- NetworkManager::NetworkList list;
- list = GetNetworks(manager, false);
- bool found_dummy = false;
- LOG(LS_INFO) << "Looking for dummy network: ";
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- LOG(LS_INFO) << " Network name: " << (*it)->name();
- found_dummy |= (*it)->name().find("dummy0") != std::string::npos;
- }
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- delete (*it);
- }
- if (!found_dummy) {
- LOG(LS_INFO) << "No dummy found, quitting.";
- return;
- }
- LOG(LS_INFO) << "Found dummy, running again while ignoring non-default "
- << "routes.";
- manager.set_ignore_non_default_routes(true);
- list = GetNetworks(manager, false);
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- LOG(LS_INFO) << " Network name: " << (*it)->name();
- EXPECT_TRUE((*it)->name().find("dummy0") == std::string::npos);
- }
- for (NetworkManager::NetworkList::iterator it = list.begin();
- it != list.end(); ++it) {
- delete (*it);
- }
-}
-#endif
-
-} // namespace talk_base
diff --git a/base/nssidentity.cc b/base/nssidentity.cc
deleted file mode 100644
index a0cd8b2..0000000
--- a/base/nssidentity.cc
+++ /dev/null
@@ -1,539 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- * Copyright 2012, RTFM, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <algorithm>
-#include <string>
-#include <vector>
-
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#if HAVE_NSS_SSL_H
-
-#include "talk/base/nssidentity.h"
-
-#include "cert.h"
-#include "cryptohi.h"
-#include "keyhi.h"
-#include "nss.h"
-#include "pk11pub.h"
-#include "sechash.h"
-
-#include "talk/base/logging.h"
-#include "talk/base/helpers.h"
-#include "talk/base/nssstreamadapter.h"
-#include "talk/base/safe_conversions.h"
-
-namespace talk_base {
-
-// Certificate validity lifetime in seconds.
-static const int CERTIFICATE_LIFETIME = 60*60*24*30; // 30 days, arbitrarily
-// Certificate validity window in seconds.
-// This is to compensate for slightly incorrect system clocks.
-static const int CERTIFICATE_WINDOW = -60*60*24;
-
-NSSKeyPair::~NSSKeyPair() {
- if (privkey_)
- SECKEY_DestroyPrivateKey(privkey_);
- if (pubkey_)
- SECKEY_DestroyPublicKey(pubkey_);
-}
-
-NSSKeyPair *NSSKeyPair::Generate() {
- SECKEYPrivateKey *privkey = NULL;
- SECKEYPublicKey *pubkey = NULL;
- PK11RSAGenParams rsaparams;
- rsaparams.keySizeInBits = 1024;
- rsaparams.pe = 0x010001; // 65537 -- a common RSA public exponent.
-
- privkey = PK11_GenerateKeyPair(NSSContext::GetSlot(),
- CKM_RSA_PKCS_KEY_PAIR_GEN,
- &rsaparams, &pubkey, PR_FALSE /*permanent*/,
- PR_FALSE /*sensitive*/, NULL);
- if (!privkey) {
- LOG(LS_ERROR) << "Couldn't generate key pair";
- return NULL;
- }
-
- return new NSSKeyPair(privkey, pubkey);
-}
-
-// Just make a copy.
-NSSKeyPair *NSSKeyPair::GetReference() {
- SECKEYPrivateKey *privkey = SECKEY_CopyPrivateKey(privkey_);
- if (!privkey)
- return NULL;
-
- SECKEYPublicKey *pubkey = SECKEY_CopyPublicKey(pubkey_);
- if (!pubkey) {
- SECKEY_DestroyPrivateKey(privkey);
- return NULL;
- }
-
- return new NSSKeyPair(privkey, pubkey);
-}
-
-NSSCertificate::NSSCertificate(CERTCertificate* cert)
- : certificate_(CERT_DupCertificate(cert)) {
- ASSERT(certificate_ != NULL);
-}
-
-static void DeleteCert(SSLCertificate* cert) {
- delete cert;
-}
-
-NSSCertificate::NSSCertificate(CERTCertList* cert_list) {
- // Copy the first cert into certificate_.
- CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
- certificate_ = CERT_DupCertificate(node->cert);
-
- // Put any remaining certificates into the chain.
- node = CERT_LIST_NEXT(node);
- std::vector<SSLCertificate*> certs;
- for (; !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) {
- certs.push_back(new NSSCertificate(node->cert));
- }
-
- if (!certs.empty())
- chain_.reset(new SSLCertChain(certs));
-
- // The SSLCertChain constructor copies its input, so now we have to delete
- // the originals.
- std::for_each(certs.begin(), certs.end(), DeleteCert);
-}
-
-NSSCertificate::NSSCertificate(CERTCertificate* cert, SSLCertChain* chain)
- : certificate_(CERT_DupCertificate(cert)) {
- ASSERT(certificate_ != NULL);
- if (chain)
- chain_.reset(chain->Copy());
-}
-
-
-NSSCertificate *NSSCertificate::FromPEMString(const std::string &pem_string) {
- std::string der;
- if (!SSLIdentity::PemToDer(kPemTypeCertificate, pem_string, &der))
- return NULL;
-
- SECItem der_cert;
- der_cert.data = reinterpret_cast<unsigned char *>(const_cast<char *>(
- der.data()));
- der_cert.len = checked_cast<unsigned int>(der.size());
- CERTCertificate *cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
- &der_cert, NULL, PR_FALSE, PR_TRUE);
-
- if (!cert)
- return NULL;
-
- NSSCertificate* ret = new NSSCertificate(cert);
- CERT_DestroyCertificate(cert);
- return ret;
-}
-
-NSSCertificate *NSSCertificate::GetReference() const {
- return new NSSCertificate(certificate_, chain_.get());
-}
-
-std::string NSSCertificate::ToPEMString() const {
- return SSLIdentity::DerToPem(kPemTypeCertificate,
- certificate_->derCert.data,
- certificate_->derCert.len);
-}
-
-void NSSCertificate::ToDER(Buffer* der_buffer) const {
- der_buffer->SetData(certificate_->derCert.data, certificate_->derCert.len);
-}
-
-static bool Certifies(CERTCertificate* parent, CERTCertificate* child) {
- // TODO(bemasc): Identify stricter validation checks to use here. In the
- // context of some future identity standard, it might make sense to check
- // the certificates' roles, expiration dates, self-signatures (if
- // self-signed), certificate transparency logging, or many other attributes.
- // NOTE: Future changes to this validation may reject some previously allowed
- // certificate chains. Users should be advised not to deploy chained
- // certificates except in controlled environments until the validity
- // requirements are finalized.
-
- // Check that the parent's name is the same as the child's claimed issuer.
- SECComparison name_status =
- CERT_CompareName(&child->issuer, &parent->subject);
- if (name_status != SECEqual)
- return false;
-
- // Extract the parent's public key, or fail if the key could not be read
- // (e.g. certificate is corrupted).
- SECKEYPublicKey* parent_key = CERT_ExtractPublicKey(parent);
- if (!parent_key)
- return false;
-
- // Check that the parent's privkey was actually used to generate the child's
- // signature.
- SECStatus verified = CERT_VerifySignedDataWithPublicKey(
- &child->signatureWrap, parent_key, NULL);
- SECKEY_DestroyPublicKey(parent_key);
- return verified == SECSuccess;
-}
-
-bool NSSCertificate::IsValidChain(const CERTCertList* cert_list) {
- CERTCertListNode* child = CERT_LIST_HEAD(cert_list);
- for (CERTCertListNode* parent = CERT_LIST_NEXT(child);
- !CERT_LIST_END(parent, cert_list);
- child = parent, parent = CERT_LIST_NEXT(parent)) {
- if (!Certifies(parent->cert, child->cert))
- return false;
- }
- return true;
-}
-
-bool NSSCertificate::GetDigestLength(const std::string& algorithm,
- size_t* length) {
- const SECHashObject *ho;
-
- if (!GetDigestObject(algorithm, &ho))
- return false;
-
- *length = ho->length;
-
- return true;
-}
-
-bool NSSCertificate::GetSignatureDigestAlgorithm(std::string* algorithm) const {
- // The function sec_DecodeSigAlg in NSS provides this mapping functionality.
- // Unfortunately it is private, so the functionality must be duplicated here.
- // See https://bugzilla.mozilla.org/show_bug.cgi?id=925165 .
- SECOidTag sig_alg = SECOID_GetAlgorithmTag(&certificate_->signature);
- switch (sig_alg) {
- case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION:
- *algorithm = DIGEST_MD5;
- break;
- case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION:
- case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE:
- case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE:
- case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST:
- case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST:
- case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE:
- case SEC_OID_MISSI_DSS:
- case SEC_OID_MISSI_KEA_DSS:
- case SEC_OID_MISSI_KEA_DSS_OLD:
- case SEC_OID_MISSI_DSS_OLD:
- *algorithm = DIGEST_SHA_1;
- break;
- case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE:
- case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION:
- case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST:
- *algorithm = DIGEST_SHA_224;
- break;
- case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE:
- case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION:
- case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST:
- *algorithm = DIGEST_SHA_256;
- break;
- case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE:
- case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION:
- *algorithm = DIGEST_SHA_384;
- break;
- case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE:
- case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION:
- *algorithm = DIGEST_SHA_512;
- break;
- default:
- // Unknown algorithm. There are several unhandled options that are less
- // common and more complex.
- algorithm->clear();
- return false;
- }
- return true;
-}
-
-bool NSSCertificate::ComputeDigest(const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length) const {
- const SECHashObject *ho;
-
- if (!GetDigestObject(algorithm, &ho))
- return false;
-
- if (size < ho->length) // Sanity check for fit
- return false;
-
- SECStatus rv = HASH_HashBuf(ho->type, digest,
- certificate_->derCert.data,
- certificate_->derCert.len);
- if (rv != SECSuccess)
- return false;
-
- *length = ho->length;
-
- return true;
-}
-
-bool NSSCertificate::GetChain(SSLCertChain** chain) const {
- if (!chain_)
- return false;
-
- *chain = chain_->Copy();
- return true;
-}
-
-bool NSSCertificate::Equals(const NSSCertificate *tocompare) const {
- if (!certificate_->derCert.len)
- return false;
- if (!tocompare->certificate_->derCert.len)
- return false;
-
- if (certificate_->derCert.len != tocompare->certificate_->derCert.len)
- return false;
-
- return memcmp(certificate_->derCert.data,
- tocompare->certificate_->derCert.data,
- certificate_->derCert.len) == 0;
-}
-
-
-bool NSSCertificate::GetDigestObject(const std::string &algorithm,
- const SECHashObject **hop) {
- const SECHashObject *ho;
- HASH_HashType hash_type;
-
- if (algorithm == DIGEST_SHA_1) {
- hash_type = HASH_AlgSHA1;
- // HASH_AlgSHA224 is not supported in the chromium linux build system.
-#if 0
- } else if (algorithm == DIGEST_SHA_224) {
- hash_type = HASH_AlgSHA224;
-#endif
- } else if (algorithm == DIGEST_SHA_256) {
- hash_type = HASH_AlgSHA256;
- } else if (algorithm == DIGEST_SHA_384) {
- hash_type = HASH_AlgSHA384;
- } else if (algorithm == DIGEST_SHA_512) {
- hash_type = HASH_AlgSHA512;
- } else {
- return false;
- }
-
- ho = HASH_GetHashObject(hash_type);
-
- ASSERT(ho->length >= 20); // Can't happen
- *hop = ho;
-
- return true;
-}
-
-
-NSSIdentity* NSSIdentity::GenerateInternal(const SSLIdentityParams& params) {
- std::string subject_name_string = "CN=" + params.common_name;
- CERTName *subject_name = CERT_AsciiToName(
- const_cast<char *>(subject_name_string.c_str()));
- NSSIdentity *identity = NULL;
- CERTSubjectPublicKeyInfo *spki = NULL;
- CERTCertificateRequest *certreq = NULL;
- CERTValidity *validity = NULL;
- CERTCertificate *certificate = NULL;
- NSSKeyPair *keypair = NSSKeyPair::Generate();
- SECItem inner_der;
- SECStatus rv;
- PLArenaPool* arena;
- SECItem signed_cert;
- PRTime now = PR_Now();
- PRTime not_before =
- now + static_cast<PRTime>(params.not_before) * PR_USEC_PER_SEC;
- PRTime not_after =
- now + static_cast<PRTime>(params.not_after) * PR_USEC_PER_SEC;
-
- inner_der.len = 0;
- inner_der.data = NULL;
-
- if (!keypair) {
- LOG(LS_ERROR) << "Couldn't generate key pair";
- goto fail;
- }
-
- if (!subject_name) {
- LOG(LS_ERROR) << "Couldn't convert subject name " << subject_name;
- goto fail;
- }
-
- spki = SECKEY_CreateSubjectPublicKeyInfo(keypair->pubkey());
- if (!spki) {
- LOG(LS_ERROR) << "Couldn't create SPKI";
- goto fail;
- }
-
- certreq = CERT_CreateCertificateRequest(subject_name, spki, NULL);
- if (!certreq) {
- LOG(LS_ERROR) << "Couldn't create certificate signing request";
- goto fail;
- }
-
- validity = CERT_CreateValidity(not_before, not_after);
- if (!validity) {
- LOG(LS_ERROR) << "Couldn't create validity";
- goto fail;
- }
-
- unsigned long serial;
- // Note: This serial in principle could collide, but it's unlikely
- rv = PK11_GenerateRandom(reinterpret_cast<unsigned char *>(&serial),
- sizeof(serial));
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Couldn't generate random serial";
- goto fail;
- }
-
- certificate = CERT_CreateCertificate(serial, subject_name, validity, certreq);
- if (!certificate) {
- LOG(LS_ERROR) << "Couldn't create certificate";
- goto fail;
- }
-
- arena = certificate->arena;
-
- rv = SECOID_SetAlgorithmID(arena, &certificate->signature,
- SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION, NULL);
- if (rv != SECSuccess)
- goto fail;
-
- // Set version to X509v3.
- *(certificate->version.data) = 2;
- certificate->version.len = 1;
-
- if (!SEC_ASN1EncodeItem(arena, &inner_der, certificate,
- SEC_ASN1_GET(CERT_CertificateTemplate)))
- goto fail;
-
- rv = SEC_DerSignData(arena, &signed_cert, inner_der.data, inner_der.len,
- keypair->privkey(),
- SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Couldn't sign certificate";
- goto fail;
- }
- certificate->derCert = signed_cert;
-
- identity = new NSSIdentity(keypair, new NSSCertificate(certificate));
-
- goto done;
-
- fail:
- delete keypair;
-
- done:
- if (certificate) CERT_DestroyCertificate(certificate);
- if (subject_name) CERT_DestroyName(subject_name);
- if (spki) SECKEY_DestroySubjectPublicKeyInfo(spki);
- if (certreq) CERT_DestroyCertificateRequest(certreq);
- if (validity) CERT_DestroyValidity(validity);
- return identity;
-}
-
-NSSIdentity* NSSIdentity::Generate(const std::string &common_name) {
- SSLIdentityParams params;
- params.common_name = common_name;
- params.not_before = CERTIFICATE_WINDOW;
- params.not_after = CERTIFICATE_LIFETIME;
- return GenerateInternal(params);
-}
-
-NSSIdentity* NSSIdentity::GenerateForTest(const SSLIdentityParams& params) {
- return GenerateInternal(params);
-}
-
-SSLIdentity* NSSIdentity::FromPEMStrings(const std::string& private_key,
- const std::string& certificate) {
- std::string private_key_der;
- if (!SSLIdentity::PemToDer(
- kPemTypeRsaPrivateKey, private_key, &private_key_der))
- return NULL;
-
- SECItem private_key_item;
- private_key_item.data = reinterpret_cast<unsigned char *>(
- const_cast<char *>(private_key_der.c_str()));
- private_key_item.len = checked_cast<unsigned int>(private_key_der.size());
-
- const unsigned int key_usage = KU_KEY_ENCIPHERMENT | KU_DATA_ENCIPHERMENT |
- KU_DIGITAL_SIGNATURE;
-
- SECKEYPrivateKey* privkey = NULL;
- SECStatus rv =
- PK11_ImportDERPrivateKeyInfoAndReturnKey(NSSContext::GetSlot(),
- &private_key_item,
- NULL, NULL, PR_FALSE, PR_FALSE,
- key_usage, &privkey, NULL);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Couldn't import private key";
- return NULL;
- }
-
- SECKEYPublicKey *pubkey = SECKEY_ConvertToPublicKey(privkey);
- if (rv != SECSuccess) {
- SECKEY_DestroyPrivateKey(privkey);
- LOG(LS_ERROR) << "Couldn't convert private key to public key";
- return NULL;
- }
-
- // Assign to a scoped_ptr so we don't leak on error.
- scoped_ptr<NSSKeyPair> keypair(new NSSKeyPair(privkey, pubkey));
-
- scoped_ptr<NSSCertificate> cert(NSSCertificate::FromPEMString(certificate));
- if (!cert) {
- LOG(LS_ERROR) << "Couldn't parse certificate";
- return NULL;
- }
-
- // TODO(ekr@rtfm.com): Check the public key against the certificate.
-
- return new NSSIdentity(keypair.release(), cert.release());
-}
-
-NSSIdentity *NSSIdentity::GetReference() const {
- NSSKeyPair *keypair = keypair_->GetReference();
- if (!keypair)
- return NULL;
-
- NSSCertificate *certificate = certificate_->GetReference();
- if (!certificate) {
- delete keypair;
- return NULL;
- }
-
- return new NSSIdentity(keypair, certificate);
-}
-
-
-NSSCertificate &NSSIdentity::certificate() const {
- return *certificate_;
-}
-
-
-} // talk_base namespace
-
-#endif // HAVE_NSS_SSL_H
-
diff --git a/base/nssidentity.h b/base/nssidentity.h
deleted file mode 100644
index b4376d5..0000000
--- a/base/nssidentity.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NSSIDENTITY_H_
-#define TALK_BASE_NSSIDENTITY_H_
-
-#include <string>
-
-#include "cert.h"
-#include "nspr.h"
-#include "hasht.h"
-#include "keythi.h"
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslidentity.h"
-
-namespace talk_base {
-
-class NSSKeyPair {
- public:
- NSSKeyPair(SECKEYPrivateKey* privkey, SECKEYPublicKey* pubkey) :
- privkey_(privkey), pubkey_(pubkey) {}
- ~NSSKeyPair();
-
- // Generate a 1024-bit RSA key pair.
- static NSSKeyPair* Generate();
- NSSKeyPair* GetReference();
-
- SECKEYPrivateKey* privkey() const { return privkey_; }
- SECKEYPublicKey * pubkey() const { return pubkey_; }
-
- private:
- SECKEYPrivateKey* privkey_;
- SECKEYPublicKey* pubkey_;
-
- DISALLOW_EVIL_CONSTRUCTORS(NSSKeyPair);
-};
-
-
-class NSSCertificate : public SSLCertificate {
- public:
- static NSSCertificate* FromPEMString(const std::string& pem_string);
- // The caller retains ownership of the argument to all the constructors,
- // and the constructor makes a copy.
- explicit NSSCertificate(CERTCertificate* cert);
- explicit NSSCertificate(CERTCertList* cert_list);
- virtual ~NSSCertificate() {
- if (certificate_)
- CERT_DestroyCertificate(certificate_);
- }
-
- virtual NSSCertificate* GetReference() const;
-
- virtual std::string ToPEMString() const;
-
- virtual void ToDER(Buffer* der_buffer) const;
-
- virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const;
-
- virtual bool ComputeDigest(const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length) const;
-
- virtual bool GetChain(SSLCertChain** chain) const;
-
- CERTCertificate* certificate() { return certificate_; }
-
- // Performs minimal checks to determine if the list is a valid chain. This
- // only checks that each certificate certifies the preceding certificate,
- // and ignores many other certificate features such as expiration dates.
- static bool IsValidChain(const CERTCertList* cert_list);
-
- // Helper function to get the length of a digest
- static bool GetDigestLength(const std::string& algorithm, size_t* length);
-
- // Comparison. Only the certificate itself is considered, not the chain.
- bool Equals(const NSSCertificate* tocompare) const;
-
- private:
- NSSCertificate(CERTCertificate* cert, SSLCertChain* chain);
- static bool GetDigestObject(const std::string& algorithm,
- const SECHashObject** hash_object);
-
- CERTCertificate* certificate_;
- scoped_ptr<SSLCertChain> chain_;
-
- DISALLOW_EVIL_CONSTRUCTORS(NSSCertificate);
-};
-
-// Represents a SSL key pair and certificate for NSS.
-class NSSIdentity : public SSLIdentity {
- public:
- static NSSIdentity* Generate(const std::string& common_name);
- static NSSIdentity* GenerateForTest(const SSLIdentityParams& params);
- static SSLIdentity* FromPEMStrings(const std::string& private_key,
- const std::string& certificate);
- virtual ~NSSIdentity() {
- LOG(LS_INFO) << "Destroying NSS identity";
- }
-
- virtual NSSIdentity* GetReference() const;
- virtual NSSCertificate& certificate() const;
-
- NSSKeyPair* keypair() const { return keypair_.get(); }
-
- private:
- NSSIdentity(NSSKeyPair* keypair, NSSCertificate* cert) :
- keypair_(keypair), certificate_(cert) {}
-
- static NSSIdentity* GenerateInternal(const SSLIdentityParams& params);
-
- talk_base::scoped_ptr<NSSKeyPair> keypair_;
- talk_base::scoped_ptr<NSSCertificate> certificate_;
-
- DISALLOW_EVIL_CONSTRUCTORS(NSSIdentity);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_NSSIDENTITY_H_
diff --git a/base/nssstreamadapter.cc b/base/nssstreamadapter.cc
deleted file mode 100644
index 60fa738..0000000
--- a/base/nssstreamadapter.cc
+++ /dev/null
@@ -1,1038 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- * Copyright 2004--2011, RTFM, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <vector>
-
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#if HAVE_NSS_SSL_H
-
-#include "talk/base/nssstreamadapter.h"
-
-#include "keyhi.h"
-#include "nspr.h"
-#include "nss.h"
-#include "pk11pub.h"
-#include "secerr.h"
-
-#ifdef NSS_SSL_RELATIVE_PATH
-#include "ssl.h"
-#include "sslerr.h"
-#include "sslproto.h"
-#else
-#include "net/third_party/nss/ssl/ssl.h"
-#include "net/third_party/nss/ssl/sslerr.h"
-#include "net/third_party/nss/ssl/sslproto.h"
-#endif
-
-#include "talk/base/nssidentity.h"
-#include "talk/base/safe_conversions.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-PRDescIdentity NSSStreamAdapter::nspr_layer_identity = PR_INVALID_IO_LAYER;
-
-#define UNIMPLEMENTED \
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); \
- LOG(LS_ERROR) \
- << "Call to unimplemented function "<< __FUNCTION__; ASSERT(false)
-
-#ifdef SRTP_AES128_CM_HMAC_SHA1_80
-#define HAVE_DTLS_SRTP
-#endif
-
-#ifdef HAVE_DTLS_SRTP
-// SRTP cipher suite table
-struct SrtpCipherMapEntry {
- const char* external_name;
- PRUint16 cipher_id;
-};
-
-// This isn't elegant, but it's better than an external reference
-static const SrtpCipherMapEntry kSrtpCipherMap[] = {
- {"AES_CM_128_HMAC_SHA1_80", SRTP_AES128_CM_HMAC_SHA1_80 },
- {"AES_CM_128_HMAC_SHA1_32", SRTP_AES128_CM_HMAC_SHA1_32 },
- {NULL, 0}
-};
-#endif
-
-
-// Implementation of NSPR methods
-static PRStatus StreamClose(PRFileDesc *socket) {
- ASSERT(!socket->lower);
- socket->dtor(socket);
- return PR_SUCCESS;
-}
-
-static PRInt32 StreamRead(PRFileDesc *socket, void *buf, PRInt32 length) {
- StreamInterface *stream = reinterpret_cast<StreamInterface *>(socket->secret);
- size_t read;
- int error;
- StreamResult result = stream->Read(buf, length, &read, &error);
- if (result == SR_SUCCESS) {
- return checked_cast<PRInt32>(read);
- }
-
- if (result == SR_EOS) {
- return 0;
- }
-
- if (result == SR_BLOCK) {
- PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
- return -1;
- }
-
- PR_SetError(PR_UNKNOWN_ERROR, error);
- return -1;
-}
-
-static PRInt32 StreamWrite(PRFileDesc *socket, const void *buf,
- PRInt32 length) {
- StreamInterface *stream = reinterpret_cast<StreamInterface *>(socket->secret);
- size_t written;
- int error;
- StreamResult result = stream->Write(buf, length, &written, &error);
- if (result == SR_SUCCESS) {
- return checked_cast<PRInt32>(written);
- }
-
- if (result == SR_BLOCK) {
- LOG(LS_INFO) <<
- "NSSStreamAdapter: write to underlying transport would block";
- PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
- return -1;
- }
-
- LOG(LS_ERROR) << "Write error";
- PR_SetError(PR_UNKNOWN_ERROR, error);
- return -1;
-}
-
-static PRInt32 StreamAvailable(PRFileDesc *socket) {
- UNIMPLEMENTED;
- return -1;
-}
-
-PRInt64 StreamAvailable64(PRFileDesc *socket) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRStatus StreamSync(PRFileDesc *socket) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PROffset32 StreamSeek(PRFileDesc *socket, PROffset32 offset,
- PRSeekWhence how) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PROffset64 StreamSeek64(PRFileDesc *socket, PROffset64 offset,
- PRSeekWhence how) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRStatus StreamFileInfo(PRFileDesc *socket, PRFileInfo *info) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PRStatus StreamFileInfo64(PRFileDesc *socket, PRFileInfo64 *info) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PRInt32 StreamWritev(PRFileDesc *socket, const PRIOVec *iov,
- PRInt32 iov_size, PRIntervalTime timeout) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRStatus StreamConnect(PRFileDesc *socket, const PRNetAddr *addr,
- PRIntervalTime timeout) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PRFileDesc *StreamAccept(PRFileDesc *sd, PRNetAddr *addr,
- PRIntervalTime timeout) {
- UNIMPLEMENTED;
- return NULL;
-}
-
-static PRStatus StreamBind(PRFileDesc *socket, const PRNetAddr *addr) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PRStatus StreamListen(PRFileDesc *socket, PRIntn depth) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PRStatus StreamShutdown(PRFileDesc *socket, PRIntn how) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-// Note: this is always nonblocking and ignores the timeout.
-// TODO(ekr@rtfm.com): In future verify that the socket is
-// actually in non-blocking mode.
-// This function does not support peek.
-static PRInt32 StreamRecv(PRFileDesc *socket, void *buf, PRInt32 amount,
- PRIntn flags, PRIntervalTime to) {
- ASSERT(flags == 0);
-
- if (flags != 0) {
- PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
- return -1;
- }
-
- return StreamRead(socket, buf, amount);
-}
-
-// Note: this is always nonblocking and assumes a zero timeout.
-// This function does not support peek.
-static PRInt32 StreamSend(PRFileDesc *socket, const void *buf,
- PRInt32 amount, PRIntn flags,
- PRIntervalTime to) {
- ASSERT(flags == 0);
-
- return StreamWrite(socket, buf, amount);
-}
-
-static PRInt32 StreamRecvfrom(PRFileDesc *socket, void *buf,
- PRInt32 amount, PRIntn flags,
- PRNetAddr *addr, PRIntervalTime to) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRInt32 StreamSendto(PRFileDesc *socket, const void *buf,
- PRInt32 amount, PRIntn flags,
- const PRNetAddr *addr, PRIntervalTime to) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRInt16 StreamPoll(PRFileDesc *socket, PRInt16 in_flags,
- PRInt16 *out_flags) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRInt32 StreamAcceptRead(PRFileDesc *sd, PRFileDesc **nd,
- PRNetAddr **raddr,
- void *buf, PRInt32 amount, PRIntervalTime t) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRInt32 StreamTransmitFile(PRFileDesc *sd, PRFileDesc *socket,
- const void *headers, PRInt32 hlen,
- PRTransmitFileFlags flags, PRIntervalTime t) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRStatus StreamGetPeerName(PRFileDesc *socket, PRNetAddr *addr) {
- // TODO(ekr@rtfm.com): Modify to return unique names for each channel
- // somehow, as opposed to always the same static address. The current
- // implementation messes up the session cache, which is why it's off
- // elsewhere
- addr->inet.family = PR_AF_INET;
- addr->inet.port = 0;
- addr->inet.ip = 0;
-
- return PR_SUCCESS;
-}
-
-static PRStatus StreamGetSockName(PRFileDesc *socket, PRNetAddr *addr) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PRStatus StreamGetSockOption(PRFileDesc *socket, PRSocketOptionData *opt) {
- switch (opt->option) {
- case PR_SockOpt_Nonblocking:
- opt->value.non_blocking = PR_TRUE;
- return PR_SUCCESS;
- default:
- UNIMPLEMENTED;
- break;
- }
-
- return PR_FAILURE;
-}
-
-// Imitate setting socket options. These are mostly noops.
-static PRStatus StreamSetSockOption(PRFileDesc *socket,
- const PRSocketOptionData *opt) {
- switch (opt->option) {
- case PR_SockOpt_Nonblocking:
- return PR_SUCCESS;
- case PR_SockOpt_NoDelay:
- return PR_SUCCESS;
- default:
- UNIMPLEMENTED;
- break;
- }
-
- return PR_FAILURE;
-}
-
-static PRInt32 StreamSendfile(PRFileDesc *out, PRSendFileData *in,
- PRTransmitFileFlags flags, PRIntervalTime to) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static PRStatus StreamConnectContinue(PRFileDesc *socket, PRInt16 flags) {
- UNIMPLEMENTED;
- return PR_FAILURE;
-}
-
-static PRIntn StreamReserved(PRFileDesc *socket) {
- UNIMPLEMENTED;
- return -1;
-}
-
-static const struct PRIOMethods nss_methods = {
- PR_DESC_LAYERED,
- StreamClose,
- StreamRead,
- StreamWrite,
- StreamAvailable,
- StreamAvailable64,
- StreamSync,
- StreamSeek,
- StreamSeek64,
- StreamFileInfo,
- StreamFileInfo64,
- StreamWritev,
- StreamConnect,
- StreamAccept,
- StreamBind,
- StreamListen,
- StreamShutdown,
- StreamRecv,
- StreamSend,
- StreamRecvfrom,
- StreamSendto,
- StreamPoll,
- StreamAcceptRead,
- StreamTransmitFile,
- StreamGetSockName,
- StreamGetPeerName,
- StreamReserved,
- StreamReserved,
- StreamGetSockOption,
- StreamSetSockOption,
- StreamSendfile,
- StreamConnectContinue,
- StreamReserved,
- StreamReserved,
- StreamReserved,
- StreamReserved
-};
-
-NSSStreamAdapter::NSSStreamAdapter(StreamInterface *stream)
- : SSLStreamAdapterHelper(stream),
- ssl_fd_(NULL),
- cert_ok_(false) {
-}
-
-bool NSSStreamAdapter::Init() {
- if (nspr_layer_identity == PR_INVALID_IO_LAYER) {
- nspr_layer_identity = PR_GetUniqueIdentity("nssstreamadapter");
- }
- PRFileDesc *pr_fd = PR_CreateIOLayerStub(nspr_layer_identity, &nss_methods);
- if (!pr_fd)
- return false;
- pr_fd->secret = reinterpret_cast<PRFilePrivate *>(stream());
-
- PRFileDesc *ssl_fd;
- if (ssl_mode_ == SSL_MODE_DTLS) {
- ssl_fd = DTLS_ImportFD(NULL, pr_fd);
- } else {
- ssl_fd = SSL_ImportFD(NULL, pr_fd);
- }
- ASSERT(ssl_fd != NULL); // This should never happen
- if (!ssl_fd) {
- PR_Close(pr_fd);
- return false;
- }
-
- SECStatus rv;
- // Turn on security.
- rv = SSL_OptionSet(ssl_fd, SSL_SECURITY, PR_TRUE);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Error enabling security on SSL Socket";
- return false;
- }
-
- // Disable SSLv2.
- rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_SSL2, PR_FALSE);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Error disabling SSL2";
- return false;
- }
-
- // Disable caching.
- // TODO(ekr@rtfm.com): restore this when I have the caching
- // identity set.
- rv = SSL_OptionSet(ssl_fd, SSL_NO_CACHE, PR_TRUE);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Error disabling cache";
- return false;
- }
-
- // Disable session tickets.
- rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_SESSION_TICKETS, PR_FALSE);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Error enabling tickets";
- return false;
- }
-
- // Disable renegotiation.
- rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_RENEGOTIATION,
- SSL_RENEGOTIATE_NEVER);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Error disabling renegotiation";
- return false;
- }
-
- // Disable false start.
- rv = SSL_OptionSet(ssl_fd, SSL_ENABLE_FALSE_START, PR_FALSE);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Error disabling false start";
- return false;
- }
-
- ssl_fd_ = ssl_fd;
-
- return true;
-}
-
-NSSStreamAdapter::~NSSStreamAdapter() {
- if (ssl_fd_)
- PR_Close(ssl_fd_);
-};
-
-
-int NSSStreamAdapter::BeginSSL() {
- SECStatus rv;
-
- if (!Init()) {
- Error("Init", -1, false);
- return -1;
- }
-
- ASSERT(state_ == SSL_CONNECTING);
- // The underlying stream has been opened. If we are in peer-to-peer mode
- // then a peer certificate must have been specified by now.
- ASSERT(!ssl_server_name_.empty() ||
- peer_certificate_.get() != NULL ||
- !peer_certificate_digest_algorithm_.empty());
- LOG(LS_INFO) << "BeginSSL: "
- << (!ssl_server_name_.empty() ? ssl_server_name_ :
- "with peer");
-
- if (role_ == SSL_CLIENT) {
- LOG(LS_INFO) << "BeginSSL: as client";
-
- rv = SSL_GetClientAuthDataHook(ssl_fd_, GetClientAuthDataHook,
- this);
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
- } else {
- LOG(LS_INFO) << "BeginSSL: as server";
- NSSIdentity *identity;
-
- if (identity_.get()) {
- identity = static_cast<NSSIdentity *>(identity_.get());
- } else {
- LOG(LS_ERROR) << "Can't be an SSL server without an identity";
- Error("BeginSSL", -1, false);
- return -1;
- }
- rv = SSL_ConfigSecureServer(ssl_fd_, identity->certificate().certificate(),
- identity->keypair()->privkey(),
- kt_rsa);
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
-
- // Insist on a certificate from the client
- rv = SSL_OptionSet(ssl_fd_, SSL_REQUEST_CERTIFICATE, PR_TRUE);
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
-
- rv = SSL_OptionSet(ssl_fd_, SSL_REQUIRE_CERTIFICATE, PR_TRUE);
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
- }
-
- // Set the version range.
- SSLVersionRange vrange;
- vrange.min = (ssl_mode_ == SSL_MODE_DTLS) ?
- SSL_LIBRARY_VERSION_TLS_1_1 :
- SSL_LIBRARY_VERSION_TLS_1_0;
- vrange.max = SSL_LIBRARY_VERSION_TLS_1_1;
-
- rv = SSL_VersionRangeSet(ssl_fd_, &vrange);
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
-
- // SRTP
-#ifdef HAVE_DTLS_SRTP
- if (!srtp_ciphers_.empty()) {
- rv = SSL_SetSRTPCiphers(
- ssl_fd_, &srtp_ciphers_[0],
- checked_cast<unsigned int>(srtp_ciphers_.size()));
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
- }
-#endif
-
- // Certificate validation
- rv = SSL_AuthCertificateHook(ssl_fd_, AuthCertificateHook, this);
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
-
- // Now start the handshake
- rv = SSL_ResetHandshake(ssl_fd_, role_ == SSL_SERVER ? PR_TRUE : PR_FALSE);
- if (rv != SECSuccess) {
- Error("BeginSSL", -1, false);
- return -1;
- }
-
- return ContinueSSL();
-}
-
-int NSSStreamAdapter::ContinueSSL() {
- LOG(LS_INFO) << "ContinueSSL";
- ASSERT(state_ == SSL_CONNECTING);
-
- // Clear the DTLS timer
- Thread::Current()->Clear(this, MSG_DTLS_TIMEOUT);
-
- SECStatus rv = SSL_ForceHandshake(ssl_fd_);
-
- if (rv == SECSuccess) {
- LOG(LS_INFO) << "Handshake complete";
-
- ASSERT(cert_ok_);
- if (!cert_ok_) {
- Error("ContinueSSL", -1, true);
- return -1;
- }
-
- state_ = SSL_CONNECTED;
- StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
- return 0;
- }
-
- PRInt32 err = PR_GetError();
- switch (err) {
- case SSL_ERROR_RX_MALFORMED_HANDSHAKE:
- if (ssl_mode_ != SSL_MODE_DTLS) {
- Error("ContinueSSL", -1, true);
- return -1;
- } else {
- LOG(LS_INFO) << "Malformed DTLS message. Ignoring.";
- // Fall through
- }
- case PR_WOULD_BLOCK_ERROR:
- LOG(LS_INFO) << "Would have blocked";
- if (ssl_mode_ == SSL_MODE_DTLS) {
- PRIntervalTime timeout;
-
- SECStatus rv = DTLS_GetHandshakeTimeout(ssl_fd_, &timeout);
- if (rv == SECSuccess) {
- LOG(LS_INFO) << "Timeout is " << timeout << " ms";
- Thread::Current()->PostDelayed(PR_IntervalToMilliseconds(timeout),
- this, MSG_DTLS_TIMEOUT, 0);
- }
- }
-
- return 0;
- default:
- LOG(LS_INFO) << "Error " << err;
- break;
- }
-
- Error("ContinueSSL", -1, true);
- return -1;
-}
-
-void NSSStreamAdapter::Cleanup() {
- if (state_ != SSL_ERROR) {
- state_ = SSL_CLOSED;
- }
-
- if (ssl_fd_) {
- PR_Close(ssl_fd_);
- ssl_fd_ = NULL;
- }
-
- identity_.reset();
- peer_certificate_.reset();
-
- Thread::Current()->Clear(this, MSG_DTLS_TIMEOUT);
-}
-
-StreamResult NSSStreamAdapter::Read(void* data, size_t data_len,
- size_t* read, int* error) {
- // SSL_CONNECTED sanity check.
- switch (state_) {
- case SSL_NONE:
- case SSL_WAIT:
- case SSL_CONNECTING:
- return SR_BLOCK;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_CLOSED:
- return SR_EOS;
-
- case SSL_ERROR:
- default:
- if (error)
- *error = ssl_error_code_;
- return SR_ERROR;
- }
-
- PRInt32 rv = PR_Read(ssl_fd_, data, checked_cast<PRInt32>(data_len));
-
- if (rv == 0) {
- return SR_EOS;
- }
-
- // Error
- if (rv < 0) {
- PRInt32 err = PR_GetError();
-
- switch (err) {
- case PR_WOULD_BLOCK_ERROR:
- return SR_BLOCK;
- default:
- Error("Read", -1, false);
- *error = err; // libjingle semantics are that this is impl-specific
- return SR_ERROR;
- }
- }
-
- // Success
- *read = rv;
-
- return SR_SUCCESS;
-}
-
-StreamResult NSSStreamAdapter::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- // SSL_CONNECTED sanity check.
- switch (state_) {
- case SSL_NONE:
- case SSL_WAIT:
- case SSL_CONNECTING:
- return SR_BLOCK;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_ERROR:
- case SSL_CLOSED:
- default:
- if (error)
- *error = ssl_error_code_;
- return SR_ERROR;
- }
-
- PRInt32 rv = PR_Write(ssl_fd_, data, checked_cast<PRInt32>(data_len));
-
- // Error
- if (rv < 0) {
- PRInt32 err = PR_GetError();
-
- switch (err) {
- case PR_WOULD_BLOCK_ERROR:
- return SR_BLOCK;
- default:
- Error("Write", -1, false);
- *error = err; // libjingle semantics are that this is impl-specific
- return SR_ERROR;
- }
- }
-
- // Success
- *written = rv;
-
- return SR_SUCCESS;
-}
-
-void NSSStreamAdapter::OnEvent(StreamInterface* stream, int events,
- int err) {
- int events_to_signal = 0;
- int signal_error = 0;
- ASSERT(stream == this->stream());
- if ((events & SE_OPEN)) {
- LOG(LS_INFO) << "NSSStreamAdapter::OnEvent SE_OPEN";
- if (state_ != SSL_WAIT) {
- ASSERT(state_ == SSL_NONE);
- events_to_signal |= SE_OPEN;
- } else {
- state_ = SSL_CONNECTING;
- if (int err = BeginSSL()) {
- Error("BeginSSL", err, true);
- return;
- }
- }
- }
- if ((events & (SE_READ|SE_WRITE))) {
- LOG(LS_INFO) << "NSSStreamAdapter::OnEvent"
- << ((events & SE_READ) ? " SE_READ" : "")
- << ((events & SE_WRITE) ? " SE_WRITE" : "");
- if (state_ == SSL_NONE) {
- events_to_signal |= events & (SE_READ|SE_WRITE);
- } else if (state_ == SSL_CONNECTING) {
- if (int err = ContinueSSL()) {
- Error("ContinueSSL", err, true);
- return;
- }
- } else if (state_ == SSL_CONNECTED) {
- if (events & SE_WRITE) {
- LOG(LS_INFO) << " -- onStreamWriteable";
- events_to_signal |= SE_WRITE;
- }
- if (events & SE_READ) {
- LOG(LS_INFO) << " -- onStreamReadable";
- events_to_signal |= SE_READ;
- }
- }
- }
- if ((events & SE_CLOSE)) {
- LOG(LS_INFO) << "NSSStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
- Cleanup();
- events_to_signal |= SE_CLOSE;
- // SE_CLOSE is the only event that uses the final parameter to OnEvent().
- ASSERT(signal_error == 0);
- signal_error = err;
- }
- if (events_to_signal)
- StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
-}
-
-void NSSStreamAdapter::OnMessage(Message* msg) {
- // Process our own messages and then pass others to the superclass
- if (MSG_DTLS_TIMEOUT == msg->message_id) {
- LOG(LS_INFO) << "DTLS timeout expired";
- ContinueSSL();
- } else {
- StreamInterface::OnMessage(msg);
- }
-}
-
-// Certificate verification callback. Called to check any certificate
-SECStatus NSSStreamAdapter::AuthCertificateHook(void *arg,
- PRFileDesc *fd,
- PRBool checksig,
- PRBool isServer) {
- LOG(LS_INFO) << "NSSStreamAdapter::AuthCertificateHook";
- // SSL_PeerCertificate returns a pointer that is owned by the caller, and
- // the NSSCertificate constructor copies its argument, so |raw_peer_cert|
- // must be destroyed in this function.
- CERTCertificate* raw_peer_cert = SSL_PeerCertificate(fd);
- NSSCertificate peer_cert(raw_peer_cert);
- CERT_DestroyCertificate(raw_peer_cert);
-
- NSSStreamAdapter *stream = reinterpret_cast<NSSStreamAdapter *>(arg);
- stream->cert_ok_ = false;
-
- // Read the peer's certificate chain.
- CERTCertList* cert_list = SSL_PeerCertificateChain(fd);
- ASSERT(cert_list != NULL);
-
- // If the peer provided multiple certificates, check that they form a valid
- // chain as defined by RFC 5246 Section 7.4.2: "Each following certificate
- // MUST directly certify the one preceding it.". This check does NOT
- // verify other requirements, such as whether the chain reaches a trusted
- // root, self-signed certificates have valid signatures, certificates are not
- // expired, etc.
- // Even if the chain is valid, the leaf certificate must still match a
- // provided certificate or digest.
- if (!NSSCertificate::IsValidChain(cert_list)) {
- CERT_DestroyCertList(cert_list);
- PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
- return SECFailure;
- }
-
- if (stream->peer_certificate_.get()) {
- LOG(LS_INFO) << "Checking against specified certificate";
-
- // The peer certificate was specified
- if (reinterpret_cast<NSSCertificate *>(stream->peer_certificate_.get())->
- Equals(&peer_cert)) {
- LOG(LS_INFO) << "Accepted peer certificate";
- stream->cert_ok_ = true;
- }
- } else if (!stream->peer_certificate_digest_algorithm_.empty()) {
- LOG(LS_INFO) << "Checking against specified digest";
- // The peer certificate digest was specified
- unsigned char digest[64]; // Maximum size
- size_t digest_length;
-
- if (!peer_cert.ComputeDigest(
- stream->peer_certificate_digest_algorithm_,
- digest, sizeof(digest), &digest_length)) {
- LOG(LS_ERROR) << "Digest computation failed";
- } else {
- Buffer computed_digest(digest, digest_length);
- if (computed_digest == stream->peer_certificate_digest_value_) {
- LOG(LS_INFO) << "Accepted peer certificate";
- stream->cert_ok_ = true;
- }
- }
- } else {
- // Other modes, but we haven't implemented yet
- // TODO(ekr@rtfm.com): Implement real certificate validation
- UNIMPLEMENTED;
- }
-
- if (!stream->cert_ok_ && stream->ignore_bad_cert()) {
- LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
- stream->cert_ok_ = true;
- }
-
- if (stream->cert_ok_)
- stream->peer_certificate_.reset(new NSSCertificate(cert_list));
-
- CERT_DestroyCertList(cert_list);
-
- if (stream->cert_ok_)
- return SECSuccess;
-
- PORT_SetError(SEC_ERROR_UNTRUSTED_CERT);
- return SECFailure;
-}
-
-
-SECStatus NSSStreamAdapter::GetClientAuthDataHook(void *arg, PRFileDesc *fd,
- CERTDistNames *caNames,
- CERTCertificate **pRetCert,
- SECKEYPrivateKey **pRetKey) {
- LOG(LS_INFO) << "Client cert requested";
- NSSStreamAdapter *stream = reinterpret_cast<NSSStreamAdapter *>(arg);
-
- if (!stream->identity_.get()) {
- LOG(LS_ERROR) << "No identity available";
- return SECFailure;
- }
-
- NSSIdentity *identity = static_cast<NSSIdentity *>(stream->identity_.get());
- // Destroyed internally by NSS
- *pRetCert = CERT_DupCertificate(identity->certificate().certificate());
- *pRetKey = SECKEY_CopyPrivateKey(identity->keypair()->privkey());
-
- return SECSuccess;
-}
-
-// RFC 5705 Key Exporter
-bool NSSStreamAdapter::ExportKeyingMaterial(const std::string& label,
- const uint8* context,
- size_t context_len,
- bool use_context,
- uint8* result,
- size_t result_len) {
- SECStatus rv = SSL_ExportKeyingMaterial(
- ssl_fd_,
- label.c_str(),
- checked_cast<unsigned int>(label.size()),
- use_context,
- context,
- checked_cast<unsigned int>(context_len),
- result,
- checked_cast<unsigned int>(result_len));
-
- return rv == SECSuccess;
-}
-
-bool NSSStreamAdapter::SetDtlsSrtpCiphers(
- const std::vector<std::string>& ciphers) {
-#ifdef HAVE_DTLS_SRTP
- std::vector<PRUint16> internal_ciphers;
- if (state_ != SSL_NONE)
- return false;
-
- for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
- cipher != ciphers.end(); ++cipher) {
- bool found = false;
- for (const SrtpCipherMapEntry *entry = kSrtpCipherMap; entry->cipher_id;
- ++entry) {
- if (*cipher == entry->external_name) {
- found = true;
- internal_ciphers.push_back(entry->cipher_id);
- break;
- }
- }
-
- if (!found) {
- LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
- return false;
- }
- }
-
- if (internal_ciphers.empty())
- return false;
-
- srtp_ciphers_ = internal_ciphers;
-
- return true;
-#else
- return false;
-#endif
-}
-
-bool NSSStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
-#ifdef HAVE_DTLS_SRTP
- ASSERT(state_ == SSL_CONNECTED);
- if (state_ != SSL_CONNECTED)
- return false;
-
- PRUint16 selected_cipher;
-
- SECStatus rv = SSL_GetSRTPCipher(ssl_fd_, &selected_cipher);
- if (rv == SECFailure)
- return false;
-
- for (const SrtpCipherMapEntry *entry = kSrtpCipherMap;
- entry->cipher_id; ++entry) {
- if (selected_cipher == entry->cipher_id) {
- *cipher = entry->external_name;
- return true;
- }
- }
-
- ASSERT(false); // This should never happen
-#endif
- return false;
-}
-
-
-bool NSSContext::initialized;
-NSSContext *NSSContext::global_nss_context;
-
-// Static initialization and shutdown
-NSSContext *NSSContext::Instance() {
- if (!global_nss_context) {
- NSSContext *new_ctx = new NSSContext();
-
- if (!(new_ctx->slot_ = PK11_GetInternalSlot())) {
- delete new_ctx;
- goto fail;
- }
-
- global_nss_context = new_ctx;
- }
-
- fail:
- return global_nss_context;
-}
-
-
-
-bool NSSContext::InitializeSSL(VerificationCallback callback) {
- ASSERT(!callback);
-
- if (!initialized) {
- SECStatus rv;
-
- rv = NSS_NoDB_Init(NULL);
- if (rv != SECSuccess) {
- LOG(LS_ERROR) << "Couldn't initialize NSS error=" <<
- PORT_GetError();
- return false;
- }
-
- NSS_SetDomesticPolicy();
-
- initialized = true;
- }
-
- return true;
-}
-
-bool NSSContext::InitializeSSLThread() {
- // Not needed
- return true;
-}
-
-bool NSSContext::CleanupSSL() {
- // Not needed
- return true;
-}
-
-bool NSSStreamAdapter::HaveDtls() {
- return true;
-}
-
-bool NSSStreamAdapter::HaveDtlsSrtp() {
-#ifdef HAVE_DTLS_SRTP
- return true;
-#else
- return false;
-#endif
-}
-
-bool NSSStreamAdapter::HaveExporter() {
- return true;
-}
-
-} // namespace talk_base
-
-#endif // HAVE_NSS_SSL_H
diff --git a/base/nssstreamadapter.h b/base/nssstreamadapter.h
deleted file mode 100644
index 3919c5a..0000000
--- a/base/nssstreamadapter.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- * Copyright 2011, RTFM, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NSSSTREAMADAPTER_H_
-#define TALK_BASE_NSSSTREAMADAPTER_H_
-
-#include <string>
-#include <vector>
-
-#include "nspr.h"
-#include "nss.h"
-#include "secmodt.h"
-
-#include "talk/base/buffer.h"
-#include "talk/base/nssidentity.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/sslstreamadapterhelper.h"
-
-namespace talk_base {
-
-// Singleton
-class NSSContext {
- public:
- NSSContext() {}
- ~NSSContext() {
- }
-
- static PK11SlotInfo *GetSlot() {
- return Instance() ? Instance()->slot_: NULL;
- }
-
- static NSSContext *Instance();
- static bool InitializeSSL(VerificationCallback callback);
- static bool InitializeSSLThread();
- static bool CleanupSSL();
-
- private:
- PK11SlotInfo *slot_; // The PKCS-11 slot
- static bool initialized; // Was this initialized?
- static NSSContext *global_nss_context; // The global context
-};
-
-
-class NSSStreamAdapter : public SSLStreamAdapterHelper {
- public:
- explicit NSSStreamAdapter(StreamInterface* stream);
- virtual ~NSSStreamAdapter();
- bool Init();
-
- virtual StreamResult Read(void* data, size_t data_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- void OnMessage(Message *msg);
-
- // Key Extractor interface
- virtual bool ExportKeyingMaterial(const std::string& label,
- const uint8* context,
- size_t context_len,
- bool use_context,
- uint8* result,
- size_t result_len);
-
- // DTLS-SRTP interface
- virtual bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers);
- virtual bool GetDtlsSrtpCipher(std::string* cipher);
-
- // Capabilities interfaces
- static bool HaveDtls();
- static bool HaveDtlsSrtp();
- static bool HaveExporter();
-
- protected:
- // Override SSLStreamAdapter
- virtual void OnEvent(StreamInterface* stream, int events, int err);
-
- // Override SSLStreamAdapterHelper
- virtual int BeginSSL();
- virtual void Cleanup();
- virtual bool GetDigestLength(const std::string& algorithm, size_t* length) {
- return NSSCertificate::GetDigestLength(algorithm, length);
- }
-
- private:
- int ContinueSSL();
- static SECStatus AuthCertificateHook(void *arg, PRFileDesc *fd,
- PRBool checksig, PRBool isServer);
- static SECStatus GetClientAuthDataHook(void *arg, PRFileDesc *fd,
- CERTDistNames *caNames,
- CERTCertificate **pRetCert,
- SECKEYPrivateKey **pRetKey);
-
- PRFileDesc *ssl_fd_; // NSS's SSL file descriptor
- static bool initialized; // Was InitializeSSL() called?
- bool cert_ok_; // Did we get and check a cert
- std::vector<PRUint16> srtp_ciphers_; // SRTP cipher list
-
- static PRDescIdentity nspr_layer_identity; // The NSPR layer identity
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_NSSSTREAMADAPTER_H_
diff --git a/base/nullsocketserver.h b/base/nullsocketserver.h
deleted file mode 100644
index 6b3b288..0000000
--- a/base/nullsocketserver.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_NULLSOCKETSERVER_H_
-#define TALK_BASE_NULLSOCKETSERVER_H_
-
-#include "talk/base/event.h"
-#include "talk/base/physicalsocketserver.h"
-
-namespace talk_base {
-
-// NullSocketServer
-
-class NullSocketServer : public talk_base::SocketServer {
- public:
- NullSocketServer() : event_(false, false) {}
-
- virtual bool Wait(int cms, bool process_io) {
- event_.Wait(cms);
- return true;
- }
-
- virtual void WakeUp() {
- event_.Set();
- }
-
- virtual talk_base::Socket* CreateSocket(int type) {
- ASSERT(false);
- return NULL;
- }
-
- virtual talk_base::Socket* CreateSocket(int family, int type) {
- ASSERT(false);
- return NULL;
- }
-
- virtual talk_base::AsyncSocket* CreateAsyncSocket(int type) {
- ASSERT(false);
- return NULL;
- }
-
- virtual talk_base::AsyncSocket* CreateAsyncSocket(int family, int type) {
- ASSERT(false);
- return NULL;
- }
-
-
- private:
- talk_base::Event event_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_NULLSOCKETSERVER_H_
diff --git a/base/nullsocketserver_unittest.cc b/base/nullsocketserver_unittest.cc
deleted file mode 100644
index 18cde2d..0000000
--- a/base/nullsocketserver_unittest.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/nullsocketserver.h"
-
-namespace talk_base {
-
-static const uint32 kTimeout = 5000U;
-
-class NullSocketServerTest
- : public testing::Test,
- public MessageHandler {
- public:
- NullSocketServerTest() {}
- protected:
- virtual void OnMessage(Message* message) {
- ss_.WakeUp();
- }
- NullSocketServer ss_;
-};
-
-TEST_F(NullSocketServerTest, WaitAndSet) {
- Thread thread;
- EXPECT_TRUE(thread.Start());
- thread.Post(this, 0);
- // The process_io will be ignored.
- const bool process_io = true;
- EXPECT_TRUE_WAIT(ss_.Wait(talk_base::kForever, process_io), kTimeout);
-}
-
-TEST_F(NullSocketServerTest, TestWait) {
- uint32 start = Time();
- ss_.Wait(200, true);
- // The actual wait time is dependent on the resolution of the timer used by
- // the Event class. Allow for the event to signal ~20ms early.
- EXPECT_GE(TimeSince(start), 180);
-}
-
-} // namespace talk_base
diff --git a/base/openssl.h b/base/openssl.h
deleted file mode 100644
index d9628a7..0000000
--- a/base/openssl.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * libjingle
- * Copyright 2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_OPENSSL_H_
-#define TALK_BASE_OPENSSL_H_
-
-#include <openssl/ssl.h>
-
-#if (OPENSSL_VERSION_NUMBER < 0x10000000L)
-#error OpenSSL is older than 1.0.0, which is the minimum supported version.
-#endif
-
-#endif // TALK_BASE_OPENSSL_H_
diff --git a/base/openssladapter.cc b/base/openssladapter.cc
deleted file mode 100644
index 9e6fe72..0000000
--- a/base/openssladapter.cc
+++ /dev/null
@@ -1,901 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if HAVE_OPENSSL_SSL_H
-
-#include "talk/base/openssladapter.h"
-
-#if defined(POSIX)
-#include <unistd.h>
-#endif
-
-// Must be included first before openssl headers.
-#include "talk/base/win32.h" // NOLINT
-
-#include <openssl/bio.h>
-#include <openssl/crypto.h>
-#include <openssl/err.h>
-#include <openssl/opensslv.h>
-#include <openssl/rand.h>
-#include <openssl/x509v3.h>
-
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/openssl.h"
-#include "talk/base/sslroots.h"
-#include "talk/base/stringutils.h"
-
-// TODO: Use a nicer abstraction for mutex.
-
-#if defined(WIN32)
- #define MUTEX_TYPE HANDLE
- #define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL)
- #define MUTEX_CLEANUP(x) CloseHandle(x)
- #define MUTEX_LOCK(x) WaitForSingleObject((x), INFINITE)
- #define MUTEX_UNLOCK(x) ReleaseMutex(x)
- #define THREAD_ID GetCurrentThreadId()
-#elif defined(POSIX)
- #define MUTEX_TYPE pthread_mutex_t
- #define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
- #define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
- #define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
- #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
- #define THREAD_ID pthread_self()
-#else
- #error You must define mutex operations appropriate for your platform!
-#endif
-
-struct CRYPTO_dynlock_value {
- MUTEX_TYPE mutex;
-};
-
-//////////////////////////////////////////////////////////////////////
-// SocketBIO
-//////////////////////////////////////////////////////////////////////
-
-static int socket_write(BIO* h, const char* buf, int num);
-static int socket_read(BIO* h, char* buf, int size);
-static int socket_puts(BIO* h, const char* str);
-static long socket_ctrl(BIO* h, int cmd, long arg1, void* arg2);
-static int socket_new(BIO* h);
-static int socket_free(BIO* data);
-
-static BIO_METHOD methods_socket = {
- BIO_TYPE_BIO,
- "socket",
- socket_write,
- socket_read,
- socket_puts,
- 0,
- socket_ctrl,
- socket_new,
- socket_free,
- NULL,
-};
-
-BIO_METHOD* BIO_s_socket2() { return(&methods_socket); }
-
-BIO* BIO_new_socket(talk_base::AsyncSocket* socket) {
- BIO* ret = BIO_new(BIO_s_socket2());
- if (ret == NULL) {
- return NULL;
- }
- ret->ptr = socket;
- return ret;
-}
-
-static int socket_new(BIO* b) {
- b->shutdown = 0;
- b->init = 1;
- b->num = 0; // 1 means socket closed
- b->ptr = 0;
- return 1;
-}
-
-static int socket_free(BIO* b) {
- if (b == NULL)
- return 0;
- return 1;
-}
-
-static int socket_read(BIO* b, char* out, int outl) {
- if (!out)
- return -1;
- talk_base::AsyncSocket* socket = static_cast<talk_base::AsyncSocket*>(b->ptr);
- BIO_clear_retry_flags(b);
- int result = socket->Recv(out, outl);
- if (result > 0) {
- return result;
- } else if (result == 0) {
- b->num = 1;
- } else if (socket->IsBlocking()) {
- BIO_set_retry_read(b);
- }
- return -1;
-}
-
-static int socket_write(BIO* b, const char* in, int inl) {
- if (!in)
- return -1;
- talk_base::AsyncSocket* socket = static_cast<talk_base::AsyncSocket*>(b->ptr);
- BIO_clear_retry_flags(b);
- int result = socket->Send(in, inl);
- if (result > 0) {
- return result;
- } else if (socket->IsBlocking()) {
- BIO_set_retry_write(b);
- }
- return -1;
-}
-
-static int socket_puts(BIO* b, const char* str) {
- return socket_write(b, str, strlen(str));
-}
-
-static long socket_ctrl(BIO* b, int cmd, long num, void* ptr) {
- UNUSED(num);
- UNUSED(ptr);
-
- switch (cmd) {
- case BIO_CTRL_RESET:
- return 0;
- case BIO_CTRL_EOF:
- return b->num;
- case BIO_CTRL_WPENDING:
- case BIO_CTRL_PENDING:
- return 0;
- case BIO_CTRL_FLUSH:
- return 1;
- default:
- return 0;
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// OpenSSLAdapter
-/////////////////////////////////////////////////////////////////////////////
-
-namespace talk_base {
-
-// This array will store all of the mutexes available to OpenSSL.
-static MUTEX_TYPE* mutex_buf = NULL;
-
-static void locking_function(int mode, int n, const char * file, int line) {
- if (mode & CRYPTO_LOCK) {
- MUTEX_LOCK(mutex_buf[n]);
- } else {
- MUTEX_UNLOCK(mutex_buf[n]);
- }
-}
-
-static unsigned long id_function() { // NOLINT
- // Use old-style C cast because THREAD_ID's type varies with the platform,
- // in some cases requiring static_cast, and in others requiring
- // reinterpret_cast.
- return (unsigned long)THREAD_ID; // NOLINT
-}
-
-static CRYPTO_dynlock_value* dyn_create_function(const char* file, int line) {
- CRYPTO_dynlock_value* value = new CRYPTO_dynlock_value;
- if (!value)
- return NULL;
- MUTEX_SETUP(value->mutex);
- return value;
-}
-
-static void dyn_lock_function(int mode, CRYPTO_dynlock_value* l,
- const char* file, int line) {
- if (mode & CRYPTO_LOCK) {
- MUTEX_LOCK(l->mutex);
- } else {
- MUTEX_UNLOCK(l->mutex);
- }
-}
-
-static void dyn_destroy_function(CRYPTO_dynlock_value* l,
- const char* file, int line) {
- MUTEX_CLEANUP(l->mutex);
- delete l;
-}
-
-VerificationCallback OpenSSLAdapter::custom_verify_callback_ = NULL;
-
-bool OpenSSLAdapter::InitializeSSL(VerificationCallback callback) {
- if (!InitializeSSLThread() || !SSL_library_init())
- return false;
-#if !defined(ADDRESS_SANITIZER) || !defined(OSX)
- // Loading the error strings crashes mac_asan. Omit this debugging aid there.
- SSL_load_error_strings();
-#endif
- ERR_load_BIO_strings();
- OpenSSL_add_all_algorithms();
- RAND_poll();
- custom_verify_callback_ = callback;
- return true;
-}
-
-bool OpenSSLAdapter::InitializeSSLThread() {
- mutex_buf = new MUTEX_TYPE[CRYPTO_num_locks()];
- if (!mutex_buf)
- return false;
- for (int i = 0; i < CRYPTO_num_locks(); ++i)
- MUTEX_SETUP(mutex_buf[i]);
-
- // we need to cast our id_function to return an unsigned long -- pthread_t is
- // a pointer
- CRYPTO_set_id_callback(id_function);
- CRYPTO_set_locking_callback(locking_function);
- CRYPTO_set_dynlock_create_callback(dyn_create_function);
- CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
- CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
- return true;
-}
-
-bool OpenSSLAdapter::CleanupSSL() {
- if (!mutex_buf)
- return false;
- CRYPTO_set_id_callback(NULL);
- CRYPTO_set_locking_callback(NULL);
- CRYPTO_set_dynlock_create_callback(NULL);
- CRYPTO_set_dynlock_lock_callback(NULL);
- CRYPTO_set_dynlock_destroy_callback(NULL);
- for (int i = 0; i < CRYPTO_num_locks(); ++i)
- MUTEX_CLEANUP(mutex_buf[i]);
- delete [] mutex_buf;
- mutex_buf = NULL;
- return true;
-}
-
-OpenSSLAdapter::OpenSSLAdapter(AsyncSocket* socket)
- : SSLAdapter(socket),
- state_(SSL_NONE),
- ssl_read_needs_write_(false),
- ssl_write_needs_read_(false),
- restartable_(false),
- ssl_(NULL), ssl_ctx_(NULL),
- custom_verification_succeeded_(false) {
-}
-
-OpenSSLAdapter::~OpenSSLAdapter() {
- Cleanup();
-}
-
-int
-OpenSSLAdapter::StartSSL(const char* hostname, bool restartable) {
- if (state_ != SSL_NONE)
- return -1;
-
- ssl_host_name_ = hostname;
- restartable_ = restartable;
-
- if (socket_->GetState() != Socket::CS_CONNECTED) {
- state_ = SSL_WAIT;
- return 0;
- }
-
- state_ = SSL_CONNECTING;
- if (int err = BeginSSL()) {
- Error("BeginSSL", err, false);
- return err;
- }
-
- return 0;
-}
-
-int
-OpenSSLAdapter::BeginSSL() {
- LOG(LS_INFO) << "BeginSSL: " << ssl_host_name_;
- ASSERT(state_ == SSL_CONNECTING);
-
- int err = 0;
- BIO* bio = NULL;
-
- // First set up the context
- if (!ssl_ctx_)
- ssl_ctx_ = SetupSSLContext();
-
- if (!ssl_ctx_) {
- err = -1;
- goto ssl_error;
- }
-
- bio = BIO_new_socket(static_cast<AsyncSocketAdapter*>(socket_));
- if (!bio) {
- err = -1;
- goto ssl_error;
- }
-
- ssl_ = SSL_new(ssl_ctx_);
- if (!ssl_) {
- err = -1;
- goto ssl_error;
- }
-
- SSL_set_app_data(ssl_, this);
-
- SSL_set_bio(ssl_, bio, bio);
- SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
- SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
-
- // the SSL object owns the bio now
- bio = NULL;
-
- // Do the connect
- err = ContinueSSL();
- if (err != 0)
- goto ssl_error;
-
- return err;
-
-ssl_error:
- Cleanup();
- if (bio)
- BIO_free(bio);
-
- return err;
-}
-
-int
-OpenSSLAdapter::ContinueSSL() {
- ASSERT(state_ == SSL_CONNECTING);
-
- int code = SSL_connect(ssl_);
- switch (SSL_get_error(ssl_, code)) {
- case SSL_ERROR_NONE:
- if (!SSLPostConnectionCheck(ssl_, ssl_host_name_.c_str())) {
- LOG(LS_ERROR) << "TLS post connection check failed";
- // make sure we close the socket
- Cleanup();
- // The connect failed so return -1 to shut down the socket
- return -1;
- }
-
- state_ = SSL_CONNECTED;
- AsyncSocketAdapter::OnConnectEvent(this);
-#if 0 // TODO: worry about this
- // Don't let ourselves go away during the callbacks
- PRefPtr<OpenSSLAdapter> lock(this);
- LOG(LS_INFO) << " -- onStreamReadable";
- AsyncSocketAdapter::OnReadEvent(this);
- LOG(LS_INFO) << " -- onStreamWriteable";
- AsyncSocketAdapter::OnWriteEvent(this);
-#endif
- break;
-
- case SSL_ERROR_WANT_READ:
- case SSL_ERROR_WANT_WRITE:
- break;
-
- case SSL_ERROR_ZERO_RETURN:
- default:
- LOG(LS_WARNING) << "ContinueSSL -- error " << code;
- return (code != 0) ? code : -1;
- }
-
- return 0;
-}
-
-void
-OpenSSLAdapter::Error(const char* context, int err, bool signal) {
- LOG(LS_WARNING) << "OpenSSLAdapter::Error("
- << context << ", " << err << ")";
- state_ = SSL_ERROR;
- SetError(err);
- if (signal)
- AsyncSocketAdapter::OnCloseEvent(this, err);
-}
-
-void
-OpenSSLAdapter::Cleanup() {
- LOG(LS_INFO) << "Cleanup";
-
- state_ = SSL_NONE;
- ssl_read_needs_write_ = false;
- ssl_write_needs_read_ = false;
- custom_verification_succeeded_ = false;
-
- if (ssl_) {
- SSL_free(ssl_);
- ssl_ = NULL;
- }
-
- if (ssl_ctx_) {
- SSL_CTX_free(ssl_ctx_);
- ssl_ctx_ = NULL;
- }
-}
-
-//
-// AsyncSocket Implementation
-//
-
-int
-OpenSSLAdapter::Send(const void* pv, size_t cb) {
- //LOG(LS_INFO) << "OpenSSLAdapter::Send(" << cb << ")";
-
- switch (state_) {
- case SSL_NONE:
- return AsyncSocketAdapter::Send(pv, cb);
-
- case SSL_WAIT:
- case SSL_CONNECTING:
- SetError(EWOULDBLOCK);
- return SOCKET_ERROR;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_ERROR:
- default:
- return SOCKET_ERROR;
- }
-
- // OpenSSL will return an error if we try to write zero bytes
- if (cb == 0)
- return 0;
-
- ssl_write_needs_read_ = false;
-
- int code = SSL_write(ssl_, pv, cb);
- switch (SSL_get_error(ssl_, code)) {
- case SSL_ERROR_NONE:
- //LOG(LS_INFO) << " -- success";
- return code;
- case SSL_ERROR_WANT_READ:
- //LOG(LS_INFO) << " -- error want read";
- ssl_write_needs_read_ = true;
- SetError(EWOULDBLOCK);
- break;
- case SSL_ERROR_WANT_WRITE:
- //LOG(LS_INFO) << " -- error want write";
- SetError(EWOULDBLOCK);
- break;
- case SSL_ERROR_ZERO_RETURN:
- //LOG(LS_INFO) << " -- remote side closed";
- SetError(EWOULDBLOCK);
- // do we need to signal closure?
- break;
- default:
- //LOG(LS_INFO) << " -- error " << code;
- Error("SSL_write", (code ? code : -1), false);
- break;
- }
-
- return SOCKET_ERROR;
-}
-
-int
-OpenSSLAdapter::Recv(void* pv, size_t cb) {
- //LOG(LS_INFO) << "OpenSSLAdapter::Recv(" << cb << ")";
- switch (state_) {
-
- case SSL_NONE:
- return AsyncSocketAdapter::Recv(pv, cb);
-
- case SSL_WAIT:
- case SSL_CONNECTING:
- SetError(EWOULDBLOCK);
- return SOCKET_ERROR;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_ERROR:
- default:
- return SOCKET_ERROR;
- }
-
- // Don't trust OpenSSL with zero byte reads
- if (cb == 0)
- return 0;
-
- ssl_read_needs_write_ = false;
-
- int code = SSL_read(ssl_, pv, cb);
- switch (SSL_get_error(ssl_, code)) {
- case SSL_ERROR_NONE:
- //LOG(LS_INFO) << " -- success";
- return code;
- case SSL_ERROR_WANT_READ:
- //LOG(LS_INFO) << " -- error want read";
- SetError(EWOULDBLOCK);
- break;
- case SSL_ERROR_WANT_WRITE:
- //LOG(LS_INFO) << " -- error want write";
- ssl_read_needs_write_ = true;
- SetError(EWOULDBLOCK);
- break;
- case SSL_ERROR_ZERO_RETURN:
- //LOG(LS_INFO) << " -- remote side closed";
- SetError(EWOULDBLOCK);
- // do we need to signal closure?
- break;
- default:
- //LOG(LS_INFO) << " -- error " << code;
- Error("SSL_read", (code ? code : -1), false);
- break;
- }
-
- return SOCKET_ERROR;
-}
-
-int
-OpenSSLAdapter::Close() {
- Cleanup();
- state_ = restartable_ ? SSL_WAIT : SSL_NONE;
- return AsyncSocketAdapter::Close();
-}
-
-Socket::ConnState
-OpenSSLAdapter::GetState() const {
- //if (signal_close_)
- // return CS_CONNECTED;
- ConnState state = socket_->GetState();
- if ((state == CS_CONNECTED)
- && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
- state = CS_CONNECTING;
- return state;
-}
-
-void
-OpenSSLAdapter::OnConnectEvent(AsyncSocket* socket) {
- LOG(LS_INFO) << "OpenSSLAdapter::OnConnectEvent";
- if (state_ != SSL_WAIT) {
- ASSERT(state_ == SSL_NONE);
- AsyncSocketAdapter::OnConnectEvent(socket);
- return;
- }
-
- state_ = SSL_CONNECTING;
- if (int err = BeginSSL()) {
- AsyncSocketAdapter::OnCloseEvent(socket, err);
- }
-}
-
-void
-OpenSSLAdapter::OnReadEvent(AsyncSocket* socket) {
- //LOG(LS_INFO) << "OpenSSLAdapter::OnReadEvent";
-
- if (state_ == SSL_NONE) {
- AsyncSocketAdapter::OnReadEvent(socket);
- return;
- }
-
- if (state_ == SSL_CONNECTING) {
- if (int err = ContinueSSL()) {
- Error("ContinueSSL", err);
- }
- return;
- }
-
- if (state_ != SSL_CONNECTED)
- return;
-
- // Don't let ourselves go away during the callbacks
- //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
- if (ssl_write_needs_read_) {
- //LOG(LS_INFO) << " -- onStreamWriteable";
- AsyncSocketAdapter::OnWriteEvent(socket);
- }
-
- //LOG(LS_INFO) << " -- onStreamReadable";
- AsyncSocketAdapter::OnReadEvent(socket);
-}
-
-void
-OpenSSLAdapter::OnWriteEvent(AsyncSocket* socket) {
- //LOG(LS_INFO) << "OpenSSLAdapter::OnWriteEvent";
-
- if (state_ == SSL_NONE) {
- AsyncSocketAdapter::OnWriteEvent(socket);
- return;
- }
-
- if (state_ == SSL_CONNECTING) {
- if (int err = ContinueSSL()) {
- Error("ContinueSSL", err);
- }
- return;
- }
-
- if (state_ != SSL_CONNECTED)
- return;
-
- // Don't let ourselves go away during the callbacks
- //PRefPtr<OpenSSLAdapter> lock(this); // TODO: fix this
-
- if (ssl_read_needs_write_) {
- //LOG(LS_INFO) << " -- onStreamReadable";
- AsyncSocketAdapter::OnReadEvent(socket);
- }
-
- //LOG(LS_INFO) << " -- onStreamWriteable";
- AsyncSocketAdapter::OnWriteEvent(socket);
-}
-
-void
-OpenSSLAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
- LOG(LS_INFO) << "OpenSSLAdapter::OnCloseEvent(" << err << ")";
- AsyncSocketAdapter::OnCloseEvent(socket, err);
-}
-
-// This code is taken from the "Network Security with OpenSSL"
-// sample in chapter 5
-
-bool OpenSSLAdapter::VerifyServerName(SSL* ssl, const char* host,
- bool ignore_bad_cert) {
- if (!host)
- return false;
-
- // Checking the return from SSL_get_peer_certificate here is not strictly
- // necessary. With our setup, it is not possible for it to return
- // NULL. However, it is good form to check the return.
- X509* certificate = SSL_get_peer_certificate(ssl);
- if (!certificate)
- return false;
-
- // Logging certificates is extremely verbose. So it is disabled by default.
-#ifdef LOG_CERTIFICATES
- {
- LOG(LS_INFO) << "Certificate from server:";
- BIO* mem = BIO_new(BIO_s_mem());
- X509_print_ex(mem, certificate, XN_FLAG_SEP_CPLUS_SPC, X509_FLAG_NO_HEADER);
- BIO_write(mem, "\0", 1);
- char* buffer;
- BIO_get_mem_data(mem, &buffer);
- LOG(LS_INFO) << buffer;
- BIO_free(mem);
-
- char* cipher_description =
- SSL_CIPHER_description(SSL_get_current_cipher(ssl), NULL, 128);
- LOG(LS_INFO) << "Cipher: " << cipher_description;
- OPENSSL_free(cipher_description);
- }
-#endif
-
- bool ok = false;
- int extension_count = X509_get_ext_count(certificate);
- for (int i = 0; i < extension_count; ++i) {
- X509_EXTENSION* extension = X509_get_ext(certificate, i);
- int extension_nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension));
-
- if (extension_nid == NID_subject_alt_name) {
- const X509V3_EXT_METHOD* meth = X509V3_EXT_get(extension);
- if (!meth)
- break;
-
- void* ext_str = NULL;
-
- // We assign this to a local variable, instead of passing the address
- // directly to ASN1_item_d2i.
- // See http://readlist.com/lists/openssl.org/openssl-users/0/4761.html.
- unsigned char* ext_value_data = extension->value->data;
-
- const unsigned char **ext_value_data_ptr =
- (const_cast<const unsigned char **>(&ext_value_data));
-
- if (meth->it) {
- ext_str = ASN1_item_d2i(NULL, ext_value_data_ptr,
- extension->value->length,
- ASN1_ITEM_ptr(meth->it));
- } else {
- ext_str = meth->d2i(NULL, ext_value_data_ptr, extension->value->length);
- }
-
- STACK_OF(CONF_VALUE)* value = meth->i2v(meth, ext_str, NULL);
- for (int j = 0; j < sk_CONF_VALUE_num(value); ++j) {
- CONF_VALUE* nval = sk_CONF_VALUE_value(value, j);
- // The value for nval can contain wildcards
- if (!strcmp(nval->name, "DNS") && string_match(host, nval->value)) {
- ok = true;
- break;
- }
- }
- sk_CONF_VALUE_pop_free(value, X509V3_conf_free);
- value = NULL;
-
- if (meth->it) {
- ASN1_item_free(reinterpret_cast<ASN1_VALUE*>(ext_str),
- ASN1_ITEM_ptr(meth->it));
- } else {
- meth->ext_free(ext_str);
- }
- ext_str = NULL;
- }
- if (ok)
- break;
- }
-
- char data[256];
- X509_name_st* subject;
- if (!ok
- && ((subject = X509_get_subject_name(certificate)) != NULL)
- && (X509_NAME_get_text_by_NID(subject, NID_commonName,
- data, sizeof(data)) > 0)) {
- data[sizeof(data)-1] = 0;
- if (_stricmp(data, host) == 0)
- ok = true;
- }
-
- X509_free(certificate);
-
- // This should only ever be turned on for debugging and development.
- if (!ok && ignore_bad_cert) {
- LOG(LS_WARNING) << "TLS certificate check FAILED. "
- << "Allowing connection anyway.";
- ok = true;
- }
-
- return ok;
-}
-
-bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const char* host) {
- bool ok = VerifyServerName(ssl, host, ignore_bad_cert());
-
- if (ok) {
- ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
- custom_verification_succeeded_);
- }
-
- if (!ok && ignore_bad_cert()) {
- LOG(LS_INFO) << "Other TLS post connection checks failed.";
- ok = true;
- }
-
- return ok;
-}
-
-#if _DEBUG
-
-// We only use this for tracing and so it is only needed in debug mode
-
-void
-OpenSSLAdapter::SSLInfoCallback(const SSL* s, int where, int ret) {
- const char* str = "undefined";
- int w = where & ~SSL_ST_MASK;
- if (w & SSL_ST_CONNECT) {
- str = "SSL_connect";
- } else if (w & SSL_ST_ACCEPT) {
- str = "SSL_accept";
- }
- if (where & SSL_CB_LOOP) {
- LOG(LS_INFO) << str << ":" << SSL_state_string_long(s);
- } else if (where & SSL_CB_ALERT) {
- str = (where & SSL_CB_READ) ? "read" : "write";
- LOG(LS_INFO) << "SSL3 alert " << str
- << ":" << SSL_alert_type_string_long(ret)
- << ":" << SSL_alert_desc_string_long(ret);
- } else if (where & SSL_CB_EXIT) {
- if (ret == 0) {
- LOG(LS_INFO) << str << ":failed in " << SSL_state_string_long(s);
- } else if (ret < 0) {
- LOG(LS_INFO) << str << ":error in " << SSL_state_string_long(s);
- }
- }
-}
-
-#endif // _DEBUG
-
-int
-OpenSSLAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
-#if _DEBUG
- if (!ok) {
- char data[256];
- X509* cert = X509_STORE_CTX_get_current_cert(store);
- int depth = X509_STORE_CTX_get_error_depth(store);
- int err = X509_STORE_CTX_get_error(store);
-
- LOG(LS_INFO) << "Error with certificate at depth: " << depth;
- X509_NAME_oneline(X509_get_issuer_name(cert), data, sizeof(data));
- LOG(LS_INFO) << " issuer = " << data;
- X509_NAME_oneline(X509_get_subject_name(cert), data, sizeof(data));
- LOG(LS_INFO) << " subject = " << data;
- LOG(LS_INFO) << " err = " << err
- << ":" << X509_verify_cert_error_string(err);
- }
-#endif
-
- // Get our stream pointer from the store
- SSL* ssl = reinterpret_cast<SSL*>(
- X509_STORE_CTX_get_ex_data(store,
- SSL_get_ex_data_X509_STORE_CTX_idx()));
-
- OpenSSLAdapter* stream =
- reinterpret_cast<OpenSSLAdapter*>(SSL_get_app_data(ssl));
-
- if (!ok && custom_verify_callback_) {
- void* cert =
- reinterpret_cast<void*>(X509_STORE_CTX_get_current_cert(store));
- if (custom_verify_callback_(cert)) {
- stream->custom_verification_succeeded_ = true;
- LOG(LS_INFO) << "validated certificate using custom callback";
- ok = true;
- }
- }
-
- // Should only be used for debugging and development.
- if (!ok && stream->ignore_bad_cert()) {
- LOG(LS_WARNING) << "Ignoring cert error while verifying cert chain";
- ok = 1;
- }
-
- return ok;
-}
-
-bool OpenSSLAdapter::ConfigureTrustedRootCertificates(SSL_CTX* ctx) {
- // Add the root cert that we care about to the SSL context
- int count_of_added_certs = 0;
- for (int i = 0; i < ARRAY_SIZE(kSSLCertCertificateList); i++) {
- const unsigned char* cert_buffer = kSSLCertCertificateList[i];
- size_t cert_buffer_len = kSSLCertCertificateSizeList[i];
- X509* cert = d2i_X509(NULL, &cert_buffer, cert_buffer_len);
- if (cert) {
- int return_value = X509_STORE_add_cert(SSL_CTX_get_cert_store(ctx), cert);
- if (return_value == 0) {
- LOG(LS_WARNING) << "Unable to add certificate.";
- } else {
- count_of_added_certs++;
- }
- X509_free(cert);
- }
- }
- return count_of_added_certs > 0;
-}
-
-SSL_CTX*
-OpenSSLAdapter::SetupSSLContext() {
- SSL_CTX* ctx = SSL_CTX_new(TLSv1_client_method());
- if (ctx == NULL) {
- unsigned long error = ERR_get_error(); // NOLINT: type used by OpenSSL.
- LOG(LS_WARNING) << "SSL_CTX creation failed: "
- << '"' << ERR_reason_error_string(error) << "\" "
- << "(error=" << error << ')';
- return NULL;
- }
- if (!ConfigureTrustedRootCertificates(ctx)) {
- SSL_CTX_free(ctx);
- return NULL;
- }
-
-#ifdef _DEBUG
- SSL_CTX_set_info_callback(ctx, SSLInfoCallback);
-#endif
-
- SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, SSLVerifyCallback);
- SSL_CTX_set_verify_depth(ctx, 4);
- SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
-
- return ctx;
-}
-
-} // namespace talk_base
-
-#endif // HAVE_OPENSSL_SSL_H
diff --git a/base/openssladapter.h b/base/openssladapter.h
deleted file mode 100644
index c89c292..0000000
--- a/base/openssladapter.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_OPENSSLADAPTER_H__
-#define TALK_BASE_OPENSSLADAPTER_H__
-
-#include <string>
-#include "talk/base/ssladapter.h"
-
-typedef struct ssl_st SSL;
-typedef struct ssl_ctx_st SSL_CTX;
-typedef struct x509_store_ctx_st X509_STORE_CTX;
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-class OpenSSLAdapter : public SSLAdapter {
-public:
- static bool InitializeSSL(VerificationCallback callback);
- static bool InitializeSSLThread();
- static bool CleanupSSL();
-
- OpenSSLAdapter(AsyncSocket* socket);
- virtual ~OpenSSLAdapter();
-
- virtual int StartSSL(const char* hostname, bool restartable);
- virtual int Send(const void* pv, size_t cb);
- virtual int Recv(void* pv, size_t cb);
- virtual int Close();
-
- // Note that the socket returns ST_CONNECTING while SSL is being negotiated.
- virtual ConnState GetState() const;
-
-protected:
- virtual void OnConnectEvent(AsyncSocket* socket);
- virtual void OnReadEvent(AsyncSocket* socket);
- virtual void OnWriteEvent(AsyncSocket* socket);
- virtual void OnCloseEvent(AsyncSocket* socket, int err);
-
-private:
- enum SSLState {
- SSL_NONE, SSL_WAIT, SSL_CONNECTING, SSL_CONNECTED, SSL_ERROR
- };
-
- int BeginSSL();
- int ContinueSSL();
- void Error(const char* context, int err, bool signal = true);
- void Cleanup();
-
- static bool VerifyServerName(SSL* ssl, const char* host,
- bool ignore_bad_cert);
- bool SSLPostConnectionCheck(SSL* ssl, const char* host);
-#if _DEBUG
- static void SSLInfoCallback(const SSL* s, int where, int ret);
-#endif // !_DEBUG
- static int SSLVerifyCallback(int ok, X509_STORE_CTX* store);
- static VerificationCallback custom_verify_callback_;
- friend class OpenSSLStreamAdapter; // for custom_verify_callback_;
-
- static bool ConfigureTrustedRootCertificates(SSL_CTX* ctx);
- static SSL_CTX* SetupSSLContext();
-
- SSLState state_;
- bool ssl_read_needs_write_;
- bool ssl_write_needs_read_;
- // If true, socket will retain SSL configuration after Close.
- bool restartable_;
-
- SSL* ssl_;
- SSL_CTX* ssl_ctx_;
- std::string ssl_host_name_;
-
- bool custom_verification_succeeded_;
-};
-
-/////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_OPENSSLADAPTER_H__
diff --git a/base/openssldigest.cc b/base/openssldigest.cc
deleted file mode 100644
index 3d0d227..0000000
--- a/base/openssldigest.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if HAVE_OPENSSL_SSL_H
-
-#include "talk/base/openssldigest.h"
-
-#include "talk/base/common.h"
-#include "talk/base/openssl.h"
-
-namespace talk_base {
-
-OpenSSLDigest::OpenSSLDigest(const std::string& algorithm) {
- EVP_MD_CTX_init(&ctx_);
- if (GetDigestEVP(algorithm, &md_)) {
- EVP_DigestInit_ex(&ctx_, md_, NULL);
- } else {
- md_ = NULL;
- }
-}
-
-OpenSSLDigest::~OpenSSLDigest() {
- EVP_MD_CTX_cleanup(&ctx_);
-}
-
-size_t OpenSSLDigest::Size() const {
- if (!md_) {
- return 0;
- }
- return EVP_MD_size(md_);
-}
-
-void OpenSSLDigest::Update(const void* buf, size_t len) {
- if (!md_) {
- return;
- }
- EVP_DigestUpdate(&ctx_, buf, len);
-}
-
-size_t OpenSSLDigest::Finish(void* buf, size_t len) {
- if (!md_ || len < Size()) {
- return 0;
- }
- unsigned int md_len;
- EVP_DigestFinal_ex(&ctx_, static_cast<unsigned char*>(buf), &md_len);
- EVP_DigestInit_ex(&ctx_, md_, NULL); // prepare for future Update()s
- ASSERT(md_len == Size());
- return md_len;
-}
-
-bool OpenSSLDigest::GetDigestEVP(const std::string& algorithm,
- const EVP_MD** mdp) {
- const EVP_MD* md;
- if (algorithm == DIGEST_MD5) {
- md = EVP_md5();
- } else if (algorithm == DIGEST_SHA_1) {
- md = EVP_sha1();
- } else if (algorithm == DIGEST_SHA_224) {
- md = EVP_sha224();
- } else if (algorithm == DIGEST_SHA_256) {
- md = EVP_sha256();
- } else if (algorithm == DIGEST_SHA_384) {
- md = EVP_sha384();
- } else if (algorithm == DIGEST_SHA_512) {
- md = EVP_sha512();
- } else {
- return false;
- }
-
- // Can't happen
- ASSERT(EVP_MD_size(md) >= 16);
- *mdp = md;
- return true;
-}
-
-bool OpenSSLDigest::GetDigestName(const EVP_MD* md,
- std::string* algorithm) {
- ASSERT(md != NULL);
- ASSERT(algorithm != NULL);
-
- int md_type = EVP_MD_type(md);
- if (md_type == NID_md5) {
- *algorithm = DIGEST_MD5;
- } else if (md_type == NID_sha1) {
- *algorithm = DIGEST_SHA_1;
- } else if (md_type == NID_sha224) {
- *algorithm = DIGEST_SHA_224;
- } else if (md_type == NID_sha256) {
- *algorithm = DIGEST_SHA_256;
- } else if (md_type == NID_sha384) {
- *algorithm = DIGEST_SHA_384;
- } else if (md_type == NID_sha512) {
- *algorithm = DIGEST_SHA_512;
- } else {
- algorithm->clear();
- return false;
- }
-
- return true;
-}
-
-bool OpenSSLDigest::GetDigestSize(const std::string& algorithm,
- size_t* length) {
- const EVP_MD *md;
- if (!GetDigestEVP(algorithm, &md))
- return false;
-
- *length = EVP_MD_size(md);
- return true;
-}
-
-} // namespace talk_base
-
-#endif // HAVE_OPENSSL_SSL_H
-
diff --git a/base/openssldigest.h b/base/openssldigest.h
deleted file mode 100644
index d5cf878..0000000
--- a/base/openssldigest.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_OPENSSLDIGEST_H_
-#define TALK_BASE_OPENSSLDIGEST_H_
-
-#include <openssl/evp.h>
-
-#include "talk/base/messagedigest.h"
-
-namespace talk_base {
-
-// An implementation of the digest class that uses OpenSSL.
-class OpenSSLDigest : public MessageDigest {
- public:
- // Creates an OpenSSLDigest with |algorithm| as the hash algorithm.
- explicit OpenSSLDigest(const std::string& algorithm);
- ~OpenSSLDigest();
- // Returns the digest output size (e.g. 16 bytes for MD5).
- virtual size_t Size() const;
- // Updates the digest with |len| bytes from |buf|.
- virtual void Update(const void* buf, size_t len);
- // Outputs the digest value to |buf| with length |len|.
- virtual size_t Finish(void* buf, size_t len);
-
- // Helper function to look up a digest's EVP by name.
- static bool GetDigestEVP(const std::string &algorithm,
- const EVP_MD** md);
- // Helper function to look up a digest's name by EVP.
- static bool GetDigestName(const EVP_MD* md,
- std::string* algorithm);
- // Helper function to get the length of a digest.
- static bool GetDigestSize(const std::string &algorithm,
- size_t* len);
-
- private:
- EVP_MD_CTX ctx_;
- const EVP_MD* md_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_OPENSSLDIGEST_H_
diff --git a/base/opensslidentity.cc b/base/opensslidentity.cc
deleted file mode 100644
index a58f839..0000000
--- a/base/opensslidentity.cc
+++ /dev/null
@@ -1,383 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if HAVE_OPENSSL_SSL_H
-
-#include "talk/base/opensslidentity.h"
-
-// Must be included first before openssl headers.
-#include "talk/base/win32.h" // NOLINT
-
-#include <openssl/bio.h>
-#include <openssl/err.h>
-#include <openssl/pem.h>
-#include <openssl/bn.h>
-#include <openssl/rsa.h>
-#include <openssl/crypto.h>
-
-#include "talk/base/checks.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/openssl.h"
-#include "talk/base/openssldigest.h"
-
-namespace talk_base {
-
-// We could have exposed a myriad of parameters for the crypto stuff,
-// but keeping it simple seems best.
-
-// Strength of generated keys. Those are RSA.
-static const int KEY_LENGTH = 1024;
-
-// Random bits for certificate serial number
-static const int SERIAL_RAND_BITS = 64;
-
-// Certificate validity lifetime
-static const int CERTIFICATE_LIFETIME = 60*60*24*30; // 30 days, arbitrarily
-// Certificate validity window.
-// This is to compensate for slightly incorrect system clocks.
-static const int CERTIFICATE_WINDOW = -60*60*24;
-
-// Generate a key pair. Caller is responsible for freeing the returned object.
-static EVP_PKEY* MakeKey() {
- LOG(LS_INFO) << "Making key pair";
- EVP_PKEY* pkey = EVP_PKEY_new();
- // RSA_generate_key is deprecated. Use _ex version.
- BIGNUM* exponent = BN_new();
- RSA* rsa = RSA_new();
- if (!pkey || !exponent || !rsa ||
- !BN_set_word(exponent, 0x10001) || // 65537 RSA exponent
- !RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||
- !EVP_PKEY_assign_RSA(pkey, rsa)) {
- EVP_PKEY_free(pkey);
- BN_free(exponent);
- RSA_free(rsa);
- return NULL;
- }
- // ownership of rsa struct was assigned, don't free it.
- BN_free(exponent);
- LOG(LS_INFO) << "Returning key pair";
- return pkey;
-}
-
-// Generate a self-signed certificate, with the public key from the
-// given key pair. Caller is responsible for freeing the returned object.
-static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
- LOG(LS_INFO) << "Making certificate for " << params.common_name;
- X509* x509 = NULL;
- BIGNUM* serial_number = NULL;
- X509_NAME* name = NULL;
-
- if ((x509=X509_new()) == NULL)
- goto error;
-
- if (!X509_set_pubkey(x509, pkey))
- goto error;
-
- // serial number
- // temporary reference to serial number inside x509 struct
- ASN1_INTEGER* asn1_serial_number;
- if ((serial_number = BN_new()) == NULL ||
- !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
- (asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||
- !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
- goto error;
-
- if (!X509_set_version(x509, 0L)) // version 1
- goto error;
-
- // There are a lot of possible components for the name entries. In
- // our P2P SSL mode however, the certificates are pre-exchanged
- // (through the secure XMPP channel), and so the certificate
- // identification is arbitrary. It can't be empty, so we set some
- // arbitrary common_name. Note that this certificate goes out in
- // clear during SSL negotiation, so there may be a privacy issue in
- // putting anything recognizable here.
- if ((name = X509_NAME_new()) == NULL ||
- !X509_NAME_add_entry_by_NID(
- name, NID_commonName, MBSTRING_UTF8,
- (unsigned char*)params.common_name.c_str(), -1, -1, 0) ||
- !X509_set_subject_name(x509, name) ||
- !X509_set_issuer_name(x509, name))
- goto error;
-
- if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||
- !X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))
- goto error;
-
- if (!X509_sign(x509, pkey, EVP_sha1()))
- goto error;
-
- BN_free(serial_number);
- X509_NAME_free(name);
- LOG(LS_INFO) << "Returning certificate";
- return x509;
-
- error:
- BN_free(serial_number);
- X509_NAME_free(name);
- X509_free(x509);
- return NULL;
-}
-
-// This dumps the SSL error stack to the log.
-static void LogSSLErrors(const std::string& prefix) {
- char error_buf[200];
- unsigned long err;
-
- while ((err = ERR_get_error()) != 0) {
- ERR_error_string_n(err, error_buf, sizeof(error_buf));
- LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
- }
-}
-
-OpenSSLKeyPair* OpenSSLKeyPair::Generate() {
- EVP_PKEY* pkey = MakeKey();
- if (!pkey) {
- LogSSLErrors("Generating key pair");
- return NULL;
- }
- return new OpenSSLKeyPair(pkey);
-}
-
-OpenSSLKeyPair::~OpenSSLKeyPair() {
- EVP_PKEY_free(pkey_);
-}
-
-void OpenSSLKeyPair::AddReference() {
- CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
-}
-
-#ifdef _DEBUG
-// Print a certificate to the log, for debugging.
-static void PrintCert(X509* x509) {
- BIO* temp_memory_bio = BIO_new(BIO_s_mem());
- if (!temp_memory_bio) {
- LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
- return;
- }
- X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
- BIO_write(temp_memory_bio, "\0", 1);
- char* buffer;
- BIO_get_mem_data(temp_memory_bio, &buffer);
- LOG(LS_VERBOSE) << buffer;
- BIO_free(temp_memory_bio);
-}
-#endif
-
-OpenSSLCertificate* OpenSSLCertificate::Generate(
- OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
- SSLIdentityParams actual_params(params);
- if (actual_params.common_name.empty()) {
- // Use a random string, arbitrarily 8chars long.
- actual_params.common_name = CreateRandomString(8);
- }
- X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
- if (!x509) {
- LogSSLErrors("Generating certificate");
- return NULL;
- }
-#ifdef _DEBUG
- PrintCert(x509);
-#endif
- OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
- X509_free(x509);
- return ret;
-}
-
-OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
- const std::string& pem_string) {
- BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
- if (!bio)
- return NULL;
- BIO_set_mem_eof_return(bio, 0);
- X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,
- const_cast<char*>("\0"));
- BIO_free(bio); // Frees the BIO, but not the pointed-to string.
-
- if (!x509)
- return NULL;
-
- OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
- X509_free(x509);
- return ret;
-}
-
-// NOTE: This implementation only functions correctly after InitializeSSL
-// and before CleanupSSL.
-bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
- std::string* algorithm) const {
- return OpenSSLDigest::GetDigestName(
- EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm);
-}
-
-bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length) const {
- return ComputeDigest(x509_, algorithm, digest, size, length);
-}
-
-bool OpenSSLCertificate::ComputeDigest(const X509* x509,
- const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length) {
- const EVP_MD *md;
- unsigned int n;
-
- if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
- return false;
-
- if (size < static_cast<size_t>(EVP_MD_size(md)))
- return false;
-
- X509_digest(x509, md, digest, &n);
-
- *length = n;
-
- return true;
-}
-
-OpenSSLCertificate::~OpenSSLCertificate() {
- X509_free(x509_);
-}
-
-std::string OpenSSLCertificate::ToPEMString() const {
- BIO* bio = BIO_new(BIO_s_mem());
- if (!bio) {
- UNREACHABLE();
- return std::string();
- }
- if (!PEM_write_bio_X509(bio, x509_)) {
- BIO_free(bio);
- UNREACHABLE();
- return std::string();
- }
- BIO_write(bio, "\0", 1);
- char* buffer;
- BIO_get_mem_data(bio, &buffer);
- std::string ret(buffer);
- BIO_free(bio);
- return ret;
-}
-
-void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
- // In case of failure, make sure to leave the buffer empty.
- der_buffer->SetData(NULL, 0);
-
- // Calculates the DER representation of the certificate, from scratch.
- BIO* bio = BIO_new(BIO_s_mem());
- if (!bio) {
- UNREACHABLE();
- return;
- }
- if (!i2d_X509_bio(bio, x509_)) {
- BIO_free(bio);
- UNREACHABLE();
- return;
- }
- char* data;
- size_t length = BIO_get_mem_data(bio, &data);
- der_buffer->SetData(data, length);
- BIO_free(bio);
-}
-
-void OpenSSLCertificate::AddReference() const {
- ASSERT(x509_ != NULL);
- CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
-}
-
-OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
- const SSLIdentityParams& params) {
- OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
- if (key_pair) {
- OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(
- key_pair, params);
- if (certificate)
- return new OpenSSLIdentity(key_pair, certificate);
- delete key_pair;
- }
- LOG(LS_INFO) << "Identity generation failed";
- return NULL;
-}
-
-OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
- SSLIdentityParams params;
- params.common_name = common_name;
- params.not_before = CERTIFICATE_WINDOW;
- params.not_after = CERTIFICATE_LIFETIME;
- return GenerateInternal(params);
-}
-
-OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
- const SSLIdentityParams& params) {
- return GenerateInternal(params);
-}
-
-SSLIdentity* OpenSSLIdentity::FromPEMStrings(
- const std::string& private_key,
- const std::string& certificate) {
- scoped_ptr<OpenSSLCertificate> cert(
- OpenSSLCertificate::FromPEMString(certificate));
- if (!cert) {
- LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
- return NULL;
- }
-
- BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
- if (!bio) {
- LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
- return NULL;
- }
- BIO_set_mem_eof_return(bio, 0);
- EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
- const_cast<char*>("\0"));
- BIO_free(bio); // Frees the BIO, but not the pointed-to string.
-
- if (!pkey) {
- LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
- return NULL;
- }
-
- return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
- cert.release());
-}
-
-bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
- // 1 is the documented success return code.
- if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
- SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
- LogSSLErrors("Configuring key and certificate");
- return false;
- }
- return true;
-}
-
-} // namespace talk_base
-
-#endif // HAVE_OPENSSL_SSL_H
diff --git a/base/opensslidentity.h b/base/opensslidentity.h
deleted file mode 100644
index 84b2826..0000000
--- a/base/opensslidentity.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_OPENSSLIDENTITY_H_
-#define TALK_BASE_OPENSSLIDENTITY_H_
-
-#include <openssl/evp.h>
-#include <openssl/x509.h>
-
-#include <string>
-
-#include "talk/base/common.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslidentity.h"
-
-typedef struct ssl_ctx_st SSL_CTX;
-
-namespace talk_base {
-
-// OpenSSLKeyPair encapsulates an OpenSSL EVP_PKEY* keypair object,
-// which is reference counted inside the OpenSSL library.
-class OpenSSLKeyPair {
- public:
- explicit OpenSSLKeyPair(EVP_PKEY* pkey) : pkey_(pkey) {
- ASSERT(pkey_ != NULL);
- }
-
- static OpenSSLKeyPair* Generate();
-
- virtual ~OpenSSLKeyPair();
-
- virtual OpenSSLKeyPair* GetReference() {
- AddReference();
- return new OpenSSLKeyPair(pkey_);
- }
-
- EVP_PKEY* pkey() const { return pkey_; }
-
- private:
- void AddReference();
-
- EVP_PKEY* pkey_;
-
- DISALLOW_EVIL_CONSTRUCTORS(OpenSSLKeyPair);
-};
-
-// OpenSSLCertificate encapsulates an OpenSSL X509* certificate object,
-// which is also reference counted inside the OpenSSL library.
-class OpenSSLCertificate : public SSLCertificate {
- public:
- // Caller retains ownership of the X509 object.
- explicit OpenSSLCertificate(X509* x509) : x509_(x509) {
- AddReference();
- }
-
- static OpenSSLCertificate* Generate(OpenSSLKeyPair* key_pair,
- const SSLIdentityParams& params);
- static OpenSSLCertificate* FromPEMString(const std::string& pem_string);
-
- virtual ~OpenSSLCertificate();
-
- virtual OpenSSLCertificate* GetReference() const {
- return new OpenSSLCertificate(x509_);
- }
-
- X509* x509() const { return x509_; }
-
- virtual std::string ToPEMString() const;
-
- virtual void ToDER(Buffer* der_buffer) const;
-
- // Compute the digest of the certificate given algorithm
- virtual bool ComputeDigest(const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length) const;
-
- // Compute the digest of a certificate as an X509 *
- static bool ComputeDigest(const X509* x509,
- const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length);
-
- virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const;
-
- virtual bool GetChain(SSLCertChain** chain) const {
- // Chains are not yet supported when using OpenSSL.
- // OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
- // certificate to be self-signed.
- return false;
- }
-
- private:
- void AddReference() const;
-
- X509* x509_;
-
- DISALLOW_EVIL_CONSTRUCTORS(OpenSSLCertificate);
-};
-
-// Holds a keypair and certificate together, and a method to generate
-// them consistently.
-class OpenSSLIdentity : public SSLIdentity {
- public:
- static OpenSSLIdentity* Generate(const std::string& common_name);
- static OpenSSLIdentity* GenerateForTest(const SSLIdentityParams& params);
- static SSLIdentity* FromPEMStrings(const std::string& private_key,
- const std::string& certificate);
- virtual ~OpenSSLIdentity() { }
-
- virtual const OpenSSLCertificate& certificate() const {
- return *certificate_;
- }
-
- virtual OpenSSLIdentity* GetReference() const {
- return new OpenSSLIdentity(key_pair_->GetReference(),
- certificate_->GetReference());
- }
-
- // Configure an SSL context object to use our key and certificate.
- bool ConfigureIdentity(SSL_CTX* ctx);
-
- private:
- OpenSSLIdentity(OpenSSLKeyPair* key_pair,
- OpenSSLCertificate* certificate)
- : key_pair_(key_pair), certificate_(certificate) {
- ASSERT(key_pair != NULL);
- ASSERT(certificate != NULL);
- }
-
- static OpenSSLIdentity* GenerateInternal(const SSLIdentityParams& params);
-
- scoped_ptr<OpenSSLKeyPair> key_pair_;
- scoped_ptr<OpenSSLCertificate> certificate_;
-
- DISALLOW_EVIL_CONSTRUCTORS(OpenSSLIdentity);
-};
-
-
-} // namespace talk_base
-
-#endif // TALK_BASE_OPENSSLIDENTITY_H_
diff --git a/base/opensslstreamadapter.cc b/base/opensslstreamadapter.cc
deleted file mode 100644
index 218f656..0000000
--- a/base/opensslstreamadapter.cc
+++ /dev/null
@@ -1,874 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#if HAVE_OPENSSL_SSL_H
-
-#include "talk/base/opensslstreamadapter.h"
-
-#include <openssl/bio.h>
-#include <openssl/crypto.h>
-#include <openssl/err.h>
-#include <openssl/rand.h>
-#include <openssl/x509v3.h>
-
-#include <vector>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/stream.h"
-#include "talk/base/openssl.h"
-#include "talk/base/openssladapter.h"
-#include "talk/base/openssldigest.h"
-#include "talk/base/opensslidentity.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-#if (OPENSSL_VERSION_NUMBER >= 0x10001000L)
-#define HAVE_DTLS_SRTP
-#endif
-
-#ifdef HAVE_DTLS_SRTP
-// SRTP cipher suite table
-struct SrtpCipherMapEntry {
- const char* external_name;
- const char* internal_name;
-};
-
-// This isn't elegant, but it's better than an external reference
-static SrtpCipherMapEntry SrtpCipherMap[] = {
- {"AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_SHA1_80"},
- {"AES_CM_128_HMAC_SHA1_32", "SRTP_AES128_CM_SHA1_32"},
- {NULL, NULL}
-};
-#endif
-
-//////////////////////////////////////////////////////////////////////
-// StreamBIO
-//////////////////////////////////////////////////////////////////////
-
-static int stream_write(BIO* h, const char* buf, int num);
-static int stream_read(BIO* h, char* buf, int size);
-static int stream_puts(BIO* h, const char* str);
-static long stream_ctrl(BIO* h, int cmd, long arg1, void* arg2);
-static int stream_new(BIO* h);
-static int stream_free(BIO* data);
-
-static BIO_METHOD methods_stream = {
- BIO_TYPE_BIO,
- "stream",
- stream_write,
- stream_read,
- stream_puts,
- 0,
- stream_ctrl,
- stream_new,
- stream_free,
- NULL,
-};
-
-static BIO_METHOD* BIO_s_stream() { return(&methods_stream); }
-
-static BIO* BIO_new_stream(StreamInterface* stream) {
- BIO* ret = BIO_new(BIO_s_stream());
- if (ret == NULL)
- return NULL;
- ret->ptr = stream;
- return ret;
-}
-
-// bio methods return 1 (or at least non-zero) on success and 0 on failure.
-
-static int stream_new(BIO* b) {
- b->shutdown = 0;
- b->init = 1;
- b->num = 0; // 1 means end-of-stream
- b->ptr = 0;
- return 1;
-}
-
-static int stream_free(BIO* b) {
- if (b == NULL)
- return 0;
- return 1;
-}
-
-static int stream_read(BIO* b, char* out, int outl) {
- if (!out)
- return -1;
- StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
- BIO_clear_retry_flags(b);
- size_t read;
- int error;
- StreamResult result = stream->Read(out, outl, &read, &error);
- if (result == SR_SUCCESS) {
- return read;
- } else if (result == SR_EOS) {
- b->num = 1;
- } else if (result == SR_BLOCK) {
- BIO_set_retry_read(b);
- }
- return -1;
-}
-
-static int stream_write(BIO* b, const char* in, int inl) {
- if (!in)
- return -1;
- StreamInterface* stream = static_cast<StreamInterface*>(b->ptr);
- BIO_clear_retry_flags(b);
- size_t written;
- int error;
- StreamResult result = stream->Write(in, inl, &written, &error);
- if (result == SR_SUCCESS) {
- return written;
- } else if (result == SR_BLOCK) {
- BIO_set_retry_write(b);
- }
- return -1;
-}
-
-static int stream_puts(BIO* b, const char* str) {
- return stream_write(b, str, strlen(str));
-}
-
-static long stream_ctrl(BIO* b, int cmd, long num, void* ptr) {
- UNUSED(num);
- UNUSED(ptr);
-
- switch (cmd) {
- case BIO_CTRL_RESET:
- return 0;
- case BIO_CTRL_EOF:
- return b->num;
- case BIO_CTRL_WPENDING:
- case BIO_CTRL_PENDING:
- return 0;
- case BIO_CTRL_FLUSH:
- return 1;
- default:
- return 0;
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// OpenSSLStreamAdapter
-/////////////////////////////////////////////////////////////////////////////
-
-OpenSSLStreamAdapter::OpenSSLStreamAdapter(StreamInterface* stream)
- : SSLStreamAdapter(stream),
- state_(SSL_NONE),
- role_(SSL_CLIENT),
- ssl_read_needs_write_(false), ssl_write_needs_read_(false),
- ssl_(NULL), ssl_ctx_(NULL),
- custom_verification_succeeded_(false),
- ssl_mode_(SSL_MODE_TLS) {
-}
-
-OpenSSLStreamAdapter::~OpenSSLStreamAdapter() {
- Cleanup();
-}
-
-void OpenSSLStreamAdapter::SetIdentity(SSLIdentity* identity) {
- ASSERT(!identity_);
- identity_.reset(static_cast<OpenSSLIdentity*>(identity));
-}
-
-void OpenSSLStreamAdapter::SetServerRole(SSLRole role) {
- role_ = role;
-}
-
-bool OpenSSLStreamAdapter::GetPeerCertificate(SSLCertificate** cert) const {
- if (!peer_certificate_)
- return false;
-
- *cert = peer_certificate_->GetReference();
- return true;
-}
-
-bool OpenSSLStreamAdapter::SetPeerCertificateDigest(const std::string
- &digest_alg,
- const unsigned char*
- digest_val,
- size_t digest_len) {
- ASSERT(!peer_certificate_);
- ASSERT(peer_certificate_digest_algorithm_.size() == 0);
- ASSERT(ssl_server_name_.empty());
- size_t expected_len;
-
- if (!OpenSSLDigest::GetDigestSize(digest_alg, &expected_len)) {
- LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
- return false;
- }
- if (expected_len != digest_len)
- return false;
-
- peer_certificate_digest_value_.SetData(digest_val, digest_len);
- peer_certificate_digest_algorithm_ = digest_alg;
-
- return true;
-}
-
-// Key Extractor interface
-bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label,
- const uint8* context,
- size_t context_len,
- bool use_context,
- uint8* result,
- size_t result_len) {
-#ifdef HAVE_DTLS_SRTP
- int i;
-
- i = SSL_export_keying_material(ssl_, result, result_len,
- label.c_str(), label.length(),
- const_cast<uint8 *>(context),
- context_len, use_context);
-
- if (i != 1)
- return false;
-
- return true;
-#else
- return false;
-#endif
-}
-
-bool OpenSSLStreamAdapter::SetDtlsSrtpCiphers(
- const std::vector<std::string>& ciphers) {
-#ifdef HAVE_DTLS_SRTP
- std::string internal_ciphers;
-
- if (state_ != SSL_NONE)
- return false;
-
- for (std::vector<std::string>::const_iterator cipher = ciphers.begin();
- cipher != ciphers.end(); ++cipher) {
- bool found = false;
- for (SrtpCipherMapEntry *entry = SrtpCipherMap; entry->internal_name;
- ++entry) {
- if (*cipher == entry->external_name) {
- found = true;
- if (!internal_ciphers.empty())
- internal_ciphers += ":";
- internal_ciphers += entry->internal_name;
- break;
- }
- }
-
- if (!found) {
- LOG(LS_ERROR) << "Could not find cipher: " << *cipher;
- return false;
- }
- }
-
- if (internal_ciphers.empty())
- return false;
-
- srtp_ciphers_ = internal_ciphers;
- return true;
-#else
- return false;
-#endif
-}
-
-bool OpenSSLStreamAdapter::GetDtlsSrtpCipher(std::string* cipher) {
-#ifdef HAVE_DTLS_SRTP
- ASSERT(state_ == SSL_CONNECTED);
- if (state_ != SSL_CONNECTED)
- return false;
-
- SRTP_PROTECTION_PROFILE *srtp_profile =
- SSL_get_selected_srtp_profile(ssl_);
-
- if (!srtp_profile)
- return false;
-
- for (SrtpCipherMapEntry *entry = SrtpCipherMap;
- entry->internal_name; ++entry) {
- if (!strcmp(entry->internal_name, srtp_profile->name)) {
- *cipher = entry->external_name;
- return true;
- }
- }
-
- ASSERT(false); // This should never happen
-
- return false;
-#else
- return false;
-#endif
-}
-
-int OpenSSLStreamAdapter::StartSSLWithServer(const char* server_name) {
- ASSERT(server_name != NULL && server_name[0] != '\0');
- ssl_server_name_ = server_name;
- return StartSSL();
-}
-
-int OpenSSLStreamAdapter::StartSSLWithPeer() {
- ASSERT(ssl_server_name_.empty());
- // It is permitted to specify peer_certificate_ only later.
- return StartSSL();
-}
-
-void OpenSSLStreamAdapter::SetMode(SSLMode mode) {
- ASSERT(state_ == SSL_NONE);
- ssl_mode_ = mode;
-}
-
-//
-// StreamInterface Implementation
-//
-
-StreamResult OpenSSLStreamAdapter::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Write(" << data_len << ")";
-
- switch (state_) {
- case SSL_NONE:
- // pass-through in clear text
- return StreamAdapterInterface::Write(data, data_len, written, error);
-
- case SSL_WAIT:
- case SSL_CONNECTING:
- return SR_BLOCK;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_ERROR:
- case SSL_CLOSED:
- default:
- if (error)
- *error = ssl_error_code_;
- return SR_ERROR;
- }
-
- // OpenSSL will return an error if we try to write zero bytes
- if (data_len == 0) {
- if (written)
- *written = 0;
- return SR_SUCCESS;
- }
-
- ssl_write_needs_read_ = false;
-
- int code = SSL_write(ssl_, data, data_len);
- int ssl_error = SSL_get_error(ssl_, code);
- switch (ssl_error) {
- case SSL_ERROR_NONE:
- LOG(LS_VERBOSE) << " -- success";
- ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
- if (written)
- *written = code;
- return SR_SUCCESS;
- case SSL_ERROR_WANT_READ:
- LOG(LS_VERBOSE) << " -- error want read";
- ssl_write_needs_read_ = true;
- return SR_BLOCK;
- case SSL_ERROR_WANT_WRITE:
- LOG(LS_VERBOSE) << " -- error want write";
- return SR_BLOCK;
-
- case SSL_ERROR_ZERO_RETURN:
- default:
- Error("SSL_write", (ssl_error ? ssl_error : -1), false);
- if (error)
- *error = ssl_error_code_;
- return SR_ERROR;
- }
- // not reached
-}
-
-StreamResult OpenSSLStreamAdapter::Read(void* data, size_t data_len,
- size_t* read, int* error) {
- LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::Read(" << data_len << ")";
- switch (state_) {
- case SSL_NONE:
- // pass-through in clear text
- return StreamAdapterInterface::Read(data, data_len, read, error);
-
- case SSL_WAIT:
- case SSL_CONNECTING:
- return SR_BLOCK;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_CLOSED:
- return SR_EOS;
-
- case SSL_ERROR:
- default:
- if (error)
- *error = ssl_error_code_;
- return SR_ERROR;
- }
-
- // Don't trust OpenSSL with zero byte reads
- if (data_len == 0) {
- if (read)
- *read = 0;
- return SR_SUCCESS;
- }
-
- ssl_read_needs_write_ = false;
-
- int code = SSL_read(ssl_, data, data_len);
- int ssl_error = SSL_get_error(ssl_, code);
- switch (ssl_error) {
- case SSL_ERROR_NONE:
- LOG(LS_VERBOSE) << " -- success";
- ASSERT(0 < code && static_cast<unsigned>(code) <= data_len);
- if (read)
- *read = code;
-
- if (ssl_mode_ == SSL_MODE_DTLS) {
- // Enforce atomic reads -- this is a short read
- unsigned int pending = SSL_pending(ssl_);
-
- if (pending) {
- LOG(LS_INFO) << " -- short DTLS read. flushing";
- FlushInput(pending);
- if (error)
- *error = SSE_MSG_TRUNC;
- return SR_ERROR;
- }
- }
- return SR_SUCCESS;
- case SSL_ERROR_WANT_READ:
- LOG(LS_VERBOSE) << " -- error want read";
- return SR_BLOCK;
- case SSL_ERROR_WANT_WRITE:
- LOG(LS_VERBOSE) << " -- error want write";
- ssl_read_needs_write_ = true;
- return SR_BLOCK;
- case SSL_ERROR_ZERO_RETURN:
- LOG(LS_VERBOSE) << " -- remote side closed";
- return SR_EOS;
- break;
- default:
- LOG(LS_VERBOSE) << " -- error " << code;
- Error("SSL_read", (ssl_error ? ssl_error : -1), false);
- if (error)
- *error = ssl_error_code_;
- return SR_ERROR;
- }
- // not reached
-}
-
-void OpenSSLStreamAdapter::FlushInput(unsigned int left) {
- unsigned char buf[2048];
-
- while (left) {
- // This should always succeed
- int toread = (sizeof(buf) < left) ? sizeof(buf) : left;
- int code = SSL_read(ssl_, buf, toread);
-
- int ssl_error = SSL_get_error(ssl_, code);
- ASSERT(ssl_error == SSL_ERROR_NONE);
-
- if (ssl_error != SSL_ERROR_NONE) {
- LOG(LS_VERBOSE) << " -- error " << code;
- Error("SSL_read", (ssl_error ? ssl_error : -1), false);
- return;
- }
-
- LOG(LS_VERBOSE) << " -- flushed " << code << " bytes";
- left -= code;
- }
-}
-
-void OpenSSLStreamAdapter::Close() {
- Cleanup();
- ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
- StreamAdapterInterface::Close();
-}
-
-StreamState OpenSSLStreamAdapter::GetState() const {
- switch (state_) {
- case SSL_WAIT:
- case SSL_CONNECTING:
- return SS_OPENING;
- case SSL_CONNECTED:
- return SS_OPEN;
- default:
- return SS_CLOSED;
- };
- // not reached
-}
-
-void OpenSSLStreamAdapter::OnEvent(StreamInterface* stream, int events,
- int err) {
- int events_to_signal = 0;
- int signal_error = 0;
- ASSERT(stream == this->stream());
- if ((events & SE_OPEN)) {
- LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent SE_OPEN";
- if (state_ != SSL_WAIT) {
- ASSERT(state_ == SSL_NONE);
- events_to_signal |= SE_OPEN;
- } else {
- state_ = SSL_CONNECTING;
- if (int err = BeginSSL()) {
- Error("BeginSSL", err, true);
- return;
- }
- }
- }
- if ((events & (SE_READ|SE_WRITE))) {
- LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent"
- << ((events & SE_READ) ? " SE_READ" : "")
- << ((events & SE_WRITE) ? " SE_WRITE" : "");
- if (state_ == SSL_NONE) {
- events_to_signal |= events & (SE_READ|SE_WRITE);
- } else if (state_ == SSL_CONNECTING) {
- if (int err = ContinueSSL()) {
- Error("ContinueSSL", err, true);
- return;
- }
- } else if (state_ == SSL_CONNECTED) {
- if (((events & SE_READ) && ssl_write_needs_read_) ||
- (events & SE_WRITE)) {
- LOG(LS_VERBOSE) << " -- onStreamWriteable";
- events_to_signal |= SE_WRITE;
- }
- if (((events & SE_WRITE) && ssl_read_needs_write_) ||
- (events & SE_READ)) {
- LOG(LS_VERBOSE) << " -- onStreamReadable";
- events_to_signal |= SE_READ;
- }
- }
- }
- if ((events & SE_CLOSE)) {
- LOG(LS_VERBOSE) << "OpenSSLStreamAdapter::OnEvent(SE_CLOSE, " << err << ")";
- Cleanup();
- events_to_signal |= SE_CLOSE;
- // SE_CLOSE is the only event that uses the final parameter to OnEvent().
- ASSERT(signal_error == 0);
- signal_error = err;
- }
- if (events_to_signal)
- StreamAdapterInterface::OnEvent(stream, events_to_signal, signal_error);
-}
-
-int OpenSSLStreamAdapter::StartSSL() {
- ASSERT(state_ == SSL_NONE);
-
- if (StreamAdapterInterface::GetState() != SS_OPEN) {
- state_ = SSL_WAIT;
- return 0;
- }
-
- state_ = SSL_CONNECTING;
- if (int err = BeginSSL()) {
- Error("BeginSSL", err, false);
- return err;
- }
-
- return 0;
-}
-
-int OpenSSLStreamAdapter::BeginSSL() {
- ASSERT(state_ == SSL_CONNECTING);
- // The underlying stream has open. If we are in peer-to-peer mode
- // then a peer certificate must have been specified by now.
- ASSERT(!ssl_server_name_.empty() ||
- !peer_certificate_digest_algorithm_.empty());
- LOG(LS_INFO) << "BeginSSL: "
- << (!ssl_server_name_.empty() ? ssl_server_name_ :
- "with peer");
-
- BIO* bio = NULL;
-
- // First set up the context
- ASSERT(ssl_ctx_ == NULL);
- ssl_ctx_ = SetupSSLContext();
- if (!ssl_ctx_)
- return -1;
-
- bio = BIO_new_stream(static_cast<StreamInterface*>(stream()));
- if (!bio)
- return -1;
-
- ssl_ = SSL_new(ssl_ctx_);
- if (!ssl_) {
- BIO_free(bio);
- return -1;
- }
-
- SSL_set_app_data(ssl_, this);
-
- SSL_set_bio(ssl_, bio, bio); // the SSL object owns the bio now.
-
- SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE |
- SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
-
- // Do the connect
- return ContinueSSL();
-}
-
-int OpenSSLStreamAdapter::ContinueSSL() {
- LOG(LS_VERBOSE) << "ContinueSSL";
- ASSERT(state_ == SSL_CONNECTING);
-
- // Clear the DTLS timer
- Thread::Current()->Clear(this, MSG_TIMEOUT);
-
- int code = (role_ == SSL_CLIENT) ? SSL_connect(ssl_) : SSL_accept(ssl_);
- int ssl_error;
- switch (ssl_error = SSL_get_error(ssl_, code)) {
- case SSL_ERROR_NONE:
- LOG(LS_VERBOSE) << " -- success";
-
- if (!SSLPostConnectionCheck(ssl_, ssl_server_name_.c_str(), NULL,
- peer_certificate_digest_algorithm_)) {
- LOG(LS_ERROR) << "TLS post connection check failed";
- return -1;
- }
-
- state_ = SSL_CONNECTED;
- StreamAdapterInterface::OnEvent(stream(), SE_OPEN|SE_READ|SE_WRITE, 0);
- break;
-
- case SSL_ERROR_WANT_READ: {
- LOG(LS_VERBOSE) << " -- error want read";
- struct timeval timeout;
- if (DTLSv1_get_timeout(ssl_, &timeout)) {
- int delay = timeout.tv_sec * 1000 + timeout.tv_usec/1000;
-
- Thread::Current()->PostDelayed(delay, this, MSG_TIMEOUT, 0);
- }
- }
- break;
-
- case SSL_ERROR_WANT_WRITE:
- LOG(LS_VERBOSE) << " -- error want write";
- break;
-
- case SSL_ERROR_ZERO_RETURN:
- default:
- LOG(LS_VERBOSE) << " -- error " << code;
- return (ssl_error != 0) ? ssl_error : -1;
- }
-
- return 0;
-}
-
-void OpenSSLStreamAdapter::Error(const char* context, int err, bool signal) {
- LOG(LS_WARNING) << "OpenSSLStreamAdapter::Error("
- << context << ", " << err << ")";
- state_ = SSL_ERROR;
- ssl_error_code_ = err;
- Cleanup();
- if (signal)
- StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
-}
-
-void OpenSSLStreamAdapter::Cleanup() {
- LOG(LS_INFO) << "Cleanup";
-
- if (state_ != SSL_ERROR) {
- state_ = SSL_CLOSED;
- ssl_error_code_ = 0;
- }
-
- if (ssl_) {
- SSL_free(ssl_);
- ssl_ = NULL;
- }
- if (ssl_ctx_) {
- SSL_CTX_free(ssl_ctx_);
- ssl_ctx_ = NULL;
- }
- identity_.reset();
- peer_certificate_.reset();
-
- // Clear the DTLS timer
- Thread::Current()->Clear(this, MSG_TIMEOUT);
-}
-
-
-void OpenSSLStreamAdapter::OnMessage(Message* msg) {
- // Process our own messages and then pass others to the superclass
- if (MSG_TIMEOUT == msg->message_id) {
- LOG(LS_INFO) << "DTLS timeout expired";
- DTLSv1_handle_timeout(ssl_);
- ContinueSSL();
- } else {
- StreamInterface::OnMessage(msg);
- }
-}
-
-SSL_CTX* OpenSSLStreamAdapter::SetupSSLContext() {
- SSL_CTX *ctx = NULL;
-
- if (role_ == SSL_CLIENT) {
- ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
- DTLSv1_client_method() : TLSv1_client_method());
- } else {
- ctx = SSL_CTX_new(ssl_mode_ == SSL_MODE_DTLS ?
- DTLSv1_server_method() : TLSv1_server_method());
- }
- if (ctx == NULL)
- return NULL;
-
- if (identity_ && !identity_->ConfigureIdentity(ctx)) {
- SSL_CTX_free(ctx);
- return NULL;
- }
-
-#ifdef _DEBUG
- SSL_CTX_set_info_callback(ctx, OpenSSLAdapter::SSLInfoCallback);
-#endif
-
- SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
- SSLVerifyCallback);
- SSL_CTX_set_verify_depth(ctx, 4);
- SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
-
-#ifdef HAVE_DTLS_SRTP
- if (!srtp_ciphers_.empty()) {
- if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_ciphers_.c_str())) {
- SSL_CTX_free(ctx);
- return NULL;
- }
- }
-#endif
-
- return ctx;
-}
-
-int OpenSSLStreamAdapter::SSLVerifyCallback(int ok, X509_STORE_CTX* store) {
- // Get our SSL structure from the store
- SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
- store,
- SSL_get_ex_data_X509_STORE_CTX_idx()));
- OpenSSLStreamAdapter* stream =
- reinterpret_cast<OpenSSLStreamAdapter*>(SSL_get_app_data(ssl));
-
- if (stream->peer_certificate_digest_algorithm_.empty()) {
- return 0;
- }
- X509* cert = X509_STORE_CTX_get_current_cert(store);
- int depth = X509_STORE_CTX_get_error_depth(store);
-
- // For now We ignore the parent certificates and verify the leaf against
- // the digest.
- //
- // TODO(jiayl): Verify the chain is a proper chain and report the chain to
- // |stream->peer_certificate_|, like what NSS does.
- if (depth > 0) {
- LOG(LS_INFO) << "Ignored chained certificate at depth " << depth;
- return 1;
- }
-
- unsigned char digest[EVP_MAX_MD_SIZE];
- size_t digest_length;
- if (!OpenSSLCertificate::ComputeDigest(
- cert,
- stream->peer_certificate_digest_algorithm_,
- digest, sizeof(digest),
- &digest_length)) {
- LOG(LS_WARNING) << "Failed to compute peer cert digest.";
- return 0;
- }
-
- Buffer computed_digest(digest, digest_length);
- if (computed_digest != stream->peer_certificate_digest_value_) {
- LOG(LS_WARNING) << "Rejected peer certificate due to mismatched digest.";
- return 0;
- }
- // Ignore any verification error if the digest matches, since there is no
- // value in checking the validity of a self-signed cert issued by untrusted
- // sources.
- LOG(LS_INFO) << "Accepted peer certificate.";
-
- // Record the peer's certificate.
- stream->peer_certificate_.reset(new OpenSSLCertificate(cert));
- return 1;
-}
-
-// This code is taken from the "Network Security with OpenSSL"
-// sample in chapter 5
-bool OpenSSLStreamAdapter::SSLPostConnectionCheck(SSL* ssl,
- const char* server_name,
- const X509* peer_cert,
- const std::string
- &peer_digest) {
- ASSERT(server_name != NULL);
- bool ok;
- if (server_name[0] != '\0') { // traditional mode
- ok = OpenSSLAdapter::VerifyServerName(ssl, server_name, ignore_bad_cert());
-
- if (ok) {
- ok = (SSL_get_verify_result(ssl) == X509_V_OK ||
- custom_verification_succeeded_);
- }
- } else { // peer-to-peer mode
- ASSERT((peer_cert != NULL) || (!peer_digest.empty()));
- // no server name validation
- ok = true;
- }
-
- if (!ok && ignore_bad_cert()) {
- LOG(LS_ERROR) << "SSL_get_verify_result(ssl) = "
- << SSL_get_verify_result(ssl);
- LOG(LS_INFO) << "Other TLS post connection checks failed.";
- ok = true;
- }
-
- return ok;
-}
-
-bool OpenSSLStreamAdapter::HaveDtls() {
- return true;
-}
-
-bool OpenSSLStreamAdapter::HaveDtlsSrtp() {
-#ifdef HAVE_DTLS_SRTP
- return true;
-#else
- return false;
-#endif
-}
-
-bool OpenSSLStreamAdapter::HaveExporter() {
-#ifdef HAVE_DTLS_SRTP
- return true;
-#else
- return false;
-#endif
-}
-
-} // namespace talk_base
-
-#endif // HAVE_OPENSSL_SSL_H
diff --git a/base/opensslstreamadapter.h b/base/opensslstreamadapter.h
deleted file mode 100644
index 744d299..0000000
--- a/base/opensslstreamadapter.h
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_OPENSSLSTREAMADAPTER_H__
-#define TALK_BASE_OPENSSLSTREAMADAPTER_H__
-
-#include <string>
-#include <vector>
-
-#include "talk/base/buffer.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/opensslidentity.h"
-
-typedef struct ssl_st SSL;
-typedef struct ssl_ctx_st SSL_CTX;
-typedef struct x509_store_ctx_st X509_STORE_CTX;
-
-namespace talk_base {
-
-// This class was written with OpenSSLAdapter (a socket adapter) as a
-// starting point. It has similar structure and functionality, with
-// the peer-to-peer mode added.
-//
-// Static methods to initialize and deinit the SSL library are in
-// OpenSSLAdapter. This class also uses
-// OpenSSLAdapter::custom_verify_callback_ (a static field). These
-// should probably be moved out to a neutral class.
-//
-// In a few cases I have factored out some OpenSSLAdapter code into
-// static methods so it can be reused from this class. Eventually that
-// code should probably be moved to a common support
-// class. Unfortunately there remain a few duplicated sections of
-// code. I have not done more restructuring because I did not want to
-// affect existing code that uses OpenSSLAdapter.
-//
-// This class does not support the SSL connection restart feature
-// present in OpenSSLAdapter. I am not entirely sure how the feature
-// is useful and I am not convinced that it works properly.
-//
-// This implementation is careful to disallow data exchange after an
-// SSL error, and it has an explicit SSL_CLOSED state. It should not
-// be possible to send any data in clear after one of the StartSSL
-// methods has been called.
-
-// Look in sslstreamadapter.h for documentation of the methods.
-
-class OpenSSLIdentity;
-
-///////////////////////////////////////////////////////////////////////////////
-
-class OpenSSLStreamAdapter : public SSLStreamAdapter {
- public:
- explicit OpenSSLStreamAdapter(StreamInterface* stream);
- virtual ~OpenSSLStreamAdapter();
-
- virtual void SetIdentity(SSLIdentity* identity);
-
- // Default argument is for compatibility
- virtual void SetServerRole(SSLRole role = SSL_SERVER);
- virtual bool SetPeerCertificateDigest(const std::string& digest_alg,
- const unsigned char* digest_val,
- size_t digest_len);
-
- virtual bool GetPeerCertificate(SSLCertificate** cert) const;
-
- virtual int StartSSLWithServer(const char* server_name);
- virtual int StartSSLWithPeer();
- virtual void SetMode(SSLMode mode);
-
- virtual StreamResult Read(void* data, size_t data_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- virtual void Close();
- virtual StreamState GetState() const;
-
- // Key Extractor interface
- virtual bool ExportKeyingMaterial(const std::string& label,
- const uint8* context,
- size_t context_len,
- bool use_context,
- uint8* result,
- size_t result_len);
-
-
- // DTLS-SRTP interface
- virtual bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers);
- virtual bool GetDtlsSrtpCipher(std::string* cipher);
-
- // Capabilities interfaces
- static bool HaveDtls();
- static bool HaveDtlsSrtp();
- static bool HaveExporter();
-
- protected:
- virtual void OnEvent(StreamInterface* stream, int events, int err);
-
- private:
- enum SSLState {
- // Before calling one of the StartSSL methods, data flows
- // in clear text.
- SSL_NONE,
- SSL_WAIT, // waiting for the stream to open to start SSL negotiation
- SSL_CONNECTING, // SSL negotiation in progress
- SSL_CONNECTED, // SSL stream successfully established
- SSL_ERROR, // some SSL error occurred, stream is closed
- SSL_CLOSED // Clean close
- };
-
- enum { MSG_TIMEOUT = MSG_MAX+1};
-
- // The following three methods return 0 on success and a negative
- // error code on failure. The error code may be from OpenSSL or -1
- // on some other error cases, so it can't really be interpreted
- // unfortunately.
-
- // Go from state SSL_NONE to either SSL_CONNECTING or SSL_WAIT,
- // depending on whether the underlying stream is already open or
- // not.
- int StartSSL();
- // Prepare SSL library, state is SSL_CONNECTING.
- int BeginSSL();
- // Perform SSL negotiation steps.
- int ContinueSSL();
-
- // Error handler helper. signal is given as true for errors in
- // asynchronous contexts (when an error method was not returned
- // through some other method), and in that case an SE_CLOSE event is
- // raised on the stream with the specified error.
- // A 0 error means a graceful close, otherwise there is not really enough
- // context to interpret the error code.
- void Error(const char* context, int err, bool signal);
- void Cleanup();
-
- // Override MessageHandler
- virtual void OnMessage(Message* msg);
-
- // Flush the input buffers by reading left bytes (for DTLS)
- void FlushInput(unsigned int left);
-
- // SSL library configuration
- SSL_CTX* SetupSSLContext();
- // SSL verification check
- bool SSLPostConnectionCheck(SSL* ssl, const char* server_name,
- const X509* peer_cert,
- const std::string& peer_digest);
- // SSL certification verification error handler, called back from
- // the openssl library. Returns an int interpreted as a boolean in
- // the C style: zero means verification failure, non-zero means
- // passed.
- static int SSLVerifyCallback(int ok, X509_STORE_CTX* store);
-
- SSLState state_;
- SSLRole role_;
- int ssl_error_code_; // valid when state_ == SSL_ERROR or SSL_CLOSED
- // Whether the SSL negotiation is blocked on needing to read or
- // write to the wrapped stream.
- bool ssl_read_needs_write_;
- bool ssl_write_needs_read_;
-
- SSL* ssl_;
- SSL_CTX* ssl_ctx_;
-
- // Our key and certificate, mostly useful in peer-to-peer mode.
- scoped_ptr<OpenSSLIdentity> identity_;
- // in traditional mode, the server name that the server's certificate
- // must specify. Empty in peer-to-peer mode.
- std::string ssl_server_name_;
- // The certificate that the peer must present or did present. Initially
- // null in traditional mode, until the connection is established.
- scoped_ptr<OpenSSLCertificate> peer_certificate_;
- // In peer-to-peer mode, the digest of the certificate that
- // the peer must present.
- Buffer peer_certificate_digest_value_;
- std::string peer_certificate_digest_algorithm_;
-
- // OpenSSLAdapter::custom_verify_callback_ result
- bool custom_verification_succeeded_;
-
- // The DtlsSrtp ciphers
- std::string srtp_ciphers_;
-
- // Do DTLS or not
- SSLMode ssl_mode_;
-};
-
-/////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_OPENSSLSTREAMADAPTER_H__
diff --git a/base/optionsfile.cc b/base/optionsfile.cc
deleted file mode 100644
index 82a5c86..0000000
--- a/base/optionsfile.cc
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/optionsfile.h"
-
-#include <ctype.h>
-
-#include "talk/base/logging.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringencode.h"
-
-namespace talk_base {
-
-OptionsFile::OptionsFile(const std::string &path) : path_(path) {
-}
-
-bool OptionsFile::Load() {
- options_.clear();
- // Open file.
- FileStream stream;
- int err;
- if (!stream.Open(path_, "r", &err)) {
- LOG_F(LS_WARNING) << "Could not open file, err=" << err;
- // We do not consider this an error because we expect there to be no file
- // until the user saves a setting.
- return true;
- }
- // Read in all its data.
- std::string line;
- StreamResult res;
- for (;;) {
- res = stream.ReadLine(&line);
- if (res != SR_SUCCESS) {
- break;
- }
- size_t equals_pos = line.find('=');
- if (equals_pos == std::string::npos) {
- // We do not consider this an error. Instead we ignore the line and
- // keep going.
- LOG_F(LS_WARNING) << "Ignoring malformed line in " << path_;
- continue;
- }
- std::string key(line, 0, equals_pos);
- std::string value(line, equals_pos + 1, line.length() - (equals_pos + 1));
- options_[key] = value;
- }
- if (res != SR_EOS) {
- LOG_F(LS_ERROR) << "Error when reading from file";
- return false;
- } else {
- return true;
- }
-}
-
-bool OptionsFile::Save() {
- // Open file.
- FileStream stream;
- int err;
- if (!stream.Open(path_, "w", &err)) {
- LOG_F(LS_ERROR) << "Could not open file, err=" << err;
- return false;
- }
- // Write out all the data.
- StreamResult res = SR_SUCCESS;
- size_t written;
- int error;
- for (OptionsMap::const_iterator i = options_.begin(); i != options_.end();
- ++i) {
- res = stream.WriteAll(i->first.c_str(), i->first.length(), &written,
- &error);
- if (res != SR_SUCCESS) {
- break;
- }
- res = stream.WriteAll("=", 1, &written, &error);
- if (res != SR_SUCCESS) {
- break;
- }
- res = stream.WriteAll(i->second.c_str(), i->second.length(), &written,
- &error);
- if (res != SR_SUCCESS) {
- break;
- }
- res = stream.WriteAll("\n", 1, &written, &error);
- if (res != SR_SUCCESS) {
- break;
- }
- }
- if (res != SR_SUCCESS) {
- LOG_F(LS_ERROR) << "Unable to write to file";
- return false;
- } else {
- return true;
- }
-}
-
-bool OptionsFile::IsLegalName(const std::string &name) {
- for (size_t pos = 0; pos < name.length(); ++pos) {
- if (name[pos] == '\n' || name[pos] == '\\' || name[pos] == '=') {
- // Illegal character.
- LOG(LS_WARNING) << "Ignoring operation for illegal option " << name;
- return false;
- }
- }
- return true;
-}
-
-bool OptionsFile::IsLegalValue(const std::string &value) {
- for (size_t pos = 0; pos < value.length(); ++pos) {
- if (value[pos] == '\n' || value[pos] == '\\') {
- // Illegal character.
- LOG(LS_WARNING) << "Ignoring operation for illegal value " << value;
- return false;
- }
- }
- return true;
-}
-
-bool OptionsFile::GetStringValue(const std::string& option,
- std::string *out_val) const {
- LOG(LS_VERBOSE) << "OptionsFile::GetStringValue "
- << option;
- if (!IsLegalName(option)) {
- return false;
- }
- OptionsMap::const_iterator i = options_.find(option);
- if (i == options_.end()) {
- return false;
- }
- *out_val = i->second;
- return true;
-}
-
-bool OptionsFile::GetIntValue(const std::string& option,
- int *out_val) const {
- LOG(LS_VERBOSE) << "OptionsFile::GetIntValue "
- << option;
- if (!IsLegalName(option)) {
- return false;
- }
- OptionsMap::const_iterator i = options_.find(option);
- if (i == options_.end()) {
- return false;
- }
- return FromString(i->second, out_val);
-}
-
-bool OptionsFile::SetStringValue(const std::string& option,
- const std::string& value) {
- LOG(LS_VERBOSE) << "OptionsFile::SetStringValue "
- << option << ":" << value;
- if (!IsLegalName(option) || !IsLegalValue(value)) {
- return false;
- }
- options_[option] = value;
- return true;
-}
-
-bool OptionsFile::SetIntValue(const std::string& option,
- int value) {
- LOG(LS_VERBOSE) << "OptionsFile::SetIntValue "
- << option << ":" << value;
- if (!IsLegalName(option)) {
- return false;
- }
- return ToString(value, &options_[option]);
-}
-
-bool OptionsFile::RemoveValue(const std::string& option) {
- LOG(LS_VERBOSE) << "OptionsFile::RemoveValue " << option;
- if (!IsLegalName(option)) {
- return false;
- }
- options_.erase(option);
- return true;
-}
-
-} // namespace talk_base
diff --git a/base/optionsfile.h b/base/optionsfile.h
deleted file mode 100644
index 9e5f457..0000000
--- a/base/optionsfile.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_OPTIONSFILE_H_
-#define TALK_BASE_OPTIONSFILE_H_
-
-#include <map>
-#include <string>
-
-namespace talk_base {
-
-// Implements storage of simple options in a text file on disk. This is
-// cross-platform, but it is intended mostly for Linux where there is no
-// first-class options storage system.
-class OptionsFile {
- public:
- OptionsFile(const std::string &path);
-
- // Loads the file from disk, overwriting the in-memory values.
- bool Load();
- // Saves the contents in memory, overwriting the on-disk values.
- bool Save();
-
- bool GetStringValue(const std::string& option, std::string* out_val) const;
- bool GetIntValue(const std::string& option, int* out_val) const;
- bool SetStringValue(const std::string& option, const std::string& val);
- bool SetIntValue(const std::string& option, int val);
- bool RemoveValue(const std::string& option);
-
- private:
- typedef std::map<std::string, std::string> OptionsMap;
-
- static bool IsLegalName(const std::string &name);
- static bool IsLegalValue(const std::string &value);
-
- std::string path_;
- OptionsMap options_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_OPTIONSFILE_H_
diff --git a/base/optionsfile_unittest.cc b/base/optionsfile_unittest.cc
deleted file mode 100644
index afb79cf..0000000
--- a/base/optionsfile_unittest.cc
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/optionsfile.h"
-#include "talk/base/pathutils.h"
-
-namespace talk_base {
-
-static const std::string kTestOptionA = "test-option-a";
-static const std::string kTestOptionB = "test-option-b";
-static const std::string kTestString1 = "a string";
-static const std::string kTestString2 = "different string";
-static const std::string kOptionWithEquals = "foo=bar";
-static const std::string kOptionWithNewline = "foo\nbar";
-static const std::string kValueWithEquals = "baz=quux";
-static const std::string kValueWithNewline = "baz\nquux";
-static const std::string kEmptyString = "";
-static const char kOptionWithUtf8[] = {'O', 'p', 't', '\302', '\256', 'i', 'o',
- 'n', '\342', '\204', '\242', '\0'}; // Opt(R)io(TM).
-static const char kValueWithUtf8[] = {'V', 'a', 'l', '\302', '\256', 'v', 'e',
- '\342', '\204', '\242', '\0'}; // Val(R)ue(TM).
-static int kTestInt1 = 12345;
-static int kTestInt2 = 67890;
-static int kNegInt = -634;
-static int kZero = 0;
-
-class OptionsFileTest : public testing::Test {
- public:
- OptionsFileTest() {
- Pathname dir;
- ASSERT(Filesystem::GetTemporaryFolder(dir, true, NULL));
- test_file_ = Filesystem::TempFilename(dir, ".testfile");
- OpenStore();
- }
-
- protected:
- void OpenStore() {
- store_.reset(new OptionsFile(test_file_));
- }
-
- talk_base::scoped_ptr<OptionsFile> store_;
-
- private:
- std::string test_file_;
-};
-
-TEST_F(OptionsFileTest, GetSetString) {
- // Clear contents of the file on disk.
- EXPECT_TRUE(store_->Save());
- std::string out1, out2;
- EXPECT_FALSE(store_->GetStringValue(kTestOptionA, &out1));
- EXPECT_FALSE(store_->GetStringValue(kTestOptionB, &out2));
- EXPECT_TRUE(store_->SetStringValue(kTestOptionA, kTestString1));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->SetStringValue(kTestOptionB, kTestString2));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->GetStringValue(kTestOptionA, &out1));
- EXPECT_TRUE(store_->GetStringValue(kTestOptionB, &out2));
- EXPECT_EQ(kTestString1, out1);
- EXPECT_EQ(kTestString2, out2);
- EXPECT_TRUE(store_->RemoveValue(kTestOptionA));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->RemoveValue(kTestOptionB));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_FALSE(store_->GetStringValue(kTestOptionA, &out1));
- EXPECT_FALSE(store_->GetStringValue(kTestOptionB, &out2));
-}
-
-TEST_F(OptionsFileTest, GetSetInt) {
- // Clear contents of the file on disk.
- EXPECT_TRUE(store_->Save());
- int out1, out2;
- EXPECT_FALSE(store_->GetIntValue(kTestOptionA, &out1));
- EXPECT_FALSE(store_->GetIntValue(kTestOptionB, &out2));
- EXPECT_TRUE(store_->SetIntValue(kTestOptionA, kTestInt1));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->SetIntValue(kTestOptionB, kTestInt2));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->GetIntValue(kTestOptionA, &out1));
- EXPECT_TRUE(store_->GetIntValue(kTestOptionB, &out2));
- EXPECT_EQ(kTestInt1, out1);
- EXPECT_EQ(kTestInt2, out2);
- EXPECT_TRUE(store_->RemoveValue(kTestOptionA));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->RemoveValue(kTestOptionB));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_FALSE(store_->GetIntValue(kTestOptionA, &out1));
- EXPECT_FALSE(store_->GetIntValue(kTestOptionB, &out2));
- EXPECT_TRUE(store_->SetIntValue(kTestOptionA, kNegInt));
- EXPECT_TRUE(store_->GetIntValue(kTestOptionA, &out1));
- EXPECT_EQ(kNegInt, out1);
- EXPECT_TRUE(store_->SetIntValue(kTestOptionA, kZero));
- EXPECT_TRUE(store_->GetIntValue(kTestOptionA, &out1));
- EXPECT_EQ(kZero, out1);
-}
-
-TEST_F(OptionsFileTest, Persist) {
- // Clear contents of the file on disk.
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->SetStringValue(kTestOptionA, kTestString1));
- EXPECT_TRUE(store_->SetIntValue(kTestOptionB, kNegInt));
- EXPECT_TRUE(store_->Save());
-
- // Load the saved contents from above.
- OpenStore();
- EXPECT_TRUE(store_->Load());
- std::string out1;
- int out2;
- EXPECT_TRUE(store_->GetStringValue(kTestOptionA, &out1));
- EXPECT_TRUE(store_->GetIntValue(kTestOptionB, &out2));
- EXPECT_EQ(kTestString1, out1);
- EXPECT_EQ(kNegInt, out2);
-}
-
-TEST_F(OptionsFileTest, SpecialCharacters) {
- // Clear contents of the file on disk.
- EXPECT_TRUE(store_->Save());
- std::string out;
- EXPECT_FALSE(store_->SetStringValue(kOptionWithEquals, kTestString1));
- EXPECT_FALSE(store_->GetStringValue(kOptionWithEquals, &out));
- EXPECT_FALSE(store_->SetStringValue(kOptionWithNewline, kTestString1));
- EXPECT_FALSE(store_->GetStringValue(kOptionWithNewline, &out));
- EXPECT_TRUE(store_->SetStringValue(kOptionWithUtf8, kValueWithUtf8));
- EXPECT_TRUE(store_->SetStringValue(kTestOptionA, kTestString1));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->GetStringValue(kTestOptionA, &out));
- EXPECT_EQ(kTestString1, out);
- EXPECT_TRUE(store_->GetStringValue(kOptionWithUtf8, &out));
- EXPECT_EQ(kValueWithUtf8, out);
- EXPECT_FALSE(store_->SetStringValue(kTestOptionA, kValueWithNewline));
- EXPECT_TRUE(store_->GetStringValue(kTestOptionA, &out));
- EXPECT_EQ(kTestString1, out);
- EXPECT_TRUE(store_->SetStringValue(kTestOptionA, kValueWithEquals));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->GetStringValue(kTestOptionA, &out));
- EXPECT_EQ(kValueWithEquals, out);
- EXPECT_TRUE(store_->SetStringValue(kEmptyString, kTestString2));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->GetStringValue(kEmptyString, &out));
- EXPECT_EQ(kTestString2, out);
- EXPECT_TRUE(store_->SetStringValue(kTestOptionB, kEmptyString));
- EXPECT_TRUE(store_->Save());
- EXPECT_TRUE(store_->Load());
- EXPECT_TRUE(store_->GetStringValue(kTestOptionB, &out));
- EXPECT_EQ(kEmptyString, out);
-}
-
-} // namespace talk_base
diff --git a/base/pathutils.cc b/base/pathutils.cc
deleted file mode 100644
index 02aba7f..0000000
--- a/base/pathutils.cc
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#include <shellapi.h>
-#include <shlobj.h>
-#include <tchar.h>
-#endif // WIN32
-
-#include "talk/base/common.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/urlencode.h"
-
-namespace talk_base {
-
-static const char EMPTY_STR[] = "";
-
-// EXT_DELIM separates a file basename from extension
-const char EXT_DELIM = '.';
-
-// FOLDER_DELIMS separate folder segments and the filename
-const char* const FOLDER_DELIMS = "/\\";
-
-// DEFAULT_FOLDER_DELIM is the preferred delimiter for this platform
-#if WIN32
-const char DEFAULT_FOLDER_DELIM = '\\';
-#else // !WIN32
-const char DEFAULT_FOLDER_DELIM = '/';
-#endif // !WIN32
-
-///////////////////////////////////////////////////////////////////////////////
-// Pathname - parsing of pathnames into components, and vice versa
-///////////////////////////////////////////////////////////////////////////////
-
-bool Pathname::IsFolderDelimiter(char ch) {
- return (NULL != ::strchr(FOLDER_DELIMS, ch));
-}
-
-char Pathname::DefaultFolderDelimiter() {
- return DEFAULT_FOLDER_DELIM;
-}
-
-Pathname::Pathname()
- : folder_delimiter_(DEFAULT_FOLDER_DELIM) {
-}
-
-Pathname::Pathname(const std::string& pathname)
- : folder_delimiter_(DEFAULT_FOLDER_DELIM) {
- SetPathname(pathname);
-}
-
-Pathname::Pathname(const std::string& folder, const std::string& filename)
- : folder_delimiter_(DEFAULT_FOLDER_DELIM) {
- SetPathname(folder, filename);
-}
-
-void Pathname::SetFolderDelimiter(char delimiter) {
- ASSERT(IsFolderDelimiter(delimiter));
- folder_delimiter_ = delimiter;
-}
-
-void Pathname::Normalize() {
- for (size_t i=0; i<folder_.length(); ++i) {
- if (IsFolderDelimiter(folder_[i])) {
- folder_[i] = folder_delimiter_;
- }
- }
-}
-
-void Pathname::clear() {
- folder_.clear();
- basename_.clear();
- extension_.clear();
-}
-
-bool Pathname::empty() const {
- return folder_.empty() && basename_.empty() && extension_.empty();
-}
-
-std::string Pathname::pathname() const {
- std::string pathname(folder_);
- pathname.append(basename_);
- pathname.append(extension_);
- if (pathname.empty()) {
- // Instead of the empty pathname, return the current working directory.
- pathname.push_back('.');
- pathname.push_back(folder_delimiter_);
- }
- return pathname;
-}
-
-std::string Pathname::url() const {
- std::string s = "file:///";
- for (size_t i=0; i<folder_.length(); ++i) {
- if (IsFolderDelimiter(folder_[i]))
- s += '/';
- else
- s += folder_[i];
- }
- s += basename_;
- s += extension_;
- return UrlEncodeStringForOnlyUnsafeChars(s);
-}
-
-void Pathname::SetPathname(const std::string& pathname) {
- std::string::size_type pos = pathname.find_last_of(FOLDER_DELIMS);
- if (pos != std::string::npos) {
- SetFolder(pathname.substr(0, pos + 1));
- SetFilename(pathname.substr(pos + 1));
- } else {
- SetFolder(EMPTY_STR);
- SetFilename(pathname);
- }
-}
-
-void Pathname::SetPathname(const std::string& folder,
- const std::string& filename) {
- SetFolder(folder);
- SetFilename(filename);
-}
-
-void Pathname::AppendPathname(const std::string& pathname) {
- std::string full_pathname(folder_);
- full_pathname.append(pathname);
- SetPathname(full_pathname);
-}
-
-std::string Pathname::folder() const {
- return folder_;
-}
-
-std::string Pathname::folder_name() const {
- std::string::size_type pos = std::string::npos;
- if (folder_.size() >= 2) {
- pos = folder_.find_last_of(FOLDER_DELIMS, folder_.length() - 2);
- }
- if (pos != std::string::npos) {
- return folder_.substr(pos + 1);
- } else {
- return folder_;
- }
-}
-
-std::string Pathname::parent_folder() const {
- std::string::size_type pos = std::string::npos;
- if (folder_.size() >= 2) {
- pos = folder_.find_last_of(FOLDER_DELIMS, folder_.length() - 2);
- }
- if (pos != std::string::npos) {
- return folder_.substr(0, pos + 1);
- } else {
- return EMPTY_STR;
- }
-}
-
-void Pathname::SetFolder(const std::string& folder) {
- folder_.assign(folder);
- // Ensure folder ends in a path delimiter
- if (!folder_.empty() && !IsFolderDelimiter(folder_[folder_.length()-1])) {
- folder_.push_back(folder_delimiter_);
- }
-}
-
-void Pathname::AppendFolder(const std::string& folder) {
- folder_.append(folder);
- // Ensure folder ends in a path delimiter
- if (!folder_.empty() && !IsFolderDelimiter(folder_[folder_.length()-1])) {
- folder_.push_back(folder_delimiter_);
- }
-}
-
-std::string Pathname::basename() const {
- return basename_;
-}
-
-bool Pathname::SetBasename(const std::string& basename) {
- if(basename.find_first_of(FOLDER_DELIMS) != std::string::npos) {
- return false;
- }
- basename_.assign(basename);
- return true;
-}
-
-std::string Pathname::extension() const {
- return extension_;
-}
-
-bool Pathname::SetExtension(const std::string& extension) {
- if (extension.find_first_of(FOLDER_DELIMS) != std::string::npos ||
- extension.find_first_of(EXT_DELIM, 1) != std::string::npos) {
- return false;
- }
- extension_.assign(extension);
- // Ensure extension begins with the extension delimiter
- if (!extension_.empty() && (extension_[0] != EXT_DELIM)) {
- extension_.insert(extension_.begin(), EXT_DELIM);
- }
- return true;
-}
-
-std::string Pathname::filename() const {
- std::string filename(basename_);
- filename.append(extension_);
- return filename;
-}
-
-bool Pathname::SetFilename(const std::string& filename) {
- std::string::size_type pos = filename.rfind(EXT_DELIM);
- if ((pos == std::string::npos) || (pos == 0)) {
- return SetExtension(EMPTY_STR) && SetBasename(filename);
- } else {
- return SetExtension(filename.substr(pos)) && SetBasename(filename.substr(0, pos));
- }
-}
-
-#ifdef WIN32
-bool Pathname::GetDrive(char *drive, uint32 bytes) const {
- return GetDrive(drive, bytes, folder_);
-}
-
-// static
-bool Pathname::GetDrive(char *drive, uint32 bytes,
- const std::string& pathname) {
- // need at lease 4 bytes to save c:
- if (bytes < 4 || pathname.size() < 3) {
- return false;
- }
-
- memcpy(drive, pathname.c_str(), 3);
- drive[3] = 0;
- // sanity checking
- return (isalpha(drive[0]) &&
- drive[1] == ':' &&
- drive[2] == '\\');
-}
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/pathutils.h b/base/pathutils.h
deleted file mode 100644
index ab2aacd..0000000
--- a/base/pathutils.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_PATHUTILS_H__
-#define TALK_BASE_PATHUTILS_H__
-
-#include <string>
-// Temporary, until deprecated helpers are removed.
-#include "talk/base/fileutils.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// Pathname - parsing of pathnames into components, and vice versa.
-//
-// To establish consistent terminology, a filename never contains a folder
-// component. A folder never contains a filename. A pathname may include
-// a folder and/or filename component. Here are some examples:
-//
-// pathname() /home/john/example.txt
-// folder() /home/john/
-// filename() example.txt
-// parent_folder() /home/
-// folder_name() john/
-// basename() example
-// extension() .txt
-//
-// Basename may begin, end, and/or include periods, but no folder delimiters.
-// If extension exists, it consists of a period followed by zero or more
-// non-period/non-delimiter characters, and basename is non-empty.
-///////////////////////////////////////////////////////////////////////////////
-
-class Pathname {
-public:
- // Folder delimiters are slash and backslash
- static bool IsFolderDelimiter(char ch);
- static char DefaultFolderDelimiter();
-
- Pathname();
- Pathname(const std::string& pathname);
- Pathname(const std::string& folder, const std::string& filename);
-
- // Set's the default folder delimiter for this Pathname
- char folder_delimiter() const { return folder_delimiter_; }
- void SetFolderDelimiter(char delimiter);
-
- // Normalize changes all folder delimiters to folder_delimiter()
- void Normalize();
-
- // Reset to the empty pathname
- void clear();
-
- // Returns true if the pathname is empty. Note: this->pathname().empty()
- // is always false.
- bool empty() const;
-
- std::string url() const;
-
- // Returns the folder and filename components. If the pathname is empty,
- // returns a string representing the current directory (as a relative path,
- // i.e., ".").
- std::string pathname() const;
- void SetPathname(const std::string& pathname);
- void SetPathname(const std::string& folder, const std::string& filename);
-
- // Append pathname to the current folder (if any). Any existing filename
- // will be discarded.
- void AppendPathname(const std::string& pathname);
-
- std::string folder() const;
- std::string folder_name() const;
- std::string parent_folder() const;
- // SetFolder and AppendFolder will append a folder delimiter, if needed.
- void SetFolder(const std::string& folder);
- void AppendFolder(const std::string& folder);
-
- std::string basename() const;
- bool SetBasename(const std::string& basename);
-
- std::string extension() const;
- // SetExtension will prefix a period, if needed.
- bool SetExtension(const std::string& extension);
-
- std::string filename() const;
- bool SetFilename(const std::string& filename);
-
-#ifdef WIN32
- bool GetDrive(char *drive, uint32 bytes) const;
- static bool GetDrive(char *drive, uint32 bytes,const std::string& pathname);
-#endif
-
-private:
- std::string folder_, basename_, extension_;
- char folder_delimiter_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Global Helpers (deprecated)
-///////////////////////////////////////////////////////////////////////////////
-
-inline void SetOrganizationName(const std::string& organization) {
- Filesystem::SetOrganizationName(organization);
-}
-inline void SetApplicationName(const std::string& application) {
- Filesystem::SetApplicationName(application);
-}
-inline void GetOrganizationName(std::string* organization) {
- Filesystem::GetOrganizationName(organization);
-}
-inline void GetApplicationName(std::string* application) {
- Filesystem::GetApplicationName(application);
-}
-inline bool CreateFolder(const Pathname& path) {
- return Filesystem::CreateFolder(path);
-}
-inline bool FinishPath(Pathname& path, bool create, const std::string& append) {
- if (!append.empty())
- path.AppendFolder(append);
- return !create || CreateFolder(path);
-}
-// Note: this method uses the convention of <temp>/<appname> for the temporary
-// folder. Filesystem uses <temp>/<exename>. We will be migrating exclusively
-// to <temp>/<orgname>/<appname> eventually. Since these are temp folders,
-// it's probably ok to orphan them during the transition.
-inline bool GetTemporaryFolder(Pathname& path, bool create,
- const std::string& append) {
- std::string application_name;
- Filesystem::GetApplicationName(&application_name);
- ASSERT(!application_name.empty());
- return Filesystem::GetTemporaryFolder(path, create, &application_name)
- && FinishPath(path, create, append);
-}
-inline bool GetAppDataFolder(Pathname& path, bool create,
- const std::string& append) {
- ASSERT(!create); // TODO: Support create flag on Filesystem::GetAppDataFolder.
- return Filesystem::GetAppDataFolder(&path, true)
- && FinishPath(path, create, append);
-}
-inline bool CleanupTemporaryFolder() {
- Pathname path;
- if (!GetTemporaryFolder(path, false, ""))
- return false;
- if (Filesystem::IsAbsent(path))
- return true;
- if (!Filesystem::IsTemporaryPath(path)) {
- ASSERT(false);
- return false;
- }
- return Filesystem::DeleteFolderContents(path);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_PATHUTILS_H__
diff --git a/base/pathutils_unittest.cc b/base/pathutils_unittest.cc
deleted file mode 100644
index 0a9739b..0000000
--- a/base/pathutils_unittest.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * libjingle
- * Copyright 2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/pathutils.h"
-#include "talk/base/gunit.h"
-
-TEST(Pathname, ReturnsDotForEmptyPathname) {
- const std::string kCWD =
- std::string(".") + talk_base::Pathname::DefaultFolderDelimiter();
-
- talk_base::Pathname path("/", "");
- EXPECT_FALSE(path.empty());
- EXPECT_FALSE(path.folder().empty());
- EXPECT_TRUE (path.filename().empty());
- EXPECT_FALSE(path.pathname().empty());
- EXPECT_EQ(std::string("/"), path.pathname());
-
- path.SetPathname("", "foo");
- EXPECT_FALSE(path.empty());
- EXPECT_TRUE (path.folder().empty());
- EXPECT_FALSE(path.filename().empty());
- EXPECT_FALSE(path.pathname().empty());
- EXPECT_EQ(std::string("foo"), path.pathname());
-
- path.SetPathname("", "");
- EXPECT_TRUE (path.empty());
- EXPECT_TRUE (path.folder().empty());
- EXPECT_TRUE (path.filename().empty());
- EXPECT_FALSE(path.pathname().empty());
- EXPECT_EQ(kCWD, path.pathname());
-
- path.SetPathname(kCWD, "");
- EXPECT_FALSE(path.empty());
- EXPECT_FALSE(path.folder().empty());
- EXPECT_TRUE (path.filename().empty());
- EXPECT_FALSE(path.pathname().empty());
- EXPECT_EQ(kCWD, path.pathname());
-
- talk_base::Pathname path2("c:/foo bar.txt");
- EXPECT_EQ(path2.url(), std::string("file:///c:/foo%20bar.txt"));
-}
diff --git a/base/physicalsocketserver.cc b/base/physicalsocketserver.cc
deleted file mode 100644
index a7f65c5..0000000
--- a/base/physicalsocketserver.cc
+++ /dev/null
@@ -1,1676 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if defined(_MSC_VER) && _MSC_VER < 1300
-#pragma warning(disable:4786)
-#endif
-
-#include <assert.h>
-
-#ifdef POSIX
-#include <string.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/time.h>
-#include <sys/select.h>
-#include <unistd.h>
-#include <signal.h>
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#undef SetPort
-#endif
-
-#include <algorithm>
-#include <map>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/timeutils.h"
-#include "talk/base/winping.h"
-#include "talk/base/win32socketinit.h"
-
-// stm: this will tell us if we are on OSX
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef POSIX
-#include <netinet/tcp.h> // for TCP_NODELAY
-#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
-typedef void* SockOptArg;
-#endif // POSIX
-
-#ifdef WIN32
-typedef char* SockOptArg;
-#endif
-
-namespace talk_base {
-
-#if defined(WIN32)
-// Standard MTUs, from RFC 1191
-const uint16 PACKET_MAXIMUMS[] = {
- 65535, // Theoretical maximum, Hyperchannel
- 32000, // Nothing
- 17914, // 16Mb IBM Token Ring
- 8166, // IEEE 802.4
- //4464, // IEEE 802.5 (4Mb max)
- 4352, // FDDI
- //2048, // Wideband Network
- 2002, // IEEE 802.5 (4Mb recommended)
- //1536, // Expermental Ethernet Networks
- //1500, // Ethernet, Point-to-Point (default)
- 1492, // IEEE 802.3
- 1006, // SLIP, ARPANET
- //576, // X.25 Networks
- //544, // DEC IP Portal
- //512, // NETBIOS
- 508, // IEEE 802/Source-Rt Bridge, ARCNET
- 296, // Point-to-Point (low delay)
- 68, // Official minimum
- 0, // End of list marker
-};
-
-static const int IP_HEADER_SIZE = 20u;
-static const int IPV6_HEADER_SIZE = 40u;
-static const int ICMP_HEADER_SIZE = 8u;
-static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
-#endif
-
-class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
- public:
- PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET)
- : ss_(ss), s_(s), enabled_events_(0), error_(0),
- state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
- resolver_(NULL) {
-#ifdef WIN32
- // EnsureWinsockInit() ensures that winsock is initialized. The default
- // version of this function doesn't do anything because winsock is
- // initialized by constructor of a static object. If neccessary libjingle
- // users can link it with a different version of this function by replacing
- // win32socketinit.cc. See win32socketinit.cc for more details.
- EnsureWinsockInit();
-#endif
- if (s_ != INVALID_SOCKET) {
- enabled_events_ = DE_READ | DE_WRITE;
-
- int type = SOCK_STREAM;
- socklen_t len = sizeof(type);
- VERIFY(0 == getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len));
- udp_ = (SOCK_DGRAM == type);
- }
- }
-
- virtual ~PhysicalSocket() {
- Close();
- }
-
- // Creates the underlying OS socket (same as the "socket" function).
- virtual bool Create(int family, int type) {
- Close();
- s_ = ::socket(family, type, 0);
- udp_ = (SOCK_DGRAM == type);
- UpdateLastError();
- if (udp_)
- enabled_events_ = DE_READ | DE_WRITE;
- return s_ != INVALID_SOCKET;
- }
-
- SocketAddress GetLocalAddress() const {
- sockaddr_storage addr_storage = {0};
- socklen_t addrlen = sizeof(addr_storage);
- sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
- int result = ::getsockname(s_, addr, &addrlen);
- SocketAddress address;
- if (result >= 0) {
- SocketAddressFromSockAddrStorage(addr_storage, &address);
- } else {
- LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
- << s_;
- }
- return address;
- }
-
- SocketAddress GetRemoteAddress() const {
- sockaddr_storage addr_storage = {0};
- socklen_t addrlen = sizeof(addr_storage);
- sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
- int result = ::getpeername(s_, addr, &addrlen);
- SocketAddress address;
- if (result >= 0) {
- SocketAddressFromSockAddrStorage(addr_storage, &address);
- } else {
- LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
- << s_;
- }
- return address;
- }
-
- int Bind(const SocketAddress& bind_addr) {
- sockaddr_storage addr_storage;
- size_t len = bind_addr.ToSockAddrStorage(&addr_storage);
- sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
- int err = ::bind(s_, addr, static_cast<int>(len));
- UpdateLastError();
-#ifdef _DEBUG
- if (0 == err) {
- dbg_addr_ = "Bound @ ";
- dbg_addr_.append(GetLocalAddress().ToString());
- }
-#endif // _DEBUG
- return err;
- }
-
- int Connect(const SocketAddress& addr) {
- // TODO: Implicit creation is required to reconnect...
- // ...but should we make it more explicit?
- if (state_ != CS_CLOSED) {
- SetError(EALREADY);
- return SOCKET_ERROR;
- }
- if (addr.IsUnresolved()) {
- LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
- resolver_ = new AsyncResolver();
- resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
- resolver_->Start(addr);
- state_ = CS_CONNECTING;
- return 0;
- }
-
- return DoConnect(addr);
- }
-
- int DoConnect(const SocketAddress& connect_addr) {
- if ((s_ == INVALID_SOCKET) &&
- !Create(connect_addr.family(), SOCK_STREAM)) {
- return SOCKET_ERROR;
- }
- sockaddr_storage addr_storage;
- size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
- sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
- int err = ::connect(s_, addr, static_cast<int>(len));
- UpdateLastError();
- if (err == 0) {
- state_ = CS_CONNECTED;
- } else if (IsBlockingError(GetError())) {
- state_ = CS_CONNECTING;
- enabled_events_ |= DE_CONNECT;
- } else {
- return SOCKET_ERROR;
- }
-
- enabled_events_ |= DE_READ | DE_WRITE;
- return 0;
- }
-
- int GetError() const {
- CritScope cs(&crit_);
- return error_;
- }
-
- void SetError(int error) {
- CritScope cs(&crit_);
- error_ = error;
- }
-
- ConnState GetState() const {
- return state_;
- }
-
- int GetOption(Option opt, int* value) {
- int slevel;
- int sopt;
- if (TranslateOption(opt, &slevel, &sopt) == -1)
- return -1;
- socklen_t optlen = sizeof(*value);
- int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
- if (ret != -1 && opt == OPT_DONTFRAGMENT) {
-#ifdef LINUX
- *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
-#endif
- }
- return ret;
- }
-
- int SetOption(Option opt, int value) {
- int slevel;
- int sopt;
- if (TranslateOption(opt, &slevel, &sopt) == -1)
- return -1;
- if (opt == OPT_DONTFRAGMENT) {
-#ifdef LINUX
- value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
-#endif
- }
- return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
- }
-
- int Send(const void *pv, size_t cb) {
- int sent = ::send(s_, reinterpret_cast<const char *>(pv), (int)cb,
-#ifdef LINUX
- // Suppress SIGPIPE. Without this, attempting to send on a socket whose
- // other end is closed will result in a SIGPIPE signal being raised to
- // our process, which by default will terminate the process, which we
- // don't want. By specifying this flag, we'll just get the error EPIPE
- // instead and can handle the error gracefully.
- MSG_NOSIGNAL
-#else
- 0
-#endif
- );
- UpdateLastError();
- MaybeRemapSendError();
- // We have seen minidumps where this may be false.
- ASSERT(sent <= static_cast<int>(cb));
- if ((sent < 0) && IsBlockingError(GetError())) {
- enabled_events_ |= DE_WRITE;
- }
- return sent;
- }
-
- int SendTo(const void* buffer, size_t length, const SocketAddress& addr) {
- sockaddr_storage saddr;
- size_t len = addr.ToSockAddrStorage(&saddr);
- int sent = ::sendto(
- s_, static_cast<const char *>(buffer), static_cast<int>(length),
-#ifdef LINUX
- // Suppress SIGPIPE. See above for explanation.
- MSG_NOSIGNAL,
-#else
- 0,
-#endif
- reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
- UpdateLastError();
- MaybeRemapSendError();
- // We have seen minidumps where this may be false.
- ASSERT(sent <= static_cast<int>(length));
- if ((sent < 0) && IsBlockingError(GetError())) {
- enabled_events_ |= DE_WRITE;
- }
- return sent;
- }
-
- int Recv(void* buffer, size_t length) {
- int received = ::recv(s_, static_cast<char*>(buffer),
- static_cast<int>(length), 0);
- if ((received == 0) && (length != 0)) {
- // Note: on graceful shutdown, recv can return 0. In this case, we
- // pretend it is blocking, and then signal close, so that simplifying
- // assumptions can be made about Recv.
- LOG(LS_WARNING) << "EOF from socket; deferring close event";
- // Must turn this back on so that the select() loop will notice the close
- // event.
- enabled_events_ |= DE_READ;
- SetError(EWOULDBLOCK);
- return SOCKET_ERROR;
- }
- UpdateLastError();
- int error = GetError();
- bool success = (received >= 0) || IsBlockingError(error);
- if (udp_ || success) {
- enabled_events_ |= DE_READ;
- }
- if (!success) {
- LOG_F(LS_VERBOSE) << "Error = " << error;
- }
- return received;
- }
-
- int RecvFrom(void* buffer, size_t length, SocketAddress *out_addr) {
- sockaddr_storage addr_storage;
- socklen_t addr_len = sizeof(addr_storage);
- sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
- int received = ::recvfrom(s_, static_cast<char*>(buffer),
- static_cast<int>(length), 0, addr, &addr_len);
- UpdateLastError();
- if ((received >= 0) && (out_addr != NULL))
- SocketAddressFromSockAddrStorage(addr_storage, out_addr);
- int error = GetError();
- bool success = (received >= 0) || IsBlockingError(error);
- if (udp_ || success) {
- enabled_events_ |= DE_READ;
- }
- if (!success) {
- LOG_F(LS_VERBOSE) << "Error = " << error;
- }
- return received;
- }
-
- int Listen(int backlog) {
- int err = ::listen(s_, backlog);
- UpdateLastError();
- if (err == 0) {
- state_ = CS_CONNECTING;
- enabled_events_ |= DE_ACCEPT;
-#ifdef _DEBUG
- dbg_addr_ = "Listening @ ";
- dbg_addr_.append(GetLocalAddress().ToString());
-#endif // _DEBUG
- }
- return err;
- }
-
- AsyncSocket* Accept(SocketAddress *out_addr) {
- sockaddr_storage addr_storage;
- socklen_t addr_len = sizeof(addr_storage);
- sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
- SOCKET s = ::accept(s_, addr, &addr_len);
- UpdateLastError();
- if (s == INVALID_SOCKET)
- return NULL;
- enabled_events_ |= DE_ACCEPT;
- if (out_addr != NULL)
- SocketAddressFromSockAddrStorage(addr_storage, out_addr);
- return ss_->WrapSocket(s);
- }
-
- int Close() {
- if (s_ == INVALID_SOCKET)
- return 0;
- int err = ::closesocket(s_);
- UpdateLastError();
- s_ = INVALID_SOCKET;
- state_ = CS_CLOSED;
- enabled_events_ = 0;
- if (resolver_) {
- resolver_->Destroy(false);
- resolver_ = NULL;
- }
- return err;
- }
-
- int EstimateMTU(uint16* mtu) {
- SocketAddress addr = GetRemoteAddress();
- if (addr.IsAny()) {
- SetError(ENOTCONN);
- return -1;
- }
-
-#if defined(WIN32)
- // Gets the interface MTU (TTL=1) for the interface used to reach |addr|.
- WinPing ping;
- if (!ping.IsValid()) {
- SetError(EINVAL); // can't think of a better error ID
- return -1;
- }
- int header_size = ICMP_HEADER_SIZE;
- if (addr.family() == AF_INET6) {
- header_size += IPV6_HEADER_SIZE;
- } else if (addr.family() == AF_INET) {
- header_size += IP_HEADER_SIZE;
- }
-
- for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
- int32 size = PACKET_MAXIMUMS[level] - header_size;
- WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
- ICMP_PING_TIMEOUT_MILLIS,
- 1, false);
- if (result == WinPing::PING_FAIL) {
- SetError(EINVAL); // can't think of a better error ID
- return -1;
- } else if (result != WinPing::PING_TOO_LARGE) {
- *mtu = PACKET_MAXIMUMS[level];
- return 0;
- }
- }
-
- ASSERT(false);
- return -1;
-#elif defined(IOS) || defined(OSX)
- // No simple way to do this on Mac OS X.
- // SIOCGIFMTU would work if we knew which interface would be used, but
- // figuring that out is pretty complicated. For now we'll return an error
- // and let the caller pick a default MTU.
- SetError(EINVAL);
- return -1;
-#elif defined(LINUX) || defined(ANDROID)
- // Gets the path MTU.
- int value;
- socklen_t vlen = sizeof(value);
- int err = getsockopt(s_, IPPROTO_IP, IP_MTU, &value, &vlen);
- if (err < 0) {
- UpdateLastError();
- return err;
- }
-
- ASSERT((0 <= value) && (value <= 65536));
- *mtu = value;
- return 0;
-#elif defined(__native_client__)
- // Most socket operations, including this, will fail in NaCl's sandbox.
- error_ = EACCES;
- return -1;
-#endif
- }
-
- SocketServer* socketserver() { return ss_; }
-
- protected:
- void OnResolveResult(AsyncResolverInterface* resolver) {
- if (resolver != resolver_) {
- return;
- }
-
- int error = resolver_->GetError();
- if (error == 0) {
- error = DoConnect(resolver_->address());
- } else {
- Close();
- }
-
- if (error) {
- SetError(error);
- SignalCloseEvent(this, error);
- }
- }
-
- void UpdateLastError() {
- SetError(LAST_SYSTEM_ERROR);
- }
-
- void MaybeRemapSendError() {
-#if defined(OSX) || defined(IOS)
- // https://developer.apple.com/library/mac/documentation/Darwin/
- // Reference/ManPages/man2/sendto.2.html
- // ENOBUFS - The output queue for a network interface is full.
- // This generally indicates that the interface has stopped sending,
- // but may be caused by transient congestion.
- if (GetError() == ENOBUFS) {
- SetError(EWOULDBLOCK);
- }
-#endif
- }
-
- static int TranslateOption(Option opt, int* slevel, int* sopt) {
- switch (opt) {
- case OPT_DONTFRAGMENT:
-#ifdef WIN32
- *slevel = IPPROTO_IP;
- *sopt = IP_DONTFRAGMENT;
- break;
-#elif defined(IOS) || defined(OSX) || defined(BSD) || defined(__native_client__)
- LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
- return -1;
-#elif defined(POSIX)
- *slevel = IPPROTO_IP;
- *sopt = IP_MTU_DISCOVER;
- break;
-#endif
- case OPT_RCVBUF:
- *slevel = SOL_SOCKET;
- *sopt = SO_RCVBUF;
- break;
- case OPT_SNDBUF:
- *slevel = SOL_SOCKET;
- *sopt = SO_SNDBUF;
- break;
- case OPT_NODELAY:
- *slevel = IPPROTO_TCP;
- *sopt = TCP_NODELAY;
- break;
- case OPT_DSCP:
- LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
- return -1;
- case OPT_RTP_SENDTIME_EXTN_ID:
- return -1; // No logging is necessary as this not a OS socket option.
- default:
- ASSERT(false);
- return -1;
- }
- return 0;
- }
-
- PhysicalSocketServer* ss_;
- SOCKET s_;
- uint8 enabled_events_;
- bool udp_;
- int error_;
- // Protects |error_| that is accessed from different threads.
- mutable CriticalSection crit_;
- ConnState state_;
- AsyncResolver* resolver_;
-
-#ifdef _DEBUG
- std::string dbg_addr_;
-#endif // _DEBUG;
-};
-
-#ifdef POSIX
-class EventDispatcher : public Dispatcher {
- public:
- EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
- if (pipe(afd_) < 0)
- LOG(LERROR) << "pipe failed";
- ss_->Add(this);
- }
-
- virtual ~EventDispatcher() {
- ss_->Remove(this);
- close(afd_[0]);
- close(afd_[1]);
- }
-
- virtual void Signal() {
- CritScope cs(&crit_);
- if (!fSignaled_) {
- const uint8 b[1] = { 0 };
- if (VERIFY(1 == write(afd_[1], b, sizeof(b)))) {
- fSignaled_ = true;
- }
- }
- }
-
- virtual uint32 GetRequestedEvents() {
- return DE_READ;
- }
-
- virtual void OnPreEvent(uint32 ff) {
- // It is not possible to perfectly emulate an auto-resetting event with
- // pipes. This simulates it by resetting before the event is handled.
-
- CritScope cs(&crit_);
- if (fSignaled_) {
- uint8 b[4]; // Allow for reading more than 1 byte, but expect 1.
- VERIFY(1 == read(afd_[0], b, sizeof(b)));
- fSignaled_ = false;
- }
- }
-
- virtual void OnEvent(uint32 ff, int err) {
- ASSERT(false);
- }
-
- virtual int GetDescriptor() {
- return afd_[0];
- }
-
- virtual bool IsDescriptorClosed() {
- return false;
- }
-
- private:
- PhysicalSocketServer *ss_;
- int afd_[2];
- bool fSignaled_;
- CriticalSection crit_;
-};
-
-// These two classes use the self-pipe trick to deliver POSIX signals to our
-// select loop. This is the only safe, reliable, cross-platform way to do
-// non-trivial things with a POSIX signal in an event-driven program (until
-// proper pselect() implementations become ubiquitous).
-
-class PosixSignalHandler {
- public:
- // POSIX only specifies 32 signals, but in principle the system might have
- // more and the programmer might choose to use them, so we size our array
- // for 128.
- static const int kNumPosixSignals = 128;
-
- // There is just a single global instance. (Signal handlers do not get any
- // sort of user-defined void * parameter, so they can't access anything that
- // isn't global.)
- static PosixSignalHandler* Instance() {
- LIBJINGLE_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
- return &instance;
- }
-
- // Returns true if the given signal number is set.
- bool IsSignalSet(int signum) const {
- ASSERT(signum < ARRAY_SIZE(received_signal_));
- if (signum < ARRAY_SIZE(received_signal_)) {
- return received_signal_[signum];
- } else {
- return false;
- }
- }
-
- // Clears the given signal number.
- void ClearSignal(int signum) {
- ASSERT(signum < ARRAY_SIZE(received_signal_));
- if (signum < ARRAY_SIZE(received_signal_)) {
- received_signal_[signum] = false;
- }
- }
-
- // Returns the file descriptor to monitor for signal events.
- int GetDescriptor() const {
- return afd_[0];
- }
-
- // This is called directly from our real signal handler, so it must be
- // signal-handler-safe. That means it cannot assume anything about the
- // user-level state of the process, since the handler could be executed at any
- // time on any thread.
- void OnPosixSignalReceived(int signum) {
- if (signum >= ARRAY_SIZE(received_signal_)) {
- // We don't have space in our array for this.
- return;
- }
- // Set a flag saying we've seen this signal.
- received_signal_[signum] = true;
- // Notify application code that we got a signal.
- const uint8 b[1] = { 0 };
- if (-1 == write(afd_[1], b, sizeof(b))) {
- // Nothing we can do here. If there's an error somehow then there's
- // nothing we can safely do from a signal handler.
- // No, we can't even safely log it.
- // But, we still have to check the return value here. Otherwise,
- // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
- return;
- }
- }
-
- private:
- PosixSignalHandler() {
- if (pipe(afd_) < 0) {
- LOG_ERR(LS_ERROR) << "pipe failed";
- return;
- }
- if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
- LOG_ERR(LS_WARNING) << "fcntl #1 failed";
- }
- if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
- LOG_ERR(LS_WARNING) << "fcntl #2 failed";
- }
- memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
- 0,
- sizeof(received_signal_));
- }
-
- ~PosixSignalHandler() {
- int fd1 = afd_[0];
- int fd2 = afd_[1];
- // We clobber the stored file descriptor numbers here or else in principle
- // a signal that happens to be delivered during application termination
- // could erroneously write a zero byte to an unrelated file handle in
- // OnPosixSignalReceived() if some other file happens to be opened later
- // during shutdown and happens to be given the same file descriptor number
- // as our pipe had. Unfortunately even with this precaution there is still a
- // race where that could occur if said signal happens to be handled
- // concurrently with this code and happens to have already read the value of
- // afd_[1] from memory before we clobber it, but that's unlikely.
- afd_[0] = -1;
- afd_[1] = -1;
- close(fd1);
- close(fd2);
- }
-
- int afd_[2];
- // These are boolean flags that will be set in our signal handler and read
- // and cleared from Wait(). There is a race involved in this, but it is
- // benign. The signal handler sets the flag before signaling the pipe, so
- // we'll never end up blocking in select() while a flag is still true.
- // However, if two of the same signal arrive close to each other then it's
- // possible that the second time the handler may set the flag while it's still
- // true, meaning that signal will be missed. But the first occurrence of it
- // will still be handled, so this isn't a problem.
- // Volatile is not necessary here for correctness, but this data _is_ volatile
- // so I've marked it as such.
- volatile uint8 received_signal_[kNumPosixSignals];
-};
-
-class PosixSignalDispatcher : public Dispatcher {
- public:
- PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
- owner_->Add(this);
- }
-
- virtual ~PosixSignalDispatcher() {
- owner_->Remove(this);
- }
-
- virtual uint32 GetRequestedEvents() {
- return DE_READ;
- }
-
- virtual void OnPreEvent(uint32 ff) {
- // Events might get grouped if signals come very fast, so we read out up to
- // 16 bytes to make sure we keep the pipe empty.
- uint8 b[16];
- ssize_t ret = read(GetDescriptor(), b, sizeof(b));
- if (ret < 0) {
- LOG_ERR(LS_WARNING) << "Error in read()";
- } else if (ret == 0) {
- LOG(LS_WARNING) << "Should have read at least one byte";
- }
- }
-
- virtual void OnEvent(uint32 ff, int err) {
- for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
- ++signum) {
- if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
- PosixSignalHandler::Instance()->ClearSignal(signum);
- HandlerMap::iterator i = handlers_.find(signum);
- if (i == handlers_.end()) {
- // This can happen if a signal is delivered to our process at around
- // the same time as we unset our handler for it. It is not an error
- // condition, but it's unusual enough to be worth logging.
- LOG(LS_INFO) << "Received signal with no handler: " << signum;
- } else {
- // Otherwise, execute our handler.
- (*i->second)(signum);
- }
- }
- }
- }
-
- virtual int GetDescriptor() {
- return PosixSignalHandler::Instance()->GetDescriptor();
- }
-
- virtual bool IsDescriptorClosed() {
- return false;
- }
-
- void SetHandler(int signum, void (*handler)(int)) {
- handlers_[signum] = handler;
- }
-
- void ClearHandler(int signum) {
- handlers_.erase(signum);
- }
-
- bool HasHandlers() {
- return !handlers_.empty();
- }
-
- private:
- typedef std::map<int, void (*)(int)> HandlerMap;
-
- HandlerMap handlers_;
- // Our owner.
- PhysicalSocketServer *owner_;
-};
-
-class SocketDispatcher : public Dispatcher, public PhysicalSocket {
- public:
- explicit SocketDispatcher(PhysicalSocketServer *ss) : PhysicalSocket(ss) {
- }
- SocketDispatcher(SOCKET s, PhysicalSocketServer *ss) : PhysicalSocket(ss, s) {
- }
-
- virtual ~SocketDispatcher() {
- Close();
- }
-
- bool Initialize() {
- ss_->Add(this);
- fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
- return true;
- }
-
- virtual bool Create(int type) {
- return Create(AF_INET, type);
- }
-
- virtual bool Create(int family, int type) {
- // Change the socket to be non-blocking.
- if (!PhysicalSocket::Create(family, type))
- return false;
-
- return Initialize();
- }
-
- virtual int GetDescriptor() {
- return s_;
- }
-
- virtual bool IsDescriptorClosed() {
- // We don't have a reliable way of distinguishing end-of-stream
- // from readability. So test on each readable call. Is this
- // inefficient? Probably.
- char ch;
- ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
- if (res > 0) {
- // Data available, so not closed.
- return false;
- } else if (res == 0) {
- // EOF, so closed.
- return true;
- } else { // error
- switch (errno) {
- // Returned if we've already closed s_.
- case EBADF:
- // Returned during ungraceful peer shutdown.
- case ECONNRESET:
- return true;
- default:
- // Assume that all other errors are just blocking errors, meaning the
- // connection is still good but we just can't read from it right now.
- // This should only happen when connecting (and at most once), because
- // in all other cases this function is only called if the file
- // descriptor is already known to be in the readable state. However,
- // it's not necessary a problem if we spuriously interpret a
- // "connection lost"-type error as a blocking error, because typically
- // the next recv() will get EOF, so we'll still eventually notice that
- // the socket is closed.
- LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
- return false;
- }
- }
- }
-
- virtual uint32 GetRequestedEvents() {
- return enabled_events_;
- }
-
- virtual void OnPreEvent(uint32 ff) {
- if ((ff & DE_CONNECT) != 0)
- state_ = CS_CONNECTED;
- if ((ff & DE_CLOSE) != 0)
- state_ = CS_CLOSED;
- }
-
- virtual void OnEvent(uint32 ff, int err) {
- // Make sure we deliver connect/accept first. Otherwise, consumers may see
- // something like a READ followed by a CONNECT, which would be odd.
- if ((ff & DE_CONNECT) != 0) {
- enabled_events_ &= ~DE_CONNECT;
- SignalConnectEvent(this);
- }
- if ((ff & DE_ACCEPT) != 0) {
- enabled_events_ &= ~DE_ACCEPT;
- SignalReadEvent(this);
- }
- if ((ff & DE_READ) != 0) {
- enabled_events_ &= ~DE_READ;
- SignalReadEvent(this);
- }
- if ((ff & DE_WRITE) != 0) {
- enabled_events_ &= ~DE_WRITE;
- SignalWriteEvent(this);
- }
- if ((ff & DE_CLOSE) != 0) {
- // The socket is now dead to us, so stop checking it.
- enabled_events_ = 0;
- SignalCloseEvent(this, err);
- }
- }
-
- virtual int Close() {
- if (s_ == INVALID_SOCKET)
- return 0;
-
- ss_->Remove(this);
- return PhysicalSocket::Close();
- }
-};
-
-class FileDispatcher: public Dispatcher, public AsyncFile {
- public:
- FileDispatcher(int fd, PhysicalSocketServer *ss) : ss_(ss), fd_(fd) {
- set_readable(true);
-
- ss_->Add(this);
-
- fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL, 0) | O_NONBLOCK);
- }
-
- virtual ~FileDispatcher() {
- ss_->Remove(this);
- }
-
- SocketServer* socketserver() { return ss_; }
-
- virtual int GetDescriptor() {
- return fd_;
- }
-
- virtual bool IsDescriptorClosed() {
- return false;
- }
-
- virtual uint32 GetRequestedEvents() {
- return flags_;
- }
-
- virtual void OnPreEvent(uint32 ff) {
- }
-
- virtual void OnEvent(uint32 ff, int err) {
- if ((ff & DE_READ) != 0)
- SignalReadEvent(this);
- if ((ff & DE_WRITE) != 0)
- SignalWriteEvent(this);
- if ((ff & DE_CLOSE) != 0)
- SignalCloseEvent(this, err);
- }
-
- virtual bool readable() {
- return (flags_ & DE_READ) != 0;
- }
-
- virtual void set_readable(bool value) {
- flags_ = value ? (flags_ | DE_READ) : (flags_ & ~DE_READ);
- }
-
- virtual bool writable() {
- return (flags_ & DE_WRITE) != 0;
- }
-
- virtual void set_writable(bool value) {
- flags_ = value ? (flags_ | DE_WRITE) : (flags_ & ~DE_WRITE);
- }
-
- private:
- PhysicalSocketServer* ss_;
- int fd_;
- int flags_;
-};
-
-AsyncFile* PhysicalSocketServer::CreateFile(int fd) {
- return new FileDispatcher(fd, this);
-}
-
-#endif // POSIX
-
-#ifdef WIN32
-static uint32 FlagsToEvents(uint32 events) {
- uint32 ffFD = FD_CLOSE;
- if (events & DE_READ)
- ffFD |= FD_READ;
- if (events & DE_WRITE)
- ffFD |= FD_WRITE;
- if (events & DE_CONNECT)
- ffFD |= FD_CONNECT;
- if (events & DE_ACCEPT)
- ffFD |= FD_ACCEPT;
- return ffFD;
-}
-
-class EventDispatcher : public Dispatcher {
- public:
- EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
- hev_ = WSACreateEvent();
- if (hev_) {
- ss_->Add(this);
- }
- }
-
- ~EventDispatcher() {
- if (hev_ != NULL) {
- ss_->Remove(this);
- WSACloseEvent(hev_);
- hev_ = NULL;
- }
- }
-
- virtual void Signal() {
- if (hev_ != NULL)
- WSASetEvent(hev_);
- }
-
- virtual uint32 GetRequestedEvents() {
- return 0;
- }
-
- virtual void OnPreEvent(uint32 ff) {
- WSAResetEvent(hev_);
- }
-
- virtual void OnEvent(uint32 ff, int err) {
- }
-
- virtual WSAEVENT GetWSAEvent() {
- return hev_;
- }
-
- virtual SOCKET GetSocket() {
- return INVALID_SOCKET;
- }
-
- virtual bool CheckSignalClose() { return false; }
-
-private:
- PhysicalSocketServer* ss_;
- WSAEVENT hev_;
-};
-
-class SocketDispatcher : public Dispatcher, public PhysicalSocket {
- public:
- static int next_id_;
- int id_;
- bool signal_close_;
- int signal_err_;
-
- SocketDispatcher(PhysicalSocketServer* ss)
- : PhysicalSocket(ss),
- id_(0),
- signal_close_(false) {
- }
-
- SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
- : PhysicalSocket(ss, s),
- id_(0),
- signal_close_(false) {
- }
-
- virtual ~SocketDispatcher() {
- Close();
- }
-
- bool Initialize() {
- ASSERT(s_ != INVALID_SOCKET);
- // Must be a non-blocking
- u_long argp = 1;
- ioctlsocket(s_, FIONBIO, &argp);
- ss_->Add(this);
- return true;
- }
-
- virtual bool Create(int type) {
- return Create(AF_INET, type);
- }
-
- virtual bool Create(int family, int type) {
- // Create socket
- if (!PhysicalSocket::Create(family, type))
- return false;
-
- if (!Initialize())
- return false;
-
- do { id_ = ++next_id_; } while (id_ == 0);
- return true;
- }
-
- virtual int Close() {
- if (s_ == INVALID_SOCKET)
- return 0;
-
- id_ = 0;
- signal_close_ = false;
- ss_->Remove(this);
- return PhysicalSocket::Close();
- }
-
- virtual uint32 GetRequestedEvents() {
- return enabled_events_;
- }
-
- virtual void OnPreEvent(uint32 ff) {
- if ((ff & DE_CONNECT) != 0)
- state_ = CS_CONNECTED;
- // We set CS_CLOSED from CheckSignalClose.
- }
-
- virtual void OnEvent(uint32 ff, int err) {
- int cache_id = id_;
- // Make sure we deliver connect/accept first. Otherwise, consumers may see
- // something like a READ followed by a CONNECT, which would be odd.
- if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
- if (ff != DE_CONNECT)
- LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
- enabled_events_ &= ~DE_CONNECT;
-#ifdef _DEBUG
- dbg_addr_ = "Connected @ ";
- dbg_addr_.append(GetRemoteAddress().ToString());
-#endif // _DEBUG
- SignalConnectEvent(this);
- }
- if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
- enabled_events_ &= ~DE_ACCEPT;
- SignalReadEvent(this);
- }
- if ((ff & DE_READ) != 0) {
- enabled_events_ &= ~DE_READ;
- SignalReadEvent(this);
- }
- if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
- enabled_events_ &= ~DE_WRITE;
- SignalWriteEvent(this);
- }
- if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
- signal_close_ = true;
- signal_err_ = err;
- }
- }
-
- virtual WSAEVENT GetWSAEvent() {
- return WSA_INVALID_EVENT;
- }
-
- virtual SOCKET GetSocket() {
- return s_;
- }
-
- virtual bool CheckSignalClose() {
- if (!signal_close_)
- return false;
-
- char ch;
- if (recv(s_, &ch, 1, MSG_PEEK) > 0)
- return false;
-
- state_ = CS_CLOSED;
- signal_close_ = false;
- SignalCloseEvent(this, signal_err_);
- return true;
- }
-};
-
-int SocketDispatcher::next_id_ = 0;
-
-#endif // WIN32
-
-// Sets the value of a boolean value to false when signaled.
-class Signaler : public EventDispatcher {
- public:
- Signaler(PhysicalSocketServer* ss, bool* pf)
- : EventDispatcher(ss), pf_(pf) {
- }
- virtual ~Signaler() { }
-
- void OnEvent(uint32 ff, int err) {
- if (pf_)
- *pf_ = false;
- }
-
- private:
- bool *pf_;
-};
-
-PhysicalSocketServer::PhysicalSocketServer()
- : fWait_(false) {
- signal_wakeup_ = new Signaler(this, &fWait_);
-#ifdef WIN32
- socket_ev_ = WSACreateEvent();
-#endif
-}
-
-PhysicalSocketServer::~PhysicalSocketServer() {
-#ifdef WIN32
- WSACloseEvent(socket_ev_);
-#endif
-#ifdef POSIX
- signal_dispatcher_.reset();
-#endif
- delete signal_wakeup_;
- ASSERT(dispatchers_.empty());
-}
-
-void PhysicalSocketServer::WakeUp() {
- signal_wakeup_->Signal();
-}
-
-Socket* PhysicalSocketServer::CreateSocket(int type) {
- return CreateSocket(AF_INET, type);
-}
-
-Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
- PhysicalSocket* socket = new PhysicalSocket(this);
- if (socket->Create(family, type)) {
- return socket;
- } else {
- delete socket;
- return 0;
- }
-}
-
-AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
- SocketDispatcher* dispatcher = new SocketDispatcher(this);
- if (dispatcher->Create(family, type)) {
- return dispatcher;
- } else {
- delete dispatcher;
- return 0;
- }
-}
-
-AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
- SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
- if (dispatcher->Initialize()) {
- return dispatcher;
- } else {
- delete dispatcher;
- return 0;
- }
-}
-
-void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
- CritScope cs(&crit_);
- // Prevent duplicates. This can cause dead dispatchers to stick around.
- DispatcherList::iterator pos = std::find(dispatchers_.begin(),
- dispatchers_.end(),
- pdispatcher);
- if (pos != dispatchers_.end())
- return;
- dispatchers_.push_back(pdispatcher);
-}
-
-void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
- CritScope cs(&crit_);
- DispatcherList::iterator pos = std::find(dispatchers_.begin(),
- dispatchers_.end(),
- pdispatcher);
- // We silently ignore duplicate calls to Add, so we should silently ignore
- // the (expected) symmetric calls to Remove. Note that this may still hide
- // a real issue, so we at least log a warning about it.
- if (pos == dispatchers_.end()) {
- LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
- << "dispatcher, potentially from a duplicate call to Add.";
- return;
- }
- size_t index = pos - dispatchers_.begin();
- dispatchers_.erase(pos);
- for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
- ++it) {
- if (index < **it) {
- --**it;
- }
- }
-}
-
-#ifdef POSIX
-bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
- // Calculate timing information
-
- struct timeval *ptvWait = NULL;
- struct timeval tvWait;
- struct timeval tvStop;
- if (cmsWait != kForever) {
- // Calculate wait timeval
- tvWait.tv_sec = cmsWait / 1000;
- tvWait.tv_usec = (cmsWait % 1000) * 1000;
- ptvWait = &tvWait;
-
- // Calculate when to return in a timeval
- gettimeofday(&tvStop, NULL);
- tvStop.tv_sec += tvWait.tv_sec;
- tvStop.tv_usec += tvWait.tv_usec;
- if (tvStop.tv_usec >= 1000000) {
- tvStop.tv_usec -= 1000000;
- tvStop.tv_sec += 1;
- }
- }
-
- // Zero all fd_sets. Don't need to do this inside the loop since
- // select() zeros the descriptors not signaled
-
- fd_set fdsRead;
- FD_ZERO(&fdsRead);
- fd_set fdsWrite;
- FD_ZERO(&fdsWrite);
-
- fWait_ = true;
-
- while (fWait_) {
- int fdmax = -1;
- {
- CritScope cr(&crit_);
- for (size_t i = 0; i < dispatchers_.size(); ++i) {
- // Query dispatchers for read and write wait state
- Dispatcher *pdispatcher = dispatchers_[i];
- ASSERT(pdispatcher);
- if (!process_io && (pdispatcher != signal_wakeup_))
- continue;
- int fd = pdispatcher->GetDescriptor();
- if (fd > fdmax)
- fdmax = fd;
-
- uint32 ff = pdispatcher->GetRequestedEvents();
- if (ff & (DE_READ | DE_ACCEPT))
- FD_SET(fd, &fdsRead);
- if (ff & (DE_WRITE | DE_CONNECT))
- FD_SET(fd, &fdsWrite);
- }
- }
-
- // Wait then call handlers as appropriate
- // < 0 means error
- // 0 means timeout
- // > 0 means count of descriptors ready
- int n = select(fdmax + 1, &fdsRead, &fdsWrite, NULL, ptvWait);
-
- // If error, return error.
- if (n < 0) {
- if (errno != EINTR) {
- LOG_E(LS_ERROR, EN, errno) << "select";
- return false;
- }
- // Else ignore the error and keep going. If this EINTR was for one of the
- // signals managed by this PhysicalSocketServer, the
- // PosixSignalDeliveryDispatcher will be in the signaled state in the next
- // iteration.
- } else if (n == 0) {
- // If timeout, return success
- return true;
- } else {
- // We have signaled descriptors
- CritScope cr(&crit_);
- for (size_t i = 0; i < dispatchers_.size(); ++i) {
- Dispatcher *pdispatcher = dispatchers_[i];
- int fd = pdispatcher->GetDescriptor();
- uint32 ff = 0;
- int errcode = 0;
-
- // Reap any error code, which can be signaled through reads or writes.
- // TODO: Should we set errcode if getsockopt fails?
- if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
- socklen_t len = sizeof(errcode);
- ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
- }
-
- // Check readable descriptors. If we're waiting on an accept, signal
- // that. Otherwise we're waiting for data, check to see if we're
- // readable or really closed.
- // TODO: Only peek at TCP descriptors.
- if (FD_ISSET(fd, &fdsRead)) {
- FD_CLR(fd, &fdsRead);
- if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
- ff |= DE_ACCEPT;
- } else if (errcode || pdispatcher->IsDescriptorClosed()) {
- ff |= DE_CLOSE;
- } else {
- ff |= DE_READ;
- }
- }
-
- // Check writable descriptors. If we're waiting on a connect, detect
- // success versus failure by the reaped error code.
- if (FD_ISSET(fd, &fdsWrite)) {
- FD_CLR(fd, &fdsWrite);
- if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
- if (!errcode) {
- ff |= DE_CONNECT;
- } else {
- ff |= DE_CLOSE;
- }
- } else {
- ff |= DE_WRITE;
- }
- }
-
- // Tell the descriptor about the event.
- if (ff != 0) {
- pdispatcher->OnPreEvent(ff);
- pdispatcher->OnEvent(ff, errcode);
- }
- }
- }
-
- // Recalc the time remaining to wait. Doing it here means it doesn't get
- // calced twice the first time through the loop
- if (ptvWait) {
- ptvWait->tv_sec = 0;
- ptvWait->tv_usec = 0;
- struct timeval tvT;
- gettimeofday(&tvT, NULL);
- if ((tvStop.tv_sec > tvT.tv_sec)
- || ((tvStop.tv_sec == tvT.tv_sec)
- && (tvStop.tv_usec > tvT.tv_usec))) {
- ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
- ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
- if (ptvWait->tv_usec < 0) {
- ASSERT(ptvWait->tv_sec > 0);
- ptvWait->tv_usec += 1000000;
- ptvWait->tv_sec -= 1;
- }
- }
- }
- }
-
- return true;
-}
-
-static void GlobalSignalHandler(int signum) {
- PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
-}
-
-bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
- void (*handler)(int)) {
- // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
- // otherwise set one.
- if (handler == SIG_IGN || handler == SIG_DFL) {
- if (!InstallSignal(signum, handler)) {
- return false;
- }
- if (signal_dispatcher_) {
- signal_dispatcher_->ClearHandler(signum);
- if (!signal_dispatcher_->HasHandlers()) {
- signal_dispatcher_.reset();
- }
- }
- } else {
- if (!signal_dispatcher_) {
- signal_dispatcher_.reset(new PosixSignalDispatcher(this));
- }
- signal_dispatcher_->SetHandler(signum, handler);
- if (!InstallSignal(signum, &GlobalSignalHandler)) {
- return false;
- }
- }
- return true;
-}
-
-Dispatcher* PhysicalSocketServer::signal_dispatcher() {
- return signal_dispatcher_.get();
-}
-
-bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
- struct sigaction act;
- // It doesn't really matter what we set this mask to.
- if (sigemptyset(&act.sa_mask) != 0) {
- LOG_ERR(LS_ERROR) << "Couldn't set mask";
- return false;
- }
- act.sa_handler = handler;
-#if !defined(__native_client__)
- // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
- // and it's a nuisance. Though some syscalls still return EINTR and there's no
- // real standard for which ones. :(
- act.sa_flags = SA_RESTART;
-#else
- act.sa_flags = 0;
-#endif
- if (sigaction(signum, &act, NULL) != 0) {
- LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
- return false;
- }
- return true;
-}
-#endif // POSIX
-
-#ifdef WIN32
-bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
- int cmsTotal = cmsWait;
- int cmsElapsed = 0;
- uint32 msStart = Time();
-
- fWait_ = true;
- while (fWait_) {
- std::vector<WSAEVENT> events;
- std::vector<Dispatcher *> event_owners;
-
- events.push_back(socket_ev_);
-
- {
- CritScope cr(&crit_);
- size_t i = 0;
- iterators_.push_back(&i);
- // Don't track dispatchers_.size(), because we want to pick up any new
- // dispatchers that were added while processing the loop.
- while (i < dispatchers_.size()) {
- Dispatcher* disp = dispatchers_[i++];
- if (!process_io && (disp != signal_wakeup_))
- continue;
- SOCKET s = disp->GetSocket();
- if (disp->CheckSignalClose()) {
- // We just signalled close, don't poll this socket
- } else if (s != INVALID_SOCKET) {
- WSAEventSelect(s,
- events[0],
- FlagsToEvents(disp->GetRequestedEvents()));
- } else {
- events.push_back(disp->GetWSAEvent());
- event_owners.push_back(disp);
- }
- }
- ASSERT(iterators_.back() == &i);
- iterators_.pop_back();
- }
-
- // Which is shorter, the delay wait or the asked wait?
-
- int cmsNext;
- if (cmsWait == kForever) {
- cmsNext = cmsWait;
- } else {
- cmsNext = _max(0, cmsTotal - cmsElapsed);
- }
-
- // Wait for one of the events to signal
- DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
- &events[0],
- false,
- cmsNext,
- false);
-
- if (dw == WSA_WAIT_FAILED) {
- // Failed?
- // TODO: need a better strategy than this!
- WSAGetLastError();
- ASSERT(false);
- return false;
- } else if (dw == WSA_WAIT_TIMEOUT) {
- // Timeout?
- return true;
- } else {
- // Figure out which one it is and call it
- CritScope cr(&crit_);
- int index = dw - WSA_WAIT_EVENT_0;
- if (index > 0) {
- --index; // The first event is the socket event
- event_owners[index]->OnPreEvent(0);
- event_owners[index]->OnEvent(0, 0);
- } else if (process_io) {
- size_t i = 0, end = dispatchers_.size();
- iterators_.push_back(&i);
- iterators_.push_back(&end); // Don't iterate over new dispatchers.
- while (i < end) {
- Dispatcher* disp = dispatchers_[i++];
- SOCKET s = disp->GetSocket();
- if (s == INVALID_SOCKET)
- continue;
-
- WSANETWORKEVENTS wsaEvents;
- int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
- if (err == 0) {
-
-#if LOGGING
- {
- if ((wsaEvents.lNetworkEvents & FD_READ) &&
- wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
- LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
- << wsaEvents.iErrorCode[FD_READ_BIT];
- }
- if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
- wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
- LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
- << wsaEvents.iErrorCode[FD_WRITE_BIT];
- }
- if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
- wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
- LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
- << wsaEvents.iErrorCode[FD_CONNECT_BIT];
- }
- if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
- wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
- LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
- << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
- }
- if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
- wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
- LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
- << wsaEvents.iErrorCode[FD_CLOSE_BIT];
- }
- }
-#endif
- uint32 ff = 0;
- int errcode = 0;
- if (wsaEvents.lNetworkEvents & FD_READ)
- ff |= DE_READ;
- if (wsaEvents.lNetworkEvents & FD_WRITE)
- ff |= DE_WRITE;
- if (wsaEvents.lNetworkEvents & FD_CONNECT) {
- if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
- ff |= DE_CONNECT;
- } else {
- ff |= DE_CLOSE;
- errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
- }
- }
- if (wsaEvents.lNetworkEvents & FD_ACCEPT)
- ff |= DE_ACCEPT;
- if (wsaEvents.lNetworkEvents & FD_CLOSE) {
- ff |= DE_CLOSE;
- errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
- }
- if (ff != 0) {
- disp->OnPreEvent(ff);
- disp->OnEvent(ff, errcode);
- }
- }
- }
- ASSERT(iterators_.back() == &end);
- iterators_.pop_back();
- ASSERT(iterators_.back() == &i);
- iterators_.pop_back();
- }
-
- // Reset the network event until new activity occurs
- WSAResetEvent(socket_ev_);
- }
-
- // Break?
- if (!fWait_)
- break;
- cmsElapsed = TimeSince(msStart);
- if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
- break;
- }
- }
-
- // Done
- return true;
-}
-#endif // WIN32
-
-} // namespace talk_base
diff --git a/base/physicalsocketserver.h b/base/physicalsocketserver.h
deleted file mode 100644
index 9173f23..0000000
--- a/base/physicalsocketserver.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_PHYSICALSOCKETSERVER_H__
-#define TALK_BASE_PHYSICALSOCKETSERVER_H__
-
-#include <vector>
-
-#include "talk/base/asyncfile.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketserver.h"
-#include "talk/base/criticalsection.h"
-
-#ifdef POSIX
-typedef int SOCKET;
-#endif // POSIX
-
-namespace talk_base {
-
-// Event constants for the Dispatcher class.
-enum DispatcherEvent {
- DE_READ = 0x0001,
- DE_WRITE = 0x0002,
- DE_CONNECT = 0x0004,
- DE_CLOSE = 0x0008,
- DE_ACCEPT = 0x0010,
-};
-
-class Signaler;
-#ifdef POSIX
-class PosixSignalDispatcher;
-#endif
-
-class Dispatcher {
- public:
- virtual ~Dispatcher() {}
- virtual uint32 GetRequestedEvents() = 0;
- virtual void OnPreEvent(uint32 ff) = 0;
- virtual void OnEvent(uint32 ff, int err) = 0;
-#ifdef WIN32
- virtual WSAEVENT GetWSAEvent() = 0;
- virtual SOCKET GetSocket() = 0;
- virtual bool CheckSignalClose() = 0;
-#elif POSIX
- virtual int GetDescriptor() = 0;
- virtual bool IsDescriptorClosed() = 0;
-#endif
-};
-
-// A socket server that provides the real sockets of the underlying OS.
-class PhysicalSocketServer : public SocketServer {
- public:
- PhysicalSocketServer();
- virtual ~PhysicalSocketServer();
-
- // SocketFactory:
- virtual Socket* CreateSocket(int type);
- virtual Socket* CreateSocket(int family, int type);
-
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- // Internal Factory for Accept
- AsyncSocket* WrapSocket(SOCKET s);
-
- // SocketServer:
- virtual bool Wait(int cms, bool process_io);
- virtual void WakeUp();
-
- void Add(Dispatcher* dispatcher);
- void Remove(Dispatcher* dispatcher);
-
-#ifdef POSIX
- AsyncFile* CreateFile(int fd);
-
- // Sets the function to be executed in response to the specified POSIX signal.
- // The function is executed from inside Wait() using the "self-pipe trick"--
- // regardless of which thread receives the signal--and hence can safely
- // manipulate user-level data structures.
- // "handler" may be SIG_IGN, SIG_DFL, or a user-specified function, just like
- // with signal(2).
- // Only one PhysicalSocketServer should have user-level signal handlers.
- // Dispatching signals on multiple PhysicalSocketServers is not reliable.
- // The signal mask is not modified. It is the caller's responsibily to
- // maintain it as desired.
- virtual bool SetPosixSignalHandler(int signum, void (*handler)(int));
-
- protected:
- Dispatcher* signal_dispatcher();
-#endif
-
- private:
- typedef std::vector<Dispatcher*> DispatcherList;
- typedef std::vector<size_t*> IteratorList;
-
-#ifdef POSIX
- static bool InstallSignal(int signum, void (*handler)(int));
-
- scoped_ptr<PosixSignalDispatcher> signal_dispatcher_;
-#endif
- DispatcherList dispatchers_;
- IteratorList iterators_;
- Signaler* signal_wakeup_;
- CriticalSection crit_;
- bool fWait_;
-#ifdef WIN32
- WSAEVENT socket_ev_;
-#endif
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_PHYSICALSOCKETSERVER_H__
diff --git a/base/physicalsocketserver_unittest.cc b/base/physicalsocketserver_unittest.cc
deleted file mode 100644
index cbdbd9c..0000000
--- a/base/physicalsocketserver_unittest.cc
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <signal.h>
-#include <stdarg.h>
-
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socket_unittest.h"
-#include "talk/base/testutils.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-class PhysicalSocketTest : public SocketTest {
-};
-
-TEST_F(PhysicalSocketTest, TestConnectIPv4) {
- SocketTest::TestConnectIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectIPv6) {
- SocketTest::TestConnectIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv4) {
- SocketTest::TestConnectWithDnsLookupIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv6) {
- SocketTest::TestConnectWithDnsLookupIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectFailIPv4) {
- SocketTest::TestConnectFailIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectFailIPv6) {
- SocketTest::TestConnectFailIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv4) {
- SocketTest::TestConnectWithDnsLookupFailIPv4();
-}
-
-
-TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv6) {
- SocketTest::TestConnectWithDnsLookupFailIPv6();
-}
-
-
-TEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv4) {
- SocketTest::TestConnectWithClosedSocketIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv6) {
- SocketTest::TestConnectWithClosedSocketIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv4) {
- SocketTest::TestConnectWhileNotClosedIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv6) {
- SocketTest::TestConnectWhileNotClosedIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv4) {
- SocketTest::TestServerCloseDuringConnectIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv6) {
- SocketTest::TestServerCloseDuringConnectIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv4) {
- SocketTest::TestClientCloseDuringConnectIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv6) {
- SocketTest::TestClientCloseDuringConnectIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestServerCloseIPv4) {
- SocketTest::TestServerCloseIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestServerCloseIPv6) {
- SocketTest::TestServerCloseIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv4) {
- SocketTest::TestCloseInClosedCallbackIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv6) {
- SocketTest::TestCloseInClosedCallbackIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestSocketServerWaitIPv4) {
- SocketTest::TestSocketServerWaitIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestSocketServerWaitIPv6) {
- SocketTest::TestSocketServerWaitIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestTcpIPv4) {
- SocketTest::TestTcpIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestTcpIPv6) {
- SocketTest::TestTcpIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestUdpIPv4) {
- SocketTest::TestUdpIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestUdpIPv6) {
- SocketTest::TestUdpIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv4) {
- SocketTest::TestUdpReadyToSendIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv6) {
- SocketTest::TestUdpReadyToSendIPv6();
-}
-
-TEST_F(PhysicalSocketTest, TestGetSetOptionsIPv4) {
- SocketTest::TestGetSetOptionsIPv4();
-}
-
-TEST_F(PhysicalSocketTest, TestGetSetOptionsIPv6) {
- SocketTest::TestGetSetOptionsIPv6();
-}
-
-#ifdef POSIX
-
-class PosixSignalDeliveryTest : public testing::Test {
- public:
- static void RecordSignal(int signum) {
- signals_received_.push_back(signum);
- signaled_thread_ = Thread::Current();
- }
-
- protected:
- void SetUp() {
- ss_.reset(new PhysicalSocketServer());
- }
-
- void TearDown() {
- ss_.reset(NULL);
- signals_received_.clear();
- signaled_thread_ = NULL;
- }
-
- bool ExpectSignal(int signum) {
- if (signals_received_.empty()) {
- LOG(LS_ERROR) << "ExpectSignal(): No signal received";
- return false;
- }
- if (signals_received_[0] != signum) {
- LOG(LS_ERROR) << "ExpectSignal(): Received signal " <<
- signals_received_[0] << ", expected " << signum;
- return false;
- }
- signals_received_.erase(signals_received_.begin());
- return true;
- }
-
- bool ExpectNone() {
- bool ret = signals_received_.empty();
- if (!ret) {
- LOG(LS_ERROR) << "ExpectNone(): Received signal " << signals_received_[0]
- << ", expected none";
- }
- return ret;
- }
-
- static std::vector<int> signals_received_;
- static Thread *signaled_thread_;
-
- scoped_ptr<PhysicalSocketServer> ss_;
-};
-
-std::vector<int> PosixSignalDeliveryTest::signals_received_;
-Thread *PosixSignalDeliveryTest::signaled_thread_ = NULL;
-
-// Test receiving a synchronous signal while not in Wait() and then entering
-// Wait() afterwards.
-TEST_F(PosixSignalDeliveryTest, RaiseThenWait) {
- ASSERT_TRUE(ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal));
- raise(SIGTERM);
- EXPECT_TRUE(ss_->Wait(0, true));
- EXPECT_TRUE(ExpectSignal(SIGTERM));
- EXPECT_TRUE(ExpectNone());
-}
-
-// Test that we can handle getting tons of repeated signals and that we see all
-// the different ones.
-TEST_F(PosixSignalDeliveryTest, InsanelyManySignals) {
- ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);
- ss_->SetPosixSignalHandler(SIGINT, &RecordSignal);
- for (int i = 0; i < 10000; ++i) {
- raise(SIGTERM);
- }
- raise(SIGINT);
- EXPECT_TRUE(ss_->Wait(0, true));
- // Order will be lowest signal numbers first.
- EXPECT_TRUE(ExpectSignal(SIGINT));
- EXPECT_TRUE(ExpectSignal(SIGTERM));
- EXPECT_TRUE(ExpectNone());
-}
-
-// Test that a signal during a Wait() call is detected.
-TEST_F(PosixSignalDeliveryTest, SignalDuringWait) {
- ss_->SetPosixSignalHandler(SIGALRM, &RecordSignal);
- alarm(1);
- EXPECT_TRUE(ss_->Wait(1500, true));
- EXPECT_TRUE(ExpectSignal(SIGALRM));
- EXPECT_TRUE(ExpectNone());
-}
-
-class RaiseSigTermRunnable : public Runnable {
- void Run(Thread *thread) {
- thread->socketserver()->Wait(1000, false);
-
- // Allow SIGTERM. This will be the only thread with it not masked so it will
- // be delivered to us.
- sigset_t mask;
- sigemptyset(&mask);
- pthread_sigmask(SIG_SETMASK, &mask, NULL);
-
- // Raise it.
- raise(SIGTERM);
- }
-};
-
-// Test that it works no matter what thread the kernel chooses to give the
-// signal to (since it's not guaranteed to be the one that Wait() runs on).
-TEST_F(PosixSignalDeliveryTest, SignalOnDifferentThread) {
- ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);
- // Mask out SIGTERM so that it can't be delivered to this thread.
- sigset_t mask;
- sigemptyset(&mask);
- sigaddset(&mask, SIGTERM);
- EXPECT_EQ(0, pthread_sigmask(SIG_SETMASK, &mask, NULL));
- // Start a new thread that raises it. It will have to be delivered to that
- // thread. Our implementation should safely handle it and dispatch
- // RecordSignal() on this thread.
- scoped_ptr<Thread> thread(new Thread());
- scoped_ptr<RaiseSigTermRunnable> runnable(new RaiseSigTermRunnable());
- thread->Start(runnable.get());
- EXPECT_TRUE(ss_->Wait(1500, true));
- EXPECT_TRUE(ExpectSignal(SIGTERM));
- EXPECT_EQ(Thread::Current(), signaled_thread_);
- EXPECT_TRUE(ExpectNone());
-}
-
-#endif
-
-} // namespace talk_base
diff --git a/base/posix.cc b/base/posix.cc
deleted file mode 100644
index 3502f6d..0000000
--- a/base/posix.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/posix.h"
-
-#include <sys/wait.h>
-#include <errno.h>
-#include <unistd.h>
-
-#ifdef LINUX
-#include "talk/base/linuxfdwalk.h"
-#endif
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-#ifdef LINUX
-static void closefds(void *close_errors, int fd) {
- if (fd <= 2) {
- // We leave stdin/out/err open to the browser's terminal, if any.
- return;
- }
- if (close(fd) < 0) {
- *static_cast<bool *>(close_errors) = true;
- }
-}
-#endif
-
-enum {
- EXIT_FLAG_CHDIR_ERRORS = 1 << 0,
-#ifdef LINUX
- EXIT_FLAG_FDWALK_ERRORS = 1 << 1,
- EXIT_FLAG_CLOSE_ERRORS = 1 << 2,
-#endif
- EXIT_FLAG_SECOND_FORK_FAILED = 1 << 3,
-};
-
-bool RunAsDaemon(const char *file, const char *const argv[]) {
- // Fork intermediate child to daemonize.
- pid_t pid = fork();
- if (pid < 0) {
- LOG_ERR(LS_ERROR) << "fork()";
- return false;
- } else if (!pid) {
- // Child.
-
- // We try to close all fds and change directory to /, but if that fails we
- // keep going because it's not critical.
- int exit_code = 0;
- if (chdir("/") < 0) {
- exit_code |= EXIT_FLAG_CHDIR_ERRORS;
- }
-#ifdef LINUX
- bool close_errors = false;
- if (fdwalk(&closefds, &close_errors) < 0) {
- exit_code |= EXIT_FLAG_FDWALK_ERRORS;
- }
- if (close_errors) {
- exit_code |= EXIT_FLAG_CLOSE_ERRORS;
- }
-#endif
-
- // Fork again to become a daemon.
- pid = fork();
- // It is important that everything here use _exit() and not exit(), because
- // exit() would call the destructors of all global variables in the whole
- // process, which is both unnecessary and unsafe.
- if (pid < 0) {
- exit_code |= EXIT_FLAG_SECOND_FORK_FAILED;
- _exit(exit_code); // if second fork failed
- } else if (!pid) {
- // Child.
- // Successfully daemonized. Run command.
- // POSIX requires the args to be typed as non-const for historical
- // reasons, but it mandates that the actual implementation be const, so
- // the cast is safe.
- execvp(file, const_cast<char *const *>(argv));
- _exit(255); // if execvp failed
- }
-
- // Parent.
- // Successfully spawned process, but report any problems to the parent where
- // we can log them.
- _exit(exit_code);
- }
-
- // Parent. Reap intermediate child.
- int status;
- pid_t child = waitpid(pid, &status, 0);
- if (child < 0) {
- LOG_ERR(LS_ERROR) << "Error in waitpid()";
- return false;
- }
- if (child != pid) {
- // Should never happen (see man page).
- LOG(LS_ERROR) << "waitpid() chose wrong child???";
- return false;
- }
- if (!WIFEXITED(status)) {
- LOG(LS_ERROR) << "Intermediate child killed uncleanly"; // Probably crashed
- return false;
- }
-
- int exit_code = WEXITSTATUS(status);
- if (exit_code & EXIT_FLAG_CHDIR_ERRORS) {
- LOG(LS_WARNING) << "Child reported probles calling chdir()";
- }
-#ifdef LINUX
- if (exit_code & EXIT_FLAG_FDWALK_ERRORS) {
- LOG(LS_WARNING) << "Child reported problems calling fdwalk()";
- }
- if (exit_code & EXIT_FLAG_CLOSE_ERRORS) {
- LOG(LS_WARNING) << "Child reported problems calling close()";
- }
-#endif
- if (exit_code & EXIT_FLAG_SECOND_FORK_FAILED) {
- LOG(LS_ERROR) << "Failed to daemonize";
- // This means the command was not launched, so failure.
- return false;
- }
- return true;
-}
-
-} // namespace talk_base
diff --git a/base/posix.h b/base/posix.h
deleted file mode 100644
index 15c2c90..0000000
--- a/base/posix.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_POSIX_H_
-#define TALK_BASE_POSIX_H_
-
-namespace talk_base {
-
-// Runs the given executable name as a daemon, so that it executes concurrently
-// with this process. Upon completion, the daemon process will automatically be
-// reaped by init(8), so an error exit status or a failure to start the
-// executable are not reported. Returns true if the daemon process was forked
-// successfully, else false.
-bool RunAsDaemon(const char *file, const char *const argv[]);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_POSIX_H_
diff --git a/base/profiler.cc b/base/profiler.cc
deleted file mode 100644
index 4c2aac4..0000000
--- a/base/profiler.cc
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * libjingle
- * Copyright 2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/profiler.h"
-
-#include <math.h>
-
-#include "talk/base/timeutils.h"
-
-namespace {
-
-// When written to an ostream, FormattedTime chooses an appropriate scale and
-// suffix for a time value given in seconds.
-class FormattedTime {
- public:
- explicit FormattedTime(double t) : time_(t) {}
- double time() const { return time_; }
- private:
- double time_;
-};
-
-std::ostream& operator<<(std::ostream& stream, const FormattedTime& time) {
- if (time.time() < 1.0) {
- stream << (time.time() * 1000.0) << "ms";
- } else {
- stream << time.time() << 's';
- }
- return stream;
-}
-
-} // namespace
-
-namespace talk_base {
-
-ProfilerEvent::ProfilerEvent()
- : total_time_(0.0),
- mean_(0.0),
- sum_of_squared_differences_(0.0),
- start_count_(0),
- event_count_(0) {
-}
-
-void ProfilerEvent::Start() {
- if (start_count_ == 0) {
- current_start_time_ = TimeNanos();
- }
- ++start_count_;
-}
-
-void ProfilerEvent::Stop(uint64 stop_time) {
- --start_count_;
- ASSERT(start_count_ >= 0);
- if (start_count_ == 0) {
- double elapsed = static_cast<double>(stop_time - current_start_time_) /
- kNumNanosecsPerSec;
- total_time_ += elapsed;
- if (event_count_ == 0) {
- minimum_ = maximum_ = elapsed;
- } else {
- minimum_ = _min(minimum_, elapsed);
- maximum_ = _max(maximum_, elapsed);
- }
- // Online variance and mean algorithm: http://en.wikipedia.org/wiki/
- // Algorithms_for_calculating_variance#Online_algorithm
- ++event_count_;
- double delta = elapsed - mean_;
- mean_ = mean_ + delta / event_count_;
- sum_of_squared_differences_ += delta * (elapsed - mean_);
- }
-}
-
-void ProfilerEvent::Stop() {
- Stop(TimeNanos());
-}
-
-double ProfilerEvent::standard_deviation() const {
- if (event_count_ <= 1) return 0.0;
- return sqrt(sum_of_squared_differences_ / (event_count_ - 1.0));
-}
-
-Profiler* Profiler::Instance() {
- LIBJINGLE_DEFINE_STATIC_LOCAL(Profiler, instance, ());
- return &instance;
-}
-
-void Profiler::StartEvent(const std::string& event_name) {
- lock_.LockShared();
- EventMap::iterator it = events_.find(event_name);
- bool needs_insert = (it == events_.end());
- lock_.UnlockShared();
-
- if (needs_insert) {
- // Need an exclusive lock to modify the map.
- ExclusiveScope scope(&lock_);
- it = events_.insert(
- EventMap::value_type(event_name, ProfilerEvent())).first;
- }
-
- it->second.Start();
-}
-
-void Profiler::StopEvent(const std::string& event_name) {
- // Get the time ASAP, then wait for the lock.
- uint64 stop_time = TimeNanos();
- SharedScope scope(&lock_);
- EventMap::iterator it = events_.find(event_name);
- if (it != events_.end()) {
- it->second.Stop(stop_time);
- }
-}
-
-void Profiler::ReportToLog(const char* file, int line,
- LoggingSeverity severity_to_use,
- const std::string& event_prefix) {
- if (!LogMessage::Loggable(severity_to_use)) {
- return;
- }
-
- SharedScope scope(&lock_);
-
- { // Output first line.
- LogMessage msg(file, line, severity_to_use);
- msg.stream() << "=== Profile report ";
- if (event_prefix.empty()) {
- msg.stream() << "(prefix: '" << event_prefix << "') ";
- }
- msg.stream() << "===";
- }
- for (EventMap::const_iterator it = events_.begin();
- it != events_.end(); ++it) {
- if (event_prefix.empty() || it->first.find(event_prefix) == 0) {
- LogMessage(file, line, severity_to_use).stream()
- << it->first << " " << it->second;
- }
- }
- LogMessage(file, line, severity_to_use).stream()
- << "=== End profile report ===";
-}
-
-void Profiler::ReportAllToLog(const char* file, int line,
- LoggingSeverity severity_to_use) {
- ReportToLog(file, line, severity_to_use, "");
-}
-
-const ProfilerEvent* Profiler::GetEvent(const std::string& event_name) const {
- SharedScope scope(&lock_);
- EventMap::const_iterator it =
- events_.find(event_name);
- return (it == events_.end()) ? NULL : &it->second;
-}
-
-bool Profiler::Clear() {
- ExclusiveScope scope(&lock_);
- bool result = true;
- // Clear all events that aren't started.
- EventMap::iterator it = events_.begin();
- while (it != events_.end()) {
- if (it->second.is_started()) {
- ++it; // Can't clear started events.
- result = false;
- } else {
- events_.erase(it++);
- }
- }
- return result;
-}
-
-std::ostream& operator<<(std::ostream& stream,
- const ProfilerEvent& profiler_event) {
- stream << "count=" << profiler_event.event_count()
- << " total=" << FormattedTime(profiler_event.total_time())
- << " mean=" << FormattedTime(profiler_event.mean())
- << " min=" << FormattedTime(profiler_event.minimum())
- << " max=" << FormattedTime(profiler_event.maximum())
- << " sd=" << profiler_event.standard_deviation();
- return stream;
-}
-
-} // namespace talk_base
diff --git a/base/profiler.h b/base/profiler.h
deleted file mode 100644
index f74a540..0000000
--- a/base/profiler.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * libjingle
- * Copyright 2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// A simple wall-clock profiler for instrumented code.
-// Example:
-// void MyLongFunction() {
-// PROFILE_F(); // Time the execution of this function.
-// // Do something
-// { // Time just what is in this scope.
-// PROFILE("My event");
-// // Do something else
-// }
-// }
-// Another example:
-// void StartAsyncProcess() {
-// PROFILE_START("My async event");
-// DoSomethingAsyncAndThenCall(&Callback);
-// }
-// void Callback() {
-// PROFILE_STOP("My async event");
-// // Handle callback.
-// }
-
-#ifndef TALK_BASE_PROFILER_H_
-#define TALK_BASE_PROFILER_H_
-
-#include <map>
-#include <string>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/sharedexclusivelock.h"
-
-// Profiling could be switched via a build flag, but for now, it's always on.
-#ifndef ENABLE_PROFILING
-#define ENABLE_PROFILING
-#endif
-
-#ifdef ENABLE_PROFILING
-
-#define UV_HELPER2(x) _uv_ ## x
-#define UV_HELPER(x) UV_HELPER2(x)
-#define UNIQUE_VAR UV_HELPER(__LINE__)
-
-// Profiles the current scope.
-#define PROFILE(msg) talk_base::ProfilerScope UNIQUE_VAR(msg)
-// When placed at the start of a function, profiles the current function.
-#define PROFILE_F() PROFILE(__FUNCTION__)
-// Reports current timings to the log at severity |sev|.
-#define PROFILE_DUMP_ALL(sev) \
- talk_base::Profiler::Instance()->ReportAllToLog(__FILE__, __LINE__, sev)
-// Reports current timings for all events whose names are prefixed by |prefix|
-// to the log at severity |sev|. Using a unique event name as |prefix| will
-// report only that event.
-#define PROFILE_DUMP(sev, prefix) \
- talk_base::Profiler::Instance()->ReportToLog(__FILE__, __LINE__, sev, prefix)
-// Starts and stops a profile event. Useful when an event is not easily
-// captured within a scope (eg, an async call with a callback when done).
-#define PROFILE_START(msg) talk_base::Profiler::Instance()->StartEvent(msg)
-#define PROFILE_STOP(msg) talk_base::Profiler::Instance()->StopEvent(msg)
-// TODO(ryanpetrie): Consider adding PROFILE_DUMP_EVERY(sev, iterations)
-
-#undef UV_HELPER2
-#undef UV_HELPER
-#undef UNIQUE_VAR
-
-#else // ENABLE_PROFILING
-
-#define PROFILE(msg) (void)0
-#define PROFILE_F() (void)0
-#define PROFILE_DUMP_ALL(sev) (void)0
-#define PROFILE_DUMP(sev, prefix) (void)0
-#define PROFILE_START(msg) (void)0
-#define PROFILE_STOP(msg) (void)0
-
-#endif // ENABLE_PROFILING
-
-namespace talk_base {
-
-// Tracks information for one profiler event.
-class ProfilerEvent {
- public:
- ProfilerEvent();
- void Start();
- void Stop();
- void Stop(uint64 stop_time);
- double standard_deviation() const;
- double total_time() const { return total_time_; }
- double mean() const { return mean_; }
- double minimum() const { return minimum_; }
- double maximum() const { return maximum_; }
- int event_count() const { return event_count_; }
- bool is_started() const { return start_count_ > 0; }
-
- private:
- uint64 current_start_time_;
- double total_time_;
- double mean_;
- double sum_of_squared_differences_;
- double minimum_;
- double maximum_;
- int start_count_;
- int event_count_;
-};
-
-// Singleton that owns ProfilerEvents and reports results. Prefer to use
-// macros, defined above, rather than directly calling Profiler methods.
-class Profiler {
- public:
- void StartEvent(const std::string& event_name);
- void StopEvent(const std::string& event_name);
- void ReportToLog(const char* file, int line, LoggingSeverity severity_to_use,
- const std::string& event_prefix);
- void ReportAllToLog(const char* file, int line,
- LoggingSeverity severity_to_use);
- const ProfilerEvent* GetEvent(const std::string& event_name) const;
- // Clears all _stopped_ events. Returns true if _all_ events were cleared.
- bool Clear();
-
- static Profiler* Instance();
- private:
- Profiler() {}
-
- typedef std::map<std::string, ProfilerEvent> EventMap;
- EventMap events_;
- mutable SharedExclusiveLock lock_;
-
- DISALLOW_COPY_AND_ASSIGN(Profiler);
-};
-
-// Starts an event on construction and stops it on destruction.
-// Used by PROFILE macro.
-class ProfilerScope {
- public:
- explicit ProfilerScope(const std::string& event_name)
- : event_name_(event_name) {
- Profiler::Instance()->StartEvent(event_name_);
- }
- ~ProfilerScope() {
- Profiler::Instance()->StopEvent(event_name_);
- }
- private:
- std::string event_name_;
-
- DISALLOW_COPY_AND_ASSIGN(ProfilerScope);
-};
-
-std::ostream& operator<<(std::ostream& stream,
- const ProfilerEvent& profiler_event);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_PROFILER_H_
diff --git a/base/profiler_unittest.cc b/base/profiler_unittest.cc
deleted file mode 100644
index a39b32c..0000000
--- a/base/profiler_unittest.cc
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2013, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/profiler.h"
-#include "talk/base/thread.h"
-
-namespace {
-
-const int kWaitMs = 250;
-const double kWaitSec = 0.250;
-const double kTolerance = 0.1;
-
-const char* TestFunc() {
- PROFILE_F();
- talk_base::Thread::SleepMs(kWaitMs);
- return __FUNCTION__;
-}
-
-} // namespace
-
-namespace talk_base {
-
-TEST(ProfilerTest, TestFunction) {
- ASSERT_TRUE(Profiler::Instance()->Clear());
-
- // Profile a long-running function.
- const char* function_name = TestFunc();
- const ProfilerEvent* event = Profiler::Instance()->GetEvent(function_name);
- ASSERT_TRUE(event != NULL);
- EXPECT_FALSE(event->is_started());
- EXPECT_EQ(1, event->event_count());
- EXPECT_NEAR(kWaitSec, event->mean(), kTolerance * 3);
-
- // Run it a second time.
- TestFunc();
- EXPECT_FALSE(event->is_started());
- EXPECT_EQ(2, event->event_count());
- EXPECT_NEAR(kWaitSec, event->mean(), kTolerance);
- EXPECT_NEAR(kWaitSec * 2, event->total_time(), kTolerance * 2);
- EXPECT_DOUBLE_EQ(event->mean(), event->total_time() / event->event_count());
-}
-
-TEST(ProfilerTest, TestScopedEvents) {
- const std::string kEvent1Name = "Event 1";
- const std::string kEvent2Name = "Event 2";
- const int kEvent2WaitMs = 150;
- const double kEvent2WaitSec = 0.150;
- const ProfilerEvent* event1;
- const ProfilerEvent* event2;
- ASSERT_TRUE(Profiler::Instance()->Clear());
- { // Profile a scope.
- PROFILE(kEvent1Name);
- event1 = Profiler::Instance()->GetEvent(kEvent1Name);
- ASSERT_TRUE(event1 != NULL);
- EXPECT_TRUE(event1->is_started());
- EXPECT_EQ(0, event1->event_count());
- talk_base::Thread::SleepMs(kWaitMs);
- EXPECT_TRUE(event1->is_started());
- }
- // Check the result.
- EXPECT_FALSE(event1->is_started());
- EXPECT_EQ(1, event1->event_count());
- EXPECT_NEAR(kWaitSec, event1->mean(), kTolerance);
- { // Profile a second event.
- PROFILE(kEvent2Name);
- event2 = Profiler::Instance()->GetEvent(kEvent2Name);
- ASSERT_TRUE(event2 != NULL);
- EXPECT_FALSE(event1->is_started());
- EXPECT_TRUE(event2->is_started());
- talk_base::Thread::SleepMs(kEvent2WaitMs);
- }
- // Check the result.
- EXPECT_FALSE(event2->is_started());
- EXPECT_EQ(1, event2->event_count());
-
- // The difference here can be as much as 0.33, so we need high tolerance.
- EXPECT_NEAR(kEvent2WaitSec, event2->mean(), kTolerance * 4);
- // Make sure event1 is unchanged.
- EXPECT_FALSE(event1->is_started());
- EXPECT_EQ(1, event1->event_count());
- { // Run another event 1.
- PROFILE(kEvent1Name);
- EXPECT_TRUE(event1->is_started());
- talk_base::Thread::SleepMs(kWaitMs);
- }
- // Check the result.
- EXPECT_FALSE(event1->is_started());
- EXPECT_EQ(2, event1->event_count());
- EXPECT_NEAR(kWaitSec, event1->mean(), kTolerance);
- EXPECT_NEAR(kWaitSec * 2, event1->total_time(), kTolerance * 2);
- EXPECT_DOUBLE_EQ(event1->mean(),
- event1->total_time() / event1->event_count());
-}
-
-TEST(ProfilerTest, Clear) {
- ASSERT_TRUE(Profiler::Instance()->Clear());
- PROFILE_START("event");
- EXPECT_FALSE(Profiler::Instance()->Clear());
- EXPECT_TRUE(Profiler::Instance()->GetEvent("event") != NULL);
- PROFILE_STOP("event");
- EXPECT_TRUE(Profiler::Instance()->Clear());
- EXPECT_EQ(NULL, Profiler::Instance()->GetEvent("event"));
-}
-
-} // namespace talk_base
diff --git a/base/proxy_unittest.cc b/base/proxy_unittest.cc
deleted file mode 100644
index 4ace292..0000000
--- a/base/proxy_unittest.cc
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-#include "talk/base/autodetectproxy.h"
-#include "talk/base/gunit.h"
-#include "talk/base/httpserver.h"
-#include "talk/base/proxyserver.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/testclient.h"
-#include "talk/base/testechoserver.h"
-#include "talk/base/virtualsocketserver.h"
-
-using talk_base::Socket;
-using talk_base::Thread;
-using talk_base::SocketAddress;
-
-static const SocketAddress kSocksProxyIntAddr("1.2.3.4", 1080);
-static const SocketAddress kSocksProxyExtAddr("1.2.3.5", 0);
-static const SocketAddress kHttpsProxyIntAddr("1.2.3.4", 443);
-static const SocketAddress kHttpsProxyExtAddr("1.2.3.5", 0);
-static const SocketAddress kBogusProxyIntAddr("1.2.3.4", 999);
-
-// Used to run a proxy detect on the current thread. Otherwise we would need
-// to make both threads share the same VirtualSocketServer.
-class AutoDetectProxyRunner : public talk_base::AutoDetectProxy {
- public:
- explicit AutoDetectProxyRunner(const std::string& agent)
- : AutoDetectProxy(agent) {}
- void Run() {
- DoWork();
- Thread::Current()->Restart(); // needed to reset the messagequeue
- }
-};
-
-// Sets up a virtual socket server and HTTPS/SOCKS5 proxy servers.
-class ProxyTest : public testing::Test {
- public:
- ProxyTest() : ss_(new talk_base::VirtualSocketServer(NULL)) {
- Thread::Current()->set_socketserver(ss_.get());
- socks_.reset(new talk_base::SocksProxyServer(
- ss_.get(), kSocksProxyIntAddr, ss_.get(), kSocksProxyExtAddr));
- https_.reset(new talk_base::HttpListenServer());
- https_->Listen(kHttpsProxyIntAddr);
- }
- ~ProxyTest() {
- Thread::Current()->set_socketserver(NULL);
- }
-
- talk_base::SocketServer* ss() { return ss_.get(); }
-
- talk_base::ProxyType DetectProxyType(const SocketAddress& address) {
- talk_base::ProxyType type;
- AutoDetectProxyRunner* detect = new AutoDetectProxyRunner("unittest/1.0");
- detect->set_proxy(address);
- detect->Run(); // blocks until done
- type = detect->proxy().type;
- detect->Destroy(false);
- return type;
- }
-
- private:
- talk_base::scoped_ptr<talk_base::SocketServer> ss_;
- talk_base::scoped_ptr<talk_base::SocksProxyServer> socks_;
- // TODO: Make this a real HTTPS proxy server.
- talk_base::scoped_ptr<talk_base::HttpListenServer> https_;
-};
-
-// Tests whether we can use a SOCKS5 proxy to connect to a server.
-TEST_F(ProxyTest, TestSocks5Connect) {
- talk_base::AsyncSocket* socket =
- ss()->CreateAsyncSocket(kSocksProxyIntAddr.family(), SOCK_STREAM);
- talk_base::AsyncSocksProxySocket* proxy_socket =
- new talk_base::AsyncSocksProxySocket(socket, kSocksProxyIntAddr,
- "", talk_base::CryptString());
- // TODO: IPv6-ize these tests when proxy supports IPv6.
-
- talk_base::TestEchoServer server(Thread::Current(),
- SocketAddress(INADDR_ANY, 0));
-
- talk_base::AsyncTCPSocket* packet_socket = talk_base::AsyncTCPSocket::Create(
- proxy_socket, SocketAddress(INADDR_ANY, 0), server.address());
- EXPECT_TRUE(packet_socket != NULL);
- talk_base::TestClient client(packet_socket);
-
- EXPECT_EQ(Socket::CS_CONNECTING, proxy_socket->GetState());
- EXPECT_TRUE(client.CheckConnected());
- EXPECT_EQ(Socket::CS_CONNECTED, proxy_socket->GetState());
- EXPECT_EQ(server.address(), client.remote_address());
- client.Send("foo", 3);
- EXPECT_TRUE(client.CheckNextPacket("foo", 3, NULL));
- EXPECT_TRUE(client.CheckNoPacket());
-}
-
-/*
-// Tests whether we can use a HTTPS proxy to connect to a server.
-TEST_F(ProxyTest, TestHttpsConnect) {
- AsyncSocket* socket = ss()->CreateAsyncSocket(SOCK_STREAM);
- AsyncHttpsProxySocket* proxy_socket = new AsyncHttpsProxySocket(
- socket, "unittest/1.0", kHttpsProxyIntAddress, "", CryptString());
- TestClient client(new AsyncTCPSocket(proxy_socket));
- TestEchoServer server(Thread::Current(), SocketAddress());
-
- EXPECT_TRUE(client.Connect(server.address()));
- EXPECT_TRUE(client.CheckConnected());
- EXPECT_EQ(server.address(), client.remote_address());
- client.Send("foo", 3);
- EXPECT_TRUE(client.CheckNextPacket("foo", 3, NULL));
- EXPECT_TRUE(client.CheckNoPacket());
-}
-*/
-
-// Tests whether we can autodetect a SOCKS5 proxy.
-TEST_F(ProxyTest, TestAutoDetectSocks5) {
- EXPECT_EQ(talk_base::PROXY_SOCKS5, DetectProxyType(kSocksProxyIntAddr));
-}
-
-/*
-// Tests whether we can autodetect a HTTPS proxy.
-TEST_F(ProxyTest, TestAutoDetectHttps) {
- EXPECT_EQ(talk_base::PROXY_HTTPS, DetectProxyType(kHttpsProxyIntAddr));
-}
-*/
-
-// Tests whether we fail properly for no proxy.
-TEST_F(ProxyTest, TestAutoDetectBogus) {
- EXPECT_EQ(talk_base::PROXY_UNKNOWN, DetectProxyType(kBogusProxyIntAddr));
-}
diff --git a/base/proxydetect.cc b/base/proxydetect.cc
deleted file mode 100644
index 8f7f7f8..0000000
--- a/base/proxydetect.cc
+++ /dev/null
@@ -1,1263 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/proxydetect.h"
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#include <shlobj.h>
-#endif // WIN32
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef OSX
-#include <SystemConfiguration/SystemConfiguration.h>
-#include <CoreFoundation/CoreFoundation.h>
-#include <CoreServices/CoreServices.h>
-#include <Security/Security.h>
-#include "macconversion.h"
-#endif
-
-#include <map>
-
-#include "talk/base/fileutils.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/httpcommon-inl.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stringutils.h"
-
-#ifdef WIN32
-#define _TRY_WINHTTP 1
-#define _TRY_JSPROXY 0
-#define _TRY_WM_FINDPROXY 0
-#define _TRY_IE_LAN_SETTINGS 1
-#endif // WIN32
-
-// For all platforms try Firefox.
-#define _TRY_FIREFOX 1
-
-// Use profiles.ini to find the correct profile for this user.
-// If not set, we'll just look for the default one.
-#define USE_FIREFOX_PROFILES_INI 1
-
-static const size_t kMaxLineLength = 1024;
-static const char kFirefoxPattern[] = "Firefox";
-static const char kInternetExplorerPattern[] = "MSIE";
-
-struct StringMap {
- public:
- void Add(const char * name, const char * value) { map_[name] = value; }
- const std::string& Get(const char * name, const char * def = "") const {
- std::map<std::string, std::string>::const_iterator it =
- map_.find(name);
- if (it != map_.end())
- return it->second;
- def_ = def;
- return def_;
- }
- bool IsSet(const char * name) const {
- return (map_.find(name) != map_.end());
- }
- private:
- std::map<std::string, std::string> map_;
- mutable std::string def_;
-};
-
-enum UserAgent {
- UA_FIREFOX,
- UA_INTERNETEXPLORER,
- UA_OTHER,
- UA_UNKNOWN
-};
-
-#if _TRY_WINHTTP
-//#include <winhttp.h>
-// Note: From winhttp.h
-
-const char WINHTTP[] = "winhttp";
-
-typedef LPVOID HINTERNET;
-
-typedef struct {
- DWORD dwAccessType; // see WINHTTP_ACCESS_* types below
- LPWSTR lpszProxy; // proxy server list
- LPWSTR lpszProxyBypass; // proxy bypass list
-} WINHTTP_PROXY_INFO, * LPWINHTTP_PROXY_INFO;
-
-typedef struct {
- DWORD dwFlags;
- DWORD dwAutoDetectFlags;
- LPCWSTR lpszAutoConfigUrl;
- LPVOID lpvReserved;
- DWORD dwReserved;
- BOOL fAutoLogonIfChallenged;
-} WINHTTP_AUTOPROXY_OPTIONS;
-
-typedef struct {
- BOOL fAutoDetect;
- LPWSTR lpszAutoConfigUrl;
- LPWSTR lpszProxy;
- LPWSTR lpszProxyBypass;
-} WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
-
-extern "C" {
- typedef HINTERNET (WINAPI * pfnWinHttpOpen)
- (
- IN LPCWSTR pwszUserAgent,
- IN DWORD dwAccessType,
- IN LPCWSTR pwszProxyName OPTIONAL,
- IN LPCWSTR pwszProxyBypass OPTIONAL,
- IN DWORD dwFlags
- );
- typedef BOOL (STDAPICALLTYPE * pfnWinHttpCloseHandle)
- (
- IN HINTERNET hInternet
- );
- typedef BOOL (STDAPICALLTYPE * pfnWinHttpGetProxyForUrl)
- (
- IN HINTERNET hSession,
- IN LPCWSTR lpcwszUrl,
- IN WINHTTP_AUTOPROXY_OPTIONS * pAutoProxyOptions,
- OUT WINHTTP_PROXY_INFO * pProxyInfo
- );
- typedef BOOL (STDAPICALLTYPE * pfnWinHttpGetIEProxyConfig)
- (
- IN OUT WINHTTP_CURRENT_USER_IE_PROXY_CONFIG * pProxyConfig
- );
-
-} // extern "C"
-
-#define WINHTTP_AUTOPROXY_AUTO_DETECT 0x00000001
-#define WINHTTP_AUTOPROXY_CONFIG_URL 0x00000002
-#define WINHTTP_AUTOPROXY_RUN_INPROCESS 0x00010000
-#define WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY 0x00020000
-#define WINHTTP_AUTO_DETECT_TYPE_DHCP 0x00000001
-#define WINHTTP_AUTO_DETECT_TYPE_DNS_A 0x00000002
-#define WINHTTP_ACCESS_TYPE_DEFAULT_PROXY 0
-#define WINHTTP_ACCESS_TYPE_NO_PROXY 1
-#define WINHTTP_ACCESS_TYPE_NAMED_PROXY 3
-#define WINHTTP_NO_PROXY_NAME NULL
-#define WINHTTP_NO_PROXY_BYPASS NULL
-
-#endif // _TRY_WINHTTP
-
-#if _TRY_JSPROXY
-extern "C" {
- typedef BOOL (STDAPICALLTYPE * pfnInternetGetProxyInfo)
- (
- LPCSTR lpszUrl,
- DWORD dwUrlLength,
- LPSTR lpszUrlHostName,
- DWORD dwUrlHostNameLength,
- LPSTR * lplpszProxyHostName,
- LPDWORD lpdwProxyHostNameLength
- );
-} // extern "C"
-#endif // _TRY_JSPROXY
-
-#if _TRY_WM_FINDPROXY
-#include <comutil.h>
-#include <wmnetsourcecreator.h>
-#include <wmsinternaladminnetsource.h>
-#endif // _TRY_WM_FINDPROXY
-
-#if _TRY_IE_LAN_SETTINGS
-#include <wininet.h>
-#include <string>
-#endif // _TRY_IE_LAN_SETTINGS
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// Utility Functions
-//////////////////////////////////////////////////////////////////////
-
-#ifdef WIN32
-#ifdef _UNICODE
-
-typedef std::wstring tstring;
-std::string Utf8String(const tstring& str) { return ToUtf8(str); }
-
-#else // !_UNICODE
-
-typedef std::string tstring;
-std::string Utf8String(const tstring& str) { return str; }
-
-#endif // !_UNICODE
-#endif // WIN32
-
-bool ProxyItemMatch(const Url<char>& url, char * item, size_t len) {
- // hostname:443
- if (char * port = ::strchr(item, ':')) {
- *port++ = '\0';
- if (url.port() != atol(port)) {
- return false;
- }
- }
-
- // A.B.C.D or A.B.C.D/24
- int a, b, c, d, m;
- int match = sscanf(item, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &m);
- if (match >= 4) {
- uint32 ip = ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) |
- (d & 0xFF);
- if ((match < 5) || (m > 32))
- m = 32;
- else if (m < 0)
- m = 0;
- uint32 mask = (m == 0) ? 0 : (~0UL) << (32 - m);
- SocketAddress addr(url.host(), 0);
- // TODO: Support IPv6 proxyitems. This code block is IPv4 only anyway.
- return !addr.IsUnresolved() &&
- ((addr.ipaddr().v4AddressAsHostOrderInteger() & mask) == (ip & mask));
- }
-
- // .foo.com
- if (*item == '.') {
- size_t hostlen = url.host().length();
- return (hostlen > len)
- && (stricmp(url.host().c_str() + (hostlen - len), item) == 0);
- }
-
- // localhost or www.*.com
- if (!string_match(url.host().c_str(), item))
- return false;
-
- return true;
-}
-
-bool ProxyListMatch(const Url<char>& url, const std::string& proxy_list,
- char sep) {
- const size_t BUFSIZE = 256;
- char buffer[BUFSIZE];
- const char* list = proxy_list.c_str();
- while (*list) {
- // Remove leading space
- if (isspace(*list)) {
- ++list;
- continue;
- }
- // Break on separator
- size_t len;
- const char * start = list;
- if (const char * end = ::strchr(list, sep)) {
- len = (end - list);
- list += len + 1;
- } else {
- len = strlen(list);
- list += len;
- }
- // Remove trailing space
- while ((len > 0) && isspace(start[len-1]))
- --len;
- // Check for oversized entry
- if (len >= BUFSIZE)
- continue;
- memcpy(buffer, start, len);
- buffer[len] = 0;
- if (!ProxyItemMatch(url, buffer, len))
- continue;
- return true;
- }
- return false;
-}
-
-bool Better(ProxyType lhs, const ProxyType rhs) {
- // PROXY_NONE, PROXY_HTTPS, PROXY_SOCKS5, PROXY_UNKNOWN
- const int PROXY_VALUE[5] = { 0, 2, 3, 1 };
- return (PROXY_VALUE[lhs] > PROXY_VALUE[rhs]);
-}
-
-bool ParseProxy(const std::string& saddress, ProxyInfo* proxy) {
- const size_t kMaxAddressLength = 1024;
- // Allow semicolon, space, or tab as an address separator
- const char* const kAddressSeparator = " ;\t";
-
- ProxyType ptype;
- std::string host;
- uint16 port;
-
- const char* address = saddress.c_str();
- while (*address) {
- size_t len;
- const char * start = address;
- if (const char * sep = strchr(address, kAddressSeparator)) {
- len = (sep - address);
- address += len + 1;
- while (*address != '\0' && ::strchr(kAddressSeparator, *address)) {
- address += 1;
- }
- } else {
- len = strlen(address);
- address += len;
- }
-
- if (len > kMaxAddressLength - 1) {
- LOG(LS_WARNING) << "Proxy address too long [" << start << "]";
- continue;
- }
-
- char buffer[kMaxAddressLength];
- memcpy(buffer, start, len);
- buffer[len] = 0;
-
- char * colon = ::strchr(buffer, ':');
- if (!colon) {
- LOG(LS_WARNING) << "Proxy address without port [" << buffer << "]";
- continue;
- }
-
- *colon = 0;
- char * endptr;
- port = static_cast<uint16>(strtol(colon + 1, &endptr, 0));
- if (*endptr != 0) {
- LOG(LS_WARNING) << "Proxy address with invalid port [" << buffer << "]";
- continue;
- }
-
- if (char * equals = ::strchr(buffer, '=')) {
- *equals = 0;
- host = equals + 1;
- if (_stricmp(buffer, "socks") == 0) {
- ptype = PROXY_SOCKS5;
- } else if (_stricmp(buffer, "https") == 0) {
- ptype = PROXY_HTTPS;
- } else {
- LOG(LS_WARNING) << "Proxy address with unknown protocol ["
- << buffer << "]";
- ptype = PROXY_UNKNOWN;
- }
- } else {
- host = buffer;
- ptype = PROXY_UNKNOWN;
- }
-
- if (Better(ptype, proxy->type)) {
- proxy->type = ptype;
- proxy->address.SetIP(host);
- proxy->address.SetPort(port);
- }
- }
-
- return proxy->type != PROXY_NONE;
-}
-
-UserAgent GetAgent(const char* agent) {
- if (agent) {
- std::string agent_str(agent);
- if (agent_str.find(kFirefoxPattern) != std::string::npos) {
- return UA_FIREFOX;
- } else if (agent_str.find(kInternetExplorerPattern) != std::string::npos) {
- return UA_INTERNETEXPLORER;
- } else if (agent_str.empty()) {
- return UA_UNKNOWN;
- }
- }
- return UA_OTHER;
-}
-
-bool EndsWith(const std::string& a, const std::string& b) {
- if (b.size() > a.size()) {
- return false;
- }
- int result = a.compare(a.size() - b.size(), b.size(), b);
- return result == 0;
-}
-
-bool GetFirefoxProfilePath(Pathname* path) {
-#ifdef WIN32
- wchar_t w_path[MAX_PATH];
- if (SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, w_path) !=
- S_OK) {
- LOG(LS_ERROR) << "SHGetFolderPath failed";
- return false;
- }
- path->SetFolder(ToUtf8(w_path, wcslen(w_path)));
- path->AppendFolder("Mozilla");
- path->AppendFolder("Firefox");
-#elif OSX
- FSRef fr;
- if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
- kCreateFolder, &fr)) {
- LOG(LS_ERROR) << "FSFindFolder failed";
- return false;
- }
- char buffer[NAME_MAX + 1];
- if (0 != FSRefMakePath(&fr, reinterpret_cast<uint8*>(buffer),
- ARRAY_SIZE(buffer))) {
- LOG(LS_ERROR) << "FSRefMakePath failed";
- return false;
- }
- path->SetFolder(std::string(buffer));
- path->AppendFolder("Firefox");
-#else
- char* user_home = getenv("HOME");
- if (user_home == NULL) {
- return false;
- }
- path->SetFolder(std::string(user_home));
- path->AppendFolder(".mozilla");
- path->AppendFolder("firefox");
-#endif // WIN32
- return true;
-}
-
-bool GetDefaultFirefoxProfile(Pathname* profile_path) {
- ASSERT(NULL != profile_path);
- Pathname path;
- if (!GetFirefoxProfilePath(&path)) {
- return false;
- }
-
-#if USE_FIREFOX_PROFILES_INI
- // [Profile0]
- // Name=default
- // IsRelative=1
- // Path=Profiles/2de53ejb.default
- // Default=1
-
- // Note: we are looking for the first entry with "Default=1", or the last
- // entry in the file
- path.SetFilename("profiles.ini");
- scoped_ptr<FileStream> fs(Filesystem::OpenFile(path, "r"));
- if (!fs) {
- return false;
- }
- Pathname candidate;
- bool relative = true;
- std::string line;
- while (fs->ReadLine(&line) == SR_SUCCESS) {
- if (line.length() == 0) {
- continue;
- }
- if (line.at(0) == '[') {
- relative = true;
- candidate.clear();
- } else if (line.find("IsRelative=") == 0 &&
- line.length() >= 12) {
- // TODO: The initial Linux public launch revealed a fairly
- // high number of machines where IsRelative= did not have anything after
- // it. Perhaps that is legal profiles.ini syntax?
- relative = (line.at(11) != '0');
- } else if (line.find("Path=") == 0 &&
- line.length() >= 6) {
- if (relative) {
- candidate = path;
- } else {
- candidate.clear();
- }
- candidate.AppendFolder(line.substr(5));
- } else if (line.find("Default=") == 0 &&
- line.length() >= 9) {
- if ((line.at(8) != '0') && !candidate.empty()) {
- break;
- }
- }
- }
- fs->Close();
- if (candidate.empty()) {
- return false;
- }
- profile_path->SetPathname(candidate.pathname());
-
-#else // !USE_FIREFOX_PROFILES_INI
- path.AppendFolder("Profiles");
- DirectoryIterator* it = Filesystem::IterateDirectory();
- it->Iterate(path);
- std::string extension(".default");
- while (!EndsWith(it->Name(), extension)) {
- if (!it->Next()) {
- return false;
- }
- }
-
- profile_path->SetPathname(path);
- profile->AppendFolder("Profiles");
- profile->AppendFolder(it->Name());
- delete it;
-
-#endif // !USE_FIREFOX_PROFILES_INI
-
- return true;
-}
-
-bool ReadFirefoxPrefs(const Pathname& filename,
- const char * prefix,
- StringMap* settings) {
- scoped_ptr<FileStream> fs(Filesystem::OpenFile(filename, "r"));
- if (!fs) {
- LOG(LS_ERROR) << "Failed to open file: " << filename.pathname();
- return false;
- }
-
- std::string line;
- while (fs->ReadLine(&line) == SR_SUCCESS) {
- size_t prefix_len = strlen(prefix);
-
- // Skip blank lines and too long lines.
- if ((line.length() == 0) || (line.length() > kMaxLineLength)
- || (line.at(0) == '#') || line.compare(0, 2, "/*") == 0
- || line.compare(0, 2, " *") == 0) {
- continue;
- }
-
- char buffer[kMaxLineLength];
- strcpyn(buffer, sizeof(buffer), line.c_str());
- int nstart = 0, nend = 0, vstart = 0, vend = 0;
- sscanf(buffer, "user_pref(\"%n%*[^\"]%n\", %n%*[^)]%n);",
- &nstart, &nend, &vstart, &vend);
- if (vend > 0) {
- char* name = buffer + nstart;
- name[nend - nstart] = 0;
- if ((vend - vstart >= 2) && (buffer[vstart] == '"')) {
- vstart += 1;
- vend -= 1;
- }
- char* value = buffer + vstart;
- value[vend - vstart] = 0;
- if ((strncmp(name, prefix, prefix_len) == 0) && *value) {
- settings->Add(name + prefix_len, value);
- }
- } else {
- LOG_F(LS_WARNING) << "Unparsed pref [" << buffer << "]";
- }
- }
- fs->Close();
- return true;
-}
-
-bool GetFirefoxProxySettings(const char* url, ProxyInfo* proxy) {
- Url<char> purl(url);
- Pathname path;
- bool success = false;
- if (GetDefaultFirefoxProfile(&path)) {
- StringMap settings;
- path.SetFilename("prefs.js");
- if (ReadFirefoxPrefs(path, "network.proxy.", &settings)) {
- success = true;
- proxy->bypass_list =
- settings.Get("no_proxies_on", "localhost, 127.0.0.1");
- if (settings.Get("type") == "1") {
- // User has manually specified a proxy, try to figure out what
- // type it is.
- if (ProxyListMatch(purl, proxy->bypass_list.c_str(), ',')) {
- // Our url is in the list of url's to bypass proxy.
- } else if (settings.Get("share_proxy_settings") == "true") {
- proxy->type = PROXY_UNKNOWN;
- proxy->address.SetIP(settings.Get("http"));
- proxy->address.SetPort(atoi(settings.Get("http_port").c_str()));
- } else if (settings.IsSet("socks")) {
- proxy->type = PROXY_SOCKS5;
- proxy->address.SetIP(settings.Get("socks"));
- proxy->address.SetPort(atoi(settings.Get("socks_port").c_str()));
- } else if (settings.IsSet("ssl")) {
- proxy->type = PROXY_HTTPS;
- proxy->address.SetIP(settings.Get("ssl"));
- proxy->address.SetPort(atoi(settings.Get("ssl_port").c_str()));
- } else if (settings.IsSet("http")) {
- proxy->type = PROXY_HTTPS;
- proxy->address.SetIP(settings.Get("http"));
- proxy->address.SetPort(atoi(settings.Get("http_port").c_str()));
- }
- } else if (settings.Get("type") == "2") {
- // Browser is configured to get proxy settings from a given url.
- proxy->autoconfig_url = settings.Get("autoconfig_url").c_str();
- } else if (settings.Get("type") == "4") {
- // Browser is configured to auto detect proxy config.
- proxy->autodetect = true;
- } else {
- // No proxy set.
- }
- }
- }
- return success;
-}
-
-#ifdef WIN32 // Windows specific implementation for reading Internet
- // Explorer proxy settings.
-
-void LogGetProxyFault() {
- LOG_GLEM(LERROR, WINHTTP) << "WinHttpGetProxyForUrl faulted!!";
-}
-
-BOOL MyWinHttpGetProxyForUrl(pfnWinHttpGetProxyForUrl pWHGPFU,
- HINTERNET hWinHttp, LPCWSTR url,
- WINHTTP_AUTOPROXY_OPTIONS *options,
- WINHTTP_PROXY_INFO *info) {
- // WinHttpGetProxyForUrl() can call plugins which can crash.
- // In the case of McAfee scriptproxy.dll, it does crash in
- // older versions. Try to catch crashes here and treat as an
- // error.
- BOOL success = FALSE;
-
-#if (_HAS_EXCEPTIONS == 0)
- __try {
- success = pWHGPFU(hWinHttp, url, options, info);
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- // This is a separate function to avoid
- // Visual C++ error 2712 when compiling with C++ EH
- LogGetProxyFault();
- }
-#else
- success = pWHGPFU(hWinHttp, url, options, info);
-#endif // (_HAS_EXCEPTIONS == 0)
-
- return success;
-}
-
-bool IsDefaultBrowserFirefox() {
- HKEY key;
- LONG result = RegOpenKeyEx(HKEY_CLASSES_ROOT, L"http\\shell\\open\\command",
- 0, KEY_READ, &key);
- if (ERROR_SUCCESS != result)
- return false;
-
- DWORD size, type;
- bool success = false;
- result = RegQueryValueEx(key, L"", 0, &type, NULL, &size);
- if (result == ERROR_SUCCESS && type == REG_SZ) {
- wchar_t* value = new wchar_t[size+1];
- BYTE* buffer = reinterpret_cast<BYTE*>(value);
- result = RegQueryValueEx(key, L"", 0, &type, buffer, &size);
- if (result == ERROR_SUCCESS) {
- // Size returned by RegQueryValueEx is in bytes, convert to number of
- // wchar_t's.
- size /= sizeof(value[0]);
- value[size] = L'\0';
- for (size_t i = 0; i < size; ++i) {
- value[i] = tolowercase(value[i]);
- }
- success = (NULL != strstr(value, L"firefox.exe"));
- }
- delete[] value;
- }
-
- RegCloseKey(key);
- return success;
-}
-
-bool GetWinHttpProxySettings(const char* url, ProxyInfo* proxy) {
- HMODULE winhttp_handle = LoadLibrary(L"winhttp.dll");
- if (winhttp_handle == NULL) {
- LOG(LS_ERROR) << "Failed to load winhttp.dll.";
- return false;
- }
- WINHTTP_CURRENT_USER_IE_PROXY_CONFIG iecfg;
- memset(&iecfg, 0, sizeof(iecfg));
- Url<char> purl(url);
- pfnWinHttpGetIEProxyConfig pWHGIEPC =
- reinterpret_cast<pfnWinHttpGetIEProxyConfig>(
- GetProcAddress(winhttp_handle,
- "WinHttpGetIEProxyConfigForCurrentUser"));
- bool success = false;
- if (pWHGIEPC && pWHGIEPC(&iecfg)) {
- // We were read proxy config successfully.
- success = true;
- if (iecfg.fAutoDetect) {
- proxy->autodetect = true;
- }
- if (iecfg.lpszAutoConfigUrl) {
- proxy->autoconfig_url = ToUtf8(iecfg.lpszAutoConfigUrl);
- GlobalFree(iecfg.lpszAutoConfigUrl);
- }
- if (iecfg.lpszProxyBypass) {
- proxy->bypass_list = ToUtf8(iecfg.lpszProxyBypass);
- GlobalFree(iecfg.lpszProxyBypass);
- }
- if (iecfg.lpszProxy) {
- if (!ProxyListMatch(purl, proxy->bypass_list, ';')) {
- ParseProxy(ToUtf8(iecfg.lpszProxy), proxy);
- }
- GlobalFree(iecfg.lpszProxy);
- }
- }
- FreeLibrary(winhttp_handle);
- return success;
-}
-
-// Uses the WinHTTP API to auto detect proxy for the given url. Firefox and IE
-// have slightly different option dialogs for proxy settings. In Firefox,
-// either a location of a proxy configuration file can be specified or auto
-// detection can be selected. In IE theese two options can be independently
-// selected. For the case where both options are selected (only IE) we try to
-// fetch the config file first, and if that fails we'll perform an auto
-// detection.
-//
-// Returns true if we successfully performed an auto detection not depending on
-// whether we found a proxy or not. Returns false on error.
-bool WinHttpAutoDetectProxyForUrl(const char* agent, const char* url,
- ProxyInfo* proxy) {
- Url<char> purl(url);
- bool success = true;
- HMODULE winhttp_handle = LoadLibrary(L"winhttp.dll");
- if (winhttp_handle == NULL) {
- LOG(LS_ERROR) << "Failed to load winhttp.dll.";
- return false;
- }
- pfnWinHttpOpen pWHO =
- reinterpret_cast<pfnWinHttpOpen>(GetProcAddress(winhttp_handle,
- "WinHttpOpen"));
- pfnWinHttpCloseHandle pWHCH =
- reinterpret_cast<pfnWinHttpCloseHandle>(
- GetProcAddress(winhttp_handle, "WinHttpCloseHandle"));
- pfnWinHttpGetProxyForUrl pWHGPFU =
- reinterpret_cast<pfnWinHttpGetProxyForUrl>(
- GetProcAddress(winhttp_handle, "WinHttpGetProxyForUrl"));
- if (pWHO && pWHCH && pWHGPFU) {
- if (HINTERNET hWinHttp = pWHO(ToUtf16(agent).c_str(),
- WINHTTP_ACCESS_TYPE_NO_PROXY,
- WINHTTP_NO_PROXY_NAME,
- WINHTTP_NO_PROXY_BYPASS,
- 0)) {
- BOOL result = FALSE;
- WINHTTP_PROXY_INFO info;
- memset(&info, 0, sizeof(info));
- if (proxy->autodetect) {
- // Use DHCP and DNS to try to find any proxy to use.
- WINHTTP_AUTOPROXY_OPTIONS options;
- memset(&options, 0, sizeof(options));
- options.fAutoLogonIfChallenged = TRUE;
-
- options.dwFlags |= WINHTTP_AUTOPROXY_AUTO_DETECT;
- options.dwAutoDetectFlags |= WINHTTP_AUTO_DETECT_TYPE_DHCP
- | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
- result = MyWinHttpGetProxyForUrl(
- pWHGPFU, hWinHttp, ToUtf16(url).c_str(), &options, &info);
- }
- if (!result && !proxy->autoconfig_url.empty()) {
- // We have the location of a proxy config file. Download it and
- // execute it to find proxy settings for our url.
- WINHTTP_AUTOPROXY_OPTIONS options;
- memset(&options, 0, sizeof(options));
- memset(&info, 0, sizeof(info));
- options.fAutoLogonIfChallenged = TRUE;
-
- std::wstring autoconfig_url16((ToUtf16)(proxy->autoconfig_url));
- options.dwFlags |= WINHTTP_AUTOPROXY_CONFIG_URL;
- options.lpszAutoConfigUrl = autoconfig_url16.c_str();
-
- result = MyWinHttpGetProxyForUrl(
- pWHGPFU, hWinHttp, ToUtf16(url).c_str(), &options, &info);
- }
- if (result) {
- // Either the given auto config url was valid or auto
- // detection found a proxy on this network.
- if (info.lpszProxy) {
- // TODO: Does this bypass list differ from the list
- // retreived from GetWinHttpProxySettings earlier?
- if (info.lpszProxyBypass) {
- proxy->bypass_list = ToUtf8(info.lpszProxyBypass);
- GlobalFree(info.lpszProxyBypass);
- } else {
- proxy->bypass_list.clear();
- }
- if (!ProxyListMatch(purl, proxy->bypass_list, ';')) {
- // Found proxy for this URL. If parsing the address turns
- // out ok then we are successful.
- success = ParseProxy(ToUtf8(info.lpszProxy), proxy);
- }
- GlobalFree(info.lpszProxy);
- }
- } else {
- // We could not find any proxy for this url.
- LOG(LS_INFO) << "No proxy detected for " << url;
- }
- pWHCH(hWinHttp);
- }
- } else {
- LOG(LS_ERROR) << "Failed loading WinHTTP functions.";
- success = false;
- }
- FreeLibrary(winhttp_handle);
- return success;
-}
-
-#if 0 // Below functions currently not used.
-
-bool GetJsProxySettings(const char* url, ProxyInfo* proxy) {
- Url<char> purl(url);
- bool success = false;
-
- if (HMODULE hModJS = LoadLibrary(_T("jsproxy.dll"))) {
- pfnInternetGetProxyInfo pIGPI =
- reinterpret_cast<pfnInternetGetProxyInfo>(
- GetProcAddress(hModJS, "InternetGetProxyInfo"));
- if (pIGPI) {
- char proxy[256], host[256];
- memset(proxy, 0, sizeof(proxy));
- char * ptr = proxy;
- DWORD proxylen = sizeof(proxy);
- std::string surl = Utf8String(url);
- DWORD hostlen = _snprintf(host, sizeof(host), "http%s://%S",
- purl.secure() ? "s" : "", purl.server());
- if (pIGPI(surl.data(), surl.size(), host, hostlen, &ptr, &proxylen)) {
- LOG(INFO) << "Proxy: " << proxy;
- } else {
- LOG_GLE(INFO) << "InternetGetProxyInfo";
- }
- }
- FreeLibrary(hModJS);
- }
- return success;
-}
-
-bool GetWmProxySettings(const char* url, ProxyInfo* proxy) {
- Url<char> purl(url);
- bool success = false;
-
- INSNetSourceCreator * nsc = 0;
- HRESULT hr = CoCreateInstance(CLSID_ClientNetManager, 0, CLSCTX_ALL,
- IID_INSNetSourceCreator, (LPVOID *) &nsc);
- if (SUCCEEDED(hr)) {
- if (SUCCEEDED(hr = nsc->Initialize())) {
- VARIANT dispatch;
- VariantInit(&dispatch);
- if (SUCCEEDED(hr = nsc->GetNetSourceAdminInterface(L"http", &dispatch))) {
- IWMSInternalAdminNetSource * ians = 0;
- if (SUCCEEDED(hr = dispatch.pdispVal->QueryInterface(
- IID_IWMSInternalAdminNetSource, (LPVOID *) &ians))) {
- _bstr_t host(purl.server());
- BSTR proxy = 0;
- BOOL bProxyEnabled = FALSE;
- DWORD port, context = 0;
- if (SUCCEEDED(hr = ians->FindProxyForURL(
- L"http", host, &bProxyEnabled, &proxy, &port, &context))) {
- success = true;
- if (bProxyEnabled) {
- _bstr_t sproxy = proxy;
- proxy->ptype = PT_HTTPS;
- proxy->host = sproxy;
- proxy->port = port;
- }
- }
- SysFreeString(proxy);
- if (FAILED(hr = ians->ShutdownProxyContext(context))) {
- LOG(LS_INFO) << "IWMSInternalAdminNetSource::ShutdownProxyContext"
- << "failed: " << hr;
- }
- ians->Release();
- }
- }
- VariantClear(&dispatch);
- if (FAILED(hr = nsc->Shutdown())) {
- LOG(LS_INFO) << "INSNetSourceCreator::Shutdown failed: " << hr;
- }
- }
- nsc->Release();
- }
- return success;
-}
-
-bool GetIePerConnectionProxySettings(const char* url, ProxyInfo* proxy) {
- Url<char> purl(url);
- bool success = false;
-
- INTERNET_PER_CONN_OPTION_LIST list;
- INTERNET_PER_CONN_OPTION options[3];
- memset(&list, 0, sizeof(list));
- memset(&options, 0, sizeof(options));
-
- list.dwSize = sizeof(list);
- list.dwOptionCount = 3;
- list.pOptions = options;
- options[0].dwOption = INTERNET_PER_CONN_FLAGS;
- options[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER;
- options[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS;
- DWORD dwSize = sizeof(list);
-
- if (!InternetQueryOption(0, INTERNET_OPTION_PER_CONNECTION_OPTION, &list,
- &dwSize)) {
- LOG(LS_INFO) << "InternetQueryOption failed: " << GetLastError();
- } else if ((options[0].Value.dwValue & PROXY_TYPE_PROXY) != 0) {
- success = true;
- if (!ProxyListMatch(purl, nonnull(options[2].Value.pszValue), _T(';'))) {
- ParseProxy(nonnull(options[1].Value.pszValue), proxy);
- }
- } else if ((options[0].Value.dwValue & PROXY_TYPE_DIRECT) != 0) {
- success = true;
- } else {
- LOG(LS_INFO) << "unknown internet access type: "
- << options[0].Value.dwValue;
- }
- if (options[1].Value.pszValue) {
- GlobalFree(options[1].Value.pszValue);
- }
- if (options[2].Value.pszValue) {
- GlobalFree(options[2].Value.pszValue);
- }
- return success;
-}
-
-#endif // 0
-
-// Uses the InternetQueryOption function to retrieve proxy settings
-// from the registry. This will only give us the 'static' settings,
-// ie, not any information about auto config etc.
-bool GetIeLanProxySettings(const char* url, ProxyInfo* proxy) {
- Url<char> purl(url);
- bool success = false;
-
- wchar_t buffer[1024];
- memset(buffer, 0, sizeof(buffer));
- INTERNET_PROXY_INFO * info = reinterpret_cast<INTERNET_PROXY_INFO *>(buffer);
- DWORD dwSize = sizeof(buffer);
-
- if (!InternetQueryOption(0, INTERNET_OPTION_PROXY, info, &dwSize)) {
- LOG(LS_INFO) << "InternetQueryOption failed: " << GetLastError();
- } else if (info->dwAccessType == INTERNET_OPEN_TYPE_DIRECT) {
- success = true;
- } else if (info->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
- success = true;
- if (!ProxyListMatch(purl, nonnull(reinterpret_cast<const char*>(
- info->lpszProxyBypass)), ' ')) {
- ParseProxy(nonnull(reinterpret_cast<const char*>(info->lpszProxy)),
- proxy);
- }
- } else {
- LOG(LS_INFO) << "unknown internet access type: " << info->dwAccessType;
- }
- return success;
-}
-
-bool GetIeProxySettings(const char* agent, const char* url, ProxyInfo* proxy) {
- bool success = GetWinHttpProxySettings(url, proxy);
- if (!success) {
- // TODO: Should always call this if no proxy were detected by
- // GetWinHttpProxySettings?
- // WinHttp failed. Try using the InternetOptionQuery method instead.
- return GetIeLanProxySettings(url, proxy);
- }
- return true;
-}
-
-#endif // WIN32
-
-#ifdef OSX // OSX specific implementation for reading system wide
- // proxy settings.
-
-bool p_getProxyInfoForTypeFromDictWithKeys(ProxyInfo* proxy,
- ProxyType type,
- const CFDictionaryRef proxyDict,
- const CFStringRef enabledKey,
- const CFStringRef hostKey,
- const CFStringRef portKey) {
- // whether or not we set up the proxy info.
- bool result = false;
-
- // we use this as a scratch variable for determining if operations
- // succeeded.
- bool converted = false;
-
- // the data we need to construct the SocketAddress for the proxy.
- std::string hostname;
- int port;
-
- if ((proxyDict != NULL) &&
- (CFGetTypeID(proxyDict) == CFDictionaryGetTypeID())) {
- // CoreFoundation stuff that we'll have to get from
- // the dictionaries and interpret or convert into more usable formats.
- CFNumberRef enabledCFNum;
- CFNumberRef portCFNum;
- CFStringRef hostCFStr;
-
- enabledCFNum = (CFNumberRef)CFDictionaryGetValue(proxyDict, enabledKey);
-
- if (p_isCFNumberTrue(enabledCFNum)) {
- // let's see if we can get the address and port.
- hostCFStr = (CFStringRef)CFDictionaryGetValue(proxyDict, hostKey);
- converted = p_convertHostCFStringRefToCPPString(hostCFStr, hostname);
- if (converted) {
- portCFNum = (CFNumberRef)CFDictionaryGetValue(proxyDict, portKey);
- converted = p_convertCFNumberToInt(portCFNum, &port);
- if (converted) {
- // we have something enabled, with a hostname and a port.
- // That's sufficient to set up the proxy info.
- proxy->type = type;
- proxy->address.SetIP(hostname);
- proxy->address.SetPort(port);
- result = true;
- }
- }
- }
- }
-
- return result;
-}
-
-// Looks for proxy information in the given dictionary,
-// return true if it found sufficient information to define one,
-// false otherwise. This is guaranteed to not change the values in proxy
-// unless a full-fledged proxy description was discovered in the dictionary.
-// However, at the present time this does not support username or password.
-// Checks first for a SOCKS proxy, then for HTTPS, then HTTP.
-bool GetMacProxySettingsFromDictionary(ProxyInfo* proxy,
- const CFDictionaryRef proxyDict) {
- // the function result.
- bool gotProxy = false;
-
-
- // first we see if there's a SOCKS proxy in place.
- gotProxy = p_getProxyInfoForTypeFromDictWithKeys(proxy,
- PROXY_SOCKS5,
- proxyDict,
- kSCPropNetProxiesSOCKSEnable,
- kSCPropNetProxiesSOCKSProxy,
- kSCPropNetProxiesSOCKSPort);
-
- if (!gotProxy) {
- // okay, no SOCKS proxy, let's look for https.
- gotProxy = p_getProxyInfoForTypeFromDictWithKeys(proxy,
- PROXY_HTTPS,
- proxyDict,
- kSCPropNetProxiesHTTPSEnable,
- kSCPropNetProxiesHTTPSProxy,
- kSCPropNetProxiesHTTPSPort);
- if (!gotProxy) {
- // Finally, try HTTP proxy. Note that flute doesn't
- // differentiate between HTTPS and HTTP, hence we are using the
- // same flute type here, ie. PROXY_HTTPS.
- gotProxy = p_getProxyInfoForTypeFromDictWithKeys(
- proxy, PROXY_HTTPS, proxyDict, kSCPropNetProxiesHTTPEnable,
- kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort);
- }
- }
- return gotProxy;
-}
-
-// TODO(hughv) Update keychain functions. They work on 10.8, but are depricated.
-#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
-bool p_putPasswordInProxyInfo(ProxyInfo* proxy) {
- bool result = true; // by default we assume we're good.
- // for all we know there isn't any password. We'll set to false
- // if we find a problem.
-
- // Ask the keychain for an internet password search for the given protocol.
- OSStatus oss = 0;
- SecKeychainAttributeList attrList;
- attrList.count = 3;
- SecKeychainAttribute attributes[3];
- attrList.attr = attributes;
-
- attributes[0].tag = kSecProtocolItemAttr;
- attributes[0].length = sizeof(SecProtocolType);
- SecProtocolType protocol;
- switch (proxy->type) {
- case PROXY_HTTPS :
- protocol = kSecProtocolTypeHTTPS;
- break;
- case PROXY_SOCKS5 :
- protocol = kSecProtocolTypeSOCKS;
- break;
- default :
- LOG(LS_ERROR) << "asked for proxy password for unknown proxy type.";
- result = false;
- break;
- }
- attributes[0].data = &protocol;
-
- UInt32 port = proxy->address.port();
- attributes[1].tag = kSecPortItemAttr;
- attributes[1].length = sizeof(UInt32);
- attributes[1].data = &port;
-
- std::string ip = proxy->address.ipaddr().ToString();
- attributes[2].tag = kSecServerItemAttr;
- attributes[2].length = ip.length();
- attributes[2].data = const_cast<char*>(ip.c_str());
-
- if (result) {
- LOG(LS_INFO) << "trying to get proxy username/password";
- SecKeychainSearchRef sref;
- oss = SecKeychainSearchCreateFromAttributes(NULL,
- kSecInternetPasswordItemClass,
- &attrList, &sref);
- if (0 == oss) {
- LOG(LS_INFO) << "SecKeychainSearchCreateFromAttributes was good";
- // Get the first item, if there is one.
- SecKeychainItemRef iref;
- oss = SecKeychainSearchCopyNext(sref, &iref);
- if (0 == oss) {
- LOG(LS_INFO) << "...looks like we have the username/password data";
- // If there is, get the username and the password.
-
- SecKeychainAttributeInfo attribsToGet;
- attribsToGet.count = 1;
- UInt32 tag = kSecAccountItemAttr;
- UInt32 format = CSSM_DB_ATTRIBUTE_FORMAT_STRING;
- void *data;
- UInt32 length;
- SecKeychainAttributeList *localList;
-
- attribsToGet.tag = &tag;
- attribsToGet.format = &format;
- OSStatus copyres = SecKeychainItemCopyAttributesAndData(iref,
- &attribsToGet,
- NULL,
- &localList,
- &length,
- &data);
- if (0 == copyres) {
- LOG(LS_INFO) << "...and we can pull it out.";
- // now, we know from experimentation (sadly not from docs)
- // that the username is in the local attribute list,
- // and the password in the data,
- // both without null termination but with info on their length.
- // grab the password from the data.
- std::string password;
- password.append(static_cast<const char*>(data), length);
-
- // make the password into a CryptString
- // huh, at the time of writing, you can't.
- // so we'll skip that for now and come back to it later.
-
- // now put the username in the proxy.
- if (1 <= localList->attr->length) {
- proxy->username.append(
- static_cast<const char*>(localList->attr->data),
- localList->attr->length);
- LOG(LS_INFO) << "username is " << proxy->username;
- } else {
- LOG(LS_ERROR) << "got keychain entry with no username";
- result = false;
- }
- } else {
- LOG(LS_ERROR) << "couldn't copy info from keychain.";
- result = false;
- }
- SecKeychainItemFreeAttributesAndData(localList, data);
- } else if (errSecItemNotFound == oss) {
- LOG(LS_INFO) << "...username/password info not found";
- } else {
- // oooh, neither 0 nor itemNotFound.
- LOG(LS_ERROR) << "Couldn't get keychain information, error code" << oss;
- result = false;
- }
- } else if (errSecItemNotFound == oss) { // noop
- } else {
- // oooh, neither 0 nor itemNotFound.
- LOG(LS_ERROR) << "Couldn't get keychain information, error code" << oss;
- result = false;
- }
- }
-
- return result;
-}
-
-bool GetMacProxySettings(ProxyInfo* proxy) {
- // based on the Apple Technical Q&A QA1234
- // http://developer.apple.com/qa/qa2001/qa1234.html
- CFDictionaryRef proxyDict = SCDynamicStoreCopyProxies(NULL);
- bool result = false;
-
- if (proxyDict != NULL) {
- // sending it off to another function makes it easier to unit test
- // since we can make our own dictionary to hand to that function.
- result = GetMacProxySettingsFromDictionary(proxy, proxyDict);
-
- if (result) {
- result = p_putPasswordInProxyInfo(proxy);
- }
-
- // We created the dictionary with something that had the
- // word 'copy' in it, so we have to release it, according
- // to the Carbon memory management standards.
- CFRelease(proxyDict);
- } else {
- LOG(LS_ERROR) << "SCDynamicStoreCopyProxies failed";
- }
-
- return result;
-}
-#endif // OSX
-
-bool AutoDetectProxySettings(const char* agent, const char* url,
- ProxyInfo* proxy) {
-#ifdef WIN32
- return WinHttpAutoDetectProxyForUrl(agent, url, proxy);
-#else
- LOG(LS_WARNING) << "Proxy auto-detection not implemented for this platform";
- return false;
-#endif
-}
-
-bool GetSystemDefaultProxySettings(const char* agent, const char* url,
- ProxyInfo* proxy) {
-#ifdef WIN32
- return GetIeProxySettings(agent, url, proxy);
-#elif OSX
- return GetMacProxySettings(proxy);
-#else
- // TODO: Get System settings if browser is not firefox.
- return GetFirefoxProxySettings(url, proxy);
-#endif
-}
-
-bool GetProxySettingsForUrl(const char* agent, const char* url,
- ProxyInfo* proxy, bool long_operation) {
- UserAgent a = GetAgent(agent);
- bool result;
- switch (a) {
- case UA_FIREFOX: {
- result = GetFirefoxProxySettings(url, proxy);
- break;
- }
-#ifdef WIN32
- case UA_INTERNETEXPLORER:
- result = GetIeProxySettings(agent, url, proxy);
- break;
- case UA_UNKNOWN:
- // Agent not defined, check default browser.
- if (IsDefaultBrowserFirefox()) {
- result = GetFirefoxProxySettings(url, proxy);
- } else {
- result = GetIeProxySettings(agent, url, proxy);
- }
- break;
-#endif // WIN32
- default:
- result = GetSystemDefaultProxySettings(agent, url, proxy);
- break;
- }
-
- // TODO: Consider using the 'long_operation' parameter to
- // decide whether to do the auto detection.
- if (result && (proxy->autodetect ||
- !proxy->autoconfig_url.empty())) {
- // Use WinHTTP to auto detect proxy for us.
- result = AutoDetectProxySettings(agent, url, proxy);
- if (!result) {
- // Either auto detection is not supported or we simply didn't
- // find any proxy, reset type.
- proxy->type = talk_base::PROXY_NONE;
- }
- }
- return result;
-}
-
-} // namespace talk_base
diff --git a/base/proxydetect.h b/base/proxydetect.h
deleted file mode 100644
index 4218fbb..0000000
--- a/base/proxydetect.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * libjingle
- * Copyright 2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _PROXYDETECT_H_
-#define _PROXYDETECT_H_
-
-#include "talk/base/proxyinfo.h"
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-namespace talk_base {
-// Auto-detect the proxy server. Returns true if a proxy is configured,
-// although hostname may be empty if the proxy is not required for
-// the given URL.
-
-bool GetProxySettingsForUrl(const char* agent, const char* url,
- talk_base::ProxyInfo* proxy,
- bool long_operation = false);
-
-} // namespace talk_base
-
-#endif // _PROXYDETECT_H_
diff --git a/base/proxydetect_unittest.cc b/base/proxydetect_unittest.cc
deleted file mode 100644
index e09518b..0000000
--- a/base/proxydetect_unittest.cc
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/fileutils_mock.h"
-#include "talk/base/proxydetect.h"
-
-namespace talk_base {
-
-static const std::string kFirefoxProfilesIni =
- "[Profile0]\n"
- "Name=default\n"
- "IsRelative=1\n"
- "Path=Profiles/2de53ejb.default\n"
- "Default=1\n";
-
-static const std::string kFirefoxHeader =
- "# Mozilla User Preferences\n"
- "\n"
- "/* Some Comments\n"
- "*\n"
- "*/\n"
- "\n";
-
-static const std::string kFirefoxCorruptHeader =
- "iuahueqe32164";
-
-static const std::string kProxyAddress = "proxy.net.com";
-
-// Mocking out platform specific path to firefox prefs file.
-class FirefoxPrefsFileSystem : public FakeFileSystem {
- public:
- explicit FirefoxPrefsFileSystem(const std::vector<File>& all_files) :
- FakeFileSystem(all_files) {
- }
- virtual FileStream* OpenFile(const Pathname& filename,
- const std::string& mode) {
- // TODO: We could have a platform dependent check of paths here.
- std::string name = filename.basename();
- name.append(filename.extension());
- EXPECT_TRUE(name.compare("prefs.js") == 0 ||
- name.compare("profiles.ini") == 0);
- FileStream* stream = FakeFileSystem::OpenFile(name, mode);
- return stream;
- }
-};
-
-class ProxyDetectTest : public testing::Test {
-};
-
-bool GetProxyInfo(const std::string prefs, ProxyInfo* info) {
- std::vector<talk_base::FakeFileSystem::File> files;
- files.push_back(talk_base::FakeFileSystem::File("profiles.ini",
- kFirefoxProfilesIni));
- files.push_back(talk_base::FakeFileSystem::File("prefs.js", prefs));
- talk_base::FilesystemScope fs(new talk_base::FirefoxPrefsFileSystem(files));
- return GetProxySettingsForUrl("Firefox", "www.google.com", info, false);
-}
-
-// Verifies that an empty Firefox prefs file results in no proxy detected.
-TEST_F(ProxyDetectTest, DISABLED_TestFirefoxEmptyPrefs) {
- ProxyInfo proxy_info;
- EXPECT_TRUE(GetProxyInfo(kFirefoxHeader, &proxy_info));
- EXPECT_EQ(PROXY_NONE, proxy_info.type);
-}
-
-// Verifies that corrupted prefs file results in no proxy detected.
-TEST_F(ProxyDetectTest, DISABLED_TestFirefoxCorruptedPrefs) {
- ProxyInfo proxy_info;
- EXPECT_TRUE(GetProxyInfo(kFirefoxCorruptHeader, &proxy_info));
- EXPECT_EQ(PROXY_NONE, proxy_info.type);
-}
-
-// Verifies that SOCKS5 proxy is detected if configured. SOCKS uses a
-// handshake protocol to inform the proxy software about the
-// connection that the client is trying to make and may be used for
-// any form of TCP or UDP socket connection.
-TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxySocks) {
- ProxyInfo proxy_info;
- SocketAddress proxy_address("proxy.socks.com", 6666);
- std::string prefs(kFirefoxHeader);
- prefs.append("user_pref(\"network.proxy.socks\", \"proxy.socks.com\");\n");
- prefs.append("user_pref(\"network.proxy.socks_port\", 6666);\n");
- prefs.append("user_pref(\"network.proxy.type\", 1);\n");
-
- EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info));
-
- EXPECT_EQ(PROXY_SOCKS5, proxy_info.type);
- EXPECT_EQ(proxy_address, proxy_info.address);
-}
-
-// Verified that SSL proxy is detected if configured. SSL proxy is an
-// extention of a HTTP proxy to support secure connections.
-TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxySsl) {
- ProxyInfo proxy_info;
- SocketAddress proxy_address("proxy.ssl.com", 7777);
- std::string prefs(kFirefoxHeader);
-
- prefs.append("user_pref(\"network.proxy.ssl\", \"proxy.ssl.com\");\n");
- prefs.append("user_pref(\"network.proxy.ssl_port\", 7777);\n");
- prefs.append("user_pref(\"network.proxy.type\", 1);\n");
-
- EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info));
-
- EXPECT_EQ(PROXY_HTTPS, proxy_info.type);
- EXPECT_EQ(proxy_address, proxy_info.address);
-}
-
-// Verifies that a HTTP proxy is detected if configured.
-TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxyHttp) {
- ProxyInfo proxy_info;
- SocketAddress proxy_address("proxy.http.com", 8888);
- std::string prefs(kFirefoxHeader);
-
- prefs.append("user_pref(\"network.proxy.http\", \"proxy.http.com\");\n");
- prefs.append("user_pref(\"network.proxy.http_port\", 8888);\n");
- prefs.append("user_pref(\"network.proxy.type\", 1);\n");
-
- EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info));
-
- EXPECT_EQ(PROXY_HTTPS, proxy_info.type);
- EXPECT_EQ(proxy_address, proxy_info.address);
-}
-
-// Verifies detection of automatic proxy detection.
-TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxyAuto) {
- ProxyInfo proxy_info;
- std::string prefs(kFirefoxHeader);
-
- prefs.append("user_pref(\"network.proxy.type\", 4);\n");
-
- EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info));
-
- EXPECT_EQ(PROXY_NONE, proxy_info.type);
- EXPECT_TRUE(proxy_info.autodetect);
- EXPECT_TRUE(proxy_info.autoconfig_url.empty());
-}
-
-// Verifies detection of automatic proxy detection using a static url
-// to config file.
-TEST_F(ProxyDetectTest, DISABLED_TestFirefoxProxyAutoUrl) {
- ProxyInfo proxy_info;
- std::string prefs(kFirefoxHeader);
-
- prefs.append(
- "user_pref(\"network.proxy.autoconfig_url\", \"http://a/b.pac\");\n");
- prefs.append("user_pref(\"network.proxy.type\", 2);\n");
-
- EXPECT_TRUE(GetProxyInfo(prefs, &proxy_info));
-
- EXPECT_FALSE(proxy_info.autodetect);
- EXPECT_EQ(PROXY_NONE, proxy_info.type);
- EXPECT_EQ(0, proxy_info.autoconfig_url.compare("http://a/b.pac"));
-}
-
-} // namespace talk_base
diff --git a/base/proxyinfo.cc b/base/proxyinfo.cc
deleted file mode 100644
index 1d9c588..0000000
--- a/base/proxyinfo.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/proxyinfo.h"
-
-namespace talk_base {
-
-const char * ProxyToString(ProxyType proxy) {
- const char * const PROXY_NAMES[] = { "none", "https", "socks5", "unknown" };
- return PROXY_NAMES[proxy];
-}
-
-} // namespace talk_base
diff --git a/base/proxyinfo.h b/base/proxyinfo.h
deleted file mode 100644
index 9e28f1a..0000000
--- a/base/proxyinfo.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_PROXYINFO_H__
-#define TALK_BASE_PROXYINFO_H__
-
-#include <string>
-#include "talk/base/socketaddress.h"
-#include "talk/base/cryptstring.h"
-
-namespace talk_base {
-
-enum ProxyType {
- PROXY_NONE,
- PROXY_HTTPS,
- PROXY_SOCKS5,
- PROXY_UNKNOWN
-};
-const char * ProxyToString(ProxyType proxy);
-
-struct ProxyInfo {
- ProxyType type;
- SocketAddress address;
- std::string autoconfig_url;
- bool autodetect;
- std::string bypass_list;
- std::string username;
- CryptString password;
-
- ProxyInfo() : type(PROXY_NONE), autodetect(false) { }
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_PROXYINFO_H__
diff --git a/base/proxyserver.cc b/base/proxyserver.cc
deleted file mode 100644
index 416a5c7..0000000
--- a/base/proxyserver.cc
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/proxyserver.h"
-
-#include <algorithm>
-#include "talk/base/socketfactory.h"
-
-namespace talk_base {
-
-// ProxyServer
-ProxyServer::ProxyServer(
- SocketFactory* int_factory, const SocketAddress& int_addr,
- SocketFactory* ext_factory, const SocketAddress& ext_ip)
- : ext_factory_(ext_factory), ext_ip_(ext_ip.ipaddr(), 0), // strip off port
- server_socket_(int_factory->CreateAsyncSocket(int_addr.family(),
- SOCK_STREAM)) {
- ASSERT(server_socket_.get() != NULL);
- ASSERT(int_addr.family() == AF_INET || int_addr.family() == AF_INET6);
- server_socket_->Bind(int_addr);
- server_socket_->Listen(5);
- server_socket_->SignalReadEvent.connect(this, &ProxyServer::OnAcceptEvent);
-}
-
-ProxyServer::~ProxyServer() {
- for (BindingList::iterator it = bindings_.begin();
- it != bindings_.end(); ++it) {
- delete (*it);
- }
-}
-
-void ProxyServer::OnAcceptEvent(AsyncSocket* socket) {
- ASSERT(socket != NULL && socket == server_socket_.get());
- AsyncSocket* int_socket = socket->Accept(NULL);
- AsyncProxyServerSocket* wrapped_socket = WrapSocket(int_socket);
- AsyncSocket* ext_socket = ext_factory_->CreateAsyncSocket(ext_ip_.family(),
- SOCK_STREAM);
- if (ext_socket) {
- ext_socket->Bind(ext_ip_);
- bindings_.push_back(new ProxyBinding(wrapped_socket, ext_socket));
- } else {
- LOG(LS_ERROR) << "Unable to create external socket on proxy accept event";
- }
-}
-
-void ProxyServer::OnBindingDestroyed(ProxyBinding* binding) {
- BindingList::iterator it =
- std::find(bindings_.begin(), bindings_.end(), binding);
- delete (*it);
- bindings_.erase(it);
-}
-
-// ProxyBinding
-ProxyBinding::ProxyBinding(AsyncProxyServerSocket* int_socket,
- AsyncSocket* ext_socket)
- : int_socket_(int_socket), ext_socket_(ext_socket), connected_(false),
- out_buffer_(kBufferSize), in_buffer_(kBufferSize) {
- int_socket_->SignalConnectRequest.connect(this,
- &ProxyBinding::OnConnectRequest);
- int_socket_->SignalReadEvent.connect(this, &ProxyBinding::OnInternalRead);
- int_socket_->SignalWriteEvent.connect(this, &ProxyBinding::OnInternalWrite);
- int_socket_->SignalCloseEvent.connect(this, &ProxyBinding::OnInternalClose);
- ext_socket_->SignalConnectEvent.connect(this,
- &ProxyBinding::OnExternalConnect);
- ext_socket_->SignalReadEvent.connect(this, &ProxyBinding::OnExternalRead);
- ext_socket_->SignalWriteEvent.connect(this, &ProxyBinding::OnExternalWrite);
- ext_socket_->SignalCloseEvent.connect(this, &ProxyBinding::OnExternalClose);
-}
-
-void ProxyBinding::OnConnectRequest(AsyncProxyServerSocket* socket,
- const SocketAddress& addr) {
- ASSERT(!connected_ && ext_socket_.get() != NULL);
- ext_socket_->Connect(addr);
- // TODO: handle errors here
-}
-
-void ProxyBinding::OnInternalRead(AsyncSocket* socket) {
- Read(int_socket_.get(), &out_buffer_);
- Write(ext_socket_.get(), &out_buffer_);
-}
-
-void ProxyBinding::OnInternalWrite(AsyncSocket* socket) {
- Write(int_socket_.get(), &in_buffer_);
-}
-
-void ProxyBinding::OnInternalClose(AsyncSocket* socket, int err) {
- Destroy();
-}
-
-void ProxyBinding::OnExternalConnect(AsyncSocket* socket) {
- ASSERT(socket != NULL);
- connected_ = true;
- int_socket_->SendConnectResult(0, socket->GetRemoteAddress());
-}
-
-void ProxyBinding::OnExternalRead(AsyncSocket* socket) {
- Read(ext_socket_.get(), &in_buffer_);
- Write(int_socket_.get(), &in_buffer_);
-}
-
-void ProxyBinding::OnExternalWrite(AsyncSocket* socket) {
- Write(ext_socket_.get(), &out_buffer_);
-}
-
-void ProxyBinding::OnExternalClose(AsyncSocket* socket, int err) {
- if (!connected_) {
- int_socket_->SendConnectResult(err, SocketAddress());
- }
- Destroy();
-}
-
-void ProxyBinding::Read(AsyncSocket* socket, FifoBuffer* buffer) {
- // Only read if the buffer is empty.
- ASSERT(socket != NULL);
- size_t size;
- int read;
- if (buffer->GetBuffered(&size) && size == 0) {
- void* p = buffer->GetWriteBuffer(&size);
- read = socket->Recv(p, size);
- buffer->ConsumeWriteBuffer(_max(read, 0));
- }
-}
-
-void ProxyBinding::Write(AsyncSocket* socket, FifoBuffer* buffer) {
- ASSERT(socket != NULL);
- size_t size;
- int written;
- const void* p = buffer->GetReadData(&size);
- written = socket->Send(p, size);
- buffer->ConsumeReadData(_max(written, 0));
-}
-
-void ProxyBinding::Destroy() {
- SignalDestroyed(this);
-}
-
-} // namespace talk_base
diff --git a/base/proxyserver.h b/base/proxyserver.h
deleted file mode 100644
index 8e1ab6b..0000000
--- a/base/proxyserver.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_PROXYSERVER_H_
-#define TALK_BASE_PROXYSERVER_H_
-
-#include <list>
-#include "talk/base/asyncsocket.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-class SocketFactory;
-
-// ProxyServer is a base class that allows for easy construction of proxy
-// servers. With its helper class ProxyBinding, it contains all the necessary
-// logic for receiving and bridging connections. The specific client-server
-// proxy protocol is implemented by an instance of the AsyncProxyServerSocket
-// class; children of ProxyServer implement WrapSocket appropriately to return
-// the correct protocol handler.
-
-class ProxyBinding : public sigslot::has_slots<> {
- public:
- ProxyBinding(AsyncProxyServerSocket* in_socket, AsyncSocket* out_socket);
- sigslot::signal1<ProxyBinding*> SignalDestroyed;
-
- private:
- void OnConnectRequest(AsyncProxyServerSocket* socket,
- const SocketAddress& addr);
- void OnInternalRead(AsyncSocket* socket);
- void OnInternalWrite(AsyncSocket* socket);
- void OnInternalClose(AsyncSocket* socket, int err);
- void OnExternalConnect(AsyncSocket* socket);
- void OnExternalRead(AsyncSocket* socket);
- void OnExternalWrite(AsyncSocket* socket);
- void OnExternalClose(AsyncSocket* socket, int err);
-
- static void Read(AsyncSocket* socket, FifoBuffer* buffer);
- static void Write(AsyncSocket* socket, FifoBuffer* buffer);
- void Destroy();
-
- static const int kBufferSize = 4096;
- scoped_ptr<AsyncProxyServerSocket> int_socket_;
- scoped_ptr<AsyncSocket> ext_socket_;
- bool connected_;
- FifoBuffer out_buffer_;
- FifoBuffer in_buffer_;
- DISALLOW_EVIL_CONSTRUCTORS(ProxyBinding);
-};
-
-class ProxyServer : public sigslot::has_slots<> {
- public:
- ProxyServer(SocketFactory* int_factory, const SocketAddress& int_addr,
- SocketFactory* ext_factory, const SocketAddress& ext_ip);
- virtual ~ProxyServer();
-
- protected:
- void OnAcceptEvent(AsyncSocket* socket);
- virtual AsyncProxyServerSocket* WrapSocket(AsyncSocket* socket) = 0;
- void OnBindingDestroyed(ProxyBinding* binding);
-
- private:
- typedef std::list<ProxyBinding*> BindingList;
- SocketFactory* ext_factory_;
- SocketAddress ext_ip_;
- scoped_ptr<AsyncSocket> server_socket_;
- BindingList bindings_;
- DISALLOW_EVIL_CONSTRUCTORS(ProxyServer);
-};
-
-// SocksProxyServer is a simple extension of ProxyServer to implement SOCKS.
-class SocksProxyServer : public ProxyServer {
- public:
- SocksProxyServer(SocketFactory* int_factory, const SocketAddress& int_addr,
- SocketFactory* ext_factory, const SocketAddress& ext_ip)
- : ProxyServer(int_factory, int_addr, ext_factory, ext_ip) {
- }
- protected:
- AsyncProxyServerSocket* WrapSocket(AsyncSocket* socket) {
- return new AsyncSocksProxyServerSocket(socket);
- }
- DISALLOW_EVIL_CONSTRUCTORS(SocksProxyServer);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_PROXYSERVER_H_
diff --git a/base/ratelimiter.cc b/base/ratelimiter.cc
deleted file mode 100644
index 6df7a18..0000000
--- a/base/ratelimiter.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/ratelimiter.h"
-
-namespace talk_base {
-
-bool RateLimiter::CanUse(size_t desired, double time) {
- return ((time > period_end_ && desired <= max_per_period_) ||
- (used_in_period_ + desired) <= max_per_period_);
-}
-
-void RateLimiter::Use(size_t used, double time) {
- if (time > period_end_) {
- period_start_ = time;
- period_end_ = time + period_length_;
- used_in_period_ = 0;
- }
- used_in_period_ += used;
-}
-
-} // namespace talk_base
diff --git a/base/ratelimiter.h b/base/ratelimiter.h
deleted file mode 100644
index 255afb4..0000000
--- a/base/ratelimiter.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_RATELIMITER_H_
-#define TALK_BASE_RATELIMITER_H_
-
-#include <stdlib.h>
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-// Limits the rate of use to a certain maximum quantity per period of
-// time. Use, for example, for simple bandwidth throttling.
-//
-// It's implemented like a diet plan: You have so many calories per
-// day. If you hit the limit, you can't eat any more until the next
-// day.
-class RateLimiter {
- public:
- // For example, 100kb per second.
- RateLimiter(size_t max, double period)
- : max_per_period_(max),
- period_length_(period),
- used_in_period_(0),
- period_start_(0.0),
- period_end_(period) {
- }
- virtual ~RateLimiter() {}
-
- // Returns true if if the desired quantity is available in the
- // current period (< (max - used)). Once the given time passes the
- // end of the period, used is set to zero and more use is available.
- bool CanUse(size_t desired, double time);
- // Increment the quantity used this period. If past the end of a
- // period, a new period is started.
- void Use(size_t used, double time);
-
- size_t used_in_period() const {
- return used_in_period_;
- }
-
- size_t max_per_period() const {
- return max_per_period_;
- }
-
- private:
- size_t max_per_period_;
- double period_length_;
- size_t used_in_period_;
- double period_start_;
- double period_end_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_RATELIMITER_H_
diff --git a/base/ratelimiter_unittest.cc b/base/ratelimiter_unittest.cc
deleted file mode 100644
index 3c1a1df..0000000
--- a/base/ratelimiter_unittest.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/ratelimiter.h"
-
-namespace talk_base {
-
-TEST(RateLimiterTest, TestCanUse) {
- // Diet: Can eat 2,000 calories per day.
- RateLimiter limiter = RateLimiter(2000, 1.0);
-
- double monday = 1.0;
- double tuesday = 2.0;
- double thursday = 4.0;
-
- EXPECT_TRUE(limiter.CanUse(0, monday));
- EXPECT_TRUE(limiter.CanUse(1000, monday));
- EXPECT_TRUE(limiter.CanUse(1999, monday));
- EXPECT_TRUE(limiter.CanUse(2000, monday));
- EXPECT_FALSE(limiter.CanUse(2001, monday));
-
- limiter.Use(1000, monday);
-
- EXPECT_TRUE(limiter.CanUse(0, monday));
- EXPECT_TRUE(limiter.CanUse(999, monday));
- EXPECT_TRUE(limiter.CanUse(1000, monday));
- EXPECT_FALSE(limiter.CanUse(1001, monday));
-
- limiter.Use(1000, monday);
-
- EXPECT_TRUE(limiter.CanUse(0, monday));
- EXPECT_FALSE(limiter.CanUse(1, monday));
-
- EXPECT_TRUE(limiter.CanUse(0, tuesday));
- EXPECT_TRUE(limiter.CanUse(1, tuesday));
- EXPECT_TRUE(limiter.CanUse(1999, tuesday));
- EXPECT_TRUE(limiter.CanUse(2000, tuesday));
- EXPECT_FALSE(limiter.CanUse(2001, tuesday));
-
- limiter.Use(1000, tuesday);
-
- EXPECT_TRUE(limiter.CanUse(1000, tuesday));
- EXPECT_FALSE(limiter.CanUse(1001, tuesday));
-
- limiter.Use(1000, thursday);
-
- EXPECT_TRUE(limiter.CanUse(1000, tuesday));
- EXPECT_FALSE(limiter.CanUse(1001, tuesday));
-}
-
-} // namespace talk_base
diff --git a/base/ratetracker.cc b/base/ratetracker.cc
deleted file mode 100644
index 383df93..0000000
--- a/base/ratetracker.cc
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/ratetracker.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-RateTracker::RateTracker()
- : total_units_(0), units_second_(0),
- last_units_second_time_(static_cast<uint32>(-1)),
- last_units_second_calc_(0) {
-}
-
-size_t RateTracker::total_units() const {
- return total_units_;
-}
-
-size_t RateTracker::units_second() {
- // Snapshot units / second calculator. Determine how many seconds have
- // elapsed since our last reference point. If over 1 second, establish
- // a new reference point that is an integer number of seconds since the
- // last one, and compute the units over that interval.
- uint32 current_time = Time();
- if (last_units_second_time_ != static_cast<uint32>(-1)) {
- int delta = talk_base::TimeDiff(current_time, last_units_second_time_);
- if (delta >= 1000) {
- int fraction_time = delta % 1000;
- int seconds = delta / 1000;
- int fraction_units =
- static_cast<int>(total_units_ - last_units_second_calc_) *
- fraction_time / delta;
- // Compute "units received during the interval" / "seconds in interval"
- units_second_ =
- (total_units_ - last_units_second_calc_ - fraction_units) / seconds;
- last_units_second_time_ = current_time - fraction_time;
- last_units_second_calc_ = total_units_ - fraction_units;
- }
- }
- if (last_units_second_time_ == static_cast<uint32>(-1)) {
- last_units_second_time_ = current_time;
- last_units_second_calc_ = total_units_;
- }
-
- return units_second_;
-}
-
-void RateTracker::Update(size_t units) {
- total_units_ += units;
-}
-
-uint32 RateTracker::Time() const {
- return talk_base::Time();
-}
-
-} // namespace talk_base
diff --git a/base/ratetracker.h b/base/ratetracker.h
deleted file mode 100644
index 28c7bb3..0000000
--- a/base/ratetracker.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_RATETRACKER_H_
-#define TALK_BASE_RATETRACKER_H_
-
-#include <stdlib.h>
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-// Computes instantaneous units per second.
-class RateTracker {
- public:
- RateTracker();
- virtual ~RateTracker() {}
-
- size_t total_units() const;
- size_t units_second();
- void Update(size_t units);
-
- protected:
- // overrideable for tests
- virtual uint32 Time() const;
-
- private:
- size_t total_units_;
- size_t units_second_;
- uint32 last_units_second_time_;
- size_t last_units_second_calc_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_RATETRACKER_H_
diff --git a/base/ratetracker_unittest.cc b/base/ratetracker_unittest.cc
deleted file mode 100644
index 979d907..0000000
--- a/base/ratetracker_unittest.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/ratetracker.h"
-
-namespace talk_base {
-
-class RateTrackerForTest : public RateTracker {
- public:
- RateTrackerForTest() : time_(0) {}
- virtual uint32 Time() const { return time_; }
- void AdvanceTime(uint32 delta) { time_ += delta; }
-
- private:
- uint32 time_;
-};
-
-TEST(RateTrackerTest, TestBasics) {
- RateTrackerForTest tracker;
- EXPECT_EQ(0U, tracker.total_units());
- EXPECT_EQ(0U, tracker.units_second());
-
- // Add a sample.
- tracker.Update(1234);
- // Advance the clock by 100 ms.
- tracker.AdvanceTime(100);
- // total_units should advance, but units_second should stay 0.
- EXPECT_EQ(1234U, tracker.total_units());
- EXPECT_EQ(0U, tracker.units_second());
-
- // Repeat.
- tracker.Update(1234);
- tracker.AdvanceTime(100);
- EXPECT_EQ(1234U * 2, tracker.total_units());
- EXPECT_EQ(0U, tracker.units_second());
-
- // Advance the clock by 800 ms, so we've elapsed a full second.
- // units_second should now be filled in properly.
- tracker.AdvanceTime(800);
- EXPECT_EQ(1234U * 2, tracker.total_units());
- EXPECT_EQ(1234U * 2, tracker.units_second());
-
- // Poll the tracker again immediately. The reported rate should stay the same.
- EXPECT_EQ(1234U * 2, tracker.total_units());
- EXPECT_EQ(1234U * 2, tracker.units_second());
-
- // Do nothing and advance by a second. We should drop down to zero.
- tracker.AdvanceTime(1000);
- EXPECT_EQ(1234U * 2, tracker.total_units());
- EXPECT_EQ(0U, tracker.units_second());
-
- // Send a bunch of data at a constant rate for 5.5 "seconds".
- // We should report the rate properly.
- for (int i = 0; i < 5500; i += 100) {
- tracker.Update(9876U);
- tracker.AdvanceTime(100);
- }
- EXPECT_EQ(9876U * 10, tracker.units_second());
-
- // Advance the clock by 500 ms. Since we sent nothing over this half-second,
- // the reported rate should be reduced by half.
- tracker.AdvanceTime(500);
- EXPECT_EQ(9876U * 5, tracker.units_second());
-}
-
-} // namespace talk_base
diff --git a/base/refcount.h b/base/refcount.h
deleted file mode 100644
index e8950e9..0000000
--- a/base/refcount.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_APP_BASE_REFCOUNT_H_
-#define TALK_APP_BASE_REFCOUNT_H_
-
-#include <string.h>
-
-#include "talk/base/criticalsection.h"
-
-namespace talk_base {
-
-// Reference count interface.
-class RefCountInterface {
- public:
- virtual int AddRef() = 0;
- virtual int Release() = 0;
- protected:
- virtual ~RefCountInterface() {}
-};
-
-template <class T>
-class RefCountedObject : public T {
- public:
- RefCountedObject() : ref_count_(0) {
- }
-
- template<typename P>
- explicit RefCountedObject(P p) : T(p), ref_count_(0) {
- }
-
- template<typename P1, typename P2>
- RefCountedObject(P1 p1, P2 p2) : T(p1, p2), ref_count_(0) {
- }
-
- template<typename P1, typename P2, typename P3>
- RefCountedObject(P1 p1, P2 p2, P3 p3) : T(p1, p2, p3), ref_count_(0) {
- }
-
- template<typename P1, typename P2, typename P3, typename P4>
- RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4)
- : T(p1, p2, p3, p4), ref_count_(0) {
- }
-
- template<typename P1, typename P2, typename P3, typename P4, typename P5>
- RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
- : T(p1, p2, p3, p4, p5), ref_count_(0) {
- }
-
- virtual int AddRef() {
- return talk_base::AtomicOps::Increment(&ref_count_);
- }
-
- virtual int Release() {
- int count = talk_base::AtomicOps::Decrement(&ref_count_);
- if (!count) {
- delete this;
- }
- return count;
- }
-
- protected:
- virtual ~RefCountedObject() {
- }
-
- int ref_count_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_APP_BASE_REFCOUNT_H_
diff --git a/base/referencecountedsingletonfactory.h b/base/referencecountedsingletonfactory.h
deleted file mode 100644
index 7f90b04..0000000
--- a/base/referencecountedsingletonfactory.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_
-#define TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_
-
-#include "talk/base/common.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-template <typename Interface> class rcsf_ptr;
-
-// A ReferenceCountedSingletonFactory is an object which owns another object,
-// and doles out the owned object to consumers in a reference-counted manner.
-// Thus, the factory owns at most one object of the desired kind, and
-// hands consumers a special pointer to it, through which they can access it.
-// When the consumers delete the pointer, the reference count goes down,
-// and if the reference count hits zero, the factory can throw the object
-// away. If a consumer requests the pointer and the factory has none,
-// it can create one on the fly and pass it back.
-template <typename Interface>
-class ReferenceCountedSingletonFactory {
- friend class rcsf_ptr<Interface>;
- public:
- ReferenceCountedSingletonFactory() : ref_count_(0) {}
-
- virtual ~ReferenceCountedSingletonFactory() {
- ASSERT(ref_count_ == 0);
- }
-
- protected:
- // Must be implemented in a sub-class. The sub-class may choose whether or not
- // to cache the instance across lifetimes by either reset()'ing or not
- // reset()'ing the scoped_ptr in CleanupInstance().
- virtual bool SetupInstance() = 0;
- virtual void CleanupInstance() = 0;
-
- scoped_ptr<Interface> instance_;
-
- private:
- Interface* GetInstance() {
- talk_base::CritScope cs(&crit_);
- if (ref_count_ == 0) {
- if (!SetupInstance()) {
- LOG(LS_VERBOSE) << "Failed to setup instance";
- return NULL;
- }
- ASSERT(instance_.get() != NULL);
- }
- ++ref_count_;
-
- LOG(LS_VERBOSE) << "Number of references: " << ref_count_;
- return instance_.get();
- }
-
- void ReleaseInstance() {
- talk_base::CritScope cs(&crit_);
- ASSERT(ref_count_ > 0);
- ASSERT(instance_.get() != NULL);
- --ref_count_;
- LOG(LS_VERBOSE) << "Number of references: " << ref_count_;
- if (ref_count_ == 0) {
- CleanupInstance();
- }
- }
-
- CriticalSection crit_;
- int ref_count_;
-
- DISALLOW_COPY_AND_ASSIGN(ReferenceCountedSingletonFactory);
-};
-
-template <typename Interface>
-class rcsf_ptr {
- public:
- // Create a pointer that uses the factory to get the instance.
- // This is lazy - it won't generate the instance until it is requested.
- explicit rcsf_ptr(ReferenceCountedSingletonFactory<Interface>* factory)
- : instance_(NULL),
- factory_(factory) {
- }
-
- ~rcsf_ptr() {
- release();
- }
-
- Interface& operator*() {
- EnsureAcquired();
- return *instance_;
- }
-
- Interface* operator->() {
- EnsureAcquired();
- return instance_;
- }
-
- // Gets the pointer, creating the singleton if necessary. May return NULL if
- // creation failed.
- Interface* get() {
- Acquire();
- return instance_;
- }
-
- // Set instance to NULL and tell the factory we aren't using the instance
- // anymore.
- void release() {
- if (instance_) {
- instance_ = NULL;
- factory_->ReleaseInstance();
- }
- }
-
- // Lets us know whether instance is valid or not right now.
- // Even though attempts to use the instance will automatically create it, it
- // is advisable to check this because creation can fail.
- bool valid() const {
- return instance_ != NULL;
- }
-
- // Returns the factory that this pointer is using.
- ReferenceCountedSingletonFactory<Interface>* factory() const {
- return factory_;
- }
-
- private:
- void EnsureAcquired() {
- Acquire();
- ASSERT(instance_ != NULL);
- }
-
- void Acquire() {
- // Since we're getting a singleton back, acquire is a noop if instance is
- // already populated.
- if (!instance_) {
- instance_ = factory_->GetInstance();
- }
- }
-
- Interface* instance_;
- ReferenceCountedSingletonFactory<Interface>* factory_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(rcsf_ptr);
-};
-
-}; // namespace talk_base
-
-#endif // TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_
diff --git a/base/referencecountedsingletonfactory_unittest.cc b/base/referencecountedsingletonfactory_unittest.cc
deleted file mode 100644
index 3fc7fd2..0000000
--- a/base/referencecountedsingletonfactory_unittest.cc
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/referencecountedsingletonfactory.h"
-
-namespace talk_base {
-
-class MyExistenceWatcher {
- public:
- MyExistenceWatcher() { create_called_ = true; }
- ~MyExistenceWatcher() { delete_called_ = true; }
-
- static bool create_called_;
- static bool delete_called_;
-};
-
-bool MyExistenceWatcher::create_called_ = false;
-bool MyExistenceWatcher::delete_called_ = false;
-
-class TestReferenceCountedSingletonFactory :
- public ReferenceCountedSingletonFactory<MyExistenceWatcher> {
- protected:
- virtual bool SetupInstance() {
- instance_.reset(new MyExistenceWatcher());
- return true;
- }
-
- virtual void CleanupInstance() {
- instance_.reset();
- }
-};
-
-static void DoCreateAndGoOutOfScope(
- ReferenceCountedSingletonFactory<MyExistenceWatcher> *factory) {
- rcsf_ptr<MyExistenceWatcher> ptr(factory);
- ptr.get();
- // and now ptr should go out of scope.
-}
-
-TEST(ReferenceCountedSingletonFactory, ZeroReferenceCountCausesDeletion) {
- TestReferenceCountedSingletonFactory factory;
- MyExistenceWatcher::delete_called_ = false;
- DoCreateAndGoOutOfScope(&factory);
- EXPECT_TRUE(MyExistenceWatcher::delete_called_);
-}
-
-TEST(ReferenceCountedSingletonFactory, NonZeroReferenceCountDoesNotDelete) {
- TestReferenceCountedSingletonFactory factory;
- rcsf_ptr<MyExistenceWatcher> ptr(&factory);
- ptr.get();
- MyExistenceWatcher::delete_called_ = false;
- DoCreateAndGoOutOfScope(&factory);
- EXPECT_FALSE(MyExistenceWatcher::delete_called_);
-}
-
-TEST(ReferenceCountedSingletonFactory, ReturnedPointersReferToSameThing) {
- TestReferenceCountedSingletonFactory factory;
- rcsf_ptr<MyExistenceWatcher> one(&factory), two(&factory);
-
- EXPECT_EQ(one.get(), two.get());
-}
-
-TEST(ReferenceCountedSingletonFactory, Release) {
- TestReferenceCountedSingletonFactory factory;
-
- rcsf_ptr<MyExistenceWatcher> one(&factory);
- one.get();
-
- MyExistenceWatcher::delete_called_ = false;
- one.release();
- EXPECT_TRUE(MyExistenceWatcher::delete_called_);
-}
-
-TEST(ReferenceCountedSingletonFactory, GetWithoutRelease) {
- TestReferenceCountedSingletonFactory factory;
- rcsf_ptr<MyExistenceWatcher> one(&factory);
- one.get();
-
- MyExistenceWatcher::create_called_ = false;
- one.get();
- EXPECT_FALSE(MyExistenceWatcher::create_called_);
-}
-
-TEST(ReferenceCountedSingletonFactory, GetAfterRelease) {
- TestReferenceCountedSingletonFactory factory;
- rcsf_ptr<MyExistenceWatcher> one(&factory);
-
- MyExistenceWatcher::create_called_ = false;
- one.release();
- one.get();
- EXPECT_TRUE(MyExistenceWatcher::create_called_);
-}
-
-TEST(ReferenceCountedSingletonFactory, MultipleReleases) {
- TestReferenceCountedSingletonFactory factory;
- rcsf_ptr<MyExistenceWatcher> one(&factory), two(&factory);
-
- MyExistenceWatcher::create_called_ = false;
- MyExistenceWatcher::delete_called_ = false;
- one.release();
- EXPECT_FALSE(MyExistenceWatcher::delete_called_);
- one.release();
- EXPECT_FALSE(MyExistenceWatcher::delete_called_);
- one.release();
- EXPECT_FALSE(MyExistenceWatcher::delete_called_);
- one.get();
- EXPECT_TRUE(MyExistenceWatcher::create_called_);
-}
-
-TEST(ReferenceCountedSingletonFactory, Existentialism) {
- TestReferenceCountedSingletonFactory factory;
-
- rcsf_ptr<MyExistenceWatcher> one(&factory);
-
- MyExistenceWatcher::create_called_ = false;
- MyExistenceWatcher::delete_called_ = false;
-
- one.get();
- EXPECT_TRUE(MyExistenceWatcher::create_called_);
- one.release();
- EXPECT_TRUE(MyExistenceWatcher::delete_called_);
-}
-
-} // namespace talk_base
diff --git a/base/rollingaccumulator.h b/base/rollingaccumulator.h
deleted file mode 100644
index dfda8fe..0000000
--- a/base/rollingaccumulator.h
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_ROLLINGACCUMULATOR_H_
-#define TALK_BASE_ROLLINGACCUMULATOR_H_
-
-#include <vector>
-
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-// RollingAccumulator stores and reports statistics
-// over N most recent samples.
-//
-// T is assumed to be an int, long, double or float.
-template<typename T>
-class RollingAccumulator {
- public:
- explicit RollingAccumulator(size_t max_count)
- : samples_(max_count) {
- Reset();
- }
- ~RollingAccumulator() {
- }
-
- size_t max_count() const {
- return samples_.size();
- }
-
- size_t count() const {
- return count_;
- }
-
- void Reset() {
- count_ = 0U;
- next_index_ = 0U;
- sum_ = 0.0;
- sum_2_ = 0.0;
- max_ = T();
- max_stale_ = false;
- min_ = T();
- min_stale_ = false;
- }
-
- void AddSample(T sample) {
- if (count_ == max_count()) {
- // Remove oldest sample.
- T sample_to_remove = samples_[next_index_];
- sum_ -= sample_to_remove;
- sum_2_ -= sample_to_remove * sample_to_remove;
- if (sample_to_remove >= max_) {
- max_stale_ = true;
- }
- if (sample_to_remove <= min_) {
- min_stale_ = true;
- }
- } else {
- // Increase count of samples.
- ++count_;
- }
- // Add new sample.
- samples_[next_index_] = sample;
- sum_ += sample;
- sum_2_ += sample * sample;
- if (count_ == 1 || sample >= max_) {
- max_ = sample;
- max_stale_ = false;
- }
- if (count_ == 1 || sample <= min_) {
- min_ = sample;
- min_stale_ = false;
- }
- // Update next_index_.
- next_index_ = (next_index_ + 1) % max_count();
- }
-
- T ComputeSum() const {
- return static_cast<T>(sum_);
- }
-
- double ComputeMean() const {
- if (count_ == 0) {
- return 0.0;
- }
- return sum_ / count_;
- }
-
- T ComputeMax() const {
- if (max_stale_) {
- ASSERT(count_ > 0 &&
- "It shouldn't be possible for max_stale_ && count_ == 0");
- max_ = samples_[next_index_];
- for (size_t i = 1u; i < count_; i++) {
- max_ = _max(max_, samples_[(next_index_ + i) % max_count()]);
- }
- max_stale_ = false;
- }
- return max_;
- }
-
- T ComputeMin() const {
- if (min_stale_) {
- ASSERT(count_ > 0 &&
- "It shouldn't be possible for min_stale_ && count_ == 0");
- min_ = samples_[next_index_];
- for (size_t i = 1u; i < count_; i++) {
- min_ = _min(min_, samples_[(next_index_ + i) % max_count()]);
- }
- min_stale_ = false;
- }
- return min_;
- }
-
- // O(n) time complexity.
- // Weights nth sample with weight (learning_rate)^n. Learning_rate should be
- // between (0.0, 1.0], otherwise the non-weighted mean is returned.
- double ComputeWeightedMean(double learning_rate) const {
- if (count_ < 1 || learning_rate <= 0.0 || learning_rate >= 1.0) {
- return ComputeMean();
- }
- double weighted_mean = 0.0;
- double current_weight = 1.0;
- double weight_sum = 0.0;
- const size_t max_size = max_count();
- for (size_t i = 0; i < count_; ++i) {
- current_weight *= learning_rate;
- weight_sum += current_weight;
- // Add max_size to prevent underflow.
- size_t index = (next_index_ + max_size - i - 1) % max_size;
- weighted_mean += current_weight * samples_[index];
- }
- return weighted_mean / weight_sum;
- }
-
- // Compute estimated variance. Estimation is more accurate
- // as the number of samples grows.
- double ComputeVariance() const {
- if (count_ == 0) {
- return 0.0;
- }
- // Var = E[x^2] - (E[x])^2
- double count_inv = 1.0 / count_;
- double mean_2 = sum_2_ * count_inv;
- double mean = sum_ * count_inv;
- return mean_2 - (mean * mean);
- }
-
- private:
- size_t count_;
- size_t next_index_;
- double sum_; // Sum(x) - double to avoid overflow
- double sum_2_; // Sum(x*x) - double to avoid overflow
- mutable T max_;
- mutable bool max_stale_;
- mutable T min_;
- mutable bool min_stale_;
- std::vector<T> samples_;
-
- DISALLOW_COPY_AND_ASSIGN(RollingAccumulator);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_ROLLINGACCUMULATOR_H_
diff --git a/base/rollingaccumulator_unittest.cc b/base/rollingaccumulator_unittest.cc
deleted file mode 100644
index e6d0ea2..0000000
--- a/base/rollingaccumulator_unittest.cc
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/rollingaccumulator.h"
-
-namespace talk_base {
-
-namespace {
-
-const double kLearningRate = 0.5;
-
-} // namespace
-
-TEST(RollingAccumulatorTest, ZeroSamples) {
- RollingAccumulator<int> accum(10);
-
- EXPECT_EQ(0U, accum.count());
- EXPECT_DOUBLE_EQ(0.0, accum.ComputeMean());
- EXPECT_DOUBLE_EQ(0.0, accum.ComputeVariance());
- EXPECT_EQ(0, accum.ComputeMin());
- EXPECT_EQ(0, accum.ComputeMax());
-}
-
-TEST(RollingAccumulatorTest, SomeSamples) {
- RollingAccumulator<int> accum(10);
- for (int i = 0; i < 4; ++i) {
- accum.AddSample(i);
- }
-
- EXPECT_EQ(4U, accum.count());
- EXPECT_EQ(6, accum.ComputeSum());
- EXPECT_DOUBLE_EQ(1.5, accum.ComputeMean());
- EXPECT_NEAR(2.26666, accum.ComputeWeightedMean(kLearningRate), 0.01);
- EXPECT_DOUBLE_EQ(1.25, accum.ComputeVariance());
- EXPECT_EQ(0, accum.ComputeMin());
- EXPECT_EQ(3, accum.ComputeMax());
-}
-
-TEST(RollingAccumulatorTest, RollingSamples) {
- RollingAccumulator<int> accum(10);
- for (int i = 0; i < 12; ++i) {
- accum.AddSample(i);
- }
-
- EXPECT_EQ(10U, accum.count());
- EXPECT_EQ(65, accum.ComputeSum());
- EXPECT_DOUBLE_EQ(6.5, accum.ComputeMean());
- EXPECT_NEAR(10.0, accum.ComputeWeightedMean(kLearningRate), 0.01);
- EXPECT_NEAR(9.0, accum.ComputeVariance(), 1.0);
- EXPECT_EQ(2, accum.ComputeMin());
- EXPECT_EQ(11, accum.ComputeMax());
-}
-
-TEST(RollingAccumulatorTest, ResetSamples) {
- RollingAccumulator<int> accum(10);
-
- for (int i = 0; i < 10; ++i) {
- accum.AddSample(100);
- }
- EXPECT_EQ(10U, accum.count());
- EXPECT_DOUBLE_EQ(100.0, accum.ComputeMean());
- EXPECT_EQ(100, accum.ComputeMin());
- EXPECT_EQ(100, accum.ComputeMax());
-
- accum.Reset();
- EXPECT_EQ(0U, accum.count());
-
- for (int i = 0; i < 5; ++i) {
- accum.AddSample(i);
- }
-
- EXPECT_EQ(5U, accum.count());
- EXPECT_EQ(10, accum.ComputeSum());
- EXPECT_DOUBLE_EQ(2.0, accum.ComputeMean());
- EXPECT_EQ(0, accum.ComputeMin());
- EXPECT_EQ(4, accum.ComputeMax());
-}
-
-TEST(RollingAccumulatorTest, RollingSamplesDouble) {
- RollingAccumulator<double> accum(10);
- for (int i = 0; i < 23; ++i) {
- accum.AddSample(5 * i);
- }
-
- EXPECT_EQ(10u, accum.count());
- EXPECT_DOUBLE_EQ(875.0, accum.ComputeSum());
- EXPECT_DOUBLE_EQ(87.5, accum.ComputeMean());
- EXPECT_NEAR(105.049, accum.ComputeWeightedMean(kLearningRate), 0.1);
- EXPECT_NEAR(229.166667, accum.ComputeVariance(), 25);
- EXPECT_DOUBLE_EQ(65.0, accum.ComputeMin());
- EXPECT_DOUBLE_EQ(110.0, accum.ComputeMax());
-}
-
-TEST(RollingAccumulatorTest, ComputeWeightedMeanCornerCases) {
- RollingAccumulator<int> accum(10);
- EXPECT_DOUBLE_EQ(0.0, accum.ComputeWeightedMean(kLearningRate));
- EXPECT_DOUBLE_EQ(0.0, accum.ComputeWeightedMean(0.0));
- EXPECT_DOUBLE_EQ(0.0, accum.ComputeWeightedMean(1.1));
-
- for (int i = 0; i < 8; ++i) {
- accum.AddSample(i);
- }
-
- EXPECT_DOUBLE_EQ(3.5, accum.ComputeMean());
- EXPECT_DOUBLE_EQ(3.5, accum.ComputeWeightedMean(0));
- EXPECT_DOUBLE_EQ(3.5, accum.ComputeWeightedMean(1.1));
- EXPECT_NEAR(6.0, accum.ComputeWeightedMean(kLearningRate), 0.1);
-}
-
-} // namespace talk_base
diff --git a/base/safe_conversions.h b/base/safe_conversions.h
deleted file mode 100644
index d246d4f..0000000
--- a/base/safe_conversions.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * libjingle
- * Copyright 2014, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Borrowed from Chromium's src/base/numerics/safe_conversions.h.
-
-#ifndef TALK_BASE_SAFE_CONVERSIONS_H_
-#define TALK_BASE_SAFE_CONVERSIONS_H_
-
-#include <limits>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/safe_conversions_impl.h"
-
-namespace talk_base {
-
-inline void Check(bool condition) {
- if (!condition) {
- LOG(LS_ERROR) << "CHECK failed.";
- Break();
- // The program should have crashed at this point.
- }
-}
-
-// Convenience function that returns true if the supplied value is in range
-// for the destination type.
-template <typename Dst, typename Src>
-inline bool IsValueInRangeForNumericType(Src value) {
- return internal::RangeCheck<Dst>(value) == internal::TYPE_VALID;
-}
-
-// checked_cast<> is analogous to static_cast<> for numeric types,
-// except that it CHECKs that the specified numeric conversion will not
-// overflow or underflow. NaN source will always trigger a CHECK.
-template <typename Dst, typename Src>
-inline Dst checked_cast(Src value) {
- Check(IsValueInRangeForNumericType<Dst>(value));
- return static_cast<Dst>(value);
-}
-
-// saturated_cast<> is analogous to static_cast<> for numeric types, except
-// that the specified numeric conversion will saturate rather than overflow or
-// underflow. NaN assignment to an integral will trigger a CHECK condition.
-template <typename Dst, typename Src>
-inline Dst saturated_cast(Src value) {
- // Optimization for floating point values, which already saturate.
- if (std::numeric_limits<Dst>::is_iec559)
- return static_cast<Dst>(value);
-
- switch (internal::RangeCheck<Dst>(value)) {
- case internal::TYPE_VALID:
- return static_cast<Dst>(value);
-
- case internal::TYPE_UNDERFLOW:
- return std::numeric_limits<Dst>::min();
-
- case internal::TYPE_OVERFLOW:
- return std::numeric_limits<Dst>::max();
-
- // Should fail only on attempting to assign NaN to a saturated integer.
- case internal::TYPE_INVALID:
- Check(false);
- return std::numeric_limits<Dst>::max();
- }
-
- Check(false); // NOTREACHED();
- return static_cast<Dst>(value);
-}
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SAFE_CONVERSIONS_H_
diff --git a/base/safe_conversions_impl.h b/base/safe_conversions_impl.h
deleted file mode 100644
index 391e596..0000000
--- a/base/safe_conversions_impl.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * libjingle
- * Copyright 2014, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Borrowed from Chromium's src/base/numerics/safe_conversions_impl.h.
-
-#ifndef TALK_BASE_SAFE_CONVERSIONS_IMPL_H_
-#define TALK_BASE_SAFE_CONVERSIONS_IMPL_H_
-
-#include <limits>
-
-namespace talk_base {
-namespace internal {
-
-enum DstSign {
- DST_UNSIGNED,
- DST_SIGNED
-};
-
-enum SrcSign {
- SRC_UNSIGNED,
- SRC_SIGNED
-};
-
-enum DstRange {
- OVERLAPS_RANGE,
- CONTAINS_RANGE
-};
-
-// Helper templates to statically determine if our destination type can contain
-// all values represented by the source type.
-
-template <typename Dst, typename Src,
- DstSign IsDstSigned = std::numeric_limits<Dst>::is_signed ?
- DST_SIGNED : DST_UNSIGNED,
- SrcSign IsSrcSigned = std::numeric_limits<Src>::is_signed ?
- SRC_SIGNED : SRC_UNSIGNED>
-struct StaticRangeCheck {};
-
-template <typename Dst, typename Src>
-struct StaticRangeCheck<Dst, Src, DST_SIGNED, SRC_SIGNED> {
- typedef std::numeric_limits<Dst> DstLimits;
- typedef std::numeric_limits<Src> SrcLimits;
- // Compare based on max_exponent, which we must compute for integrals.
- static const size_t kDstMaxExponent = DstLimits::is_iec559 ?
- DstLimits::max_exponent :
- (sizeof(Dst) * 8 - 1);
- static const size_t kSrcMaxExponent = SrcLimits::is_iec559 ?
- SrcLimits::max_exponent :
- (sizeof(Src) * 8 - 1);
- static const DstRange value = kDstMaxExponent >= kSrcMaxExponent ?
- CONTAINS_RANGE : OVERLAPS_RANGE;
-};
-
-template <typename Dst, typename Src>
-struct StaticRangeCheck<Dst, Src, DST_UNSIGNED, SRC_UNSIGNED> {
- static const DstRange value = sizeof(Dst) >= sizeof(Src) ?
- CONTAINS_RANGE : OVERLAPS_RANGE;
-};
-
-template <typename Dst, typename Src>
-struct StaticRangeCheck<Dst, Src, DST_SIGNED, SRC_UNSIGNED> {
- typedef std::numeric_limits<Dst> DstLimits;
- typedef std::numeric_limits<Src> SrcLimits;
- // Compare based on max_exponent, which we must compute for integrals.
- static const size_t kDstMaxExponent = DstLimits::is_iec559 ?
- DstLimits::max_exponent :
- (sizeof(Dst) * 8 - 1);
- static const size_t kSrcMaxExponent = sizeof(Src) * 8;
- static const DstRange value = kDstMaxExponent >= kSrcMaxExponent ?
- CONTAINS_RANGE : OVERLAPS_RANGE;
-};
-
-template <typename Dst, typename Src>
-struct StaticRangeCheck<Dst, Src, DST_UNSIGNED, SRC_SIGNED> {
- static const DstRange value = OVERLAPS_RANGE;
-};
-
-
-enum RangeCheckResult {
- TYPE_VALID = 0, // Value can be represented by the destination type.
- TYPE_UNDERFLOW = 1, // Value would overflow.
- TYPE_OVERFLOW = 2, // Value would underflow.
- TYPE_INVALID = 3 // Source value is invalid (i.e. NaN).
-};
-
-// This macro creates a RangeCheckResult from an upper and lower bound
-// check by taking advantage of the fact that only NaN can be out of range in
-// both directions at once.
-#define BASE_NUMERIC_RANGE_CHECK_RESULT(is_in_upper_bound, is_in_lower_bound) \
- RangeCheckResult(((is_in_upper_bound) ? 0 : TYPE_OVERFLOW) | \
- ((is_in_lower_bound) ? 0 : TYPE_UNDERFLOW))
-
-template <typename Dst,
- typename Src,
- DstSign IsDstSigned = std::numeric_limits<Dst>::is_signed ?
- DST_SIGNED : DST_UNSIGNED,
- SrcSign IsSrcSigned = std::numeric_limits<Src>::is_signed ?
- SRC_SIGNED : SRC_UNSIGNED,
- DstRange IsSrcRangeContained = StaticRangeCheck<Dst, Src>::value>
-struct RangeCheckImpl {};
-
-// The following templates are for ranges that must be verified at runtime. We
-// split it into checks based on signedness to avoid confusing casts and
-// compiler warnings on signed an unsigned comparisons.
-
-// Dst range always contains the result: nothing to check.
-template <typename Dst, typename Src, DstSign IsDstSigned, SrcSign IsSrcSigned>
-struct RangeCheckImpl<Dst, Src, IsDstSigned, IsSrcSigned, CONTAINS_RANGE> {
- static RangeCheckResult Check(Src value) {
- return TYPE_VALID;
- }
-};
-
-// Signed to signed narrowing.
-template <typename Dst, typename Src>
-struct RangeCheckImpl<Dst, Src, DST_SIGNED, SRC_SIGNED, OVERLAPS_RANGE> {
- static RangeCheckResult Check(Src value) {
- typedef std::numeric_limits<Dst> DstLimits;
- return DstLimits::is_iec559 ?
- BASE_NUMERIC_RANGE_CHECK_RESULT(
- value <= static_cast<Src>(DstLimits::max()),
- value >= static_cast<Src>(DstLimits::max() * -1)) :
- BASE_NUMERIC_RANGE_CHECK_RESULT(
- value <= static_cast<Src>(DstLimits::max()),
- value >= static_cast<Src>(DstLimits::min()));
- }
-};
-
-// Unsigned to unsigned narrowing.
-template <typename Dst, typename Src>
-struct RangeCheckImpl<Dst, Src, DST_UNSIGNED, SRC_UNSIGNED, OVERLAPS_RANGE> {
- static RangeCheckResult Check(Src value) {
- typedef std::numeric_limits<Dst> DstLimits;
- return BASE_NUMERIC_RANGE_CHECK_RESULT(
- value <= static_cast<Src>(DstLimits::max()), true);
- }
-};
-
-// Unsigned to signed.
-template <typename Dst, typename Src>
-struct RangeCheckImpl<Dst, Src, DST_SIGNED, SRC_UNSIGNED, OVERLAPS_RANGE> {
- static RangeCheckResult Check(Src value) {
- typedef std::numeric_limits<Dst> DstLimits;
- return sizeof(Dst) > sizeof(Src) ? TYPE_VALID :
- BASE_NUMERIC_RANGE_CHECK_RESULT(
- value <= static_cast<Src>(DstLimits::max()), true);
- }
-};
-
-// Signed to unsigned.
-template <typename Dst, typename Src>
-struct RangeCheckImpl<Dst, Src, DST_UNSIGNED, SRC_SIGNED, OVERLAPS_RANGE> {
- static RangeCheckResult Check(Src value) {
- typedef std::numeric_limits<Dst> DstLimits;
- typedef std::numeric_limits<Src> SrcLimits;
- // Compare based on max_exponent, which we must compute for integrals.
- static const size_t kDstMaxExponent = sizeof(Dst) * 8;
- static const size_t kSrcMaxExponent = SrcLimits::is_iec559 ?
- SrcLimits::max_exponent :
- (sizeof(Src) * 8 - 1);
- return (kDstMaxExponent >= kSrcMaxExponent) ?
- BASE_NUMERIC_RANGE_CHECK_RESULT(true, value >= static_cast<Src>(0)) :
- BASE_NUMERIC_RANGE_CHECK_RESULT(
- value <= static_cast<Src>(DstLimits::max()),
- value >= static_cast<Src>(0));
- }
-};
-
-template <typename Dst, typename Src>
-inline RangeCheckResult RangeCheck(Src value) {
- COMPILE_ASSERT(std::numeric_limits<Src>::is_specialized,
- argument_must_be_numeric);
- COMPILE_ASSERT(std::numeric_limits<Dst>::is_specialized,
- result_must_be_numeric);
- return RangeCheckImpl<Dst, Src>::Check(value);
-}
-
-} // namespace internal
-} // namespace talk_base
-
-#endif // TALK_BASE_SAFE_CONVERSIONS_IMPL_H_
diff --git a/base/schanneladapter.cc b/base/schanneladapter.cc
deleted file mode 100644
index a376328..0000000
--- a/base/schanneladapter.cc
+++ /dev/null
@@ -1,719 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/win32.h"
-#define SECURITY_WIN32
-#include <security.h>
-#include <schannel.h>
-
-#include <iomanip>
-#include <vector>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/schanneladapter.h"
-#include "talk/base/sec_buffer.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-/////////////////////////////////////////////////////////////////////////////
-// SChannelAdapter
-/////////////////////////////////////////////////////////////////////////////
-
-extern const ConstantLabel SECURITY_ERRORS[];
-
-const ConstantLabel SCHANNEL_BUFFER_TYPES[] = {
- KLABEL(SECBUFFER_EMPTY), // 0
- KLABEL(SECBUFFER_DATA), // 1
- KLABEL(SECBUFFER_TOKEN), // 2
- KLABEL(SECBUFFER_PKG_PARAMS), // 3
- KLABEL(SECBUFFER_MISSING), // 4
- KLABEL(SECBUFFER_EXTRA), // 5
- KLABEL(SECBUFFER_STREAM_TRAILER), // 6
- KLABEL(SECBUFFER_STREAM_HEADER), // 7
- KLABEL(SECBUFFER_MECHLIST), // 11
- KLABEL(SECBUFFER_MECHLIST_SIGNATURE), // 12
- KLABEL(SECBUFFER_TARGET), // 13
- KLABEL(SECBUFFER_CHANNEL_BINDINGS), // 14
- LASTLABEL
-};
-
-void DescribeBuffer(LoggingSeverity severity, const char* prefix,
- const SecBuffer& sb) {
- LOG_V(severity)
- << prefix
- << "(" << sb.cbBuffer
- << ", " << FindLabel(sb.BufferType & ~SECBUFFER_ATTRMASK,
- SCHANNEL_BUFFER_TYPES)
- << ", " << sb.pvBuffer << ")";
-}
-
-void DescribeBuffers(LoggingSeverity severity, const char* prefix,
- const SecBufferDesc* sbd) {
- if (!LOG_CHECK_LEVEL_V(severity))
- return;
- LOG_V(severity) << prefix << "(";
- for (size_t i=0; i<sbd->cBuffers; ++i) {
- DescribeBuffer(severity, " ", sbd->pBuffers[i]);
- }
- LOG_V(severity) << ")";
-}
-
-const ULONG SSL_FLAGS_DEFAULT = ISC_REQ_ALLOCATE_MEMORY
- | ISC_REQ_CONFIDENTIALITY
- | ISC_REQ_EXTENDED_ERROR
- | ISC_REQ_INTEGRITY
- | ISC_REQ_REPLAY_DETECT
- | ISC_REQ_SEQUENCE_DETECT
- | ISC_REQ_STREAM;
- //| ISC_REQ_USE_SUPPLIED_CREDS;
-
-typedef std::vector<char> SChannelBuffer;
-
-struct SChannelAdapter::SSLImpl {
- CredHandle cred;
- CtxtHandle ctx;
- bool cred_init, ctx_init;
- SChannelBuffer inbuf, outbuf, readable;
- SecPkgContext_StreamSizes sizes;
-
- SSLImpl() : cred_init(false), ctx_init(false) { }
-};
-
-SChannelAdapter::SChannelAdapter(AsyncSocket* socket)
- : SSLAdapter(socket), state_(SSL_NONE),
- restartable_(false), signal_close_(false), message_pending_(false),
- impl_(new SSLImpl) {
-}
-
-SChannelAdapter::~SChannelAdapter() {
- Cleanup();
-}
-
-int
-SChannelAdapter::StartSSL(const char* hostname, bool restartable) {
- if (state_ != SSL_NONE)
- return ERROR_ALREADY_INITIALIZED;
-
- ssl_host_name_ = hostname;
- restartable_ = restartable;
-
- if (socket_->GetState() != Socket::CS_CONNECTED) {
- state_ = SSL_WAIT;
- return 0;
- }
-
- state_ = SSL_CONNECTING;
- if (int err = BeginSSL()) {
- Error("BeginSSL", err, false);
- return err;
- }
-
- return 0;
-}
-
-int
-SChannelAdapter::BeginSSL() {
- LOG(LS_VERBOSE) << "BeginSSL: " << ssl_host_name_;
- ASSERT(state_ == SSL_CONNECTING);
-
- SECURITY_STATUS ret;
-
- SCHANNEL_CRED sc_cred = { 0 };
- sc_cred.dwVersion = SCHANNEL_CRED_VERSION;
- //sc_cred.dwMinimumCipherStrength = 128; // Note: use system default
- sc_cred.dwFlags = SCH_CRED_NO_DEFAULT_CREDS | SCH_CRED_AUTO_CRED_VALIDATION;
-
- ret = AcquireCredentialsHandle(NULL, UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL,
- &sc_cred, NULL, NULL, &impl_->cred, NULL);
- if (ret != SEC_E_OK) {
- LOG(LS_ERROR) << "AcquireCredentialsHandle error: "
- << ErrorName(ret, SECURITY_ERRORS);
- return ret;
- }
- impl_->cred_init = true;
-
- if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
- SecPkgCred_CipherStrengths cipher_strengths = { 0 };
- ret = QueryCredentialsAttributes(&impl_->cred,
- SECPKG_ATTR_CIPHER_STRENGTHS,
- &cipher_strengths);
- if (SUCCEEDED(ret)) {
- LOG(LS_VERBOSE) << "SChannel cipher strength: "
- << cipher_strengths.dwMinimumCipherStrength << " - "
- << cipher_strengths.dwMaximumCipherStrength;
- }
-
- SecPkgCred_SupportedAlgs supported_algs = { 0 };
- ret = QueryCredentialsAttributes(&impl_->cred,
- SECPKG_ATTR_SUPPORTED_ALGS,
- &supported_algs);
- if (SUCCEEDED(ret)) {
- LOG(LS_VERBOSE) << "SChannel supported algorithms:";
- for (DWORD i=0; i<supported_algs.cSupportedAlgs; ++i) {
- ALG_ID alg_id = supported_algs.palgSupportedAlgs[i];
- PCCRYPT_OID_INFO oinfo = CryptFindOIDInfo(CRYPT_OID_INFO_ALGID_KEY,
- &alg_id, 0);
- LPCWSTR alg_name = (NULL != oinfo) ? oinfo->pwszName : L"Unknown";
- LOG(LS_VERBOSE) << " " << ToUtf8(alg_name) << " (" << alg_id << ")";
- }
- CSecBufferBase::FreeSSPI(supported_algs.palgSupportedAlgs);
- }
- }
-
- ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
- if (ignore_bad_cert())
- flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
-
- CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
- ret = InitializeSecurityContextA(&impl_->cred, NULL,
- const_cast<char*>(ssl_host_name_.c_str()),
- flags, 0, 0, NULL, 0,
- &impl_->ctx, sb_out.desc(),
- &ret_flags, NULL);
- if (SUCCEEDED(ret))
- impl_->ctx_init = true;
- return ProcessContext(ret, NULL, sb_out.desc());
-}
-
-int
-SChannelAdapter::ContinueSSL() {
- LOG(LS_VERBOSE) << "ContinueSSL";
- ASSERT(state_ == SSL_CONNECTING);
-
- SECURITY_STATUS ret;
-
- CSecBufferBundle<2> sb_in;
- sb_in[0].BufferType = SECBUFFER_TOKEN;
- sb_in[0].cbBuffer = static_cast<unsigned long>(impl_->inbuf.size());
- sb_in[0].pvBuffer = &impl_->inbuf[0];
- //DescribeBuffers(LS_VERBOSE, "Input Buffer ", sb_in.desc());
-
- ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
- if (ignore_bad_cert())
- flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
-
- CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
- ret = InitializeSecurityContextA(&impl_->cred, &impl_->ctx,
- const_cast<char*>(ssl_host_name_.c_str()),
- flags, 0, 0, sb_in.desc(), 0,
- NULL, sb_out.desc(),
- &ret_flags, NULL);
- return ProcessContext(ret, sb_in.desc(), sb_out.desc());
-}
-
-int
-SChannelAdapter::ProcessContext(long int status, _SecBufferDesc* sbd_in,
- _SecBufferDesc* sbd_out) {
- if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED &&
- status != SEC_E_INCOMPLETE_MESSAGE) {
- LOG(LS_ERROR)
- << "InitializeSecurityContext error: "
- << ErrorName(status, SECURITY_ERRORS);
- }
- //if (sbd_in)
- // DescribeBuffers(LS_VERBOSE, "Input Buffer ", sbd_in);
- //if (sbd_out)
- // DescribeBuffers(LS_VERBOSE, "Output Buffer ", sbd_out);
-
- if (status == SEC_E_INCOMPLETE_MESSAGE) {
- // Wait for more input from server.
- return Flush();
- }
-
- if (FAILED(status)) {
- // We can't continue. Common errors:
- // SEC_E_CERT_EXPIRED - Typically, this means the computer clock is wrong.
- return status;
- }
-
- // Note: we check both input and output buffers for SECBUFFER_EXTRA.
- // Experience shows it appearing in the input, but the documentation claims
- // it should appear in the output.
- size_t extra = 0;
- if (sbd_in) {
- for (size_t i=0; i<sbd_in->cBuffers; ++i) {
- SecBuffer& buffer = sbd_in->pBuffers[i];
- if (buffer.BufferType == SECBUFFER_EXTRA) {
- extra += buffer.cbBuffer;
- }
- }
- }
- if (sbd_out) {
- for (size_t i=0; i<sbd_out->cBuffers; ++i) {
- SecBuffer& buffer = sbd_out->pBuffers[i];
- if (buffer.BufferType == SECBUFFER_EXTRA) {
- extra += buffer.cbBuffer;
- } else if (buffer.BufferType == SECBUFFER_TOKEN) {
- impl_->outbuf.insert(impl_->outbuf.end(),
- reinterpret_cast<char*>(buffer.pvBuffer),
- reinterpret_cast<char*>(buffer.pvBuffer) + buffer.cbBuffer);
- }
- }
- }
-
- if (extra) {
- ASSERT(extra <= impl_->inbuf.size());
- size_t consumed = impl_->inbuf.size() - extra;
- memmove(&impl_->inbuf[0], &impl_->inbuf[consumed], extra);
- impl_->inbuf.resize(extra);
- } else {
- impl_->inbuf.clear();
- }
-
- if (SEC_I_CONTINUE_NEEDED == status) {
- // Send data to server and wait for response.
- // Note: ContinueSSL will result in a Flush, anyway.
- return impl_->inbuf.empty() ? Flush() : ContinueSSL();
- }
-
- if (SEC_E_OK == status) {
- LOG(LS_VERBOSE) << "QueryContextAttributes";
- status = QueryContextAttributes(&impl_->ctx, SECPKG_ATTR_STREAM_SIZES,
- &impl_->sizes);
- if (FAILED(status)) {
- LOG(LS_ERROR) << "QueryContextAttributes error: "
- << ErrorName(status, SECURITY_ERRORS);
- return status;
- }
-
- state_ = SSL_CONNECTED;
-
- if (int err = DecryptData()) {
- return err;
- } else if (int err = Flush()) {
- return err;
- } else {
- // If we decrypted any data, queue up a notification here
- PostEvent();
- // Signal our connectedness
- AsyncSocketAdapter::OnConnectEvent(this);
- }
- return 0;
- }
-
- if (SEC_I_INCOMPLETE_CREDENTIALS == status) {
- // We don't support client authentication in schannel.
- return status;
- }
-
- // We don't expect any other codes
- ASSERT(false);
- return status;
-}
-
-int
-SChannelAdapter::DecryptData() {
- SChannelBuffer& inbuf = impl_->inbuf;
- SChannelBuffer& readable = impl_->readable;
-
- while (!inbuf.empty()) {
- CSecBufferBundle<4> in_buf;
- in_buf[0].BufferType = SECBUFFER_DATA;
- in_buf[0].cbBuffer = static_cast<unsigned long>(inbuf.size());
- in_buf[0].pvBuffer = &inbuf[0];
-
- //DescribeBuffers(LS_VERBOSE, "Decrypt In ", in_buf.desc());
- SECURITY_STATUS status = DecryptMessage(&impl_->ctx, in_buf.desc(), 0, 0);
- //DescribeBuffers(LS_VERBOSE, "Decrypt Out ", in_buf.desc());
-
- // Note: We are explicitly treating SEC_E_OK, SEC_I_CONTEXT_EXPIRED, and
- // any other successful results as continue.
- if (SUCCEEDED(status)) {
- size_t data_len = 0, extra_len = 0;
- for (size_t i=0; i<in_buf.desc()->cBuffers; ++i) {
- if (in_buf[i].BufferType == SECBUFFER_DATA) {
- data_len += in_buf[i].cbBuffer;
- readable.insert(readable.end(),
- reinterpret_cast<char*>(in_buf[i].pvBuffer),
- reinterpret_cast<char*>(in_buf[i].pvBuffer) + in_buf[i].cbBuffer);
- } else if (in_buf[i].BufferType == SECBUFFER_EXTRA) {
- extra_len += in_buf[i].cbBuffer;
- }
- }
- // There is a bug on Win2K where SEC_I_CONTEXT_EXPIRED is misclassified.
- if ((data_len == 0) && (inbuf[0] == 0x15)) {
- status = SEC_I_CONTEXT_EXPIRED;
- }
- if (extra_len) {
- size_t consumed = inbuf.size() - extra_len;
- memmove(&inbuf[0], &inbuf[consumed], extra_len);
- inbuf.resize(extra_len);
- } else {
- inbuf.clear();
- }
- // TODO: Handle SEC_I_CONTEXT_EXPIRED to do clean shutdown
- if (status != SEC_E_OK) {
- LOG(LS_INFO) << "DecryptMessage returned continuation code: "
- << ErrorName(status, SECURITY_ERRORS);
- }
- continue;
- }
-
- if (status == SEC_E_INCOMPLETE_MESSAGE) {
- break;
- } else {
- return status;
- }
- }
-
- return 0;
-}
-
-void
-SChannelAdapter::Cleanup() {
- if (impl_->ctx_init)
- DeleteSecurityContext(&impl_->ctx);
- if (impl_->cred_init)
- FreeCredentialsHandle(&impl_->cred);
- delete impl_;
-}
-
-void
-SChannelAdapter::PostEvent() {
- // Check if there's anything notable to signal
- if (impl_->readable.empty() && !signal_close_)
- return;
-
- // Only one post in the queue at a time
- if (message_pending_)
- return;
-
- if (Thread* thread = Thread::Current()) {
- message_pending_ = true;
- thread->Post(this);
- } else {
- LOG(LS_ERROR) << "No thread context available for SChannelAdapter";
- ASSERT(false);
- }
-}
-
-void
-SChannelAdapter::Error(const char* context, int err, bool signal) {
- LOG(LS_WARNING) << "SChannelAdapter::Error("
- << context << ", "
- << ErrorName(err, SECURITY_ERRORS) << ")";
- state_ = SSL_ERROR;
- SetError(err);
- if (signal)
- AsyncSocketAdapter::OnCloseEvent(this, err);
-}
-
-int
-SChannelAdapter::Read() {
- char buffer[4096];
- SChannelBuffer& inbuf = impl_->inbuf;
- while (true) {
- int ret = AsyncSocketAdapter::Recv(buffer, sizeof(buffer));
- if (ret > 0) {
- inbuf.insert(inbuf.end(), buffer, buffer + ret);
- } else if (GetError() == EWOULDBLOCK) {
- return 0; // Blocking
- } else {
- return GetError();
- }
- }
-}
-
-int
-SChannelAdapter::Flush() {
- int result = 0;
- size_t pos = 0;
- SChannelBuffer& outbuf = impl_->outbuf;
- while (pos < outbuf.size()) {
- int sent = AsyncSocketAdapter::Send(&outbuf[pos], outbuf.size() - pos);
- if (sent > 0) {
- pos += sent;
- } else if (GetError() == EWOULDBLOCK) {
- break; // Blocking
- } else {
- result = GetError();
- break;
- }
- }
- if (int remainder = static_cast<int>(outbuf.size() - pos)) {
- memmove(&outbuf[0], &outbuf[pos], remainder);
- outbuf.resize(remainder);
- } else {
- outbuf.clear();
- }
- return result;
-}
-
-//
-// AsyncSocket Implementation
-//
-
-int
-SChannelAdapter::Send(const void* pv, size_t cb) {
- switch (state_) {
- case SSL_NONE:
- return AsyncSocketAdapter::Send(pv, cb);
-
- case SSL_WAIT:
- case SSL_CONNECTING:
- SetError(EWOULDBLOCK);
- return SOCKET_ERROR;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_ERROR:
- default:
- return SOCKET_ERROR;
- }
-
- size_t written = 0;
- SChannelBuffer& outbuf = impl_->outbuf;
- while (written < cb) {
- const size_t encrypt_len = std::min<size_t>(cb - written,
- impl_->sizes.cbMaximumMessage);
-
- CSecBufferBundle<4> out_buf;
- out_buf[0].BufferType = SECBUFFER_STREAM_HEADER;
- out_buf[0].cbBuffer = impl_->sizes.cbHeader;
- out_buf[1].BufferType = SECBUFFER_DATA;
- out_buf[1].cbBuffer = static_cast<unsigned long>(encrypt_len);
- out_buf[2].BufferType = SECBUFFER_STREAM_TRAILER;
- out_buf[2].cbBuffer = impl_->sizes.cbTrailer;
-
- size_t packet_len = out_buf[0].cbBuffer
- + out_buf[1].cbBuffer
- + out_buf[2].cbBuffer;
-
- SChannelBuffer message;
- message.resize(packet_len);
- out_buf[0].pvBuffer = &message[0];
- out_buf[1].pvBuffer = &message[out_buf[0].cbBuffer];
- out_buf[2].pvBuffer = &message[out_buf[0].cbBuffer + out_buf[1].cbBuffer];
-
- memcpy(out_buf[1].pvBuffer,
- static_cast<const char*>(pv) + written,
- encrypt_len);
-
- //DescribeBuffers(LS_VERBOSE, "Encrypt In ", out_buf.desc());
- SECURITY_STATUS res = EncryptMessage(&impl_->ctx, 0, out_buf.desc(), 0);
- //DescribeBuffers(LS_VERBOSE, "Encrypt Out ", out_buf.desc());
-
- if (FAILED(res)) {
- Error("EncryptMessage", res, false);
- return SOCKET_ERROR;
- }
-
- // We assume that the header and data segments do not change length,
- // or else encrypting the concatenated packet in-place is wrong.
- ASSERT(out_buf[0].cbBuffer == impl_->sizes.cbHeader);
- ASSERT(out_buf[1].cbBuffer == static_cast<unsigned long>(encrypt_len));
-
- // However, the length of the trailer may change due to padding.
- ASSERT(out_buf[2].cbBuffer <= impl_->sizes.cbTrailer);
-
- packet_len = out_buf[0].cbBuffer
- + out_buf[1].cbBuffer
- + out_buf[2].cbBuffer;
-
- written += encrypt_len;
- outbuf.insert(outbuf.end(), &message[0], &message[packet_len-1]+1);
- }
-
- if (int err = Flush()) {
- state_ = SSL_ERROR;
- SetError(err);
- return SOCKET_ERROR;
- }
-
- return static_cast<int>(written);
-}
-
-int
-SChannelAdapter::Recv(void* pv, size_t cb) {
- switch (state_) {
- case SSL_NONE:
- return AsyncSocketAdapter::Recv(pv, cb);
-
- case SSL_WAIT:
- case SSL_CONNECTING:
- SetError(EWOULDBLOCK);
- return SOCKET_ERROR;
-
- case SSL_CONNECTED:
- break;
-
- case SSL_ERROR:
- default:
- return SOCKET_ERROR;
- }
-
- SChannelBuffer& readable = impl_->readable;
- if (readable.empty()) {
- SetError(EWOULDBLOCK);
- return SOCKET_ERROR;
- }
- size_t read = _min(cb, readable.size());
- memcpy(pv, &readable[0], read);
- if (size_t remaining = readable.size() - read) {
- memmove(&readable[0], &readable[read], remaining);
- readable.resize(remaining);
- } else {
- readable.clear();
- }
-
- PostEvent();
- return static_cast<int>(read);
-}
-
-int
-SChannelAdapter::Close() {
- if (!impl_->readable.empty()) {
- LOG(WARNING) << "SChannelAdapter::Close with readable data";
- // Note: this isn't strictly an error, but we're using it temporarily to
- // track bugs.
- //ASSERT(false);
- }
- if (state_ == SSL_CONNECTED) {
- DWORD token = SCHANNEL_SHUTDOWN;
- CSecBufferBundle<1> sb_in;
- sb_in[0].BufferType = SECBUFFER_TOKEN;
- sb_in[0].cbBuffer = sizeof(token);
- sb_in[0].pvBuffer = &token;
- ApplyControlToken(&impl_->ctx, sb_in.desc());
- // TODO: In theory, to do a nice shutdown, we need to begin shutdown
- // negotiation with more calls to InitializeSecurityContext. Since the
- // socket api doesn't support nice shutdown at this point, we don't bother.
- }
- Cleanup();
- impl_ = new SSLImpl;
- state_ = restartable_ ? SSL_WAIT : SSL_NONE;
- signal_close_ = false;
- message_pending_ = false;
- return AsyncSocketAdapter::Close();
-}
-
-Socket::ConnState
-SChannelAdapter::GetState() const {
- if (signal_close_)
- return CS_CONNECTED;
- ConnState state = socket_->GetState();
- if ((state == CS_CONNECTED)
- && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
- state = CS_CONNECTING;
- return state;
-}
-
-void
-SChannelAdapter::OnConnectEvent(AsyncSocket* socket) {
- LOG(LS_VERBOSE) << "SChannelAdapter::OnConnectEvent";
- if (state_ != SSL_WAIT) {
- ASSERT(state_ == SSL_NONE);
- AsyncSocketAdapter::OnConnectEvent(socket);
- return;
- }
-
- state_ = SSL_CONNECTING;
- if (int err = BeginSSL()) {
- Error("BeginSSL", err);
- }
-}
-
-void
-SChannelAdapter::OnReadEvent(AsyncSocket* socket) {
- if (state_ == SSL_NONE) {
- AsyncSocketAdapter::OnReadEvent(socket);
- return;
- }
-
- if (int err = Read()) {
- Error("Read", err);
- return;
- }
-
- if (impl_->inbuf.empty())
- return;
-
- if (state_ == SSL_CONNECTED) {
- if (int err = DecryptData()) {
- Error("DecryptData", err);
- } else if (!impl_->readable.empty()) {
- AsyncSocketAdapter::OnReadEvent(this);
- }
- } else if (state_ == SSL_CONNECTING) {
- if (int err = ContinueSSL()) {
- Error("ContinueSSL", err);
- }
- }
-}
-
-void
-SChannelAdapter::OnWriteEvent(AsyncSocket* socket) {
- if (state_ == SSL_NONE) {
- AsyncSocketAdapter::OnWriteEvent(socket);
- return;
- }
-
- if (int err = Flush()) {
- Error("Flush", err);
- return;
- }
-
- // See if we have more data to write
- if (!impl_->outbuf.empty())
- return;
-
- // Buffer is empty, submit notification
- if (state_ == SSL_CONNECTED) {
- AsyncSocketAdapter::OnWriteEvent(socket);
- }
-}
-
-void
-SChannelAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
- if ((state_ == SSL_NONE) || impl_->readable.empty()) {
- AsyncSocketAdapter::OnCloseEvent(socket, err);
- return;
- }
-
- // If readable is non-empty, then we have a pending Message
- // that will allow us to signal close (eventually).
- signal_close_ = true;
-}
-
-void
-SChannelAdapter::OnMessage(Message* pmsg) {
- if (!message_pending_)
- return; // This occurs when socket is closed
-
- message_pending_ = false;
- if (!impl_->readable.empty()) {
- AsyncSocketAdapter::OnReadEvent(this);
- } else if (signal_close_) {
- signal_close_ = false;
- AsyncSocketAdapter::OnCloseEvent(this, 0); // TODO: cache this error?
- }
-}
-
-} // namespace talk_base
diff --git a/base/schanneladapter.h b/base/schanneladapter.h
deleted file mode 100644
index a5ab7b3..0000000
--- a/base/schanneladapter.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SCHANNELADAPTER_H__
-#define TALK_BASE_SCHANNELADAPTER_H__
-
-#include <string>
-#include "talk/base/ssladapter.h"
-#include "talk/base/messagequeue.h"
-struct _SecBufferDesc;
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-class SChannelAdapter : public SSLAdapter, public MessageHandler {
-public:
- SChannelAdapter(AsyncSocket* socket);
- virtual ~SChannelAdapter();
-
- virtual int StartSSL(const char* hostname, bool restartable);
- virtual int Send(const void* pv, size_t cb);
- virtual int Recv(void* pv, size_t cb);
- virtual int Close();
-
- // Note that the socket returns ST_CONNECTING while SSL is being negotiated.
- virtual ConnState GetState() const;
-
-protected:
- enum SSLState {
- SSL_NONE, SSL_WAIT, SSL_CONNECTING, SSL_CONNECTED, SSL_ERROR
- };
- struct SSLImpl;
-
- virtual void OnConnectEvent(AsyncSocket* socket);
- virtual void OnReadEvent(AsyncSocket* socket);
- virtual void OnWriteEvent(AsyncSocket* socket);
- virtual void OnCloseEvent(AsyncSocket* socket, int err);
- virtual void OnMessage(Message* pmsg);
-
- int BeginSSL();
- int ContinueSSL();
- int ProcessContext(long int status, _SecBufferDesc* sbd_in,
- _SecBufferDesc* sbd_out);
- int DecryptData();
-
- int Read();
- int Flush();
- void Error(const char* context, int err, bool signal = true);
- void Cleanup();
-
- void PostEvent();
-
-private:
- SSLState state_;
- std::string ssl_host_name_;
- // If true, socket will retain SSL configuration after Close.
- bool restartable_;
- // If true, we are delaying signalling close until all data is read.
- bool signal_close_;
- // If true, we are waiting to be woken up to signal readability or closure.
- bool message_pending_;
- SSLImpl* impl_;
-};
-
-/////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SCHANNELADAPTER_H__
diff --git a/base/scoped_autorelease_pool.h b/base/scoped_autorelease_pool.h
deleted file mode 100644
index 611f811..0000000
--- a/base/scoped_autorelease_pool.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * libjingle
- * Copyright 2008 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Automatically initialize and and free an autoreleasepool. Never allocate
-// an instance of this class using "new" - that will result in a compile-time
-// error. Only use it as a stack object.
-//
-// Note: NSAutoreleasePool docs say that you should not normally need to
-// declare an NSAutoreleasePool as a member of an object - but there's nothing
-// that indicates it will be a problem, as long as the stack lifetime of the
-// pool exactly matches the stack lifetime of the object.
-
-#ifndef TALK_BASE_SCOPED_AUTORELEASE_POOL_H__
-#define TALK_BASE_SCOPED_AUTORELEASE_POOL_H__
-
-#if defined(IOS) || defined(OSX)
-
-#include "talk/base/common.h"
-
-// This header may be included from Obj-C files or C++ files.
-#ifdef __OBJC__
-@class NSAutoreleasePool;
-#else
-class NSAutoreleasePool;
-#endif
-
-namespace talk_base {
-
-class ScopedAutoreleasePool {
- public:
- ScopedAutoreleasePool();
- ~ScopedAutoreleasePool();
-
- private:
- // Declaring private overrides of new and delete here enforces the "only use
- // as a stack object" discipline.
- //
- // Note: new is declared as "throw()" to get around a gcc warning about new
- // returning NULL, but this method will never get called and therefore will
- // never actually throw any exception.
- void* operator new(size_t size) throw() { return NULL; }
- void operator delete (void* ptr) {}
-
- NSAutoreleasePool* pool_;
-
- DISALLOW_EVIL_CONSTRUCTORS(ScopedAutoreleasePool);
-};
-
-} // namespace talk_base
-
-#endif // IOS || OSX
-#endif // TALK_BASE_SCOPED_AUTORELEASE_POOL_H__
diff --git a/base/scoped_autorelease_pool.mm b/base/scoped_autorelease_pool.mm
deleted file mode 100644
index 4009c7b..0000000
--- a/base/scoped_autorelease_pool.mm
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import <Foundation/Foundation.h>
-
-#import "talk/base/scoped_autorelease_pool.h"
-
-namespace talk_base {
-
-ScopedAutoreleasePool::ScopedAutoreleasePool() {
- pool_ = [[NSAutoreleasePool alloc] init];
-}
-
-ScopedAutoreleasePool::~ScopedAutoreleasePool() {
- [pool_ drain];
-}
-
-} // namespace talk_base
diff --git a/base/scoped_ptr.h b/base/scoped_ptr.h
deleted file mode 100644
index 5158a9e..0000000
--- a/base/scoped_ptr.h
+++ /dev/null
@@ -1,590 +0,0 @@
-// Borrowed from chromium.
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Scopers help you manage ownership of a pointer, helping you easily manage the
-// a pointer within a scope, and automatically destroying the pointer at the
-// end of a scope. There are two main classes you will use, which correspond
-// to the operators new/delete and new[]/delete[].
-//
-// Example usage (scoped_ptr<T>):
-// {
-// scoped_ptr<Foo> foo(new Foo("wee"));
-// } // foo goes out of scope, releasing the pointer with it.
-//
-// {
-// scoped_ptr<Foo> foo; // No pointer managed.
-// foo.reset(new Foo("wee")); // Now a pointer is managed.
-// foo.reset(new Foo("wee2")); // Foo("wee") was destroyed.
-// foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed.
-// foo->Method(); // Foo::Method() called.
-// foo.get()->Method(); // Foo::Method() called.
-// SomeFunc(foo.release()); // SomeFunc takes ownership, foo no longer
-// // manages a pointer.
-// foo.reset(new Foo("wee4")); // foo manages a pointer again.
-// foo.reset(); // Foo("wee4") destroyed, foo no longer
-// // manages a pointer.
-// } // foo wasn't managing a pointer, so nothing was destroyed.
-//
-// Example usage (scoped_ptr<T[]>):
-// {
-// scoped_ptr<Foo[]> foo(new Foo[100]);
-// foo.get()->Method(); // Foo::Method on the 0th element.
-// foo[10].Method(); // Foo::Method on the 10th element.
-// }
-//
-// These scopers also implement part of the functionality of C++11 unique_ptr
-// in that they are "movable but not copyable." You can use the scopers in
-// the parameter and return types of functions to signify ownership transfer
-// in to and out of a function. When calling a function that has a scoper
-// as the argument type, it must be called with the result of an analogous
-// scoper's Pass() function or another function that generates a temporary;
-// passing by copy will NOT work. Here is an example using scoped_ptr:
-//
-// void TakesOwnership(scoped_ptr<Foo> arg) {
-// // Do something with arg
-// }
-// scoped_ptr<Foo> CreateFoo() {
-// // No need for calling Pass() because we are constructing a temporary
-// // for the return value.
-// return scoped_ptr<Foo>(new Foo("new"));
-// }
-// scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) {
-// return arg.Pass();
-// }
-//
-// {
-// scoped_ptr<Foo> ptr(new Foo("yay")); // ptr manages Foo("yay").
-// TakesOwnership(ptr.Pass()); // ptr no longer owns Foo("yay").
-// scoped_ptr<Foo> ptr2 = CreateFoo(); // ptr2 owns the return Foo.
-// scoped_ptr<Foo> ptr3 = // ptr3 now owns what was in ptr2.
-// PassThru(ptr2.Pass()); // ptr2 is correspondingly NULL.
-// }
-//
-// Notice that if you do not call Pass() when returning from PassThru(), or
-// when invoking TakesOwnership(), the code will not compile because scopers
-// are not copyable; they only implement move semantics which require calling
-// the Pass() function to signify a destructive transfer of state. CreateFoo()
-// is different though because we are constructing a temporary on the return
-// line and thus can avoid needing to call Pass().
-//
-// Pass() properly handles upcast in initialization, i.e. you can use a
-// scoped_ptr<Child> to initialize a scoped_ptr<Parent>:
-//
-// scoped_ptr<Foo> foo(new Foo());
-// scoped_ptr<FooParent> parent(foo.Pass());
-//
-// PassAs<>() should be used to upcast return value in return statement:
-//
-// scoped_ptr<Foo> CreateFoo() {
-// scoped_ptr<FooChild> result(new FooChild());
-// return result.PassAs<Foo>();
-// }
-//
-// Note that PassAs<>() is implemented only for scoped_ptr<T>, but not for
-// scoped_ptr<T[]>. This is because casting array pointers may not be safe.
-
-#ifndef TALK_BASE_SCOPED_PTR_H__
-#define TALK_BASE_SCOPED_PTR_H__
-
-#include <stddef.h> // for ptrdiff_t
-#include <stdlib.h> // for free() decl
-
-#include <algorithm> // For std::swap().
-
-#include "talk/base/common.h" // for ASSERT
-#include "talk/base/compile_assert.h" // for COMPILE_ASSERT
-#include "talk/base/move.h" // for TALK_MOVE_ONLY_TYPE_FOR_CPP_03
-#include "talk/base/template_util.h" // for is_convertible, is_array
-
-#ifdef _WIN32
-namespace std { using ::ptrdiff_t; };
-#endif // _WIN32
-
-namespace talk_base {
-
-// Function object which deletes its parameter, which must be a pointer.
-// If C is an array type, invokes 'delete[]' on the parameter; otherwise,
-// invokes 'delete'. The default deleter for scoped_ptr<T>.
-template <class T>
-struct DefaultDeleter {
- DefaultDeleter() {}
- template <typename U> DefaultDeleter(const DefaultDeleter<U>& other) {
- // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor
- // if U* is implicitly convertible to T* and U is not an array type.
- //
- // Correct implementation should use SFINAE to disable this
- // constructor. However, since there are no other 1-argument constructors,
- // using a COMPILE_ASSERT() based on is_convertible<> and requiring
- // complete types is simpler and will cause compile failures for equivalent
- // misuses.
- //
- // Note, the is_convertible<U*, T*> check also ensures that U is not an
- // array. T is guaranteed to be a non-array, so any U* where U is an array
- // cannot convert to T*.
- enum { T_must_be_complete = sizeof(T) };
- enum { U_must_be_complete = sizeof(U) };
- COMPILE_ASSERT((talk_base::is_convertible<U*, T*>::value),
- U_ptr_must_implicitly_convert_to_T_ptr);
- }
- inline void operator()(T* ptr) const {
- enum { type_must_be_complete = sizeof(T) };
- delete ptr;
- }
-};
-
-// Specialization of DefaultDeleter for array types.
-template <class T>
-struct DefaultDeleter<T[]> {
- inline void operator()(T* ptr) const {
- enum { type_must_be_complete = sizeof(T) };
- delete[] ptr;
- }
-
- private:
- // Disable this operator for any U != T because it is undefined to execute
- // an array delete when the static type of the array mismatches the dynamic
- // type.
- //
- // References:
- // C++98 [expr.delete]p3
- // http://cplusplus.github.com/LWG/lwg-defects.html#938
- template <typename U> void operator()(U* array) const;
-};
-
-template <class T, int n>
-struct DefaultDeleter<T[n]> {
- // Never allow someone to declare something like scoped_ptr<int[10]>.
- COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type);
-};
-
-// Function object which invokes 'free' on its parameter, which must be
-// a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
-//
-// scoped_ptr<int, talk_base::FreeDeleter> foo_ptr(
-// static_cast<int*>(malloc(sizeof(int))));
-struct FreeDeleter {
- inline void operator()(void* ptr) const {
- free(ptr);
- }
-};
-
-namespace internal {
-
-// Minimal implementation of the core logic of scoped_ptr, suitable for
-// reuse in both scoped_ptr and its specializations.
-template <class T, class D>
-class scoped_ptr_impl {
- public:
- explicit scoped_ptr_impl(T* p) : data_(p) { }
-
- // Initializer for deleters that have data parameters.
- scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
-
- // Templated constructor that destructively takes the value from another
- // scoped_ptr_impl.
- template <typename U, typename V>
- scoped_ptr_impl(scoped_ptr_impl<U, V>* other)
- : data_(other->release(), other->get_deleter()) {
- // We do not support move-only deleters. We could modify our move
- // emulation to have talk_base::subtle::move() and
- // talk_base::subtle::forward()
- // functions that are imperfect emulations of their C++11 equivalents,
- // but until there's a requirement, just assume deleters are copyable.
- }
-
- template <typename U, typename V>
- void TakeState(scoped_ptr_impl<U, V>* other) {
- // See comment in templated constructor above regarding lack of support
- // for move-only deleters.
- reset(other->release());
- get_deleter() = other->get_deleter();
- }
-
- ~scoped_ptr_impl() {
- if (data_.ptr != NULL) {
- // Not using get_deleter() saves one function call in non-optimized
- // builds.
- static_cast<D&>(data_)(data_.ptr);
- }
- }
-
- void reset(T* p) {
- // This is a self-reset, which is no longer allowed: http://crbug.com/162971
- if (p != NULL && p == data_.ptr)
- abort();
-
- // Note that running data_.ptr = p can lead to undefined behavior if
- // get_deleter()(get()) deletes this. In order to pevent this, reset()
- // should update the stored pointer before deleting its old value.
- //
- // However, changing reset() to use that behavior may cause current code to
- // break in unexpected ways. If the destruction of the owned object
- // dereferences the scoped_ptr when it is destroyed by a call to reset(),
- // then it will incorrectly dispatch calls to |p| rather than the original
- // value of |data_.ptr|.
- //
- // During the transition period, set the stored pointer to NULL while
- // deleting the object. Eventually, this safety check will be removed to
- // prevent the scenario initially described from occuring and
- // http://crbug.com/176091 can be closed.
- T* old = data_.ptr;
- data_.ptr = NULL;
- if (old != NULL)
- static_cast<D&>(data_)(old);
- data_.ptr = p;
- }
-
- T* get() const { return data_.ptr; }
-
- D& get_deleter() { return data_; }
- const D& get_deleter() const { return data_; }
-
- void swap(scoped_ptr_impl& p2) {
- // Standard swap idiom: 'using std::swap' ensures that std::swap is
- // present in the overload set, but we call swap unqualified so that
- // any more-specific overloads can be used, if available.
- using std::swap;
- swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
- swap(data_.ptr, p2.data_.ptr);
- }
-
- T* release() {
- T* old_ptr = data_.ptr;
- data_.ptr = NULL;
- return old_ptr;
- }
-
- T** accept() {
- reset(NULL);
- return &(data_.ptr);
- }
-
- T** use() {
- return &(data_.ptr);
- }
-
- private:
- // Needed to allow type-converting constructor.
- template <typename U, typename V> friend class scoped_ptr_impl;
-
- // Use the empty base class optimization to allow us to have a D
- // member, while avoiding any space overhead for it when D is an
- // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
- // discussion of this technique.
- struct Data : public D {
- explicit Data(T* ptr_in) : ptr(ptr_in) {}
- Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {}
- T* ptr;
- };
-
- Data data_;
-
- DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
-};
-
-} // namespace internal
-
-// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
-// automatically deletes the pointer it holds (if any).
-// That is, scoped_ptr<T> owns the T object that it points to.
-// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object.
-// Also like T*, scoped_ptr<T> is thread-compatible, and once you
-// dereference it, you get the thread safety guarantees of T.
-//
-// The size of scoped_ptr is small. On most compilers, when using the
-// DefaultDeleter, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters will
-// increase the size proportional to whatever state they need to have. See
-// comments inside scoped_ptr_impl<> for details.
-//
-// Current implementation targets having a strict subset of C++11's
-// unique_ptr<> features. Known deficiencies include not supporting move-only
-// deleteres, function pointers as deleters, and deleters with reference
-// types.
-template <class T, class D = talk_base::DefaultDeleter<T> >
-class scoped_ptr {
- TALK_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
-
- public:
- // The element and deleter types.
- typedef T element_type;
- typedef D deleter_type;
-
- // Constructor. Defaults to initializing with NULL.
- scoped_ptr() : impl_(NULL) { }
-
- // Constructor. Takes ownership of p.
- explicit scoped_ptr(element_type* p) : impl_(p) { }
-
- // Constructor. Allows initialization of a stateful deleter.
- scoped_ptr(element_type* p, const D& d) : impl_(p, d) { }
-
- // Constructor. Allows construction from a scoped_ptr rvalue for a
- // convertible type and deleter.
- //
- // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct
- // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor
- // has different post-conditions if D is a reference type. Since this
- // implementation does not support deleters with reference type,
- // we do not need a separate move constructor allowing us to avoid one
- // use of SFINAE. You only need to care about this if you modify the
- // implementation of scoped_ptr.
- template <typename U, typename V>
- scoped_ptr(scoped_ptr<U, V> other) : impl_(&other.impl_) {
- COMPILE_ASSERT(!talk_base::is_array<U>::value, U_cannot_be_an_array);
- }
-
- // Constructor. Move constructor for C++03 move emulation of this type.
- scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
-
- // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
- // type and deleter.
- //
- // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
- // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated
- // form has different requirements on for move-only Deleters. Since this
- // implementation does not support move-only Deleters, we do not need a
- // separate move assignment operator allowing us to avoid one use of SFINAE.
- // You only need to care about this if you modify the implementation of
- // scoped_ptr.
- template <typename U, typename V>
- scoped_ptr& operator=(scoped_ptr<U, V> rhs) {
- COMPILE_ASSERT(!talk_base::is_array<U>::value, U_cannot_be_an_array);
- impl_.TakeState(&rhs.impl_);
- return *this;
- }
-
- // Reset. Deletes the currently owned object, if any.
- // Then takes ownership of a new object, if given.
- void reset(element_type* p = NULL) { impl_.reset(p); }
-
- // Accessors to get the owned object.
- // operator* and operator-> will assert() if there is no current object.
- element_type& operator*() const {
- ASSERT(impl_.get() != NULL);
- return *impl_.get();
- }
- element_type* operator->() const {
- ASSERT(impl_.get() != NULL);
- return impl_.get();
- }
- element_type* get() const { return impl_.get(); }
-
- // Access to the deleter.
- deleter_type& get_deleter() { return impl_.get_deleter(); }
- const deleter_type& get_deleter() const { return impl_.get_deleter(); }
-
- // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
- // implicitly convertible to a real bool (which is dangerous).
- //
- // Note that this trick is only safe when the == and != operators
- // are declared explicitly, as otherwise "scoped_ptr1 ==
- // scoped_ptr2" will compile but do the wrong thing (i.e., convert
- // to Testable and then do the comparison).
- private:
- typedef talk_base::internal::scoped_ptr_impl<element_type, deleter_type>
- scoped_ptr::*Testable;
-
- public:
- operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
-
- // Comparison operators.
- // These return whether two scoped_ptr refer to the same object, not just to
- // two different but equal objects.
- bool operator==(const element_type* p) const { return impl_.get() == p; }
- bool operator!=(const element_type* p) const { return impl_.get() != p; }
-
- // Swap two scoped pointers.
- void swap(scoped_ptr& p2) {
- impl_.swap(p2.impl_);
- }
-
- // Release a pointer.
- // The return value is the current pointer held by this object.
- // If this object holds a NULL pointer, the return value is NULL.
- // After this operation, this object will hold a NULL pointer,
- // and will not own the object any more.
- element_type* release() WARN_UNUSED_RESULT {
- return impl_.release();
- }
-
- // Delete the currently held pointer and return a pointer
- // to allow overwriting of the current pointer address.
- element_type** accept() WARN_UNUSED_RESULT {
- return impl_.accept();
- }
-
- // Return a pointer to the current pointer address.
- element_type** use() WARN_UNUSED_RESULT {
- return impl_.use();
- }
-
- // C++98 doesn't support functions templates with default parameters which
- // makes it hard to write a PassAs() that understands converting the deleter
- // while preserving simple calling semantics.
- //
- // Until there is a use case for PassAs() with custom deleters, just ignore
- // the custom deleter.
- template <typename PassAsType>
- scoped_ptr<PassAsType> PassAs() {
- return scoped_ptr<PassAsType>(Pass());
- }
-
- private:
- // Needed to reach into |impl_| in the constructor.
- template <typename U, typename V> friend class scoped_ptr;
- talk_base::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
-
- // Forbidden for API compatibility with std::unique_ptr.
- explicit scoped_ptr(int disallow_construction_from_null);
-
- // Forbid comparison of scoped_ptr types. If U != T, it totally
- // doesn't make sense, and if U == T, it still doesn't make sense
- // because you should never have the same object owned by two different
- // scoped_ptrs.
- template <class U> bool operator==(scoped_ptr<U> const& p2) const;
- template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
-};
-
-template <class T, class D>
-class scoped_ptr<T[], D> {
- TALK_MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue)
-
- public:
- // The element and deleter types.
- typedef T element_type;
- typedef D deleter_type;
-
- // Constructor. Defaults to initializing with NULL.
- scoped_ptr() : impl_(NULL) { }
-
- // Constructor. Stores the given array. Note that the argument's type
- // must exactly match T*. In particular:
- // - it cannot be a pointer to a type derived from T, because it is
- // inherently unsafe in the general case to access an array through a
- // pointer whose dynamic type does not match its static type (eg., if
- // T and the derived types had different sizes access would be
- // incorrectly calculated). Deletion is also always undefined
- // (C++98 [expr.delete]p3). If you're doing this, fix your code.
- // - it cannot be NULL, because NULL is an integral expression, not a
- // pointer to T. Use the no-argument version instead of explicitly
- // passing NULL.
- // - it cannot be const-qualified differently from T per unique_ptr spec
- // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
- // to work around this may use implicit_cast<const T*>().
- // However, because of the first bullet in this comment, users MUST
- // NOT use implicit_cast<Base*>() to upcast the static type of the array.
- explicit scoped_ptr(element_type* array) : impl_(array) { }
-
- // Constructor. Move constructor for C++03 move emulation of this type.
- scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { }
-
- // operator=. Move operator= for C++03 move emulation of this type.
- scoped_ptr& operator=(RValue rhs) {
- impl_.TakeState(&rhs.object->impl_);
- return *this;
- }
-
- // Reset. Deletes the currently owned array, if any.
- // Then takes ownership of a new object, if given.
- void reset(element_type* array = NULL) { impl_.reset(array); }
-
- // Accessors to get the owned array.
- element_type& operator[](size_t i) const {
- ASSERT(impl_.get() != NULL);
- return impl_.get()[i];
- }
- element_type* get() const { return impl_.get(); }
-
- // Access to the deleter.
- deleter_type& get_deleter() { return impl_.get_deleter(); }
- const deleter_type& get_deleter() const { return impl_.get_deleter(); }
-
- // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
- // implicitly convertible to a real bool (which is dangerous).
- private:
- typedef talk_base::internal::scoped_ptr_impl<element_type, deleter_type>
- scoped_ptr::*Testable;
-
- public:
- operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; }
-
- // Comparison operators.
- // These return whether two scoped_ptr refer to the same object, not just to
- // two different but equal objects.
- bool operator==(element_type* array) const { return impl_.get() == array; }
- bool operator!=(element_type* array) const { return impl_.get() != array; }
-
- // Swap two scoped pointers.
- void swap(scoped_ptr& p2) {
- impl_.swap(p2.impl_);
- }
-
- // Release a pointer.
- // The return value is the current pointer held by this object.
- // If this object holds a NULL pointer, the return value is NULL.
- // After this operation, this object will hold a NULL pointer,
- // and will not own the object any more.
- element_type* release() WARN_UNUSED_RESULT {
- return impl_.release();
- }
-
- // Delete the currently held pointer and return a pointer
- // to allow overwriting of the current pointer address.
- element_type** accept() WARN_UNUSED_RESULT {
- return impl_.accept();
- }
-
- // Return a pointer to the current pointer address.
- element_type** use() WARN_UNUSED_RESULT {
- return impl_.use();
- }
-
- private:
- // Force element_type to be a complete type.
- enum { type_must_be_complete = sizeof(element_type) };
-
- // Actually hold the data.
- talk_base::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
-
- // Disable initialization from any type other than element_type*, by
- // providing a constructor that matches such an initialization, but is
- // private and has no definition. This is disabled because it is not safe to
- // call delete[] on an array whose static type does not match its dynamic
- // type.
- template <typename U> explicit scoped_ptr(U* array);
- explicit scoped_ptr(int disallow_construction_from_null);
-
- // Disable reset() from any type other than element_type*, for the same
- // reasons as the constructor above.
- template <typename U> void reset(U* array);
- void reset(int disallow_reset_from_null);
-
- // Forbid comparison of scoped_ptr types. If U != T, it totally
- // doesn't make sense, and if U == T, it still doesn't make sense
- // because you should never have the same object owned by two different
- // scoped_ptrs.
- template <class U> bool operator==(scoped_ptr<U> const& p2) const;
- template <class U> bool operator!=(scoped_ptr<U> const& p2) const;
-};
-
-} // namespace talk_base
-
-// Free functions
-template <class T, class D>
-void swap(talk_base::scoped_ptr<T, D>& p1, talk_base::scoped_ptr<T, D>& p2) {
- p1.swap(p2);
-}
-
-template <class T, class D>
-bool operator==(T* p1, const talk_base::scoped_ptr<T, D>& p2) {
- return p1 == p2.get();
-}
-
-template <class T, class D>
-bool operator!=(T* p1, const talk_base::scoped_ptr<T, D>& p2) {
- return p1 != p2.get();
-}
-
-#endif // #ifndef TALK_BASE_SCOPED_PTR_H__
diff --git a/base/scoped_ref_ptr.h b/base/scoped_ref_ptr.h
deleted file mode 100644
index ae1ab0f..0000000
--- a/base/scoped_ref_ptr.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Originally these classes are from Chromium.
-// http://src.chromium.org/viewvc/chrome/trunk/src/base/memory/ref_counted.h?view=markup
-
-//
-// A smart pointer class for reference counted objects. Use this class instead
-// of calling AddRef and Release manually on a reference counted object to
-// avoid common memory leaks caused by forgetting to Release an object
-// reference. Sample usage:
-//
-// class MyFoo : public RefCounted<MyFoo> {
-// ...
-// };
-//
-// void some_function() {
-// scoped_refptr<MyFoo> foo = new MyFoo();
-// foo->Method(param);
-// // |foo| is released when this function returns
-// }
-//
-// void some_other_function() {
-// scoped_refptr<MyFoo> foo = new MyFoo();
-// ...
-// foo = NULL; // explicitly releases |foo|
-// ...
-// if (foo)
-// foo->Method(param);
-// }
-//
-// The above examples show how scoped_refptr<T> acts like a pointer to T.
-// Given two scoped_refptr<T> classes, it is also possible to exchange
-// references between the two objects, like so:
-//
-// {
-// scoped_refptr<MyFoo> a = new MyFoo();
-// scoped_refptr<MyFoo> b;
-//
-// b.swap(a);
-// // now, |b| references the MyFoo object, and |a| references NULL.
-// }
-//
-// To make both |a| and |b| in the above example reference the same MyFoo
-// object, simply use the assignment operator:
-//
-// {
-// scoped_refptr<MyFoo> a = new MyFoo();
-// scoped_refptr<MyFoo> b;
-//
-// b = a;
-// // now, |a| and |b| each own a reference to the same MyFoo object.
-// }
-//
-
-#ifndef TALK_BASE_SCOPED_REF_PTR_H_
-#define TALK_BASE_SCOPED_REF_PTR_H_
-
-#include <stddef.h>
-
-namespace talk_base {
-
-template <class T>
-class scoped_refptr {
- public:
- scoped_refptr() : ptr_(NULL) {
- }
-
- scoped_refptr(T* p) : ptr_(p) {
- if (ptr_)
- ptr_->AddRef();
- }
-
- scoped_refptr(const scoped_refptr<T>& r) : ptr_(r.ptr_) {
- if (ptr_)
- ptr_->AddRef();
- }
-
- template <typename U>
- scoped_refptr(const scoped_refptr<U>& r) : ptr_(r.get()) {
- if (ptr_)
- ptr_->AddRef();
- }
-
- ~scoped_refptr() {
- if (ptr_)
- ptr_->Release();
- }
-
- T* get() const { return ptr_; }
- operator T*() const { return ptr_; }
- T* operator->() const { return ptr_; }
-
- // Release a pointer.
- // The return value is the current pointer held by this object.
- // If this object holds a NULL pointer, the return value is NULL.
- // After this operation, this object will hold a NULL pointer,
- // and will not own the object any more.
- T* release() {
- T* retVal = ptr_;
- ptr_ = NULL;
- return retVal;
- }
-
- scoped_refptr<T>& operator=(T* p) {
- // AddRef first so that self assignment should work
- if (p)
- p->AddRef();
- if (ptr_ )
- ptr_ ->Release();
- ptr_ = p;
- return *this;
- }
-
- scoped_refptr<T>& operator=(const scoped_refptr<T>& r) {
- return *this = r.ptr_;
- }
-
- template <typename U>
- scoped_refptr<T>& operator=(const scoped_refptr<U>& r) {
- return *this = r.get();
- }
-
- void swap(T** pp) {
- T* p = ptr_;
- ptr_ = *pp;
- *pp = p;
- }
-
- void swap(scoped_refptr<T>& r) {
- swap(&r.ptr_);
- }
-
- protected:
- T* ptr_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SCOPED_REF_PTR_H_
diff --git a/base/scopedptrcollection.h b/base/scopedptrcollection.h
deleted file mode 100644
index ec2726e..0000000
--- a/base/scopedptrcollection.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Stores a collection of pointers that are deleted when the container is
-// destructed.
-
-#ifndef TALK_BASE_SCOPEDPTRCOLLECTION_H_
-#define TALK_BASE_SCOPEDPTRCOLLECTION_H_
-
-#include <algorithm>
-#include <vector>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/constructormagic.h"
-
-namespace talk_base {
-
-template<class T>
-class ScopedPtrCollection {
- public:
- typedef std::vector<T*> VectorT;
-
- ScopedPtrCollection() { }
- ~ScopedPtrCollection() {
- for (typename VectorT::iterator it = collection_.begin();
- it != collection_.end(); ++it) {
- delete *it;
- }
- }
-
- const VectorT& collection() const { return collection_; }
- void Reserve(size_t size) {
- collection_.reserve(size);
- }
- void PushBack(T* t) {
- collection_.push_back(t);
- }
-
- // Remove |t| from the collection without deleting it.
- void Remove(T* t) {
- collection_.erase(std::remove(collection_.begin(), collection_.end(), t),
- collection_.end());
- }
-
- private:
- VectorT collection_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedPtrCollection);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SCOPEDPTRCOLLECTION_H_
diff --git a/base/scopedptrcollection_unittest.cc b/base/scopedptrcollection_unittest.cc
deleted file mode 100644
index dd9002e..0000000
--- a/base/scopedptrcollection_unittest.cc
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/scopedptrcollection.h"
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-namespace {
-
-class InstanceCounter {
- public:
- explicit InstanceCounter(int* num_instances)
- : num_instances_(num_instances) {
- ++(*num_instances_);
- }
- ~InstanceCounter() {
- --(*num_instances_);
- }
-
- private:
- int* num_instances_;
-
- DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
-};
-
-} // namespace
-
-class ScopedPtrCollectionTest : public testing::Test {
- protected:
- ScopedPtrCollectionTest()
- : num_instances_(0),
- collection_(new ScopedPtrCollection<InstanceCounter>()) {
- }
-
- int num_instances_;
- scoped_ptr<ScopedPtrCollection<InstanceCounter> > collection_;
-};
-
-TEST_F(ScopedPtrCollectionTest, PushBack) {
- EXPECT_EQ(0u, collection_->collection().size());
- EXPECT_EQ(0, num_instances_);
- const int kNum = 100;
- for (int i = 0; i < kNum; ++i) {
- collection_->PushBack(new InstanceCounter(&num_instances_));
- }
- EXPECT_EQ(static_cast<size_t>(kNum), collection_->collection().size());
- EXPECT_EQ(kNum, num_instances_);
- collection_.reset();
- EXPECT_EQ(0, num_instances_);
-}
-
-TEST_F(ScopedPtrCollectionTest, Remove) {
- InstanceCounter* ic = new InstanceCounter(&num_instances_);
- collection_->PushBack(ic);
- EXPECT_EQ(1u, collection_->collection().size());
- collection_->Remove(ic);
- EXPECT_EQ(1, num_instances_);
- collection_.reset();
- EXPECT_EQ(1, num_instances_);
- delete ic;
- EXPECT_EQ(0, num_instances_);
-}
-
-
-} // namespace talk_base
diff --git a/base/sec_buffer.h b/base/sec_buffer.h
deleted file mode 100644
index 585e27f..0000000
--- a/base/sec_buffer.h
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// @file Contains utility classes that make it easier to use SecBuffers
-
-#ifndef TALK_BASE_SEC_BUFFER_H__
-#define TALK_BASE_SEC_BUFFER_H__
-
-namespace talk_base {
-
-// A base class for CSecBuffer<T>. Contains
-// all implementation that does not require
-// template arguments.
-class CSecBufferBase : public SecBuffer {
- public:
- CSecBufferBase() {
- Clear();
- }
-
- // Uses the SSPI to free a pointer, must be
- // used for buffers returned from SSPI APIs.
- static void FreeSSPI(void *ptr) {
- if ( ptr ) {
- SECURITY_STATUS status;
- status = ::FreeContextBuffer(ptr);
- ASSERT(SEC_E_OK == status); // "Freeing context buffer"
- }
- }
-
- // Deletes a buffer with operator delete
- static void FreeDelete(void *ptr) {
- delete [] reinterpret_cast<char*>(ptr);
- }
-
- // A noop delete, for buffers over other
- // people's memory
- static void FreeNone(void *ptr) {
- }
-
- protected:
- // Clears the buffer to EMPTY & NULL
- void Clear() {
- this->BufferType = SECBUFFER_EMPTY;
- this->cbBuffer = 0;
- this->pvBuffer = NULL;
- }
-};
-
-// Wrapper class for SecBuffer to take care
-// of initialization and destruction.
-template <void (*pfnFreeBuffer)(void *ptr)>
-class CSecBuffer: public CSecBufferBase {
- public:
- // Initializes buffer to empty & NULL
- CSecBuffer() {
- }
-
- // Frees any allocated memory
- ~CSecBuffer() {
- Release();
- }
-
- // Frees the buffer appropriately, and re-nulls
- void Release() {
- pfnFreeBuffer(this->pvBuffer);
- Clear();
- }
-
- private:
- // A placeholder function for compile-time asserts on the class
- void CompileAsserts() {
- // never invoked...
- assert(false); // _T("Notreached")
-
- // This class must not extend the size of SecBuffer, since
- // we use arrays of CSecBuffer in CSecBufferBundle below
- cassert(sizeof(CSecBuffer<SSPIFree> == sizeof(SecBuffer)));
- }
-};
-
-// Contains all generic implementation for the
-// SecBufferBundle class
-class SecBufferBundleBase {
- public:
-};
-
-// A template class that bundles a SecBufferDesc with
-// one or more SecBuffers for convenience. Can take
-// care of deallocating buffers appropriately, as indicated
-// by pfnFreeBuffer function.
-// By default does no deallocation.
-template <int num_buffers,
- void (*pfnFreeBuffer)(void *ptr) = CSecBufferBase::FreeNone>
-class CSecBufferBundle : public SecBufferBundleBase {
- public:
- // Constructs a security buffer bundle with num_buffers
- // buffers, all of which are empty and nulled.
- CSecBufferBundle() {
- desc_.ulVersion = SECBUFFER_VERSION;
- desc_.cBuffers = num_buffers;
- desc_.pBuffers = buffers_;
- }
-
- // Frees all currently used buffers.
- ~CSecBufferBundle() {
- Release();
- }
-
- // Accessor for the descriptor
- PSecBufferDesc desc() {
- return &desc_;
- }
-
- // Accessor for the descriptor
- const PSecBufferDesc desc() const {
- return &desc_;
- }
-
- // returns the i-th security buffer
- SecBuffer &operator[] (size_t num) {
- ASSERT(num < num_buffers); // "Buffer index out of bounds"
- return buffers_[num];
- }
-
- // returns the i-th security buffer
- const SecBuffer &operator[] (size_t num) const {
- ASSERT(num < num_buffers); // "Buffer index out of bounds"
- return buffers_[num];
- }
-
- // Frees all non-NULL security buffers,
- // using the deallocation function
- void Release() {
- for ( size_t i = 0; i < num_buffers; ++i ) {
- buffers_[i].Release();
- }
- }
-
- private:
- // Our descriptor
- SecBufferDesc desc_;
- // Our bundled buffers, each takes care of its own
- // initialization and destruction
- CSecBuffer<pfnFreeBuffer> buffers_[num_buffers];
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SEC_BUFFER_H__
diff --git a/base/sha1.cc b/base/sha1.cc
deleted file mode 100644
index d52d56d..0000000
--- a/base/sha1.cc
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * SHA-1 in C
- * By Steve Reid <sreid@sea-to-sky.net>
- * 100% Public Domain
- *
- * -----------------
- * Modified 7/98
- * By James H. Brown <jbrown@burgoyne.com>
- * Still 100% Public Domain
- *
- * Corrected a problem which generated improper hash values on 16 bit machines
- * Routine SHA1Update changed from
- * void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int
- * len)
- * to
- * void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned
- * long len)
- *
- * The 'len' parameter was declared an int which works fine on 32 bit machines.
- * However, on 16 bit machines an int is too small for the shifts being done
- * against
- * it. This caused the hash function to generate incorrect values if len was
- * greater than 8191 (8K - 1) due to the 'len << 3' on line 3 of SHA1Update().
- *
- * Since the file IO in main() reads 16K at a time, any file 8K or larger would
- * be guaranteed to generate the wrong hash (e.g. Test Vector #3, a million
- * "a"s).
- *
- * I also changed the declaration of variables i & j in SHA1Update to
- * unsigned long from unsigned int for the same reason.
- *
- * These changes should make no difference to any 32 bit implementations since
- * an
- * int and a long are the same size in those environments.
- *
- * --
- * I also corrected a few compiler warnings generated by Borland C.
- * 1. Added #include <process.h> for exit() prototype
- * 2. Removed unused variable 'j' in SHA1Final
- * 3. Changed exit(0) to return(0) at end of main.
- *
- * ALL changes I made can be located by searching for comments containing 'JHB'
- * -----------------
- * Modified 8/98
- * By Steve Reid <sreid@sea-to-sky.net>
- * Still 100% public domain
- *
- * 1- Removed #include <process.h> and used return() instead of exit()
- * 2- Fixed overwriting of finalcount in SHA1Final() (discovered by Chris Hall)
- * 3- Changed email address from steve@edmweb.com to sreid@sea-to-sky.net
- *
- * -----------------
- * Modified 4/01
- * By Saul Kravitz <Saul.Kravitz@celera.com>
- * Still 100% PD
- * Modified to run on Compaq Alpha hardware.
- *
- * -----------------
- * Modified 07/2002
- * By Ralph Giles <giles@ghostscript.com>
- * Still 100% public domain
- * modified for use with stdint types, autoconf
- * code cleanup, removed attribution comments
- * switched SHA1Final() argument order for consistency
- * use SHA1_ prefix for public api
- * move public api to sha1.h
- *
- * -----------------
- * Modified 02/2012
- * By Justin Uberti <juberti@google.com>
- * Remove underscore from SHA1 prefix to avoid conflict with OpenSSL
- * Remove test code
- * Untabify
- *
- * -----------------
- * Modified 03/2012
- * By Ronghua Wu <ronghuawu@google.com>
- * Change the typedef of uint32(8)_t to uint32(8). We need this because in the
- * chromium android build, the stdio.h will include stdint.h which already
- * defined uint32(8)_t.
- *
- * -----------------
- * Modified 04/2012
- * By Frank Barchard <fbarchard@google.com>
- * Ported to C++, Google style, change len to size_t, enable SHA1HANDSOFF
- *
- * Test Vectors (from FIPS PUB 180-1)
- * "abc"
- * A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
- * "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
- * 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
- * A million repetitions of "a"
- * 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
- */
-
-// Enabling SHA1HANDSOFF preserves the caller's data buffer.
-// Disabling SHA1HANDSOFF the buffer will be modified (end swapped).
-#define SHA1HANDSOFF
-
-#include "talk/base/sha1.h"
-
-#include <stdio.h>
-#include <string.h>
-
-void SHA1Transform(uint32 state[5], const uint8 buffer[64]);
-
-#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
-
-// blk0() and blk() perform the initial expand.
-// I got the idea of expanding during the round function from SSLeay
-// FIXME: can we do this in an endian-proof way?
-#ifdef ARCH_CPU_BIG_ENDIAN
-#define blk0(i) block->l[i]
-#else
-#define blk0(i) (block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | \
- (rol(block->l[i], 8) & 0x00FF00FF))
-#endif
-#define blk(i) (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ \
- block->l[(i + 8) & 15] ^ block->l[(i + 2) & 15] ^ block->l[i & 15], 1))
-
-// (R0+R1), R2, R3, R4 are the different operations used in SHA1.
-#define R0(v, w, x, y, z, i) \
- z += ((w & (x ^ y)) ^ y) + blk0(i) + 0x5A827999 + rol(v, 5); \
- w = rol(w, 30);
-#define R1(v, w, x, y, z, i) \
- z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
- w = rol(w, 30);
-#define R2(v, w, x, y, z, i) \
- z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5);\
- w = rol(w, 30);
-#define R3(v, w, x, y, z, i) \
- z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
- w = rol(w, 30);
-#define R4(v, w, x, y, z, i) \
- z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
- w = rol(w, 30);
-
-#ifdef VERBOSE // SAK
-void SHAPrintContext(SHA1_CTX *context, char *msg) {
- printf("%s (%d,%d) %x %x %x %x %x\n",
- msg,
- context->count[0], context->count[1],
- context->state[0],
- context->state[1],
- context->state[2],
- context->state[3],
- context->state[4]);
-}
-#endif /* VERBOSE */
-
-// Hash a single 512-bit block. This is the core of the algorithm.
-void SHA1Transform(uint32 state[5], const uint8 buffer[64]) {
- union CHAR64LONG16 {
- uint8 c[64];
- uint32 l[16];
- };
-#ifdef SHA1HANDSOFF
- static uint8 workspace[64];
- memcpy(workspace, buffer, 64);
- CHAR64LONG16* block = reinterpret_cast<CHAR64LONG16*>(workspace);
-#else
- // Note(fbarchard): This option does modify the user's data buffer.
- CHAR64LONG16* block = const_cast<CHAR64LONG16*>(
- reinterpret_cast<const CHAR64LONG16*>(buffer));
-#endif
-
- // Copy context->state[] to working vars.
- uint32 a = state[0];
- uint32 b = state[1];
- uint32 c = state[2];
- uint32 d = state[3];
- uint32 e = state[4];
-
- // 4 rounds of 20 operations each. Loop unrolled.
- // Note(fbarchard): The following has lint warnings for multiple ; on
- // a line and no space after , but is left as-is to be similar to the
- // original code.
- R0(a,b,c,d,e,0); R0(e,a,b,c,d,1); R0(d,e,a,b,c,2); R0(c,d,e,a,b,3);
- R0(b,c,d,e,a,4); R0(a,b,c,d,e,5); R0(e,a,b,c,d,6); R0(d,e,a,b,c,7);
- R0(c,d,e,a,b,8); R0(b,c,d,e,a,9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
- R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
- R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
- R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
- R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
- R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
- R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
- R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
- R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
- R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
- R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
- R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
- R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
- R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
- R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
- R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
- R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
- R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
-
- // Add the working vars back into context.state[].
- state[0] += a;
- state[1] += b;
- state[2] += c;
- state[3] += d;
- state[4] += e;
-}
-
-// SHA1Init - Initialize new context.
-void SHA1Init(SHA1_CTX* context) {
- // SHA1 initialization constants.
- context->state[0] = 0x67452301;
- context->state[1] = 0xEFCDAB89;
- context->state[2] = 0x98BADCFE;
- context->state[3] = 0x10325476;
- context->state[4] = 0xC3D2E1F0;
- context->count[0] = context->count[1] = 0;
-}
-
-// Run your data through this.
-void SHA1Update(SHA1_CTX* context, const uint8* data, size_t input_len) {
- size_t i = 0;
-
-#ifdef VERBOSE
- SHAPrintContext(context, "before");
-#endif
-
- // Compute number of bytes mod 64.
- size_t index = (context->count[0] >> 3) & 63;
-
- // Update number of bits.
- // TODO: Use uint64 instead of 2 uint32 for count.
- // count[0] has low 29 bits for byte count + 3 pad 0's making 32 bits for
- // bit count.
- // Add bit count to low uint32
- context->count[0] += static_cast<uint32>(input_len << 3);
- if (context->count[0] < static_cast<uint32>(input_len << 3)) {
- ++context->count[1]; // if overlow (carry), add one to high word
- }
- context->count[1] += static_cast<uint32>(input_len >> 29);
- if ((index + input_len) > 63) {
- i = 64 - index;
- memcpy(&context->buffer[index], data, i);
- SHA1Transform(context->state, context->buffer);
- for (; i + 63 < input_len; i += 64) {
- SHA1Transform(context->state, data + i);
- }
- index = 0;
- }
- memcpy(&context->buffer[index], &data[i], input_len - i);
-
-#ifdef VERBOSE
- SHAPrintContext(context, "after ");
-#endif
-}
-
-// Add padding and return the message digest.
-void SHA1Final(SHA1_CTX* context, uint8 digest[SHA1_DIGEST_SIZE]) {
- uint8 finalcount[8];
- for (int i = 0; i < 8; ++i) {
- // Endian independent
- finalcount[i] = static_cast<uint8>(
- (context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8) ) & 255);
- }
- SHA1Update(context, reinterpret_cast<const uint8*>("\200"), 1);
- while ((context->count[0] & 504) != 448) {
- SHA1Update(context, reinterpret_cast<const uint8*>("\0"), 1);
- }
- SHA1Update(context, finalcount, 8); // Should cause a SHA1Transform().
- for (int i = 0; i < SHA1_DIGEST_SIZE; ++i) {
- digest[i] = static_cast<uint8>(
- (context->state[i >> 2] >> ((3 - (i & 3)) * 8) ) & 255);
- }
-
- // Wipe variables.
- memset(context->buffer, 0, 64);
- memset(context->state, 0, 20);
- memset(context->count, 0, 8);
- memset(finalcount, 0, 8); // SWR
-
-#ifdef SHA1HANDSOFF // Make SHA1Transform overwrite its own static vars.
- SHA1Transform(context->state, context->buffer);
-#endif
-}
diff --git a/base/sha1.h b/base/sha1.h
deleted file mode 100644
index 262b744..0000000
--- a/base/sha1.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * SHA-1 in C
- * By Steve Reid <sreid@sea-to-sky.net>
- * 100% Public Domain
- *
-*/
-
-// Ported to C++, Google style and uses basictypes.h
-
-#ifndef TALK_BASE_SHA1_H_
-#define TALK_BASE_SHA1_H_
-
-#include "talk/base/basictypes.h"
-
-struct SHA1_CTX {
- uint32 state[5];
- // TODO: Change bit count to uint64.
- uint32 count[2]; // Bit count of input.
- uint8 buffer[64];
-};
-
-#define SHA1_DIGEST_SIZE 20
-
-void SHA1Init(SHA1_CTX* context);
-void SHA1Update(SHA1_CTX* context, const uint8* data, size_t len);
-void SHA1Final(SHA1_CTX* context, uint8 digest[SHA1_DIGEST_SIZE]);
-
-#endif // TALK_BASE_SHA1_H_
diff --git a/base/sha1digest.h b/base/sha1digest.h
deleted file mode 100644
index c8b1e46..0000000
--- a/base/sha1digest.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SHA1DIGEST_H_
-#define TALK_BASE_SHA1DIGEST_H_
-
-#include "talk/base/messagedigest.h"
-#include "talk/base/sha1.h"
-
-namespace talk_base {
-
-// A simple wrapper for our SHA-1 implementation.
-class Sha1Digest : public MessageDigest {
- public:
- enum { kSize = SHA1_DIGEST_SIZE };
- Sha1Digest() {
- SHA1Init(&ctx_);
- }
- virtual size_t Size() const {
- return kSize;
- }
- virtual void Update(const void* buf, size_t len) {
- SHA1Update(&ctx_, static_cast<const uint8*>(buf), len);
- }
- virtual size_t Finish(void* buf, size_t len) {
- if (len < kSize) {
- return 0;
- }
- SHA1Final(&ctx_, static_cast<uint8*>(buf));
- SHA1Init(&ctx_); // Reset for next use.
- return kSize;
- }
-
- private:
- SHA1_CTX ctx_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SHA1DIGEST_H_
diff --git a/base/sha1digest_unittest.cc b/base/sha1digest_unittest.cc
deleted file mode 100644
index d6c14b6..0000000
--- a/base/sha1digest_unittest.cc
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/sha1digest.h"
-#include "talk/base/gunit.h"
-#include "talk/base/stringencode.h"
-
-namespace talk_base {
-
-std::string Sha1(const std::string& input) {
- Sha1Digest sha1;
- return ComputeDigest(&sha1, input);
-}
-
-TEST(Sha1DigestTest, TestSize) {
- Sha1Digest sha1;
- EXPECT_EQ(20, static_cast<int>(Sha1Digest::kSize));
- EXPECT_EQ(20U, sha1.Size());
-}
-
-TEST(Sha1DigestTest, TestBasic) {
- // Test vectors from sha1.c.
- EXPECT_EQ("da39a3ee5e6b4b0d3255bfef95601890afd80709", Sha1(""));
- EXPECT_EQ("a9993e364706816aba3e25717850c26c9cd0d89d", Sha1("abc"));
- EXPECT_EQ("84983e441c3bd26ebaae4aa1f95129e5e54670f1",
- Sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"));
- std::string a_million_as(1000000, 'a');
- EXPECT_EQ("34aa973cd4c4daa4f61eeb2bdbad27316534016f", Sha1(a_million_as));
-}
-
-TEST(Sha1DigestTest, TestMultipleUpdates) {
- Sha1Digest sha1;
- std::string input =
- "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
- char output[Sha1Digest::kSize];
- for (size_t i = 0; i < input.size(); ++i) {
- sha1.Update(&input[i], 1);
- }
- EXPECT_EQ(sha1.Size(), sha1.Finish(output, sizeof(output)));
- EXPECT_EQ("84983e441c3bd26ebaae4aa1f95129e5e54670f1",
- hex_encode(output, sizeof(output)));
-}
-
-TEST(Sha1DigestTest, TestReuse) {
- Sha1Digest sha1;
- std::string input = "abc";
- EXPECT_EQ("a9993e364706816aba3e25717850c26c9cd0d89d",
- ComputeDigest(&sha1, input));
- input = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
- EXPECT_EQ("84983e441c3bd26ebaae4aa1f95129e5e54670f1",
- ComputeDigest(&sha1, input));
-}
-
-TEST(Sha1DigestTest, TestBufferTooSmall) {
- Sha1Digest sha1;
- std::string input = "abcdefghijklmnopqrstuvwxyz";
- char output[Sha1Digest::kSize - 1];
- sha1.Update(input.c_str(), input.size());
- EXPECT_EQ(0U, sha1.Finish(output, sizeof(output)));
-}
-
-TEST(Sha1DigestTest, TestBufferConst) {
- Sha1Digest sha1;
- const int kLongSize = 1000000;
- std::string input(kLongSize, '\0');
- for (int i = 0; i < kLongSize; ++i) {
- input[i] = static_cast<char>(i);
- }
- sha1.Update(input.c_str(), input.size());
- for (int i = 0; i < kLongSize; ++i) {
- EXPECT_EQ(static_cast<char>(i), input[i]);
- }
-}
-
-} // namespace talk_base
diff --git a/base/sharedexclusivelock.cc b/base/sharedexclusivelock.cc
deleted file mode 100644
index 0b0439a..0000000
--- a/base/sharedexclusivelock.cc
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/sharedexclusivelock.h"
-
-namespace talk_base {
-
-SharedExclusiveLock::SharedExclusiveLock()
- : shared_count_is_zero_(true, true),
- shared_count_(0) {
-}
-
-void SharedExclusiveLock::LockExclusive() {
- cs_exclusive_.Enter();
- shared_count_is_zero_.Wait(talk_base::kForever);
-}
-
-void SharedExclusiveLock::UnlockExclusive() {
- cs_exclusive_.Leave();
-}
-
-void SharedExclusiveLock::LockShared() {
- CritScope exclusive_scope(&cs_exclusive_);
- CritScope shared_scope(&cs_shared_);
- if (++shared_count_ == 1) {
- shared_count_is_zero_.Reset();
- }
-}
-
-void SharedExclusiveLock::UnlockShared() {
- CritScope shared_scope(&cs_shared_);
- if (--shared_count_ == 0) {
- shared_count_is_zero_.Set();
- }
-}
-
-} // namespace talk_base
diff --git a/base/sharedexclusivelock.h b/base/sharedexclusivelock.h
deleted file mode 100644
index 2bdd854..0000000
--- a/base/sharedexclusivelock.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SHAREDEXCLUSIVELOCK_H_
-#define TALK_BASE_SHAREDEXCLUSIVELOCK_H_
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/event.h"
-
-namespace talk_base {
-
-// This class provides shared-exclusive lock. It can be used in cases like
-// multiple-readers/single-writer model.
-class SharedExclusiveLock {
- public:
- SharedExclusiveLock();
-
- // Locking/unlocking methods. It is encouraged to use SharedScope or
- // ExclusiveScope for protection.
- void LockExclusive();
- void UnlockExclusive();
- void LockShared();
- void UnlockShared();
-
- private:
- talk_base::CriticalSection cs_exclusive_;
- talk_base::CriticalSection cs_shared_;
- talk_base::Event shared_count_is_zero_;
- int shared_count_;
-
- DISALLOW_COPY_AND_ASSIGN(SharedExclusiveLock);
-};
-
-class SharedScope {
- public:
- explicit SharedScope(SharedExclusiveLock* lock) : lock_(lock) {
- lock_->LockShared();
- }
-
- ~SharedScope() {
- lock_->UnlockShared();
- }
-
- private:
- SharedExclusiveLock* lock_;
-
- DISALLOW_COPY_AND_ASSIGN(SharedScope);
-};
-
-class ExclusiveScope {
- public:
- explicit ExclusiveScope(SharedExclusiveLock* lock) : lock_(lock) {
- lock_->LockExclusive();
- }
-
- ~ExclusiveScope() {
- lock_->UnlockExclusive();
- }
-
- private:
- SharedExclusiveLock* lock_;
-
- DISALLOW_COPY_AND_ASSIGN(ExclusiveScope);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SHAREDEXCLUSIVELOCK_H_
diff --git a/base/sharedexclusivelock_unittest.cc b/base/sharedexclusivelock_unittest.cc
deleted file mode 100644
index e280aa2..0000000
--- a/base/sharedexclusivelock_unittest.cc
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sharedexclusivelock.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-static const uint32 kMsgRead = 0;
-static const uint32 kMsgWrite = 0;
-static const int kNoWaitThresholdInMs = 10;
-static const int kWaitThresholdInMs = 80;
-static const int kProcessTimeInMs = 100;
-static const int kProcessTimeoutInMs = 5000;
-
-class SharedExclusiveTask : public MessageHandler {
- public:
- SharedExclusiveTask(SharedExclusiveLock* shared_exclusive_lock,
- int* value,
- bool* done)
- : shared_exclusive_lock_(shared_exclusive_lock),
- waiting_time_in_ms_(0),
- value_(value),
- done_(done) {
- worker_thread_.reset(new Thread());
- worker_thread_->Start();
- }
-
- int waiting_time_in_ms() const { return waiting_time_in_ms_; }
-
- protected:
- scoped_ptr<Thread> worker_thread_;
- SharedExclusiveLock* shared_exclusive_lock_;
- int waiting_time_in_ms_;
- int* value_;
- bool* done_;
-};
-
-class ReadTask : public SharedExclusiveTask {
- public:
- ReadTask(SharedExclusiveLock* shared_exclusive_lock, int* value, bool* done)
- : SharedExclusiveTask(shared_exclusive_lock, value, done) {
- }
-
- void PostRead(int* value) {
- worker_thread_->Post(this, kMsgRead, new TypedMessageData<int*>(value));
- }
-
- private:
- virtual void OnMessage(Message* message) {
- ASSERT(talk_base::Thread::Current() == worker_thread_.get());
- ASSERT(message != NULL);
- ASSERT(message->message_id == kMsgRead);
-
- TypedMessageData<int*>* message_data =
- static_cast<TypedMessageData<int*>*>(message->pdata);
-
- uint32 start_time = Time();
- {
- SharedScope ss(shared_exclusive_lock_);
- waiting_time_in_ms_ = TimeDiff(Time(), start_time);
-
- Thread::SleepMs(kProcessTimeInMs);
- *message_data->data() = *value_;
- *done_ = true;
- }
- delete message->pdata;
- message->pdata = NULL;
- }
-};
-
-class WriteTask : public SharedExclusiveTask {
- public:
- WriteTask(SharedExclusiveLock* shared_exclusive_lock, int* value, bool* done)
- : SharedExclusiveTask(shared_exclusive_lock, value, done) {
- }
-
- void PostWrite(int value) {
- worker_thread_->Post(this, kMsgWrite, new TypedMessageData<int>(value));
- }
-
- private:
- virtual void OnMessage(Message* message) {
- ASSERT(talk_base::Thread::Current() == worker_thread_.get());
- ASSERT(message != NULL);
- ASSERT(message->message_id == kMsgWrite);
-
- TypedMessageData<int>* message_data =
- static_cast<TypedMessageData<int>*>(message->pdata);
-
- uint32 start_time = Time();
- {
- ExclusiveScope es(shared_exclusive_lock_);
- waiting_time_in_ms_ = TimeDiff(Time(), start_time);
-
- Thread::SleepMs(kProcessTimeInMs);
- *value_ = message_data->data();
- *done_ = true;
- }
- delete message->pdata;
- message->pdata = NULL;
- }
-};
-
-// Unit test for SharedExclusiveLock.
-class SharedExclusiveLockTest
- : public testing::Test {
- public:
- SharedExclusiveLockTest() : value_(0) {
- }
-
- virtual void SetUp() {
- shared_exclusive_lock_.reset(new SharedExclusiveLock());
- }
-
- protected:
- scoped_ptr<SharedExclusiveLock> shared_exclusive_lock_;
- int value_;
-};
-
-// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3318
-TEST_F(SharedExclusiveLockTest, DISABLED_TestSharedShared) {
- int value0, value1;
- bool done0, done1;
- ReadTask reader0(shared_exclusive_lock_.get(), &value_, &done0);
- ReadTask reader1(shared_exclusive_lock_.get(), &value_, &done1);
-
- // Test shared locks can be shared without waiting.
- {
- SharedScope ss(shared_exclusive_lock_.get());
- value_ = 1;
- done0 = false;
- done1 = false;
- reader0.PostRead(&value0);
- reader1.PostRead(&value1);
- Thread::SleepMs(kProcessTimeInMs);
- }
-
- EXPECT_TRUE_WAIT(done0, kProcessTimeoutInMs);
- EXPECT_EQ(1, value0);
- EXPECT_LE(reader0.waiting_time_in_ms(), kNoWaitThresholdInMs);
- EXPECT_TRUE_WAIT(done1, kProcessTimeoutInMs);
- EXPECT_EQ(1, value1);
- EXPECT_LE(reader1.waiting_time_in_ms(), kNoWaitThresholdInMs);
-}
-
-TEST_F(SharedExclusiveLockTest, TestSharedExclusive) {
- bool done;
- WriteTask writer(shared_exclusive_lock_.get(), &value_, &done);
-
- // Test exclusive lock needs to wait for shared lock.
- {
- SharedScope ss(shared_exclusive_lock_.get());
- value_ = 1;
- done = false;
- writer.PostWrite(2);
- Thread::SleepMs(kProcessTimeInMs);
- EXPECT_EQ(1, value_);
- }
-
- EXPECT_TRUE_WAIT(done, kProcessTimeoutInMs);
- EXPECT_EQ(2, value_);
- EXPECT_GE(writer.waiting_time_in_ms(), kWaitThresholdInMs);
-}
-
-TEST_F(SharedExclusiveLockTest, TestExclusiveShared) {
- int value;
- bool done;
- ReadTask reader(shared_exclusive_lock_.get(), &value_, &done);
-
- // Test shared lock needs to wait for exclusive lock.
- {
- ExclusiveScope es(shared_exclusive_lock_.get());
- value_ = 1;
- done = false;
- reader.PostRead(&value);
- Thread::SleepMs(kProcessTimeInMs);
- value_ = 2;
- }
-
- EXPECT_TRUE_WAIT(done, kProcessTimeoutInMs);
- EXPECT_EQ(2, value);
- EXPECT_GE(reader.waiting_time_in_ms(), kWaitThresholdInMs);
-}
-
-TEST_F(SharedExclusiveLockTest, TestExclusiveExclusive) {
- bool done;
- WriteTask writer(shared_exclusive_lock_.get(), &value_, &done);
-
- // Test exclusive lock needs to wait for exclusive lock.
- {
- ExclusiveScope es(shared_exclusive_lock_.get());
- value_ = 1;
- done = false;
- writer.PostWrite(2);
- Thread::SleepMs(kProcessTimeInMs);
- EXPECT_EQ(1, value_);
- }
-
- EXPECT_TRUE_WAIT(done, kProcessTimeoutInMs);
- EXPECT_EQ(2, value_);
- EXPECT_GE(writer.waiting_time_in_ms(), kWaitThresholdInMs);
-}
-
-} // namespace talk_base
diff --git a/base/signalthread.cc b/base/signalthread.cc
deleted file mode 100644
index 88f3ff7..0000000
--- a/base/signalthread.cc
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/signalthread.h"
-
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// SignalThread
-///////////////////////////////////////////////////////////////////////////////
-
-SignalThread::SignalThread()
- : main_(Thread::Current()),
- worker_(this),
- state_(kInit),
- refcount_(1) {
- main_->SignalQueueDestroyed.connect(this,
- &SignalThread::OnMainThreadDestroyed);
- worker_.SetName("SignalThread", this);
-}
-
-SignalThread::~SignalThread() {
- ASSERT(refcount_ == 0);
-}
-
-bool SignalThread::SetName(const std::string& name, const void* obj) {
- EnterExit ee(this);
- ASSERT(main_->IsCurrent());
- ASSERT(kInit == state_);
- return worker_.SetName(name, obj);
-}
-
-bool SignalThread::SetPriority(ThreadPriority priority) {
- EnterExit ee(this);
- ASSERT(main_->IsCurrent());
- ASSERT(kInit == state_);
- return worker_.SetPriority(priority);
-}
-
-void SignalThread::Start() {
- EnterExit ee(this);
- ASSERT(main_->IsCurrent());
- if (kInit == state_ || kComplete == state_) {
- state_ = kRunning;
- OnWorkStart();
- worker_.Start();
- } else {
- ASSERT(false);
- }
-}
-
-void SignalThread::Destroy(bool wait) {
- EnterExit ee(this);
- ASSERT(main_->IsCurrent());
- if ((kInit == state_) || (kComplete == state_)) {
- refcount_--;
- } else if (kRunning == state_ || kReleasing == state_) {
- state_ = kStopping;
- // OnWorkStop() must follow Quit(), so that when the thread wakes up due to
- // OWS(), ContinueWork() will return false.
- worker_.Quit();
- OnWorkStop();
- if (wait) {
- // Release the thread's lock so that it can return from ::Run.
- cs_.Leave();
- worker_.Stop();
- cs_.Enter();
- refcount_--;
- }
- } else {
- ASSERT(false);
- }
-}
-
-void SignalThread::Release() {
- EnterExit ee(this);
- ASSERT(main_->IsCurrent());
- if (kComplete == state_) {
- refcount_--;
- } else if (kRunning == state_) {
- state_ = kReleasing;
- } else {
- // if (kInit == state_) use Destroy()
- ASSERT(false);
- }
-}
-
-bool SignalThread::ContinueWork() {
- EnterExit ee(this);
- ASSERT(worker_.IsCurrent());
- return worker_.ProcessMessages(0);
-}
-
-void SignalThread::OnMessage(Message *msg) {
- EnterExit ee(this);
- if (ST_MSG_WORKER_DONE == msg->message_id) {
- ASSERT(main_->IsCurrent());
- OnWorkDone();
- bool do_delete = false;
- if (kRunning == state_) {
- state_ = kComplete;
- } else {
- do_delete = true;
- }
- if (kStopping != state_) {
- // Before signaling that the work is done, make sure that the worker
- // thread actually is done. We got here because DoWork() finished and
- // Run() posted the ST_MSG_WORKER_DONE message. This means the worker
- // thread is about to go away anyway, but sometimes it doesn't actually
- // finish before SignalWorkDone is processed, and for a reusable
- // SignalThread this makes an assert in thread.cc fire.
- //
- // Calling Stop() on the worker ensures that the OS thread that underlies
- // the worker will finish, and will be set to NULL, enabling us to call
- // Start() again.
- worker_.Stop();
- SignalWorkDone(this);
- }
- if (do_delete) {
- refcount_--;
- }
- }
-}
-
-void SignalThread::Run() {
- DoWork();
- {
- EnterExit ee(this);
- if (main_) {
- main_->Post(this, ST_MSG_WORKER_DONE);
- }
- }
-}
-
-void SignalThread::OnMainThreadDestroyed() {
- EnterExit ee(this);
- main_ = NULL;
-}
-
-} // namespace talk_base
diff --git a/base/signalthread.h b/base/signalthread.h
deleted file mode 100644
index 46dd0a3..0000000
--- a/base/signalthread.h
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SIGNALTHREAD_H_
-#define TALK_BASE_SIGNALTHREAD_H_
-
-#include <string>
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// SignalThread - Base class for worker threads. The main thread should call
-// Start() to begin work, and then follow one of these models:
-// Normal: Wait for SignalWorkDone, and then call Release to destroy.
-// Cancellation: Call Release(true), to abort the worker thread.
-// Fire-and-forget: Call Release(false), which allows the thread to run to
-// completion, and then self-destruct without further notification.
-// Periodic tasks: Wait for SignalWorkDone, then eventually call Start()
-// again to repeat the task. When the instance isn't needed anymore,
-// call Release. DoWork, OnWorkStart and OnWorkStop are called again,
-// on a new thread.
-// The subclass should override DoWork() to perform the background task. By
-// periodically calling ContinueWork(), it can check for cancellation.
-// OnWorkStart and OnWorkDone can be overridden to do pre- or post-work
-// tasks in the context of the main thread.
-///////////////////////////////////////////////////////////////////////////////
-
-class SignalThread
- : public sigslot::has_slots<>,
- protected MessageHandler {
- public:
- SignalThread();
-
- // Context: Main Thread. Call before Start to change the worker's name.
- bool SetName(const std::string& name, const void* obj);
-
- // Context: Main Thread. Call before Start to change the worker's priority.
- bool SetPriority(ThreadPriority priority);
-
- // Context: Main Thread. Call to begin the worker thread.
- void Start();
-
- // Context: Main Thread. If the worker thread is not running, deletes the
- // object immediately. Otherwise, asks the worker thread to abort processing,
- // and schedules the object to be deleted once the worker exits.
- // SignalWorkDone will not be signalled. If wait is true, does not return
- // until the thread is deleted.
- void Destroy(bool wait);
-
- // Context: Main Thread. If the worker thread is complete, deletes the
- // object immediately. Otherwise, schedules the object to be deleted once
- // the worker thread completes. SignalWorkDone will be signalled.
- void Release();
-
- // Context: Main Thread. Signalled when work is complete.
- sigslot::signal1<SignalThread *> SignalWorkDone;
-
- enum { ST_MSG_WORKER_DONE, ST_MSG_FIRST_AVAILABLE };
-
- protected:
- virtual ~SignalThread();
-
- Thread* worker() { return &worker_; }
-
- // Context: Main Thread. Subclass should override to do pre-work setup.
- virtual void OnWorkStart() { }
-
- // Context: Worker Thread. Subclass should override to do work.
- virtual void DoWork() = 0;
-
- // Context: Worker Thread. Subclass should call periodically to
- // dispatch messages and determine if the thread should terminate.
- bool ContinueWork();
-
- // Context: Worker Thread. Subclass should override when extra work is
- // needed to abort the worker thread.
- virtual void OnWorkStop() { }
-
- // Context: Main Thread. Subclass should override to do post-work cleanup.
- virtual void OnWorkDone() { }
-
- // Context: Any Thread. If subclass overrides, be sure to call the base
- // implementation. Do not use (message_id < ST_MSG_FIRST_AVAILABLE)
- virtual void OnMessage(Message *msg);
-
- private:
- enum State {
- kInit, // Initialized, but not started
- kRunning, // Started and doing work
- kReleasing, // Same as running, but to be deleted when work is done
- kComplete, // Work is done
- kStopping, // Work is being interrupted
- };
-
- class Worker : public Thread {
- public:
- explicit Worker(SignalThread* parent) : parent_(parent) {}
- virtual ~Worker() { Stop(); }
- virtual void Run() { parent_->Run(); }
-
- private:
- SignalThread* parent_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(Worker);
- };
-
- class EnterExit {
- public:
- explicit EnterExit(SignalThread* t) : t_(t) {
- t_->cs_.Enter();
- // If refcount_ is zero then the object has already been deleted and we
- // will be double-deleting it in ~EnterExit()! (shouldn't happen)
- ASSERT(t_->refcount_ != 0);
- ++t_->refcount_;
- }
- ~EnterExit() {
- bool d = (0 == --t_->refcount_);
- t_->cs_.Leave();
- if (d)
- delete t_;
- }
-
- private:
- SignalThread* t_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(EnterExit);
- };
-
- void Run();
- void OnMainThreadDestroyed();
-
- Thread* main_;
- Worker worker_;
- CriticalSection cs_;
- State state_;
- int refcount_;
-
- DISALLOW_COPY_AND_ASSIGN(SignalThread);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SIGNALTHREAD_H_
diff --git a/base/signalthread_unittest.cc b/base/signalthread_unittest.cc
deleted file mode 100644
index 7bc73f0..0000000
--- a/base/signalthread_unittest.cc
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/signalthread.h"
-#include "talk/base/thread.h"
-
-using namespace talk_base;
-
-class SignalThreadTest : public testing::Test, public sigslot::has_slots<> {
- public:
- class SlowSignalThread : public SignalThread {
- public:
- SlowSignalThread(SignalThreadTest* harness) : harness_(harness) {
- }
-
- virtual ~SlowSignalThread() {
- EXPECT_EQ(harness_->main_thread_, Thread::Current());
- ++harness_->thread_deleted_;
- }
-
- const SignalThreadTest* harness() { return harness_; }
-
- protected:
- virtual void OnWorkStart() {
- ASSERT_TRUE(harness_ != NULL);
- ++harness_->thread_started_;
- EXPECT_EQ(harness_->main_thread_, Thread::Current());
- EXPECT_FALSE(worker()->RunningForTest()); // not started yet
- }
-
- virtual void OnWorkStop() {
- ++harness_->thread_stopped_;
- EXPECT_EQ(harness_->main_thread_, Thread::Current());
- EXPECT_TRUE(worker()->RunningForTest()); // not stopped yet
- }
-
- virtual void OnWorkDone() {
- ++harness_->thread_done_;
- EXPECT_EQ(harness_->main_thread_, Thread::Current());
- EXPECT_TRUE(worker()->RunningForTest()); // not stopped yet
- }
-
- virtual void DoWork() {
- EXPECT_NE(harness_->main_thread_, Thread::Current());
- EXPECT_EQ(worker(), Thread::Current());
- Thread::Current()->socketserver()->Wait(250, false);
- }
-
- private:
- SignalThreadTest* harness_;
- DISALLOW_EVIL_CONSTRUCTORS(SlowSignalThread);
- };
-
- void OnWorkComplete(talk_base::SignalThread* thread) {
- SlowSignalThread* t = static_cast<SlowSignalThread*>(thread);
- EXPECT_EQ(t->harness(), this);
- EXPECT_EQ(main_thread_, Thread::Current());
-
- ++thread_completed_;
- if (!called_release_) {
- thread->Release();
- }
- }
-
- virtual void SetUp() {
- main_thread_ = Thread::Current();
- thread_ = new SlowSignalThread(this);
- thread_->SignalWorkDone.connect(this, &SignalThreadTest::OnWorkComplete);
- called_release_ = false;
- thread_started_ = 0;
- thread_done_ = 0;
- thread_completed_ = 0;
- thread_stopped_ = 0;
- thread_deleted_ = 0;
- }
-
- virtual void TearDown() {
- }
-
- Thread* main_thread_;
- SlowSignalThread* thread_;
- bool called_release_;
-
- int thread_started_;
- int thread_done_;
- int thread_completed_;
- int thread_stopped_;
- int thread_deleted_;
-};
-
-class OwnerThread : public Thread, public sigslot::has_slots<> {
- public:
- explicit OwnerThread(SignalThreadTest* harness)
- : harness_(harness),
- has_run_(false) {
- }
-
- virtual ~OwnerThread() {
- Stop();
- }
-
- virtual void Run() {
- SignalThreadTest::SlowSignalThread* signal_thread =
- new SignalThreadTest::SlowSignalThread(harness_);
- signal_thread->SignalWorkDone.connect(this, &OwnerThread::OnWorkDone);
- signal_thread->Start();
- Thread::Current()->socketserver()->Wait(100, false);
- signal_thread->Release();
- // Delete |signal_thread|.
- signal_thread->Destroy(true);
- has_run_ = true;
- }
-
- bool has_run() { return has_run_; }
- void OnWorkDone(SignalThread* signal_thread) {
- FAIL() << " This shouldn't get called.";
- }
-
- private:
- SignalThreadTest* harness_;
- bool has_run_;
- DISALLOW_EVIL_CONSTRUCTORS(OwnerThread);
-};
-
-// Test for when the main thread goes away while the
-// signal thread is still working. This may happen
-// when shutting down the process.
-TEST_F(SignalThreadTest, OwnerThreadGoesAway) {
- {
- scoped_ptr<OwnerThread> owner(new OwnerThread(this));
- main_thread_ = owner.get();
- owner->Start();
- while (!owner->has_run()) {
- Thread::Current()->socketserver()->Wait(10, false);
- }
- }
- // At this point the main thread has gone away.
- // Give the SignalThread a little time to do its callback,
- // which will crash if the signal thread doesn't handle
- // this situation well.
- Thread::Current()->socketserver()->Wait(500, false);
-}
-
-#define EXPECT_STATE(started, done, completed, stopped, deleted) \
- EXPECT_EQ(started, thread_started_); \
- EXPECT_EQ(done, thread_done_); \
- EXPECT_EQ(completed, thread_completed_); \
- EXPECT_EQ(stopped, thread_stopped_); \
- EXPECT_EQ(deleted, thread_deleted_);
-
-TEST_F(SignalThreadTest, ThreadFinishes) {
- thread_->Start();
- EXPECT_STATE(1, 0, 0, 0, 0);
- Thread::SleepMs(500);
- EXPECT_STATE(1, 0, 0, 0, 0);
- Thread::Current()->ProcessMessages(0);
- EXPECT_STATE(1, 1, 1, 0, 1);
-}
-
-TEST_F(SignalThreadTest, ReleasedThreadFinishes) {
- thread_->Start();
- EXPECT_STATE(1, 0, 0, 0, 0);
- thread_->Release();
- called_release_ = true;
- EXPECT_STATE(1, 0, 0, 0, 0);
- Thread::SleepMs(500);
- EXPECT_STATE(1, 0, 0, 0, 0);
- Thread::Current()->ProcessMessages(0);
- EXPECT_STATE(1, 1, 1, 0, 1);
-}
-
-TEST_F(SignalThreadTest, DestroyedThreadCleansUp) {
- thread_->Start();
- EXPECT_STATE(1, 0, 0, 0, 0);
- thread_->Destroy(true);
- EXPECT_STATE(1, 0, 0, 1, 1);
- Thread::Current()->ProcessMessages(0);
- EXPECT_STATE(1, 0, 0, 1, 1);
-}
-
-TEST_F(SignalThreadTest, DeferredDestroyedThreadCleansUp) {
- thread_->Start();
- EXPECT_STATE(1, 0, 0, 0, 0);
- thread_->Destroy(false);
- EXPECT_STATE(1, 0, 0, 1, 0);
- Thread::SleepMs(500);
- EXPECT_STATE(1, 0, 0, 1, 0);
- Thread::Current()->ProcessMessages(0);
- EXPECT_STATE(1, 1, 0, 1, 1);
-}
diff --git a/base/sigslot.h b/base/sigslot.h
deleted file mode 100644
index 192aaa7..0000000
--- a/base/sigslot.h
+++ /dev/null
@@ -1,2850 +0,0 @@
-// sigslot.h: Signal/Slot classes
-//
-// Written by Sarah Thompson (sarah@telergy.com) 2002.
-//
-// License: Public domain. You are free to use this code however you like, with the proviso that
-// the author takes on no responsibility or liability for any use.
-//
-// QUICK DOCUMENTATION
-//
-// (see also the full documentation at http://sigslot.sourceforge.net/)
-//
-// #define switches
-// SIGSLOT_PURE_ISO - Define this to force ISO C++ compliance. This also disables
-// all of the thread safety support on platforms where it is
-// available.
-//
-// SIGSLOT_USE_POSIX_THREADS - Force use of Posix threads when using a C++ compiler other than
-// gcc on a platform that supports Posix threads. (When using gcc,
-// this is the default - use SIGSLOT_PURE_ISO to disable this if
-// necessary)
-//
-// SIGSLOT_DEFAULT_MT_POLICY - Where thread support is enabled, this defaults to multi_threaded_global.
-// Otherwise, the default is single_threaded. #define this yourself to
-// override the default. In pure ISO mode, anything other than
-// single_threaded will cause a compiler error.
-//
-// PLATFORM NOTES
-//
-// Win32 - On Win32, the WIN32 symbol must be #defined. Most mainstream
-// compilers do this by default, but you may need to define it
-// yourself if your build environment is less standard. This causes
-// the Win32 thread support to be compiled in and used automatically.
-//
-// Unix/Linux/BSD, etc. - If you're using gcc, it is assumed that you have Posix threads
-// available, so they are used automatically. You can override this
-// (as under Windows) with the SIGSLOT_PURE_ISO switch. If you're using
-// something other than gcc but still want to use Posix threads, you
-// need to #define SIGSLOT_USE_POSIX_THREADS.
-//
-// ISO C++ - If none of the supported platforms are detected, or if
-// SIGSLOT_PURE_ISO is defined, all multithreading support is turned off,
-// along with any code that might cause a pure ISO C++ environment to
-// complain. Before you ask, gcc -ansi -pedantic won't compile this
-// library, but gcc -ansi is fine. Pedantic mode seems to throw a lot of
-// errors that aren't really there. If you feel like investigating this,
-// please contact the author.
-//
-//
-// THREADING MODES
-//
-// single_threaded - Your program is assumed to be single threaded from the point of view
-// of signal/slot usage (i.e. all objects using signals and slots are
-// created and destroyed from a single thread). Behaviour if objects are
-// destroyed concurrently is undefined (i.e. you'll get the occasional
-// segmentation fault/memory exception).
-//
-// multi_threaded_global - Your program is assumed to be multi threaded. Objects using signals and
-// slots can be safely created and destroyed from any thread, even when
-// connections exist. In multi_threaded_global mode, this is achieved by a
-// single global mutex (actually a critical section on Windows because they
-// are faster). This option uses less OS resources, but results in more
-// opportunities for contention, possibly resulting in more context switches
-// than are strictly necessary.
-//
-// multi_threaded_local - Behaviour in this mode is essentially the same as multi_threaded_global,
-// except that each signal, and each object that inherits has_slots, all
-// have their own mutex/critical section. In practice, this means that
-// mutex collisions (and hence context switches) only happen if they are
-// absolutely essential. However, on some platforms, creating a lot of
-// mutexes can slow down the whole OS, so use this option with care.
-//
-// USING THE LIBRARY
-//
-// See the full documentation at http://sigslot.sourceforge.net/
-//
-//
-// Libjingle specific:
-// This file has been modified such that has_slots and signalx do not have to be
-// using the same threading requirements. E.g. it is possible to connect a
-// has_slots<single_threaded> and signal0<multi_threaded_local> or
-// has_slots<multi_threaded_local> and signal0<single_threaded>.
-// If has_slots is single threaded the user must ensure that it is not trying
-// to connect or disconnect to signalx concurrently or data race may occur.
-// If signalx is single threaded the user must ensure that disconnect, connect
-// or signal is not happening concurrently or data race may occur.
-
-#ifndef TALK_BASE_SIGSLOT_H__
-#define TALK_BASE_SIGSLOT_H__
-
-#include <list>
-#include <set>
-#include <stdlib.h>
-
-// On our copy of sigslot.h, we set single threading as default.
-#define SIGSLOT_DEFAULT_MT_POLICY single_threaded
-
-#if defined(SIGSLOT_PURE_ISO) || (!defined(WIN32) && !defined(__GNUG__) && !defined(SIGSLOT_USE_POSIX_THREADS))
-# define _SIGSLOT_SINGLE_THREADED
-#elif defined(WIN32)
-# define _SIGSLOT_HAS_WIN32_THREADS
-# if !defined(WIN32_LEAN_AND_MEAN)
-# define WIN32_LEAN_AND_MEAN
-# endif
-# include "talk/base/win32.h"
-#elif defined(__GNUG__) || defined(SIGSLOT_USE_POSIX_THREADS)
-# define _SIGSLOT_HAS_POSIX_THREADS
-# include <pthread.h>
-#else
-# define _SIGSLOT_SINGLE_THREADED
-#endif
-
-#ifndef SIGSLOT_DEFAULT_MT_POLICY
-# ifdef _SIGSLOT_SINGLE_THREADED
-# define SIGSLOT_DEFAULT_MT_POLICY single_threaded
-# else
-# define SIGSLOT_DEFAULT_MT_POLICY multi_threaded_local
-# endif
-#endif
-
-// TODO: change this namespace to talk_base?
-namespace sigslot {
-
- class single_threaded
- {
- public:
- single_threaded()
- {
- ;
- }
-
- virtual ~single_threaded()
- {
- ;
- }
-
- virtual void lock()
- {
- ;
- }
-
- virtual void unlock()
- {
- ;
- }
- };
-
-#ifdef _SIGSLOT_HAS_WIN32_THREADS
- // The multi threading policies only get compiled in if they are enabled.
- class multi_threaded_global
- {
- public:
- multi_threaded_global()
- {
- static bool isinitialised = false;
-
- if(!isinitialised)
- {
- InitializeCriticalSection(get_critsec());
- isinitialised = true;
- }
- }
-
- multi_threaded_global(const multi_threaded_global&)
- {
- ;
- }
-
- virtual ~multi_threaded_global()
- {
- ;
- }
-
- virtual void lock()
- {
- EnterCriticalSection(get_critsec());
- }
-
- virtual void unlock()
- {
- LeaveCriticalSection(get_critsec());
- }
-
- private:
- CRITICAL_SECTION* get_critsec()
- {
- static CRITICAL_SECTION g_critsec;
- return &g_critsec;
- }
- };
-
- class multi_threaded_local
- {
- public:
- multi_threaded_local()
- {
- InitializeCriticalSection(&m_critsec);
- }
-
- multi_threaded_local(const multi_threaded_local&)
- {
- InitializeCriticalSection(&m_critsec);
- }
-
- virtual ~multi_threaded_local()
- {
- DeleteCriticalSection(&m_critsec);
- }
-
- virtual void lock()
- {
- EnterCriticalSection(&m_critsec);
- }
-
- virtual void unlock()
- {
- LeaveCriticalSection(&m_critsec);
- }
-
- private:
- CRITICAL_SECTION m_critsec;
- };
-#endif // _SIGSLOT_HAS_WIN32_THREADS
-
-#ifdef _SIGSLOT_HAS_POSIX_THREADS
- // The multi threading policies only get compiled in if they are enabled.
- class multi_threaded_global
- {
- public:
- multi_threaded_global()
- {
- pthread_mutex_init(get_mutex(), NULL);
- }
-
- multi_threaded_global(const multi_threaded_global&)
- {
- ;
- }
-
- virtual ~multi_threaded_global()
- {
- ;
- }
-
- virtual void lock()
- {
- pthread_mutex_lock(get_mutex());
- }
-
- virtual void unlock()
- {
- pthread_mutex_unlock(get_mutex());
- }
-
- private:
- pthread_mutex_t* get_mutex()
- {
- static pthread_mutex_t g_mutex;
- return &g_mutex;
- }
- };
-
- class multi_threaded_local
- {
- public:
- multi_threaded_local()
- {
- pthread_mutex_init(&m_mutex, NULL);
- }
-
- multi_threaded_local(const multi_threaded_local&)
- {
- pthread_mutex_init(&m_mutex, NULL);
- }
-
- virtual ~multi_threaded_local()
- {
- pthread_mutex_destroy(&m_mutex);
- }
-
- virtual void lock()
- {
- pthread_mutex_lock(&m_mutex);
- }
-
- virtual void unlock()
- {
- pthread_mutex_unlock(&m_mutex);
- }
-
- private:
- pthread_mutex_t m_mutex;
- };
-#endif // _SIGSLOT_HAS_POSIX_THREADS
-
- template<class mt_policy>
- class lock_block
- {
- public:
- mt_policy *m_mutex;
-
- lock_block(mt_policy *mtx)
- : m_mutex(mtx)
- {
- m_mutex->lock();
- }
-
- ~lock_block()
- {
- m_mutex->unlock();
- }
- };
-
- class has_slots_interface;
-
- template<class mt_policy>
- class _connection_base0
- {
- public:
- virtual ~_connection_base0() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit() = 0;
- virtual _connection_base0* clone() = 0;
- virtual _connection_base0* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class mt_policy>
- class _connection_base1
- {
- public:
- virtual ~_connection_base1() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type) = 0;
- virtual _connection_base1<arg1_type, mt_policy>* clone() = 0;
- virtual _connection_base1<arg1_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class arg2_type, class mt_policy>
- class _connection_base2
- {
- public:
- virtual ~_connection_base2() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type, arg2_type) = 0;
- virtual _connection_base2<arg1_type, arg2_type, mt_policy>* clone() = 0;
- virtual _connection_base2<arg1_type, arg2_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class mt_policy>
- class _connection_base3
- {
- public:
- virtual ~_connection_base3() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type, arg2_type, arg3_type) = 0;
- virtual _connection_base3<arg1_type, arg2_type, arg3_type, mt_policy>* clone() = 0;
- virtual _connection_base3<arg1_type, arg2_type, arg3_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type, class mt_policy>
- class _connection_base4
- {
- public:
- virtual ~_connection_base4() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type) = 0;
- virtual _connection_base4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>* clone() = 0;
- virtual _connection_base4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class mt_policy>
- class _connection_base5
- {
- public:
- virtual ~_connection_base5() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type) = 0;
- virtual _connection_base5<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>* clone() = 0;
- virtual _connection_base5<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class mt_policy>
- class _connection_base6
- {
- public:
- virtual ~_connection_base6() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type,
- arg6_type) = 0;
- virtual _connection_base6<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>* clone() = 0;
- virtual _connection_base6<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class arg7_type, class mt_policy>
- class _connection_base7
- {
- public:
- virtual ~_connection_base7() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type,
- arg6_type, arg7_type) = 0;
- virtual _connection_base7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>* clone() = 0;
- virtual _connection_base7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class arg7_type, class arg8_type, class mt_policy>
- class _connection_base8
- {
- public:
- virtual ~_connection_base8() {}
- virtual has_slots_interface* getdest() const = 0;
- virtual void emit(arg1_type, arg2_type, arg3_type, arg4_type, arg5_type,
- arg6_type, arg7_type, arg8_type) = 0;
- virtual _connection_base8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>* clone() = 0;
- virtual _connection_base8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>* duplicate(has_slots_interface* pnewdest) = 0;
- };
-
- class _signal_base_interface
- {
- public:
- virtual void slot_disconnect(has_slots_interface* pslot) = 0;
- virtual void slot_duplicate(const has_slots_interface* poldslot, has_slots_interface* pnewslot) = 0;
- };
-
- template<class mt_policy>
- class _signal_base : public _signal_base_interface, public mt_policy
- {
- };
-
- class has_slots_interface
- {
- public:
- has_slots_interface()
- {
- ;
- }
-
- virtual void signal_connect(_signal_base_interface* sender) = 0;
-
- virtual void signal_disconnect(_signal_base_interface* sender) = 0;
-
- virtual ~has_slots_interface()
- {
- }
-
- virtual void disconnect_all() = 0;
- };
-
- template<class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class has_slots : public has_slots_interface, public mt_policy
- {
- private:
- typedef std::set<_signal_base_interface*> sender_set;
- typedef sender_set::const_iterator const_iterator;
-
- public:
- has_slots()
- {
- ;
- }
-
- has_slots(const has_slots& hs)
- {
- lock_block<mt_policy> lock(this);
- const_iterator it = hs.m_senders.begin();
- const_iterator itEnd = hs.m_senders.end();
-
- while(it != itEnd)
- {
- (*it)->slot_duplicate(&hs, this);
- m_senders.insert(*it);
- ++it;
- }
- }
-
- void signal_connect(_signal_base_interface* sender)
- {
- lock_block<mt_policy> lock(this);
- m_senders.insert(sender);
- }
-
- void signal_disconnect(_signal_base_interface* sender)
- {
- lock_block<mt_policy> lock(this);
- m_senders.erase(sender);
- }
-
- virtual ~has_slots()
- {
- disconnect_all();
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- const_iterator it = m_senders.begin();
- const_iterator itEnd = m_senders.end();
-
- while(it != itEnd)
- {
- (*it)->slot_disconnect(this);
- ++it;
- }
-
- m_senders.erase(m_senders.begin(), m_senders.end());
- }
-
- private:
- sender_set m_senders;
- };
-
- template<class mt_policy>
- class _signal_base0 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base0<mt_policy> *> connections_list;
-
- _signal_base0()
- {
- ;
- }
-
- _signal_base0(const _signal_base0& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- ~_signal_base0()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class mt_policy>
- class _signal_base1 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base1<arg1_type, mt_policy> *> connections_list;
-
- _signal_base1()
- {
- ;
- }
-
- _signal_base1(const _signal_base1<arg1_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base1()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class arg2_type, class mt_policy>
- class _signal_base2 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base2<arg1_type, arg2_type, mt_policy> *>
- connections_list;
-
- _signal_base2()
- {
- ;
- }
-
- _signal_base2(const _signal_base2<arg1_type, arg2_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base2()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class mt_policy>
- class _signal_base3 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base3<arg1_type, arg2_type, arg3_type, mt_policy> *>
- connections_list;
-
- _signal_base3()
- {
- ;
- }
-
- _signal_base3(const _signal_base3<arg1_type, arg2_type, arg3_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base3()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type, class mt_policy>
- class _signal_base4 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base4<arg1_type, arg2_type, arg3_type,
- arg4_type, mt_policy> *> connections_list;
-
- _signal_base4()
- {
- ;
- }
-
- _signal_base4(const _signal_base4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base4()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class mt_policy>
- class _signal_base5 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base5<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, mt_policy> *> connections_list;
-
- _signal_base5()
- {
- ;
- }
-
- _signal_base5(const _signal_base5<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base5()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class mt_policy>
- class _signal_base6 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base6<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, mt_policy> *> connections_list;
-
- _signal_base6()
- {
- ;
- }
-
- _signal_base6(const _signal_base6<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base6()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class arg7_type, class mt_policy>
- class _signal_base7 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base7<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, arg7_type, mt_policy> *> connections_list;
-
- _signal_base7()
- {
- ;
- }
-
- _signal_base7(const _signal_base7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base7()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class arg7_type, class arg8_type, class mt_policy>
- class _signal_base8 : public _signal_base<mt_policy>
- {
- public:
- typedef std::list<_connection_base8<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, arg7_type, arg8_type, mt_policy> *>
- connections_list;
-
- _signal_base8()
- {
- ;
- }
-
- _signal_base8(const _signal_base8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>& s)
- : _signal_base<mt_policy>(s)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = s.m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = s.m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_connect(this);
- m_connected_slots.push_back((*it)->clone());
-
- ++it;
- }
- }
-
- void slot_duplicate(const has_slots_interface* oldtarget, has_slots_interface* newtarget)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == oldtarget)
- {
- m_connected_slots.push_back((*it)->duplicate(newtarget));
- }
-
- ++it;
- }
- }
-
- ~_signal_base8()
- {
- disconnect_all();
- }
-
- bool is_empty()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- return it == itEnd;
- }
-
- void disconnect_all()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- (*it)->getdest()->signal_disconnect(this);
- delete *it;
-
- ++it;
- }
-
- m_connected_slots.erase(m_connected_slots.begin(), m_connected_slots.end());
- }
-
-#ifdef _DEBUG
- bool connected(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
- if ((*it)->getdest() == pclass)
- return true;
- it = itNext;
- }
- return false;
- }
-#endif
-
- void disconnect(has_slots_interface* pclass)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- if((*it)->getdest() == pclass)
- {
- delete *it;
- m_connected_slots.erase(it);
- pclass->signal_disconnect(this);
- return;
- }
-
- ++it;
- }
- }
-
- void slot_disconnect(has_slots_interface* pslot)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::iterator it = m_connected_slots.begin();
- typename connections_list::iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- typename connections_list::iterator itNext = it;
- ++itNext;
-
- if((*it)->getdest() == pslot)
- {
- delete *it;
- m_connected_slots.erase(it);
- }
-
- it = itNext;
- }
- }
-
- protected:
- connections_list m_connected_slots;
- };
-
-
- template<class dest_type, class mt_policy>
- class _connection0 : public _connection_base0<mt_policy>
- {
- public:
- _connection0()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection0(dest_type* pobject, void (dest_type::*pmemfun)())
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection0()
- {
- }
-
- virtual _connection_base0<mt_policy>* clone()
- {
- return new _connection0<dest_type, mt_policy>(*this);
- }
-
- virtual _connection_base0<mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection0<dest_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit()
- {
- (m_pobject->*m_pmemfun)();
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)();
- };
-
- template<class dest_type, class arg1_type, class mt_policy>
- class _connection1 : public _connection_base1<arg1_type, mt_policy>
- {
- public:
- _connection1()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection1(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection1()
- {
- }
-
- virtual _connection_base1<arg1_type, mt_policy>* clone()
- {
- return new _connection1<dest_type, arg1_type, mt_policy>(*this);
- }
-
- virtual _connection_base1<arg1_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection1<dest_type, arg1_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1)
- {
- (m_pobject->*m_pmemfun)(a1);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type);
- };
-
- template<class dest_type, class arg1_type, class arg2_type, class mt_policy>
- class _connection2 : public _connection_base2<arg1_type, arg2_type, mt_policy>
- {
- public:
- _connection2()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection2(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type,
- arg2_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection2()
- {
- }
-
- virtual _connection_base2<arg1_type, arg2_type, mt_policy>* clone()
- {
- return new _connection2<dest_type, arg1_type, arg2_type, mt_policy>(*this);
- }
-
- virtual _connection_base2<arg1_type, arg2_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection2<dest_type, arg1_type, arg2_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1, arg2_type a2)
- {
- (m_pobject->*m_pmemfun)(a1, a2);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type, arg2_type);
- };
-
- template<class dest_type, class arg1_type, class arg2_type, class arg3_type, class mt_policy>
- class _connection3 : public _connection_base3<arg1_type, arg2_type, arg3_type, mt_policy>
- {
- public:
- _connection3()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection3(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type,
- arg2_type, arg3_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection3()
- {
- }
-
- virtual _connection_base3<arg1_type, arg2_type, arg3_type, mt_policy>* clone()
- {
- return new _connection3<dest_type, arg1_type, arg2_type, arg3_type, mt_policy>(*this);
- }
-
- virtual _connection_base3<arg1_type, arg2_type, arg3_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection3<dest_type, arg1_type, arg2_type, arg3_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3)
- {
- (m_pobject->*m_pmemfun)(a1, a2, a3);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type);
- };
-
- template<class dest_type, class arg1_type, class arg2_type, class arg3_type,
- class arg4_type, class mt_policy>
- class _connection4 : public _connection_base4<arg1_type, arg2_type,
- arg3_type, arg4_type, mt_policy>
- {
- public:
- _connection4()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection4(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection4()
- {
- }
-
- virtual _connection_base4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>* clone()
- {
- return new _connection4<dest_type, arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>(*this);
- }
-
- virtual _connection_base4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection4<dest_type, arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3,
- arg4_type a4)
- {
- (m_pobject->*m_pmemfun)(a1, a2, a3, a4);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type,
- arg4_type);
- };
-
- template<class dest_type, class arg1_type, class arg2_type, class arg3_type,
- class arg4_type, class arg5_type, class mt_policy>
- class _connection5 : public _connection_base5<arg1_type, arg2_type,
- arg3_type, arg4_type, arg5_type, mt_policy>
- {
- public:
- _connection5()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection5(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection5()
- {
- }
-
- virtual _connection_base5<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>* clone()
- {
- return new _connection5<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>(*this);
- }
-
- virtual _connection_base5<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection5<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5)
- {
- (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type);
- };
-
- template<class dest_type, class arg1_type, class arg2_type, class arg3_type,
- class arg4_type, class arg5_type, class arg6_type, class mt_policy>
- class _connection6 : public _connection_base6<arg1_type, arg2_type,
- arg3_type, arg4_type, arg5_type, arg6_type, mt_policy>
- {
- public:
- _connection6()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection6(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type, arg6_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection6()
- {
- }
-
- virtual _connection_base6<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>* clone()
- {
- return new _connection6<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>(*this);
- }
-
- virtual _connection_base6<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection6<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6)
- {
- (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type);
- };
-
- template<class dest_type, class arg1_type, class arg2_type, class arg3_type,
- class arg4_type, class arg5_type, class arg6_type, class arg7_type, class mt_policy>
- class _connection7 : public _connection_base7<arg1_type, arg2_type,
- arg3_type, arg4_type, arg5_type, arg6_type, arg7_type, mt_policy>
- {
- public:
- _connection7()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection7(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, arg7_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection7()
- {
- }
-
- virtual _connection_base7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>* clone()
- {
- return new _connection7<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>(*this);
- }
-
- virtual _connection_base7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection7<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6, arg7_type a7)
- {
- (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6, a7);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type);
- };
-
- template<class dest_type, class arg1_type, class arg2_type, class arg3_type,
- class arg4_type, class arg5_type, class arg6_type, class arg7_type,
- class arg8_type, class mt_policy>
- class _connection8 : public _connection_base8<arg1_type, arg2_type,
- arg3_type, arg4_type, arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>
- {
- public:
- _connection8()
- {
- m_pobject = NULL;
- m_pmemfun = NULL;
- }
-
- _connection8(dest_type* pobject, void (dest_type::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type, arg6_type,
- arg7_type, arg8_type))
- {
- m_pobject = pobject;
- m_pmemfun = pmemfun;
- }
-
- virtual ~_connection8()
- {
- }
-
- virtual _connection_base8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>* clone()
- {
- return new _connection8<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>(*this);
- }
-
- virtual _connection_base8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>* duplicate(has_slots_interface* pnewdest)
- {
- return new _connection8<dest_type, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>((dest_type *)pnewdest, m_pmemfun);
- }
-
- virtual void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8)
- {
- (m_pobject->*m_pmemfun)(a1, a2, a3, a4, a5, a6, a7, a8);
- }
-
- virtual has_slots_interface* getdest() const
- {
- return m_pobject;
- }
-
- private:
- dest_type* m_pobject;
- void (dest_type::* m_pmemfun)(arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type);
- };
-
- template<class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal0 : public _signal_base0<mt_policy>
- {
- public:
- typedef _signal_base0<mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal0()
- {
- ;
- }
-
- signal0(const signal0<mt_policy>& s)
- : _signal_base0<mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)())
- {
- lock_block<mt_policy> lock(this);
- _connection0<desttype, mt_policy>* conn =
- new _connection0<desttype, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit();
-
- it = itNext;
- }
- }
-
- void operator()()
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit();
-
- it = itNext;
- }
- }
- };
-
- template<class arg1_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal1 : public _signal_base1<arg1_type, mt_policy>
- {
- public:
- typedef _signal_base1<arg1_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal1()
- {
- ;
- }
-
- signal1(const signal1<arg1_type, mt_policy>& s)
- : _signal_base1<arg1_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type))
- {
- lock_block<mt_policy> lock(this);
- _connection1<desttype, arg1_type, mt_policy>* conn =
- new _connection1<desttype, arg1_type, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1);
-
- it = itNext;
- }
- }
- };
-
- template<class arg1_type, class arg2_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal2 : public _signal_base2<arg1_type, arg2_type, mt_policy>
- {
- public:
- typedef _signal_base2<arg1_type, arg2_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal2()
- {
- ;
- }
-
- signal2(const signal2<arg1_type, arg2_type, mt_policy>& s)
- : _signal_base2<arg1_type, arg2_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type,
- arg2_type))
- {
- lock_block<mt_policy> lock(this);
- _connection2<desttype, arg1_type, arg2_type, mt_policy>* conn = new
- _connection2<desttype, arg1_type, arg2_type, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1, arg2_type a2)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1, arg2_type a2)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2);
-
- it = itNext;
- }
- }
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal3 : public _signal_base3<arg1_type, arg2_type, arg3_type, mt_policy>
- {
- public:
- typedef _signal_base3<arg1_type, arg2_type, arg3_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal3()
- {
- ;
- }
-
- signal3(const signal3<arg1_type, arg2_type, arg3_type, mt_policy>& s)
- : _signal_base3<arg1_type, arg2_type, arg3_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type,
- arg2_type, arg3_type))
- {
- lock_block<mt_policy> lock(this);
- _connection3<desttype, arg1_type, arg2_type, arg3_type, mt_policy>* conn =
- new _connection3<desttype, arg1_type, arg2_type, arg3_type, mt_policy>(pclass,
- pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1, arg2_type a2, arg3_type a3)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1, arg2_type a2, arg3_type a3)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3);
-
- it = itNext;
- }
- }
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal4 : public _signal_base4<arg1_type, arg2_type, arg3_type,
- arg4_type, mt_policy>
- {
- public:
- typedef _signal_base4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal4()
- {
- ;
- }
-
- signal4(const signal4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>& s)
- : _signal_base4<arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type))
- {
- lock_block<mt_policy> lock(this);
- _connection4<desttype, arg1_type, arg2_type, arg3_type, arg4_type, mt_policy>*
- conn = new _connection4<desttype, arg1_type, arg2_type, arg3_type,
- arg4_type, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4);
-
- it = itNext;
- }
- }
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal5 : public _signal_base5<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, mt_policy>
- {
- public:
- typedef _signal_base5<arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal5()
- {
- ;
- }
-
- signal5(const signal5<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>& s)
- : _signal_base5<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type))
- {
- lock_block<mt_policy> lock(this);
- _connection5<desttype, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, mt_policy>* conn = new _connection5<desttype, arg1_type, arg2_type,
- arg3_type, arg4_type, arg5_type, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5);
-
- it = itNext;
- }
- }
- };
-
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal6 : public _signal_base6<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, mt_policy>
- {
- public:
- typedef _signal_base6<arg1_type, arg2_type, arg3_type, arg4_type, arg5_type, arg6_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal6()
- {
- ;
- }
-
- signal6(const signal6<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>& s)
- : _signal_base6<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type, arg6_type))
- {
- lock_block<mt_policy> lock(this);
- _connection6<desttype, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, mt_policy>* conn =
- new _connection6<desttype, arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5, a6);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5, a6);
-
- it = itNext;
- }
- }
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class arg7_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal7 : public _signal_base7<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, arg7_type, mt_policy>
- {
- public:
- typedef _signal_base7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal7()
- {
- ;
- }
-
- signal7(const signal7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>& s)
- : _signal_base7<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type, arg6_type,
- arg7_type))
- {
- lock_block<mt_policy> lock(this);
- _connection7<desttype, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, mt_policy>* conn =
- new _connection7<desttype, arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, arg7_type, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6, arg7_type a7)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5, a6, a7);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6, arg7_type a7)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5, a6, a7);
-
- it = itNext;
- }
- }
- };
-
- template<class arg1_type, class arg2_type, class arg3_type, class arg4_type,
- class arg5_type, class arg6_type, class arg7_type, class arg8_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class signal8 : public _signal_base8<arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>
- {
- public:
- typedef _signal_base8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy> base;
- typedef typename base::connections_list connections_list;
- using base::m_connected_slots;
-
- signal8()
- {
- ;
- }
-
- signal8(const signal8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>& s)
- : _signal_base8<arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>(s)
- {
- ;
- }
-
- template<class desttype>
- void connect(desttype* pclass, void (desttype::*pmemfun)(arg1_type,
- arg2_type, arg3_type, arg4_type, arg5_type, arg6_type,
- arg7_type, arg8_type))
- {
- lock_block<mt_policy> lock(this);
- _connection8<desttype, arg1_type, arg2_type, arg3_type, arg4_type,
- arg5_type, arg6_type, arg7_type, arg8_type, mt_policy>* conn =
- new _connection8<desttype, arg1_type, arg2_type, arg3_type,
- arg4_type, arg5_type, arg6_type, arg7_type,
- arg8_type, mt_policy>(pclass, pmemfun);
- m_connected_slots.push_back(conn);
- pclass->signal_connect(this);
- }
-
- void emit(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5, a6, a7, a8);
-
- it = itNext;
- }
- }
-
- void operator()(arg1_type a1, arg2_type a2, arg3_type a3, arg4_type a4,
- arg5_type a5, arg6_type a6, arg7_type a7, arg8_type a8)
- {
- lock_block<mt_policy> lock(this);
- typename connections_list::const_iterator itNext, it = m_connected_slots.begin();
- typename connections_list::const_iterator itEnd = m_connected_slots.end();
-
- while(it != itEnd)
- {
- itNext = it;
- ++itNext;
-
- (*it)->emit(a1, a2, a3, a4, a5, a6, a7, a8);
-
- it = itNext;
- }
- }
- };
-
-}; // namespace sigslot
-
-#endif // TALK_BASE_SIGSLOT_H__
diff --git a/base/sigslot_unittest.cc b/base/sigslot_unittest.cc
deleted file mode 100644
index 62b03c2..0000000
--- a/base/sigslot_unittest.cc
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/sigslot.h"
-
-#include "talk/base/gunit.h"
-
-// This function, when passed a has_slots or signalx, will break the build if
-// its threading requirement is not single threaded
-static bool TemplateIsST(const sigslot::single_threaded* p) {
- return true;
-}
-// This function, when passed a has_slots or signalx, will break the build if
-// its threading requirement is not multi threaded
-static bool TemplateIsMT(const sigslot::multi_threaded_local* p) {
- return true;
-}
-
-class SigslotDefault : public testing::Test, public sigslot::has_slots<> {
- protected:
- sigslot::signal0<> signal_;
-};
-
-template<class slot_policy = sigslot::single_threaded,
- class signal_policy = sigslot::single_threaded>
-class SigslotReceiver : public sigslot::has_slots<slot_policy> {
- public:
- SigslotReceiver() : signal_(NULL), signal_count_(0) {
- }
- ~SigslotReceiver() {
- }
-
- void Connect(sigslot::signal0<signal_policy>* signal) {
- if (!signal) return;
- Disconnect();
- signal_ = signal;
- signal->connect(this,
- &SigslotReceiver<slot_policy, signal_policy>::OnSignal);
- }
- void Disconnect() {
- if (!signal_) return;
- signal_->disconnect(this);
- signal_ = NULL;
- }
- void OnSignal() {
- ++signal_count_;
- }
- int signal_count() { return signal_count_; }
-
- private:
- sigslot::signal0<signal_policy>* signal_;
- int signal_count_;
-};
-
-template<class slot_policy = sigslot::single_threaded,
- class mt_signal_policy = sigslot::multi_threaded_local>
-class SigslotSlotTest : public testing::Test {
- protected:
- SigslotSlotTest() {
- mt_signal_policy mt_policy;
- TemplateIsMT(&mt_policy);
- }
-
- virtual void SetUp() {
- Connect();
- }
- virtual void TearDown() {
- Disconnect();
- }
-
- void Disconnect() {
- st_receiver_.Disconnect();
- mt_receiver_.Disconnect();
- }
-
- void Connect() {
- st_receiver_.Connect(&SignalSTLoopback);
- mt_receiver_.Connect(&SignalMTLoopback);
- }
-
- int st_loop_back_count() { return st_receiver_.signal_count(); }
- int mt_loop_back_count() { return mt_receiver_.signal_count(); }
-
- sigslot::signal0<> SignalSTLoopback;
- SigslotReceiver<slot_policy, sigslot::single_threaded> st_receiver_;
- sigslot::signal0<mt_signal_policy> SignalMTLoopback;
- SigslotReceiver<slot_policy, mt_signal_policy> mt_receiver_;
-};
-
-typedef SigslotSlotTest<> SigslotSTSlotTest;
-typedef SigslotSlotTest<sigslot::multi_threaded_local,
- sigslot::multi_threaded_local> SigslotMTSlotTest;
-
-class multi_threaded_local_fake : public sigslot::multi_threaded_local {
- public:
- multi_threaded_local_fake() : lock_count_(0), unlock_count_(0) {
- }
-
- virtual void lock() {
- ++lock_count_;
- }
- virtual void unlock() {
- ++unlock_count_;
- }
-
- int lock_count() { return lock_count_; }
-
- bool InCriticalSection() { return lock_count_ != unlock_count_; }
-
- protected:
- int lock_count_;
- int unlock_count_;
-};
-
-typedef SigslotSlotTest<multi_threaded_local_fake,
- multi_threaded_local_fake> SigslotMTLockBase;
-
-class SigslotMTLockTest : public SigslotMTLockBase {
- protected:
- SigslotMTLockTest() {}
-
- virtual void SetUp() {
- EXPECT_EQ(0, SlotLockCount());
- SigslotMTLockBase::SetUp();
- // Connects to two signals (ST and MT). However,
- // SlotLockCount() only gets the count for the
- // MT signal (there are two separate SigslotReceiver which
- // keep track of their own count).
- EXPECT_EQ(1, SlotLockCount());
- }
- virtual void TearDown() {
- const int previous_lock_count = SlotLockCount();
- SigslotMTLockBase::TearDown();
- // Disconnects from two signals. Note analogous to SetUp().
- EXPECT_EQ(previous_lock_count + 1, SlotLockCount());
- }
-
- int SlotLockCount() { return mt_receiver_.lock_count(); }
- void Signal() { SignalMTLoopback(); }
- int SignalLockCount() { return SignalMTLoopback.lock_count(); }
- int signal_count() { return mt_loop_back_count(); }
- bool InCriticalSection() { return SignalMTLoopback.InCriticalSection(); }
-};
-
-// This test will always succeed. However, if the default template instantiation
-// changes from single threaded to multi threaded it will break the build here.
-TEST_F(SigslotDefault, DefaultIsST) {
- EXPECT_TRUE(TemplateIsST(this));
- EXPECT_TRUE(TemplateIsST(&signal_));
-}
-
-// ST slot, ST signal
-TEST_F(SigslotSTSlotTest, STLoopbackTest) {
- SignalSTLoopback();
- EXPECT_EQ(1, st_loop_back_count());
- EXPECT_EQ(0, mt_loop_back_count());
-}
-
-// ST slot, MT signal
-TEST_F(SigslotSTSlotTest, MTLoopbackTest) {
- SignalMTLoopback();
- EXPECT_EQ(1, mt_loop_back_count());
- EXPECT_EQ(0, st_loop_back_count());
-}
-
-// ST slot, both ST and MT (separate) signal
-TEST_F(SigslotSTSlotTest, AllLoopbackTest) {
- SignalSTLoopback();
- SignalMTLoopback();
- EXPECT_EQ(1, mt_loop_back_count());
- EXPECT_EQ(1, st_loop_back_count());
-}
-
-TEST_F(SigslotSTSlotTest, Reconnect) {
- SignalSTLoopback();
- SignalMTLoopback();
- EXPECT_EQ(1, mt_loop_back_count());
- EXPECT_EQ(1, st_loop_back_count());
- Disconnect();
- SignalSTLoopback();
- SignalMTLoopback();
- EXPECT_EQ(1, mt_loop_back_count());
- EXPECT_EQ(1, st_loop_back_count());
- Connect();
- SignalSTLoopback();
- SignalMTLoopback();
- EXPECT_EQ(2, mt_loop_back_count());
- EXPECT_EQ(2, st_loop_back_count());
-}
-
-// MT slot, ST signal
-TEST_F(SigslotMTSlotTest, STLoopbackTest) {
- SignalSTLoopback();
- EXPECT_EQ(1, st_loop_back_count());
- EXPECT_EQ(0, mt_loop_back_count());
-}
-
-// MT slot, MT signal
-TEST_F(SigslotMTSlotTest, MTLoopbackTest) {
- SignalMTLoopback();
- EXPECT_EQ(1, mt_loop_back_count());
- EXPECT_EQ(0, st_loop_back_count());
-}
-
-// MT slot, both ST and MT (separate) signal
-TEST_F(SigslotMTSlotTest, AllLoopbackTest) {
- SignalMTLoopback();
- SignalSTLoopback();
- EXPECT_EQ(1, st_loop_back_count());
- EXPECT_EQ(1, mt_loop_back_count());
-}
-
-// Test that locks are acquired and released correctly.
-TEST_F(SigslotMTLockTest, LockSanity) {
- const int lock_count = SignalLockCount();
- Signal();
- EXPECT_FALSE(InCriticalSection());
- EXPECT_EQ(lock_count + 1, SignalLockCount());
- EXPECT_EQ(1, signal_count());
-}
-
-// Destroy signal and slot in different orders.
-TEST(DestructionOrder, SignalFirst) {
- sigslot::signal0<>* signal = new sigslot::signal0<>;
- SigslotReceiver<>* receiver = new SigslotReceiver<>();
- receiver->Connect(signal);
- (*signal)();
- EXPECT_EQ(1, receiver->signal_count());
- delete signal;
- delete receiver;
-}
-
-TEST(DestructionOrder, SlotFirst) {
- sigslot::signal0<>* signal = new sigslot::signal0<>;
- SigslotReceiver<>* receiver = new SigslotReceiver<>();
- receiver->Connect(signal);
- (*signal)();
- EXPECT_EQ(1, receiver->signal_count());
-
- delete receiver;
- (*signal)();
- delete signal;
-}
diff --git a/base/sigslotrepeater.h b/base/sigslotrepeater.h
deleted file mode 100644
index 628089b..0000000
--- a/base/sigslotrepeater.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SIGSLOTREPEATER_H__
-#define TALK_BASE_SIGSLOTREPEATER_H__
-
-// repeaters are both signals and slots, which are designed as intermediate
-// pass-throughs for signals and slots which don't know about each other (for
-// modularity or encapsulation). This eliminates the need to declare a signal
-// handler whose sole purpose is to fire another signal. The repeater connects
-// to the originating signal using the 'repeat' method. When the repeated
-// signal fires, the repeater will also fire.
-
-#include "talk/base/sigslot.h"
-
-namespace sigslot {
-
- template<class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class repeater0 : public signal0<mt_policy>,
- public has_slots<mt_policy>
- {
- public:
- typedef signal0<mt_policy> base_type;
- typedef repeater0<mt_policy> this_type;
-
- repeater0() { }
- repeater0(const this_type& s) : base_type(s) { }
-
- void reemit() { signal0<mt_policy>::emit(); }
- void repeat(base_type &s) { s.connect(this, &this_type::reemit); }
- void stop(base_type &s) { s.disconnect(this); }
- };
-
- template<class arg1_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class repeater1 : public signal1<arg1_type, mt_policy>,
- public has_slots<mt_policy>
- {
- public:
- typedef signal1<arg1_type, mt_policy> base_type;
- typedef repeater1<arg1_type, mt_policy> this_type;
-
- repeater1() { }
- repeater1(const this_type& s) : base_type(s) { }
-
- void reemit(arg1_type a1) { signal1<arg1_type, mt_policy>::emit(a1); }
- void repeat(base_type& s) { s.connect(this, &this_type::reemit); }
- void stop(base_type &s) { s.disconnect(this); }
- };
-
- template<class arg1_type, class arg2_type, class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class repeater2 : public signal2<arg1_type, arg2_type, mt_policy>,
- public has_slots<mt_policy>
- {
- public:
- typedef signal2<arg1_type, arg2_type, mt_policy> base_type;
- typedef repeater2<arg1_type, arg2_type, mt_policy> this_type;
-
- repeater2() { }
- repeater2(const this_type& s) : base_type(s) { }
-
- void reemit(arg1_type a1, arg2_type a2) { signal2<arg1_type, arg2_type, mt_policy>::emit(a1,a2); }
- void repeat(base_type& s) { s.connect(this, &this_type::reemit); }
- void stop(base_type &s) { s.disconnect(this); }
- };
-
- template<class arg1_type, class arg2_type, class arg3_type,
- class mt_policy = SIGSLOT_DEFAULT_MT_POLICY>
- class repeater3 : public signal3<arg1_type, arg2_type, arg3_type, mt_policy>,
- public has_slots<mt_policy>
- {
- public:
- typedef signal3<arg1_type, arg2_type, arg3_type, mt_policy> base_type;
- typedef repeater3<arg1_type, arg2_type, arg3_type, mt_policy> this_type;
-
- repeater3() { }
- repeater3(const this_type& s) : base_type(s) { }
-
- void reemit(arg1_type a1, arg2_type a2, arg3_type a3) {
- signal3<arg1_type, arg2_type, arg3_type, mt_policy>::emit(a1,a2,a3);
- }
- void repeat(base_type& s) { s.connect(this, &this_type::reemit); }
- void stop(base_type &s) { s.disconnect(this); }
- };
-
-} // namespace sigslot
-
-#endif // TALK_BASE_SIGSLOTREPEATER_H__
diff --git a/base/sigslottester.h b/base/sigslottester.h
deleted file mode 100755
index 9422318..0000000
--- a/base/sigslottester.h
+++ /dev/null
@@ -1,216 +0,0 @@
-// This file was GENERATED by command:
-// pump.py sigslottester.h.pump
-// DO NOT EDIT BY HAND!!!
-
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SIGSLOTTESTER_H_
-#define TALK_BASE_SIGSLOTTESTER_H_
-
-// To generate sigslottester.h from sigslottester.h.pump, execute:
-// /home/build/google3/third_party/gtest/scripts/pump.py sigslottester.h.pump
-
-
-// SigslotTester(s) are utility classes to check if signals owned by an
-// object are being invoked at the right time and with the right arguments.
-// They are meant to be used in tests. Tests must provide "capture" pointers
-// (i.e. address of variables) where the arguments from the signal callback
-// can be stored.
-//
-// Example:
-// /* Some signal */
-// sigslot::signal1<const std::string&> foo;
-//
-// /* We want to monitor foo in some test. Note how signal argument is
-// const std::string&, but capture-type is std::string. Capture type
-// must be type that can be assigned to. */
-// std::string capture;
-// SigslotTester1<const std::string&, std::string> slot(&foo, &capture);
-// foo.emit("hello");
-// EXPECT_EQ(1, slot.callback_count());
-// EXPECT_EQ("hello", capture);
-// /* See unit-tests for more examples */
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/sigslot.h"
-
-namespace talk_base {
-
-// For all the templates below:
-// - A1-A5 is the type of the argument i in the callback. Signals may and often
-// do use const-references here for efficiency.
-// - C1-C5 is the type of the variable to capture argument i. These should be
-// non-const value types suitable for use as lvalues.
-
-template <class A1, class C1>
-class SigslotTester1 : public sigslot::has_slots<> {
- public:
- SigslotTester1(sigslot::signal1<A1>* signal,
- C1* capture1)
- : callback_count_(0),
- capture1_(capture1) {
- signal->connect(this, &SigslotTester1::OnSignalCallback);
- }
-
- int callback_count() const { return callback_count_; }
-
- private:
- void OnSignalCallback(A1 arg1) {
- callback_count_++;
- *capture1_ = arg1;
- }
-
- int callback_count_;
- C1* capture1_;
-
- DISALLOW_COPY_AND_ASSIGN(SigslotTester1);
-};
-
-template <class A1, class A2, class C1, class C2>
-class SigslotTester2 : public sigslot::has_slots<> {
- public:
- SigslotTester2(sigslot::signal2<A1, A2>* signal,
- C1* capture1, C2* capture2)
- : callback_count_(0),
- capture1_(capture1), capture2_(capture2) {
- signal->connect(this, &SigslotTester2::OnSignalCallback);
- }
-
- int callback_count() const { return callback_count_; }
-
- private:
- void OnSignalCallback(A1 arg1, A2 arg2) {
- callback_count_++;
- *capture1_ = arg1;
- *capture2_ = arg2;
- }
-
- int callback_count_;
- C1* capture1_;
- C2* capture2_;
-
- DISALLOW_COPY_AND_ASSIGN(SigslotTester2);
-};
-
-template <class A1, class A2, class A3, class C1, class C2, class C3>
-class SigslotTester3 : public sigslot::has_slots<> {
- public:
- SigslotTester3(sigslot::signal3<A1, A2, A3>* signal,
- C1* capture1, C2* capture2, C3* capture3)
- : callback_count_(0),
- capture1_(capture1), capture2_(capture2), capture3_(capture3) {
- signal->connect(this, &SigslotTester3::OnSignalCallback);
- }
-
- int callback_count() const { return callback_count_; }
-
- private:
- void OnSignalCallback(A1 arg1, A2 arg2, A3 arg3) {
- callback_count_++;
- *capture1_ = arg1;
- *capture2_ = arg2;
- *capture3_ = arg3;
- }
-
- int callback_count_;
- C1* capture1_;
- C2* capture2_;
- C3* capture3_;
-
- DISALLOW_COPY_AND_ASSIGN(SigslotTester3);
-};
-
-template <class A1, class A2, class A3, class A4, class C1, class C2, class C3,
- class C4>
-class SigslotTester4 : public sigslot::has_slots<> {
- public:
- SigslotTester4(sigslot::signal4<A1, A2, A3, A4>* signal,
- C1* capture1, C2* capture2, C3* capture3, C4* capture4)
- : callback_count_(0),
- capture1_(capture1), capture2_(capture2), capture3_(capture3),
- capture4_(capture4) {
- signal->connect(this, &SigslotTester4::OnSignalCallback);
- }
-
- int callback_count() const { return callback_count_; }
-
- private:
- void OnSignalCallback(A1 arg1, A2 arg2, A3 arg3, A4 arg4) {
- callback_count_++;
- *capture1_ = arg1;
- *capture2_ = arg2;
- *capture3_ = arg3;
- *capture4_ = arg4;
- }
-
- int callback_count_;
- C1* capture1_;
- C2* capture2_;
- C3* capture3_;
- C4* capture4_;
-
- DISALLOW_COPY_AND_ASSIGN(SigslotTester4);
-};
-
-template <class A1, class A2, class A3, class A4, class A5, class C1, class C2,
- class C3, class C4, class C5>
-class SigslotTester5 : public sigslot::has_slots<> {
- public:
- SigslotTester5(sigslot::signal5<A1, A2, A3, A4, A5>* signal,
- C1* capture1, C2* capture2, C3* capture3, C4* capture4,
- C5* capture5)
- : callback_count_(0),
- capture1_(capture1), capture2_(capture2), capture3_(capture3),
- capture4_(capture4), capture5_(capture5) {
- signal->connect(this, &SigslotTester5::OnSignalCallback);
- }
-
- int callback_count() const { return callback_count_; }
-
- private:
- void OnSignalCallback(A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5) {
- callback_count_++;
- *capture1_ = arg1;
- *capture2_ = arg2;
- *capture3_ = arg3;
- *capture4_ = arg4;
- *capture5_ = arg5;
- }
-
- int callback_count_;
- C1* capture1_;
- C2* capture2_;
- C3* capture3_;
- C4* capture4_;
- C5* capture5_;
-
- DISALLOW_COPY_AND_ASSIGN(SigslotTester5);
-};
-} // namespace talk_base
-
-#endif // TALK_BASE_SIGSLOTTESTER_H_
diff --git a/base/sigslottester.h.pump b/base/sigslottester.h.pump
deleted file mode 100755
index dce1c7b..0000000
--- a/base/sigslottester.h.pump
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * libjingle
- * Copyright 2014 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SIGSLOTTESTER_H_
-#define TALK_BASE_SIGSLOTTESTER_H_
-
-// To generate sigslottester.h from sigslottester.h.pump, execute:
-// /home/build/google3/third_party/gtest/scripts/pump.py sigslottester.h.pump
-
-
-// SigslotTester(s) are utility classes to check if signals owned by an
-// object are being invoked at the right time and with the right arguments.
-// They are meant to be used in tests. Tests must provide "capture" pointers
-// (i.e. address of variables) where the arguments from the signal callback
-// can be stored.
-//
-// Example:
-// /* Some signal */
-// sigslot::signal1<const std::string&> foo;
-//
-// /* We want to monitor foo in some test. Note how signal argument is
-// const std::string&, but capture-type is std::string. Capture type
-// must be type that can be assigned to. */
-// std::string capture;
-// SigslotTester1<const std::string&, std::string> slot(&foo, &capture);
-// foo.emit("hello");
-// EXPECT_EQ(1, slot.callback_count());
-// EXPECT_EQ("hello", capture);
-// /* See unit-tests for more examples */
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/sigslot.h"
-
-namespace talk_base {
-
-// For all the templates below:
-// - A1-A5 is the type of the argument i in the callback. Signals may and often
-// do use const-references here for efficiency.
-// - C1-C5 is the type of the variable to capture argument i. These should be
-// non-const value types suitable for use as lvalues.
-
-$var n = 5
-$range i 1..n
-$for i [[
-$range j 1..i
-
-template <$for j , [[class A$j]], $for j , [[class C$j]]>
-class SigslotTester$i : public sigslot::has_slots<> {
- public:
- SigslotTester$i(sigslot::signal$i<$for j , [[A$j]]>* signal,
- $for j , [[C$j* capture$j]])
- : callback_count_(0),
- $for j , [[capture$j[[]]_(capture$j)]] {
- signal->connect(this, &SigslotTester$i::OnSignalCallback);
- }
-
- int callback_count() const { return callback_count_; }
-
- private:
- void OnSignalCallback($for j , [[A$j arg$j]]) {
- callback_count_++;$for j [[
-
- *capture$j[[]]_ = arg$j;]]
-
- }
-
- int callback_count_;$for j [[
-
- C$j* capture$j[[]]_;]]
-
-
- DISALLOW_COPY_AND_ASSIGN(SigslotTester$i);
-};
-
-]]
-} // namespace talk_base
-
-#endif // TALK_BASE_SIGSLOTTESTER_H_
diff --git a/base/sigslottester_unittest.cc b/base/sigslottester_unittest.cc
deleted file mode 100755
index b427ef6..0000000
--- a/base/sigslottester_unittest.cc
+++ /dev/null
@@ -1,74 +0,0 @@
-#include "talk/base/sigslottester.h"
-
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-
-namespace talk_base {
-
-TEST(SigslotTester, TestSignal1Arg) {
- sigslot::signal1<int> source1;
- int capture1;
- SigslotTester1<int, int> slot1(&source1, &capture1);
- EXPECT_EQ(0, slot1.callback_count());
-
- source1.emit(10);
- EXPECT_EQ(1, slot1.callback_count());
- EXPECT_EQ(10, capture1);
-
- source1.emit(20);
- EXPECT_EQ(2, slot1.callback_count());
- EXPECT_EQ(20, capture1);
-}
-
-TEST(SigslotTester, TestSignal2Args) {
- sigslot::signal2<int, char> source2;
- int capture1;
- char capture2;
- SigslotTester2<int, char, int, char> slot2(&source2, &capture1, &capture2);
- EXPECT_EQ(0, slot2.callback_count());
-
- source2.emit(10, 'x');
- EXPECT_EQ(1, slot2.callback_count());
- EXPECT_EQ(10, capture1);
- EXPECT_EQ('x', capture2);
-
- source2.emit(20, 'y');
- EXPECT_EQ(2, slot2.callback_count());
- EXPECT_EQ(20, capture1);
- EXPECT_EQ('y', capture2);
-}
-
-// Since it applies for 1 and 2 args, we assume it will work for up to 5 args.
-
-TEST(SigslotTester, TestSignalWithConstReferenceArgs) {
- sigslot::signal1<const std::string&> source1;
- std::string capture1;
- SigslotTester1<const std::string&, std::string> slot1(&source1, &capture1);
- EXPECT_EQ(0, slot1.callback_count());
- source1.emit("hello");
- EXPECT_EQ(1, slot1.callback_count());
- EXPECT_EQ("hello", capture1);
-}
-
-TEST(SigslotTester, TestSignalWithPointerToConstArgs) {
- sigslot::signal1<const std::string*> source1;
- const std::string* capture1;
- SigslotTester1<const std::string*, const std::string*> slot1(&source1,
- &capture1);
- EXPECT_EQ(0, slot1.callback_count());
- source1.emit(NULL);
- EXPECT_EQ(1, slot1.callback_count());
- EXPECT_EQ(NULL, capture1);
-}
-
-TEST(SigslotTester, TestSignalWithConstPointerArgs) {
- sigslot::signal1<std::string* const> source1;
- std::string* capture1;
- SigslotTester1<std::string* const, std::string*> slot1(&source1, &capture1);
- EXPECT_EQ(0, slot1.callback_count());
- source1.emit(NULL);
- EXPECT_EQ(1, slot1.callback_count());
- EXPECT_EQ(NULL, capture1);
-}
-
-} // namespace talk_base
diff --git a/base/socket.h b/base/socket.h
deleted file mode 100644
index 590645f..0000000
--- a/base/socket.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKET_H__
-#define TALK_BASE_SOCKET_H__
-
-#include <errno.h>
-
-#ifdef POSIX
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <netinet/in.h>
-#define SOCKET_EACCES EACCES
-#endif
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif
-
-#include "talk/base/basictypes.h"
-#include "talk/base/socketaddress.h"
-
-// Rather than converting errors into a private namespace,
-// Reuse the POSIX socket api errors. Note this depends on
-// Win32 compatibility.
-
-#ifdef WIN32
-#undef EWOULDBLOCK // Remove errno.h's definition for each macro below.
-#define EWOULDBLOCK WSAEWOULDBLOCK
-#undef EINPROGRESS
-#define EINPROGRESS WSAEINPROGRESS
-#undef EALREADY
-#define EALREADY WSAEALREADY
-#undef ENOTSOCK
-#define ENOTSOCK WSAENOTSOCK
-#undef EDESTADDRREQ
-#define EDESTADDRREQ WSAEDESTADDRREQ
-#undef EMSGSIZE
-#define EMSGSIZE WSAEMSGSIZE
-#undef EPROTOTYPE
-#define EPROTOTYPE WSAEPROTOTYPE
-#undef ENOPROTOOPT
-#define ENOPROTOOPT WSAENOPROTOOPT
-#undef EPROTONOSUPPORT
-#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
-#undef ESOCKTNOSUPPORT
-#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT
-#undef EOPNOTSUPP
-#define EOPNOTSUPP WSAEOPNOTSUPP
-#undef EPFNOSUPPORT
-#define EPFNOSUPPORT WSAEPFNOSUPPORT
-#undef EAFNOSUPPORT
-#define EAFNOSUPPORT WSAEAFNOSUPPORT
-#undef EADDRINUSE
-#define EADDRINUSE WSAEADDRINUSE
-#undef EADDRNOTAVAIL
-#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
-#undef ENETDOWN
-#define ENETDOWN WSAENETDOWN
-#undef ENETUNREACH
-#define ENETUNREACH WSAENETUNREACH
-#undef ENETRESET
-#define ENETRESET WSAENETRESET
-#undef ECONNABORTED
-#define ECONNABORTED WSAECONNABORTED
-#undef ECONNRESET
-#define ECONNRESET WSAECONNRESET
-#undef ENOBUFS
-#define ENOBUFS WSAENOBUFS
-#undef EISCONN
-#define EISCONN WSAEISCONN
-#undef ENOTCONN
-#define ENOTCONN WSAENOTCONN
-#undef ESHUTDOWN
-#define ESHUTDOWN WSAESHUTDOWN
-#undef ETOOMANYREFS
-#define ETOOMANYREFS WSAETOOMANYREFS
-#undef ETIMEDOUT
-#define ETIMEDOUT WSAETIMEDOUT
-#undef ECONNREFUSED
-#define ECONNREFUSED WSAECONNREFUSED
-#undef ELOOP
-#define ELOOP WSAELOOP
-#undef ENAMETOOLONG
-#define ENAMETOOLONG WSAENAMETOOLONG
-#undef EHOSTDOWN
-#define EHOSTDOWN WSAEHOSTDOWN
-#undef EHOSTUNREACH
-#define EHOSTUNREACH WSAEHOSTUNREACH
-#undef ENOTEMPTY
-#define ENOTEMPTY WSAENOTEMPTY
-#undef EPROCLIM
-#define EPROCLIM WSAEPROCLIM
-#undef EUSERS
-#define EUSERS WSAEUSERS
-#undef EDQUOT
-#define EDQUOT WSAEDQUOT
-#undef ESTALE
-#define ESTALE WSAESTALE
-#undef EREMOTE
-#define EREMOTE WSAEREMOTE
-#undef EACCES
-#define SOCKET_EACCES WSAEACCES
-#endif // WIN32
-
-#ifdef POSIX
-#define INVALID_SOCKET (-1)
-#define SOCKET_ERROR (-1)
-#define closesocket(s) close(s)
-#endif // POSIX
-
-namespace talk_base {
-
-inline bool IsBlockingError(int e) {
- return (e == EWOULDBLOCK) || (e == EAGAIN) || (e == EINPROGRESS);
-}
-
-// General interface for the socket implementations of various networks. The
-// methods match those of normal UNIX sockets very closely.
-class Socket {
- public:
- virtual ~Socket() {}
-
- // Returns the address to which the socket is bound. If the socket is not
- // bound, then the any-address is returned.
- virtual SocketAddress GetLocalAddress() const = 0;
-
- // Returns the address to which the socket is connected. If the socket is
- // not connected, then the any-address is returned.
- virtual SocketAddress GetRemoteAddress() const = 0;
-
- virtual int Bind(const SocketAddress& addr) = 0;
- virtual int Connect(const SocketAddress& addr) = 0;
- virtual int Send(const void *pv, size_t cb) = 0;
- virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr) = 0;
- virtual int Recv(void *pv, size_t cb) = 0;
- virtual int RecvFrom(void *pv, size_t cb, SocketAddress *paddr) = 0;
- virtual int Listen(int backlog) = 0;
- virtual Socket *Accept(SocketAddress *paddr) = 0;
- virtual int Close() = 0;
- virtual int GetError() const = 0;
- virtual void SetError(int error) = 0;
- inline bool IsBlocking() const { return IsBlockingError(GetError()); }
-
- enum ConnState {
- CS_CLOSED,
- CS_CONNECTING,
- CS_CONNECTED
- };
- virtual ConnState GetState() const = 0;
-
- // Fills in the given uint16 with the current estimate of the MTU along the
- // path to the address to which this socket is connected. NOTE: This method
- // can block for up to 10 seconds on Windows.
- virtual int EstimateMTU(uint16* mtu) = 0;
-
- enum Option {
- OPT_DONTFRAGMENT,
- OPT_RCVBUF, // receive buffer size
- OPT_SNDBUF, // send buffer size
- OPT_NODELAY, // whether Nagle algorithm is enabled
- OPT_IPV6_V6ONLY, // Whether the socket is IPv6 only.
- OPT_DSCP, // DSCP code
- OPT_RTP_SENDTIME_EXTN_ID, // This is a non-traditional socket option param.
- // This is specific to libjingle and will be used
- // if SendTime option is needed at socket level.
- };
- virtual int GetOption(Option opt, int* value) = 0;
- virtual int SetOption(Option opt, int value) = 0;
-
- protected:
- Socket() {}
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(Socket);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKET_H__
diff --git a/base/socket_unittest.cc b/base/socket_unittest.cc
deleted file mode 100644
index e76d113..0000000
--- a/base/socket_unittest.cc
+++ /dev/null
@@ -1,1029 +0,0 @@
-/*
- * libjingle
- * Copyright 2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/socket_unittest.h"
-
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/gunit.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/socketserver.h"
-#include "talk/base/testclient.h"
-#include "talk/base/testutils.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-#define MAYBE_SKIP_IPV6 \
- if (!HasIPv6Enabled()) { \
- LOG(LS_INFO) << "No IPv6... skipping"; \
- return; \
- }
-
-
-void SocketTest::TestConnectIPv4() {
- ConnectInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestConnectIPv6() {
- MAYBE_SKIP_IPV6;
- ConnectInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestConnectWithDnsLookupIPv4() {
- ConnectWithDnsLookupInternal(kIPv4Loopback, "localhost");
-}
-
-void SocketTest::TestConnectWithDnsLookupIPv6() {
- // TODO: Enable this when DNS resolution supports IPv6.
- LOG(LS_INFO) << "Skipping IPv6 DNS test";
- // ConnectWithDnsLookupInternal(kIPv6Loopback, "localhost6");
-}
-
-void SocketTest::TestConnectFailIPv4() {
- ConnectFailInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestConnectFailIPv6() {
- MAYBE_SKIP_IPV6;
- ConnectFailInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestConnectWithDnsLookupFailIPv4() {
- ConnectWithDnsLookupFailInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestConnectWithDnsLookupFailIPv6() {
- MAYBE_SKIP_IPV6;
- ConnectWithDnsLookupFailInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestConnectWithClosedSocketIPv4() {
- ConnectWithClosedSocketInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestConnectWithClosedSocketIPv6() {
- MAYBE_SKIP_IPV6;
- ConnectWithClosedSocketInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestConnectWhileNotClosedIPv4() {
- ConnectWhileNotClosedInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestConnectWhileNotClosedIPv6() {
- MAYBE_SKIP_IPV6;
- ConnectWhileNotClosedInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestServerCloseDuringConnectIPv4() {
- ServerCloseDuringConnectInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestServerCloseDuringConnectIPv6() {
- MAYBE_SKIP_IPV6;
- ServerCloseDuringConnectInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestClientCloseDuringConnectIPv4() {
- ClientCloseDuringConnectInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestClientCloseDuringConnectIPv6() {
- MAYBE_SKIP_IPV6;
- ClientCloseDuringConnectInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestServerCloseIPv4() {
- ServerCloseInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestServerCloseIPv6() {
- MAYBE_SKIP_IPV6;
- ServerCloseInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestCloseInClosedCallbackIPv4() {
- CloseInClosedCallbackInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestCloseInClosedCallbackIPv6() {
- MAYBE_SKIP_IPV6;
- CloseInClosedCallbackInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestSocketServerWaitIPv4() {
- SocketServerWaitInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestSocketServerWaitIPv6() {
- MAYBE_SKIP_IPV6;
- SocketServerWaitInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestTcpIPv4() {
- TcpInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestTcpIPv6() {
- MAYBE_SKIP_IPV6;
- TcpInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestSingleFlowControlCallbackIPv4() {
- SingleFlowControlCallbackInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestSingleFlowControlCallbackIPv6() {
- MAYBE_SKIP_IPV6;
- SingleFlowControlCallbackInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestUdpIPv4() {
- UdpInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestUdpIPv6() {
- MAYBE_SKIP_IPV6;
- UdpInternal(kIPv6Loopback);
-}
-
-void SocketTest::TestUdpReadyToSendIPv4() {
-#if !defined(OSX) && !defined(IOS)
- // TODO(ronghuawu): Enable this test on mac/ios.
- UdpReadyToSend(kIPv4Loopback);
-#endif
-}
-
-void SocketTest::TestUdpReadyToSendIPv6() {
-#if defined(WIN32)
- // TODO(ronghuawu): Enable this test (currently flakey) on mac and linux.
- MAYBE_SKIP_IPV6;
- UdpReadyToSend(kIPv6Loopback);
-#endif
-}
-
-void SocketTest::TestGetSetOptionsIPv4() {
- GetSetOptionsInternal(kIPv4Loopback);
-}
-
-void SocketTest::TestGetSetOptionsIPv6() {
- MAYBE_SKIP_IPV6;
- GetSetOptionsInternal(kIPv6Loopback);
-}
-
-// For unbound sockets, GetLocalAddress / GetRemoteAddress return AF_UNSPEC
-// values on Windows, but an empty address of the same family on Linux/MacOS X.
-bool IsUnspecOrEmptyIP(const IPAddress& address) {
-#ifndef WIN32
- return IPIsAny(address);
-#else
- return address.family() == AF_UNSPEC;
-#endif
-}
-
-void SocketTest::ConnectInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(ss_->CreateAsyncSocket(loopback.family(),
- SOCK_STREAM));
- sink.Monitor(client.get());
- EXPECT_EQ(AsyncSocket::CS_CLOSED, client->GetState());
- EXPECT_PRED1(IsUnspecOrEmptyIP, client->GetLocalAddress().ipaddr());
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
- EXPECT_EQ(AsyncSocket::CS_CONNECTING, server->GetState());
-
- // Ensure no pending server connections, since we haven't done anything yet.
- EXPECT_FALSE(sink.Check(server.get(), testing::SSE_READ));
- EXPECT_TRUE(NULL == server->Accept(&accept_addr));
- EXPECT_TRUE(accept_addr.IsNil());
-
- // Attempt connect to listening socket.
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
- EXPECT_FALSE(client->GetLocalAddress().IsNil());
- EXPECT_NE(server->GetLocalAddress(), client->GetLocalAddress());
-
- // Client is connecting, outcome not yet determined.
- EXPECT_EQ(AsyncSocket::CS_CONNECTING, client->GetState());
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
-
- // Server has pending connection, accept it.
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- EXPECT_FALSE(accept_addr.IsNil());
- EXPECT_EQ(accepted->GetRemoteAddress(), accept_addr);
-
- // Connected from server perspective, check the addresses are correct.
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, accepted->GetState());
- EXPECT_EQ(server->GetLocalAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(client->GetLocalAddress(), accepted->GetRemoteAddress());
-
- // Connected from client perspective, check the addresses are correct.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
-}
-
-void SocketTest::ConnectWithDnsLookupInternal(const IPAddress& loopback,
- const std::string& host) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Attempt connect to listening socket.
- SocketAddress dns_addr(server->GetLocalAddress());
- dns_addr.SetIP(host);
- EXPECT_EQ(0, client->Connect(dns_addr));
- // TODO: Bind when doing DNS lookup.
- //EXPECT_NE(kEmptyAddr, client->GetLocalAddress()); // Implicit Bind
-
- // Client is connecting, outcome not yet determined.
- EXPECT_EQ(AsyncSocket::CS_CONNECTING, client->GetState());
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
-
- // Server has pending connection, accept it.
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- EXPECT_FALSE(accept_addr.IsNil());
- EXPECT_EQ(accepted->GetRemoteAddress(), accept_addr);
-
- // Connected from server perspective, check the addresses are correct.
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, accepted->GetState());
- EXPECT_EQ(server->GetLocalAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(client->GetLocalAddress(), accepted->GetRemoteAddress());
-
- // Connected from client perspective, check the addresses are correct.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
-}
-
-void SocketTest::ConnectFailInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server, but don't listen yet.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
-
- // Attempt connect to a non-existent socket.
- // We don't connect to the server socket created above, since on
- // MacOS it takes about 75 seconds to get back an error!
- SocketAddress bogus_addr(loopback, 65535);
- EXPECT_EQ(0, client->Connect(bogus_addr));
-
- // Wait for connection to fail (ECONNREFUSED).
- EXPECT_EQ_WAIT(AsyncSocket::CS_CLOSED, client->GetState(), kTimeout);
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_ERROR));
- EXPECT_TRUE(client->GetRemoteAddress().IsNil());
-
- // Should be no pending server connections.
- EXPECT_FALSE(sink.Check(server.get(), testing::SSE_READ));
- EXPECT_TRUE(NULL == server->Accept(&accept_addr));
- EXPECT_EQ(IPAddress(), accept_addr.ipaddr());
-}
-
-void SocketTest::ConnectWithDnsLookupFailInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server, but don't listen yet.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
-
- // Attempt connect to a non-existent host.
- // We don't connect to the server socket created above, since on
- // MacOS it takes about 75 seconds to get back an error!
- SocketAddress bogus_dns_addr("not-a-real-hostname", 65535);
- EXPECT_EQ(0, client->Connect(bogus_dns_addr));
-
- // Wait for connection to fail (EHOSTNOTFOUND).
- bool dns_lookup_finished = false;
- WAIT_(client->GetState() == AsyncSocket::CS_CLOSED, kTimeout,
- dns_lookup_finished);
- if (!dns_lookup_finished) {
- LOG(LS_WARNING) << "Skipping test; DNS resolution took longer than 5 "
- << "seconds.";
- return;
- }
-
- EXPECT_EQ_WAIT(AsyncSocket::CS_CLOSED, client->GetState(), kTimeout);
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_ERROR));
- EXPECT_TRUE(client->GetRemoteAddress().IsNil());
- // Should be no pending server connections.
- EXPECT_FALSE(sink.Check(server.get(), testing::SSE_READ));
- EXPECT_TRUE(NULL == server->Accept(&accept_addr));
- EXPECT_TRUE(accept_addr.IsNil());
-}
-
-void SocketTest::ConnectWithClosedSocketInternal(const IPAddress& loopback) {
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Create a client and put in to CS_CLOSED state.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- EXPECT_EQ(0, client->Close());
- EXPECT_EQ(AsyncSocket::CS_CLOSED, client->GetState());
-
- // Connect() should reinitialize the socket, and put it in to CS_CONNECTING.
- EXPECT_EQ(0, client->Connect(SocketAddress(server->GetLocalAddress())));
- EXPECT_EQ(AsyncSocket::CS_CONNECTING, client->GetState());
-}
-
-void SocketTest::ConnectWhileNotClosedInternal(const IPAddress& loopback) {
- // Create server and listen.
- testing::StreamSink sink;
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
- // Create client, connect.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- EXPECT_EQ(0, client->Connect(SocketAddress(server->GetLocalAddress())));
- EXPECT_EQ(AsyncSocket::CS_CONNECTING, client->GetState());
- // Try to connect again. Should fail, but not interfere with original attempt.
- EXPECT_EQ(SOCKET_ERROR,
- client->Connect(SocketAddress(server->GetLocalAddress())));
-
- // Accept the original connection.
- SocketAddress accept_addr;
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- EXPECT_FALSE(accept_addr.IsNil());
-
- // Check the states and addresses.
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, accepted->GetState());
- EXPECT_EQ(server->GetLocalAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(client->GetLocalAddress(), accepted->GetRemoteAddress());
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
-
- // Try to connect again, to an unresolved hostname.
- // Shouldn't break anything.
- EXPECT_EQ(SOCKET_ERROR,
- client->Connect(SocketAddress("localhost",
- server->GetLocalAddress().port())));
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, accepted->GetState());
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, client->GetState());
- EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
-}
-
-void SocketTest::ServerCloseDuringConnectInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Attempt connect to listening socket.
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- // Close down the server while the socket is in the accept queue.
- EXPECT_TRUE_WAIT(sink.Check(server.get(), testing::SSE_READ), kTimeout);
- server->Close();
-
- // This should fail the connection for the client. Clean up.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CLOSED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_ERROR));
- client->Close();
-}
-
-void SocketTest::ClientCloseDuringConnectInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Attempt connect to listening socket.
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- // Close down the client while the socket is in the accept queue.
- EXPECT_TRUE_WAIT(sink.Check(server.get(), testing::SSE_READ), kTimeout);
- client->Close();
-
- // The connection should still be able to be accepted.
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- sink.Monitor(accepted.get());
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, accepted->GetState());
-
- // The accepted socket should then close (possibly with err, timing-related)
- EXPECT_EQ_WAIT(AsyncSocket::CS_CLOSED, accepted->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(accepted.get(), testing::SSE_CLOSE) ||
- sink.Check(accepted.get(), testing::SSE_ERROR));
-
- // The client should not get a close event.
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
-}
-
-void SocketTest::ServerCloseInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Attempt connection.
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- // Accept connection.
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- sink.Monitor(accepted.get());
-
- // Both sides are now connected.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(accepted->GetRemoteAddress(), client->GetLocalAddress());
-
- // Send data to the client, and then close the connection.
- EXPECT_EQ(1, accepted->Send("a", 1));
- accepted->Close();
- EXPECT_EQ(AsyncSocket::CS_CLOSED, accepted->GetState());
-
- // Expect that the client is notified, and has not yet closed.
- EXPECT_TRUE_WAIT(sink.Check(client.get(), testing::SSE_READ), kTimeout);
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, client->GetState());
-
- // Ensure the data can be read.
- char buffer[10];
- EXPECT_EQ(1, client->Recv(buffer, sizeof(buffer)));
- EXPECT_EQ('a', buffer[0]);
-
- // Now we should close, but the remote address will remain.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CLOSED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_FALSE(client->GetRemoteAddress().IsAnyIP());
-
- // The closer should not get a close signal.
- EXPECT_FALSE(sink.Check(accepted.get(), testing::SSE_CLOSE));
- EXPECT_TRUE(accepted->GetRemoteAddress().IsNil());
-
- // And the closee should only get a single signal.
- Thread::Current()->ProcessMessages(0);
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
-
- // Close down the client and ensure all is good.
- client->Close();
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_TRUE(client->GetRemoteAddress().IsNil());
-}
-
-class SocketCloser : public sigslot::has_slots<> {
- public:
- void OnClose(AsyncSocket* socket, int error) {
- socket->Close(); // Deleting here would blow up the vector of handlers
- // for the socket's signal.
- }
-};
-
-void SocketTest::CloseInClosedCallbackInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketCloser closer;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
- client->SignalCloseEvent.connect(&closer, &SocketCloser::OnClose);
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Attempt connection.
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- // Accept connection.
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- sink.Monitor(accepted.get());
-
- // Both sides are now connected.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(accepted->GetRemoteAddress(), client->GetLocalAddress());
-
- // Send data to the client, and then close the connection.
- accepted->Close();
- EXPECT_EQ(AsyncSocket::CS_CLOSED, accepted->GetState());
-
- // Expect that the client is notified, and has not yet closed.
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, client->GetState());
-
- // Now we should be closed and invalidated
- EXPECT_EQ_WAIT(AsyncSocket::CS_CLOSED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_TRUE(Socket::CS_CLOSED == client->GetState());
-}
-
-class Sleeper : public MessageHandler {
- public:
- Sleeper() {}
- void OnMessage(Message* msg) {
- Thread::Current()->SleepMs(500);
- }
-};
-
-void SocketTest::SocketServerWaitInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create & connect server and client sockets.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
-
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- sink.Monitor(accepted.get());
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, accepted->GetState());
- EXPECT_EQ(server->GetLocalAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(client->GetLocalAddress(), accepted->GetRemoteAddress());
-
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
- EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
-
- // Do an i/o operation, triggering an eventual callback.
- EXPECT_FALSE(sink.Check(accepted.get(), testing::SSE_READ));
- char buf[1024] = {0};
-
- EXPECT_EQ(1024, client->Send(buf, 1024));
- EXPECT_FALSE(sink.Check(accepted.get(), testing::SSE_READ));
-
- // Shouldn't signal when blocked in a thread Send, where process_io is false.
- scoped_ptr<Thread> thread(new Thread());
- thread->Start();
- Sleeper sleeper;
- TypedMessageData<AsyncSocket*> data(client.get());
- thread->Send(&sleeper, 0, &data);
- EXPECT_FALSE(sink.Check(accepted.get(), testing::SSE_READ));
-
- // But should signal when process_io is true.
- EXPECT_TRUE_WAIT((sink.Check(accepted.get(), testing::SSE_READ)), kTimeout);
- EXPECT_LT(0, accepted->Recv(buf, 1024));
-}
-
-void SocketTest::TcpInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create test data.
- const size_t kDataSize = 1024 * 1024;
- scoped_ptr<char[]> send_buffer(new char[kDataSize]);
- scoped_ptr<char[]> recv_buffer(new char[kDataSize]);
- size_t send_pos = 0, recv_pos = 0;
- for (size_t i = 0; i < kDataSize; ++i) {
- send_buffer[i] = static_cast<char>(i % 256);
- recv_buffer[i] = 0;
- }
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Attempt connection.
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- // Accept connection.
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- sink.Monitor(accepted.get());
-
- // Both sides are now connected.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(accepted->GetRemoteAddress(), client->GetLocalAddress());
-
- // Send and receive a bunch of data.
- bool send_waiting_for_writability = false;
- bool send_expect_success = true;
- bool recv_waiting_for_readability = true;
- bool recv_expect_success = false;
- int data_in_flight = 0;
- while (recv_pos < kDataSize) {
- // Send as much as we can if we've been cleared to send.
- while (!send_waiting_for_writability && send_pos < kDataSize) {
- int tosend = static_cast<int>(kDataSize - send_pos);
- int sent = accepted->Send(send_buffer.get() + send_pos, tosend);
- if (send_expect_success) {
- // The first Send() after connecting or getting writability should
- // succeed and send some data.
- EXPECT_GT(sent, 0);
- send_expect_success = false;
- }
- if (sent >= 0) {
- EXPECT_LE(sent, tosend);
- send_pos += sent;
- data_in_flight += sent;
- } else {
- ASSERT_TRUE(accepted->IsBlocking());
- send_waiting_for_writability = true;
- }
- }
-
- // Read all the sent data.
- while (data_in_flight > 0) {
- if (recv_waiting_for_readability) {
- // Wait until data is available.
- EXPECT_TRUE_WAIT(sink.Check(client.get(), testing::SSE_READ), kTimeout);
- recv_waiting_for_readability = false;
- recv_expect_success = true;
- }
-
- // Receive as much as we can get in a single recv call.
- int rcvd = client->Recv(recv_buffer.get() + recv_pos,
- kDataSize - recv_pos);
-
- if (recv_expect_success) {
- // The first Recv() after getting readability should succeed and receive
- // some data.
- // TODO: The following line is disabled due to flakey pulse
- // builds. Re-enable if/when possible.
- // EXPECT_GT(rcvd, 0);
- recv_expect_success = false;
- }
- if (rcvd >= 0) {
- EXPECT_LE(rcvd, data_in_flight);
- recv_pos += rcvd;
- data_in_flight -= rcvd;
- } else {
- ASSERT_TRUE(client->IsBlocking());
- recv_waiting_for_readability = true;
- }
- }
-
- // Once all that we've sent has been rcvd, expect to be able to send again.
- if (send_waiting_for_writability) {
- EXPECT_TRUE_WAIT(sink.Check(accepted.get(), testing::SSE_WRITE),
- kTimeout);
- send_waiting_for_writability = false;
- send_expect_success = true;
- }
- }
-
- // The received data matches the sent data.
- EXPECT_EQ(kDataSize, send_pos);
- EXPECT_EQ(kDataSize, recv_pos);
- EXPECT_EQ(0, memcmp(recv_buffer.get(), send_buffer.get(), kDataSize));
-
- // Close down.
- accepted->Close();
- EXPECT_EQ_WAIT(AsyncSocket::CS_CLOSED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_CLOSE));
- client->Close();
-}
-
-void SocketTest::SingleFlowControlCallbackInternal(const IPAddress& loopback) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
-
- // Create client.
- scoped_ptr<AsyncSocket> client(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(client.get());
-
- // Create server and listen.
- scoped_ptr<AsyncSocket> server(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_STREAM));
- sink.Monitor(server.get());
- EXPECT_EQ(0, server->Bind(SocketAddress(loopback, 0)));
- EXPECT_EQ(0, server->Listen(5));
-
- // Attempt connection.
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- // Accept connection.
- EXPECT_TRUE_WAIT((sink.Check(server.get(), testing::SSE_READ)), kTimeout);
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(accepted);
- sink.Monitor(accepted.get());
-
- // Both sides are now connected.
- EXPECT_EQ_WAIT(AsyncSocket::CS_CONNECTED, client->GetState(), kTimeout);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_OPEN));
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
- EXPECT_EQ(accepted->GetRemoteAddress(), client->GetLocalAddress());
-
- // Expect a writable callback from the connect.
- EXPECT_TRUE_WAIT(sink.Check(accepted.get(), testing::SSE_WRITE), kTimeout);
-
- // Fill the socket buffer.
- char buf[1024 * 16] = {0};
- int sends = 0;
- while (++sends && accepted->Send(&buf, ARRAY_SIZE(buf)) != -1) {}
- EXPECT_TRUE(accepted->IsBlocking());
-
- // Wait until data is available.
- EXPECT_TRUE_WAIT(sink.Check(client.get(), testing::SSE_READ), kTimeout);
-
- // Pull data.
- for (int i = 0; i < sends; ++i) {
- client->Recv(buf, ARRAY_SIZE(buf));
- }
-
- // Expect at least one additional writable callback.
- EXPECT_TRUE_WAIT(sink.Check(accepted.get(), testing::SSE_WRITE), kTimeout);
-
- // Adding data in response to the writeable callback shouldn't cause infinite
- // callbacks.
- int extras = 0;
- for (int i = 0; i < 100; ++i) {
- accepted->Send(&buf, ARRAY_SIZE(buf));
- talk_base::Thread::Current()->ProcessMessages(1);
- if (sink.Check(accepted.get(), testing::SSE_WRITE)) {
- extras++;
- }
- }
- EXPECT_LT(extras, 2);
-
- // Close down.
- accepted->Close();
- client->Close();
-}
-
-void SocketTest::UdpInternal(const IPAddress& loopback) {
- SocketAddress empty = EmptySocketAddressWithFamily(loopback.family());
- // Test basic bind and connect behavior.
- AsyncSocket* socket =
- ss_->CreateAsyncSocket(loopback.family(), SOCK_DGRAM);
- EXPECT_EQ(AsyncSocket::CS_CLOSED, socket->GetState());
- EXPECT_EQ(0, socket->Bind(SocketAddress(loopback, 0)));
- SocketAddress addr1 = socket->GetLocalAddress();
- EXPECT_EQ(0, socket->Connect(addr1));
- EXPECT_EQ(AsyncSocket::CS_CONNECTED, socket->GetState());
- socket->Close();
- EXPECT_EQ(AsyncSocket::CS_CLOSED, socket->GetState());
- delete socket;
-
- // Test send/receive behavior.
- scoped_ptr<TestClient> client1(
- new TestClient(AsyncUDPSocket::Create(ss_, addr1)));
- scoped_ptr<TestClient> client2(
- new TestClient(AsyncUDPSocket::Create(ss_, empty)));
-
- SocketAddress addr2;
- EXPECT_EQ(3, client2->SendTo("foo", 3, addr1));
- EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &addr2));
-
- SocketAddress addr3;
- EXPECT_EQ(6, client1->SendTo("bizbaz", 6, addr2));
- EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &addr3));
- EXPECT_EQ(addr3, addr1);
- // TODO: figure out what the intent is here
- for (int i = 0; i < 10; ++i) {
- client2.reset(new TestClient(AsyncUDPSocket::Create(ss_, empty)));
-
- SocketAddress addr4;
- EXPECT_EQ(3, client2->SendTo("foo", 3, addr1));
- EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &addr4));
- EXPECT_EQ(addr4.ipaddr(), addr2.ipaddr());
-
- SocketAddress addr5;
- EXPECT_EQ(6, client1->SendTo("bizbaz", 6, addr4));
- EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &addr5));
- EXPECT_EQ(addr5, addr1);
-
- addr2 = addr4;
- }
-}
-
-void SocketTest::UdpReadyToSend(const IPAddress& loopback) {
- SocketAddress empty = EmptySocketAddressWithFamily(loopback.family());
- // RFC 5737 - The blocks 192.0.2.0/24 (TEST-NET-1) ... are provided for use in
- // documentation.
- // RFC 3849 - 2001:DB8::/32 as a documentation-only prefix.
- std::string dest = (loopback.family() == AF_INET6) ?
- "2001:db8::1" : "192.0.2.0";
- SocketAddress test_addr(dest, 2345);
-
- // Test send
- scoped_ptr<TestClient> client(
- new TestClient(AsyncUDPSocket::Create(ss_, empty)));
- int test_packet_size = 1200;
- talk_base::scoped_ptr<char[]> test_packet(new char[test_packet_size]);
- // Init the test packet just to avoid memcheck warning.
- memset(test_packet.get(), 0, test_packet_size);
- // Set the send buffer size to the same size as the test packet to have a
- // better chance to get EWOULDBLOCK.
- int send_buffer_size = test_packet_size;
-#if defined(LINUX)
- send_buffer_size /= 2;
-#endif
- client->SetOption(talk_base::Socket::OPT_SNDBUF, send_buffer_size);
-
- int error = 0;
- uint32 start_ms = Time();
- int sent_packet_num = 0;
- int expected_error = EWOULDBLOCK;
- while (start_ms + kTimeout > Time()) {
- int ret = client->SendTo(test_packet.get(), test_packet_size, test_addr);
- ++sent_packet_num;
- if (ret != test_packet_size) {
- error = client->GetError();
- if (error == expected_error) {
- LOG(LS_INFO) << "Got expected error code after sending "
- << sent_packet_num << " packets.";
- break;
- }
- }
- }
- EXPECT_EQ(expected_error, error);
- EXPECT_FALSE(client->ready_to_send());
- EXPECT_TRUE_WAIT(client->ready_to_send(), kTimeout);
- LOG(LS_INFO) << "Got SignalReadyToSend";
-}
-
-void SocketTest::GetSetOptionsInternal(const IPAddress& loopback) {
- talk_base::scoped_ptr<AsyncSocket> socket(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_DGRAM));
- socket->Bind(SocketAddress(loopback, 0));
-
- // Check SNDBUF/RCVBUF.
- const int desired_size = 12345;
-#if defined(LINUX) || defined(ANDROID)
- // Yes, really. It's in the kernel source.
- const int expected_size = desired_size * 2;
-#else // !LINUX && !ANDROID
- const int expected_size = desired_size;
-#endif // !LINUX && !ANDROID
- int recv_size = 0;
- int send_size = 0;
- // get the initial sizes
- ASSERT_NE(-1, socket->GetOption(Socket::OPT_RCVBUF, &recv_size));
- ASSERT_NE(-1, socket->GetOption(Socket::OPT_SNDBUF, &send_size));
- // set our desired sizes
- ASSERT_NE(-1, socket->SetOption(Socket::OPT_RCVBUF, desired_size));
- ASSERT_NE(-1, socket->SetOption(Socket::OPT_SNDBUF, desired_size));
- // get the sizes again
- ASSERT_NE(-1, socket->GetOption(Socket::OPT_RCVBUF, &recv_size));
- ASSERT_NE(-1, socket->GetOption(Socket::OPT_SNDBUF, &send_size));
- // make sure they are right
- ASSERT_EQ(expected_size, recv_size);
- ASSERT_EQ(expected_size, send_size);
-
- // Check that we can't set NODELAY on a UDP socket.
- int current_nd, desired_nd = 1;
- ASSERT_EQ(-1, socket->GetOption(Socket::OPT_NODELAY, ¤t_nd));
- ASSERT_EQ(-1, socket->SetOption(Socket::OPT_NODELAY, desired_nd));
-
- // Skip the esimate MTU test for IPv6 for now.
- if (loopback.family() != AF_INET6) {
- // Try estimating MTU.
- talk_base::scoped_ptr<AsyncSocket>
- mtu_socket(
- ss_->CreateAsyncSocket(loopback.family(), SOCK_DGRAM));
- mtu_socket->Bind(SocketAddress(loopback, 0));
- uint16 mtu;
- // should fail until we connect
- ASSERT_EQ(-1, mtu_socket->EstimateMTU(&mtu));
- mtu_socket->Connect(SocketAddress(loopback, 0));
-#if defined(WIN32)
- // now it should succeed
- ASSERT_NE(-1, mtu_socket->EstimateMTU(&mtu));
- ASSERT_GE(mtu, 1492); // should be at least the 1492 "plateau" on localhost
-#elif defined(OSX)
- // except on OSX, where it's not yet implemented
- ASSERT_EQ(-1, mtu_socket->EstimateMTU(&mtu));
-#else
- // and the behavior seems unpredictable on Linux,
- // failing on the build machine
- // but succeeding on my Ubiquity instance.
-#endif
- }
-}
-
-} // namespace talk_base
diff --git a/base/socket_unittest.h b/base/socket_unittest.h
deleted file mode 100644
index 86c4c93..0000000
--- a/base/socket_unittest.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKET_UNITTEST_H_
-#define TALK_BASE_SOCKET_UNITTEST_H_
-
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-// Generic socket tests, to be used when testing individual socketservers.
-// Derive your specific test class from SocketTest, install your
-// socketserver, and call the SocketTest test methods.
-class SocketTest : public testing::Test {
- protected:
- SocketTest() : ss_(NULL), kIPv4Loopback(INADDR_LOOPBACK),
- kIPv6Loopback(in6addr_loopback) {}
- virtual void SetUp() { ss_ = Thread::Current()->socketserver(); }
- void TestConnectIPv4();
- void TestConnectIPv6();
- void TestConnectWithDnsLookupIPv4();
- void TestConnectWithDnsLookupIPv6();
- void TestConnectFailIPv4();
- void TestConnectFailIPv6();
- void TestConnectWithDnsLookupFailIPv4();
- void TestConnectWithDnsLookupFailIPv6();
- void TestConnectWithClosedSocketIPv4();
- void TestConnectWithClosedSocketIPv6();
- void TestConnectWhileNotClosedIPv4();
- void TestConnectWhileNotClosedIPv6();
- void TestServerCloseDuringConnectIPv4();
- void TestServerCloseDuringConnectIPv6();
- void TestClientCloseDuringConnectIPv4();
- void TestClientCloseDuringConnectIPv6();
- void TestServerCloseIPv4();
- void TestServerCloseIPv6();
- void TestCloseInClosedCallbackIPv4();
- void TestCloseInClosedCallbackIPv6();
- void TestSocketServerWaitIPv4();
- void TestSocketServerWaitIPv6();
- void TestTcpIPv4();
- void TestTcpIPv6();
- void TestSingleFlowControlCallbackIPv4();
- void TestSingleFlowControlCallbackIPv6();
- void TestUdpIPv4();
- void TestUdpIPv6();
- void TestUdpReadyToSendIPv4();
- void TestUdpReadyToSendIPv6();
- void TestGetSetOptionsIPv4();
- void TestGetSetOptionsIPv6();
-
- private:
- void ConnectInternal(const IPAddress& loopback);
- void ConnectWithDnsLookupInternal(const IPAddress& loopback,
- const std::string& host);
- void ConnectFailInternal(const IPAddress& loopback);
-
- void ConnectWithDnsLookupFailInternal(const IPAddress& loopback);
- void ConnectWithClosedSocketInternal(const IPAddress& loopback);
- void ConnectWhileNotClosedInternal(const IPAddress& loopback);
- void ServerCloseDuringConnectInternal(const IPAddress& loopback);
- void ClientCloseDuringConnectInternal(const IPAddress& loopback);
- void ServerCloseInternal(const IPAddress& loopback);
- void CloseInClosedCallbackInternal(const IPAddress& loopback);
- void SocketServerWaitInternal(const IPAddress& loopback);
- void TcpInternal(const IPAddress& loopback);
- void SingleFlowControlCallbackInternal(const IPAddress& loopback);
- void UdpInternal(const IPAddress& loopback);
- void UdpReadyToSend(const IPAddress& loopback);
- void GetSetOptionsInternal(const IPAddress& loopback);
-
- static const int kTimeout = 5000; // ms
- SocketServer* ss_;
- const IPAddress kIPv4Loopback;
- const IPAddress kIPv6Loopback;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKET_UNITTEST_H_
diff --git a/base/socketadapters.cc b/base/socketadapters.cc
deleted file mode 100644
index 4361eec..0000000
--- a/base/socketadapters.cc
+++ /dev/null
@@ -1,910 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if defined(_MSC_VER) && _MSC_VER < 1300
-#pragma warning(disable:4786)
-#endif
-
-#include <time.h>
-#include <errno.h>
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#define SECURITY_WIN32
-#include <security.h>
-#endif
-
-#include "talk/base/bytebuffer.h"
-#include "talk/base/common.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/logging.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-
-#ifdef WIN32
-#include "talk/base/sec_buffer.h"
-#endif // WIN32
-
-namespace talk_base {
-
-BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
- : AsyncSocketAdapter(socket), buffer_size_(size),
- data_len_(0), buffering_(false) {
- buffer_ = new char[buffer_size_];
-}
-
-BufferedReadAdapter::~BufferedReadAdapter() {
- delete [] buffer_;
-}
-
-int BufferedReadAdapter::Send(const void *pv, size_t cb) {
- if (buffering_) {
- // TODO: Spoof error better; Signal Writeable
- socket_->SetError(EWOULDBLOCK);
- return -1;
- }
- return AsyncSocketAdapter::Send(pv, cb);
-}
-
-int BufferedReadAdapter::Recv(void *pv, size_t cb) {
- if (buffering_) {
- socket_->SetError(EWOULDBLOCK);
- return -1;
- }
-
- size_t read = 0;
-
- if (data_len_) {
- read = _min(cb, data_len_);
- memcpy(pv, buffer_, read);
- data_len_ -= read;
- if (data_len_ > 0) {
- memmove(buffer_, buffer_ + read, data_len_);
- }
- pv = static_cast<char *>(pv) + read;
- cb -= read;
- }
-
- // FIX: If cb == 0, we won't generate another read event
-
- int res = AsyncSocketAdapter::Recv(pv, cb);
- if (res < 0)
- return res;
-
- return res + static_cast<int>(read);
-}
-
-void BufferedReadAdapter::BufferInput(bool on) {
- buffering_ = on;
-}
-
-void BufferedReadAdapter::OnReadEvent(AsyncSocket * socket) {
- ASSERT(socket == socket_);
-
- if (!buffering_) {
- AsyncSocketAdapter::OnReadEvent(socket);
- return;
- }
-
- if (data_len_ >= buffer_size_) {
- LOG(INFO) << "Input buffer overflow";
- ASSERT(false);
- data_len_ = 0;
- }
-
- int len = socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_);
- if (len < 0) {
- // TODO: Do something better like forwarding the error to the user.
- LOG_ERR(INFO) << "Recv";
- return;
- }
-
- data_len_ += len;
-
- ProcessInput(buffer_, &data_len_);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// This is a SSL v2 CLIENT_HELLO message.
-// TODO: Should this have a session id? The response doesn't have a
-// certificate, so the hello should have a session id.
-static const uint8 kSslClientHello[] = {
- 0x80, 0x46, // msg len
- 0x01, // CLIENT_HELLO
- 0x03, 0x01, // SSL 3.1
- 0x00, 0x2d, // ciphersuite len
- 0x00, 0x00, // session id len
- 0x00, 0x10, // challenge len
- 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
- 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
- 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
- 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
- 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
- 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
- 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
-};
-
-// This is a TLSv1 SERVER_HELLO message.
-static const uint8 kSslServerHello[] = {
- 0x16, // handshake message
- 0x03, 0x01, // SSL 3.1
- 0x00, 0x4a, // message len
- 0x02, // SERVER_HELLO
- 0x00, 0x00, 0x46, // handshake len
- 0x03, 0x01, // SSL 3.1
- 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
- 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
- 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
- 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
- 0x20, // session id len
- 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
- 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
- 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
- 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
- 0x00, 0x04, // RSA/RC4-128/MD5
- 0x00 // null compression
-};
-
-AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
- : BufferedReadAdapter(socket, 1024) {
-}
-
-int AsyncSSLSocket::Connect(const SocketAddress& addr) {
- // Begin buffering before we connect, so that there isn't a race condition
- // between potential senders and receiving the OnConnectEvent signal
- BufferInput(true);
- return BufferedReadAdapter::Connect(addr);
-}
-
-void AsyncSSLSocket::OnConnectEvent(AsyncSocket * socket) {
- ASSERT(socket == socket_);
- // TODO: we could buffer output too...
- VERIFY(sizeof(kSslClientHello) ==
- DirectSend(kSslClientHello, sizeof(kSslClientHello)));
-}
-
-void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
- if (*len < sizeof(kSslServerHello))
- return;
-
- if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
- Close();
- SignalCloseEvent(this, 0); // TODO: error code?
- return;
- }
-
- *len -= sizeof(kSslServerHello);
- if (*len > 0) {
- memmove(data, data + sizeof(kSslServerHello), *len);
- }
-
- bool remainder = (*len > 0);
- BufferInput(false);
- SignalConnectEvent(this);
-
- // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
- if (remainder)
- SignalReadEvent(this);
-}
-
-AsyncSSLServerSocket::AsyncSSLServerSocket(AsyncSocket* socket)
- : BufferedReadAdapter(socket, 1024) {
- BufferInput(true);
-}
-
-void AsyncSSLServerSocket::ProcessInput(char* data, size_t* len) {
- // We only accept client hello messages.
- if (*len < sizeof(kSslClientHello)) {
- return;
- }
-
- if (memcmp(kSslClientHello, data, sizeof(kSslClientHello)) != 0) {
- Close();
- SignalCloseEvent(this, 0);
- return;
- }
-
- *len -= sizeof(kSslClientHello);
-
- // Clients should not send more data until the handshake is completed.
- ASSERT(*len == 0);
-
- // Send a server hello back to the client.
- DirectSend(kSslServerHello, sizeof(kSslServerHello));
-
- // Handshake completed for us, redirect input to our parent.
- BufferInput(false);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
- const std::string& user_agent,
- const SocketAddress& proxy,
- const std::string& username,
- const CryptString& password)
- : BufferedReadAdapter(socket, 1024), proxy_(proxy), agent_(user_agent),
- user_(username), pass_(password), force_connect_(false), state_(PS_ERROR),
- context_(0) {
-}
-
-AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
- delete context_;
-}
-
-int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
- int ret;
- LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
- << proxy_.ToSensitiveString() << ")";
- dest_ = addr;
- state_ = PS_INIT;
- if (ShouldIssueConnect()) {
- BufferInput(true);
- }
- ret = BufferedReadAdapter::Connect(proxy_);
- // TODO: Set state_ appropriately if Connect fails.
- return ret;
-}
-
-SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
- return dest_;
-}
-
-int AsyncHttpsProxySocket::Close() {
- headers_.clear();
- state_ = PS_ERROR;
- dest_.Clear();
- delete context_;
- context_ = NULL;
- return BufferedReadAdapter::Close();
-}
-
-Socket::ConnState AsyncHttpsProxySocket::GetState() const {
- if (state_ < PS_TUNNEL) {
- return CS_CONNECTING;
- } else if (state_ == PS_TUNNEL) {
- return CS_CONNECTED;
- } else {
- return CS_CLOSED;
- }
-}
-
-void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket * socket) {
- LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
- if (!ShouldIssueConnect()) {
- state_ = PS_TUNNEL;
- BufferedReadAdapter::OnConnectEvent(socket);
- return;
- }
- SendRequest();
-}
-
-void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket * socket, int err) {
- LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
- if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
- state_ = PS_ERROR;
- Connect(dest_);
- } else {
- BufferedReadAdapter::OnCloseEvent(socket, err);
- }
-}
-
-void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
- size_t start = 0;
- for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
- if (state_ == PS_SKIP_BODY) {
- size_t consume = _min(*len - pos, content_length_);
- pos += consume;
- start = pos;
- content_length_ -= consume;
- if (content_length_ == 0) {
- EndResponse();
- }
- continue;
- }
-
- if (data[pos++] != '\n')
- continue;
-
- size_t len = pos - start - 1;
- if ((len > 0) && (data[start + len - 1] == '\r'))
- --len;
-
- data[start + len] = 0;
- ProcessLine(data + start, len);
- start = pos;
- }
-
- *len -= start;
- if (*len > 0) {
- memmove(data, data + start, *len);
- }
-
- if (state_ != PS_TUNNEL)
- return;
-
- bool remainder = (*len > 0);
- BufferInput(false);
- SignalConnectEvent(this);
-
- // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
- if (remainder)
- SignalReadEvent(this); // TODO: signal this??
-}
-
-bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
- // TODO: Think about whether a more sophisticated test
- // than dest port == 80 is needed.
- return force_connect_ || (dest_.port() != 80);
-}
-
-void AsyncHttpsProxySocket::SendRequest() {
- std::stringstream ss;
- ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
- ss << "User-Agent: " << agent_ << "\r\n";
- ss << "Host: " << dest_.HostAsURIString() << "\r\n";
- ss << "Content-Length: 0\r\n";
- ss << "Proxy-Connection: Keep-Alive\r\n";
- ss << headers_;
- ss << "\r\n";
- std::string str = ss.str();
- DirectSend(str.c_str(), str.size());
- state_ = PS_LEADER;
- expect_close_ = true;
- content_length_ = 0;
- headers_.clear();
-
- LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
-}
-
-void AsyncHttpsProxySocket::ProcessLine(char * data, size_t len) {
- LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
-
- if (len == 0) {
- if (state_ == PS_TUNNEL_HEADERS) {
- state_ = PS_TUNNEL;
- } else if (state_ == PS_ERROR_HEADERS) {
- Error(defer_error_);
- return;
- } else if (state_ == PS_SKIP_HEADERS) {
- if (content_length_) {
- state_ = PS_SKIP_BODY;
- } else {
- EndResponse();
- return;
- }
- } else {
- static bool report = false;
- if (!unknown_mechanisms_.empty() && !report) {
- report = true;
- std::string msg(
- "Unable to connect to the Google Talk service due to an incompatibility "
- "with your proxy.\r\nPlease help us resolve this issue by submitting the "
- "following information to us using our technical issue submission form "
- "at:\r\n\r\n"
- "http://www.google.com/support/talk/bin/request.py\r\n\r\n"
- "We apologize for the inconvenience.\r\n\r\n"
- "Information to submit to Google: "
- );
- //std::string msg("Please report the following information to foo@bar.com:\r\nUnknown methods: ");
- msg.append(unknown_mechanisms_);
-#ifdef WIN32
- MessageBoxA(0, msg.c_str(), "Oops!", MB_OK);
-#endif
-#ifdef POSIX
- // TODO: Raise a signal so the UI can be separated.
- LOG(LS_ERROR) << "Oops!\n\n" << msg;
-#endif
- }
- // Unexpected end of headers
- Error(0);
- return;
- }
- } else if (state_ == PS_LEADER) {
- unsigned int code;
- if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
- Error(0);
- return;
- }
- switch (code) {
- case 200:
- // connection good!
- state_ = PS_TUNNEL_HEADERS;
- return;
-#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
-#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
-#endif
- case 407: // HTTP_STATUS_PROXY_AUTH_REQ
- state_ = PS_AUTHENTICATE;
- return;
- default:
- defer_error_ = 0;
- state_ = PS_ERROR_HEADERS;
- return;
- }
- } else if ((state_ == PS_AUTHENTICATE)
- && (_strnicmp(data, "Proxy-Authenticate:", 19) == 0)) {
- std::string response, auth_method;
- switch (HttpAuthenticate(data + 19, len - 19,
- proxy_, "CONNECT", "/",
- user_, pass_, context_, response, auth_method)) {
- case HAR_IGNORE:
- LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
- if (!unknown_mechanisms_.empty())
- unknown_mechanisms_.append(", ");
- unknown_mechanisms_.append(auth_method);
- break;
- case HAR_RESPONSE:
- headers_ = "Proxy-Authorization: ";
- headers_.append(response);
- headers_.append("\r\n");
- state_ = PS_SKIP_HEADERS;
- unknown_mechanisms_.clear();
- break;
- case HAR_CREDENTIALS:
- defer_error_ = SOCKET_EACCES;
- state_ = PS_ERROR_HEADERS;
- unknown_mechanisms_.clear();
- break;
- case HAR_ERROR:
- defer_error_ = 0;
- state_ = PS_ERROR_HEADERS;
- unknown_mechanisms_.clear();
- break;
- }
- } else if (_strnicmp(data, "Content-Length:", 15) == 0) {
- content_length_ = strtoul(data + 15, 0, 0);
- } else if (_strnicmp(data, "Proxy-Connection: Keep-Alive", 28) == 0) {
- expect_close_ = false;
- /*
- } else if (_strnicmp(data, "Connection: close", 17) == 0) {
- expect_close_ = true;
- */
- }
-}
-
-void AsyncHttpsProxySocket::EndResponse() {
- if (!expect_close_) {
- SendRequest();
- return;
- }
-
- // No point in waiting for the server to close... let's close now
- // TODO: Refactor out PS_WAIT_CLOSE
- state_ = PS_WAIT_CLOSE;
- BufferedReadAdapter::Close();
- OnCloseEvent(this, 0);
-}
-
-void AsyncHttpsProxySocket::Error(int error) {
- BufferInput(false);
- Close();
- SetError(error);
- SignalCloseEvent(this, error);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
- const SocketAddress& proxy,
- const std::string& username,
- const CryptString& password)
- : BufferedReadAdapter(socket, 1024), state_(SS_ERROR), proxy_(proxy),
- user_(username), pass_(password) {
-}
-
-int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
- int ret;
- dest_ = addr;
- state_ = SS_INIT;
- BufferInput(true);
- ret = BufferedReadAdapter::Connect(proxy_);
- // TODO: Set state_ appropriately if Connect fails.
- return ret;
-}
-
-SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
- return dest_;
-}
-
-int AsyncSocksProxySocket::Close() {
- state_ = SS_ERROR;
- dest_.Clear();
- return BufferedReadAdapter::Close();
-}
-
-Socket::ConnState AsyncSocksProxySocket::GetState() const {
- if (state_ < SS_TUNNEL) {
- return CS_CONNECTING;
- } else if (state_ == SS_TUNNEL) {
- return CS_CONNECTED;
- } else {
- return CS_CLOSED;
- }
-}
-
-void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
- SendHello();
-}
-
-void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
- ASSERT(state_ < SS_TUNNEL);
-
- ByteBuffer response(data, *len);
-
- if (state_ == SS_HELLO) {
- uint8 ver, method;
- if (!response.ReadUInt8(&ver) ||
- !response.ReadUInt8(&method))
- return;
-
- if (ver != 5) {
- Error(0);
- return;
- }
-
- if (method == 0) {
- SendConnect();
- } else if (method == 2) {
- SendAuth();
- } else {
- Error(0);
- return;
- }
- } else if (state_ == SS_AUTH) {
- uint8 ver, status;
- if (!response.ReadUInt8(&ver) ||
- !response.ReadUInt8(&status))
- return;
-
- if ((ver != 1) || (status != 0)) {
- Error(SOCKET_EACCES);
- return;
- }
-
- SendConnect();
- } else if (state_ == SS_CONNECT) {
- uint8 ver, rep, rsv, atyp;
- if (!response.ReadUInt8(&ver) ||
- !response.ReadUInt8(&rep) ||
- !response.ReadUInt8(&rsv) ||
- !response.ReadUInt8(&atyp))
- return;
-
- if ((ver != 5) || (rep != 0)) {
- Error(0);
- return;
- }
-
- uint16 port;
- if (atyp == 1) {
- uint32 addr;
- if (!response.ReadUInt32(&addr) ||
- !response.ReadUInt16(&port))
- return;
- LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
- } else if (atyp == 3) {
- uint8 len;
- std::string addr;
- if (!response.ReadUInt8(&len) ||
- !response.ReadString(&addr, len) ||
- !response.ReadUInt16(&port))
- return;
- LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
- } else if (atyp == 4) {
- std::string addr;
- if (!response.ReadString(&addr, 16) ||
- !response.ReadUInt16(&port))
- return;
- LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
- } else {
- Error(0);
- return;
- }
-
- state_ = SS_TUNNEL;
- }
-
- // Consume parsed data
- *len = response.Length();
- memcpy(data, response.Data(), *len);
-
- if (state_ != SS_TUNNEL)
- return;
-
- bool remainder = (*len > 0);
- BufferInput(false);
- SignalConnectEvent(this);
-
- // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
- if (remainder)
- SignalReadEvent(this); // TODO: signal this??
-}
-
-void AsyncSocksProxySocket::SendHello() {
- ByteBuffer request;
- request.WriteUInt8(5); // Socks Version
- if (user_.empty()) {
- request.WriteUInt8(1); // Authentication Mechanisms
- request.WriteUInt8(0); // No authentication
- } else {
- request.WriteUInt8(2); // Authentication Mechanisms
- request.WriteUInt8(0); // No authentication
- request.WriteUInt8(2); // Username/Password
- }
- DirectSend(request.Data(), request.Length());
- state_ = SS_HELLO;
-}
-
-void AsyncSocksProxySocket::SendAuth() {
- ByteBuffer request;
- request.WriteUInt8(1); // Negotiation Version
- request.WriteUInt8(static_cast<uint8>(user_.size()));
- request.WriteString(user_); // Username
- request.WriteUInt8(static_cast<uint8>(pass_.GetLength()));
- size_t len = pass_.GetLength() + 1;
- char * sensitive = new char[len];
- pass_.CopyTo(sensitive, true);
- request.WriteString(sensitive); // Password
- memset(sensitive, 0, len);
- delete [] sensitive;
- DirectSend(request.Data(), request.Length());
- state_ = SS_AUTH;
-}
-
-void AsyncSocksProxySocket::SendConnect() {
- ByteBuffer request;
- request.WriteUInt8(5); // Socks Version
- request.WriteUInt8(1); // CONNECT
- request.WriteUInt8(0); // Reserved
- if (dest_.IsUnresolved()) {
- std::string hostname = dest_.hostname();
- request.WriteUInt8(3); // DOMAINNAME
- request.WriteUInt8(static_cast<uint8>(hostname.size()));
- request.WriteString(hostname); // Destination Hostname
- } else {
- request.WriteUInt8(1); // IPV4
- request.WriteUInt32(dest_.ip()); // Destination IP
- }
- request.WriteUInt16(dest_.port()); // Destination Port
- DirectSend(request.Data(), request.Length());
- state_ = SS_CONNECT;
-}
-
-void AsyncSocksProxySocket::Error(int error) {
- state_ = SS_ERROR;
- BufferInput(false);
- Close();
- SetError(SOCKET_EACCES);
- SignalCloseEvent(this, error);
-}
-
-AsyncSocksProxyServerSocket::AsyncSocksProxyServerSocket(AsyncSocket* socket)
- : AsyncProxyServerSocket(socket, kBufferSize), state_(SS_HELLO) {
- BufferInput(true);
-}
-
-void AsyncSocksProxyServerSocket::ProcessInput(char* data, size_t* len) {
- // TODO: See if the whole message has arrived
- ASSERT(state_ < SS_CONNECT_PENDING);
-
- ByteBuffer response(data, *len);
- if (state_ == SS_HELLO) {
- HandleHello(&response);
- } else if (state_ == SS_AUTH) {
- HandleAuth(&response);
- } else if (state_ == SS_CONNECT) {
- HandleConnect(&response);
- }
-
- // Consume parsed data
- *len = response.Length();
- memcpy(data, response.Data(), *len);
-}
-
-void AsyncSocksProxyServerSocket::DirectSend(const ByteBuffer& buf) {
- BufferedReadAdapter::DirectSend(buf.Data(), buf.Length());
-}
-
-void AsyncSocksProxyServerSocket::HandleHello(ByteBuffer* request) {
- uint8 ver, num_methods;
- if (!request->ReadUInt8(&ver) ||
- !request->ReadUInt8(&num_methods)) {
- Error(0);
- return;
- }
-
- if (ver != 5) {
- Error(0);
- return;
- }
-
- // Handle either no-auth (0) or user/pass auth (2)
- uint8 method = 0xFF;
- if (num_methods > 0 && !request->ReadUInt8(&method)) {
- Error(0);
- return;
- }
-
- // TODO: Ask the server which method to use.
- SendHelloReply(method);
- if (method == 0) {
- state_ = SS_CONNECT;
- } else if (method == 2) {
- state_ = SS_AUTH;
- } else {
- state_ = SS_ERROR;
- }
-}
-
-void AsyncSocksProxyServerSocket::SendHelloReply(int method) {
- ByteBuffer response;
- response.WriteUInt8(5); // Socks Version
- response.WriteUInt8(method); // Auth method
- DirectSend(response);
-}
-
-void AsyncSocksProxyServerSocket::HandleAuth(ByteBuffer* request) {
- uint8 ver, user_len, pass_len;
- std::string user, pass;
- if (!request->ReadUInt8(&ver) ||
- !request->ReadUInt8(&user_len) ||
- !request->ReadString(&user, user_len) ||
- !request->ReadUInt8(&pass_len) ||
- !request->ReadString(&pass, pass_len)) {
- Error(0);
- return;
- }
-
- // TODO: Allow for checking of credentials.
- SendAuthReply(0);
- state_ = SS_CONNECT;
-}
-
-void AsyncSocksProxyServerSocket::SendAuthReply(int result) {
- ByteBuffer response;
- response.WriteUInt8(1); // Negotiation Version
- response.WriteUInt8(result);
- DirectSend(response);
-}
-
-void AsyncSocksProxyServerSocket::HandleConnect(ByteBuffer* request) {
- uint8 ver, command, reserved, addr_type;
- uint32 ip;
- uint16 port;
- if (!request->ReadUInt8(&ver) ||
- !request->ReadUInt8(&command) ||
- !request->ReadUInt8(&reserved) ||
- !request->ReadUInt8(&addr_type) ||
- !request->ReadUInt32(&ip) ||
- !request->ReadUInt16(&port)) {
- Error(0);
- return;
- }
-
- if (ver != 5 || command != 1 ||
- reserved != 0 || addr_type != 1) {
- Error(0);
- return;
- }
-
- SignalConnectRequest(this, SocketAddress(ip, port));
- state_ = SS_CONNECT_PENDING;
-}
-
-void AsyncSocksProxyServerSocket::SendConnectResult(int result,
- const SocketAddress& addr) {
- if (state_ != SS_CONNECT_PENDING)
- return;
-
- ByteBuffer response;
- response.WriteUInt8(5); // Socks version
- response.WriteUInt8((result != 0)); // 0x01 is generic error
- response.WriteUInt8(0); // reserved
- response.WriteUInt8(1); // IPv4 address
- response.WriteUInt32(addr.ip());
- response.WriteUInt16(addr.port());
- DirectSend(response);
- BufferInput(false);
- state_ = SS_TUNNEL;
-}
-
-void AsyncSocksProxyServerSocket::Error(int error) {
- state_ = SS_ERROR;
- BufferInput(false);
- Close();
- SetError(SOCKET_EACCES);
- SignalCloseEvent(this, error);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-LoggingSocketAdapter::LoggingSocketAdapter(AsyncSocket* socket,
- LoggingSeverity level,
- const char * label, bool hex_mode)
- : AsyncSocketAdapter(socket), level_(level), hex_mode_(hex_mode) {
- label_.append("[");
- label_.append(label);
- label_.append("]");
-}
-
-int LoggingSocketAdapter::Send(const void *pv, size_t cb) {
- int res = AsyncSocketAdapter::Send(pv, cb);
- if (res > 0)
- LogMultiline(level_, label_.c_str(), false, pv, res, hex_mode_, &lms_);
- return res;
-}
-
-int LoggingSocketAdapter::SendTo(const void *pv, size_t cb,
- const SocketAddress& addr) {
- int res = AsyncSocketAdapter::SendTo(pv, cb, addr);
- if (res > 0)
- LogMultiline(level_, label_.c_str(), false, pv, res, hex_mode_, &lms_);
- return res;
-}
-
-int LoggingSocketAdapter::Recv(void *pv, size_t cb) {
- int res = AsyncSocketAdapter::Recv(pv, cb);
- if (res > 0)
- LogMultiline(level_, label_.c_str(), true, pv, res, hex_mode_, &lms_);
- return res;
-}
-
-int LoggingSocketAdapter::RecvFrom(void *pv, size_t cb, SocketAddress *paddr) {
- int res = AsyncSocketAdapter::RecvFrom(pv, cb, paddr);
- if (res > 0)
- LogMultiline(level_, label_.c_str(), true, pv, res, hex_mode_, &lms_);
- return res;
-}
-
-int LoggingSocketAdapter::Close() {
- LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
- LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
- LOG_V(level_) << label_ << " Closed locally";
- return socket_->Close();
-}
-
-void LoggingSocketAdapter::OnConnectEvent(AsyncSocket * socket) {
- LOG_V(level_) << label_ << " Connected";
- AsyncSocketAdapter::OnConnectEvent(socket);
-}
-
-void LoggingSocketAdapter::OnCloseEvent(AsyncSocket * socket, int err) {
- LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
- LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
- LOG_V(level_) << label_ << " Closed with error: " << err;
- AsyncSocketAdapter::OnCloseEvent(socket, err);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/socketadapters.h b/base/socketadapters.h
deleted file mode 100644
index 320da6f..0000000
--- a/base/socketadapters.h
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKETADAPTERS_H_
-#define TALK_BASE_SOCKETADAPTERS_H_
-
-#include <map>
-#include <string>
-
-#include "talk/base/asyncsocket.h"
-#include "talk/base/cryptstring.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-struct HttpAuthContext;
-class ByteBuffer;
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Implements a socket adapter that can buffer and process data internally,
-// as in the case of connecting to a proxy, where you must speak the proxy
-// protocol before commencing normal socket behavior.
-class BufferedReadAdapter : public AsyncSocketAdapter {
- public:
- BufferedReadAdapter(AsyncSocket* socket, size_t buffer_size);
- virtual ~BufferedReadAdapter();
-
- virtual int Send(const void* pv, size_t cb);
- virtual int Recv(void* pv, size_t cb);
-
- protected:
- int DirectSend(const void* pv, size_t cb) {
- return AsyncSocketAdapter::Send(pv, cb);
- }
-
- void BufferInput(bool on = true);
- virtual void ProcessInput(char* data, size_t* len) = 0;
-
- virtual void OnReadEvent(AsyncSocket * socket);
-
- private:
- char * buffer_;
- size_t buffer_size_, data_len_;
- bool buffering_;
- DISALLOW_EVIL_CONSTRUCTORS(BufferedReadAdapter);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Interface for implementing proxy server sockets.
-class AsyncProxyServerSocket : public BufferedReadAdapter {
- public:
- AsyncProxyServerSocket(AsyncSocket* socket, size_t buffer_size)
- : BufferedReadAdapter(socket, buffer_size) {}
- sigslot::signal2<AsyncProxyServerSocket*,
- const SocketAddress&> SignalConnectRequest;
- virtual void SendConnectResult(int err, const SocketAddress& addr) = 0;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Implements a socket adapter that performs the client side of a
-// fake SSL handshake. Used for "ssltcp" P2P functionality.
-class AsyncSSLSocket : public BufferedReadAdapter {
- public:
- explicit AsyncSSLSocket(AsyncSocket* socket);
-
- virtual int Connect(const SocketAddress& addr);
-
- protected:
- virtual void OnConnectEvent(AsyncSocket* socket);
- virtual void ProcessInput(char* data, size_t* len);
- DISALLOW_EVIL_CONSTRUCTORS(AsyncSSLSocket);
-};
-
-// Implements a socket adapter that performs the server side of a
-// fake SSL handshake. Used when implementing a relay server that does "ssltcp".
-class AsyncSSLServerSocket : public BufferedReadAdapter {
- public:
- explicit AsyncSSLServerSocket(AsyncSocket* socket);
-
- protected:
- virtual void ProcessInput(char* data, size_t* len);
- DISALLOW_EVIL_CONSTRUCTORS(AsyncSSLServerSocket);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Implements a socket adapter that speaks the HTTP/S proxy protocol.
-class AsyncHttpsProxySocket : public BufferedReadAdapter {
- public:
- AsyncHttpsProxySocket(AsyncSocket* socket, const std::string& user_agent,
- const SocketAddress& proxy,
- const std::string& username, const CryptString& password);
- virtual ~AsyncHttpsProxySocket();
-
- // If connect is forced, the adapter will always issue an HTTP CONNECT to the
- // target address. Otherwise, it will connect only if the destination port
- // is not port 80.
- void SetForceConnect(bool force) { force_connect_ = force; }
-
- virtual int Connect(const SocketAddress& addr);
- virtual SocketAddress GetRemoteAddress() const;
- virtual int Close();
- virtual ConnState GetState() const;
-
- protected:
- virtual void OnConnectEvent(AsyncSocket* socket);
- virtual void OnCloseEvent(AsyncSocket* socket, int err);
- virtual void ProcessInput(char* data, size_t* len);
-
- bool ShouldIssueConnect() const;
- void SendRequest();
- void ProcessLine(char* data, size_t len);
- void EndResponse();
- void Error(int error);
-
- private:
- SocketAddress proxy_, dest_;
- std::string agent_, user_, headers_;
- CryptString pass_;
- bool force_connect_;
- size_t content_length_;
- int defer_error_;
- bool expect_close_;
- enum ProxyState {
- PS_INIT, PS_LEADER, PS_AUTHENTICATE, PS_SKIP_HEADERS, PS_ERROR_HEADERS,
- PS_TUNNEL_HEADERS, PS_SKIP_BODY, PS_TUNNEL, PS_WAIT_CLOSE, PS_ERROR
- } state_;
- HttpAuthContext * context_;
- std::string unknown_mechanisms_;
- DISALLOW_EVIL_CONSTRUCTORS(AsyncHttpsProxySocket);
-};
-
-/* TODO: Implement this.
-class AsyncHttpsProxyServerSocket : public AsyncProxyServerSocket {
- public:
- explicit AsyncHttpsProxyServerSocket(AsyncSocket* socket);
-
- private:
- virtual void ProcessInput(char * data, size_t& len);
- void Error(int error);
- DISALLOW_EVIL_CONSTRUCTORS(AsyncHttpsProxyServerSocket);
-};
-*/
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Implements a socket adapter that speaks the SOCKS proxy protocol.
-class AsyncSocksProxySocket : public BufferedReadAdapter {
- public:
- AsyncSocksProxySocket(AsyncSocket* socket, const SocketAddress& proxy,
- const std::string& username, const CryptString& password);
-
- virtual int Connect(const SocketAddress& addr);
- virtual SocketAddress GetRemoteAddress() const;
- virtual int Close();
- virtual ConnState GetState() const;
-
- protected:
- virtual void OnConnectEvent(AsyncSocket* socket);
- virtual void ProcessInput(char* data, size_t* len);
-
- void SendHello();
- void SendConnect();
- void SendAuth();
- void Error(int error);
-
- private:
- enum State {
- SS_INIT, SS_HELLO, SS_AUTH, SS_CONNECT, SS_TUNNEL, SS_ERROR
- };
- State state_;
- SocketAddress proxy_, dest_;
- std::string user_;
- CryptString pass_;
- DISALLOW_EVIL_CONSTRUCTORS(AsyncSocksProxySocket);
-};
-
-// Implements a proxy server socket for the SOCKS protocol.
-class AsyncSocksProxyServerSocket : public AsyncProxyServerSocket {
- public:
- explicit AsyncSocksProxyServerSocket(AsyncSocket* socket);
-
- private:
- virtual void ProcessInput(char* data, size_t* len);
- void DirectSend(const ByteBuffer& buf);
-
- void HandleHello(ByteBuffer* request);
- void SendHelloReply(int method);
- void HandleAuth(ByteBuffer* request);
- void SendAuthReply(int result);
- void HandleConnect(ByteBuffer* request);
- virtual void SendConnectResult(int result, const SocketAddress& addr);
-
- void Error(int error);
-
- static const int kBufferSize = 1024;
- enum State {
- SS_HELLO, SS_AUTH, SS_CONNECT, SS_CONNECT_PENDING, SS_TUNNEL, SS_ERROR
- };
- State state_;
- DISALLOW_EVIL_CONSTRUCTORS(AsyncSocksProxyServerSocket);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Implements a socket adapter that logs everything that it sends and receives.
-class LoggingSocketAdapter : public AsyncSocketAdapter {
- public:
- LoggingSocketAdapter(AsyncSocket* socket, LoggingSeverity level,
- const char * label, bool hex_mode = false);
-
- virtual int Send(const void *pv, size_t cb);
- virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr);
- virtual int Recv(void *pv, size_t cb);
- virtual int RecvFrom(void *pv, size_t cb, SocketAddress *paddr);
- virtual int Close();
-
- protected:
- virtual void OnConnectEvent(AsyncSocket * socket);
- virtual void OnCloseEvent(AsyncSocket * socket, int err);
-
- private:
- LoggingSeverity level_;
- std::string label_;
- bool hex_mode_;
- LogMultilineState lms_;
- DISALLOW_EVIL_CONSTRUCTORS(LoggingSocketAdapter);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKETADAPTERS_H_
diff --git a/base/socketaddress.cc b/base/socketaddress.cc
deleted file mode 100644
index 792d414..0000000
--- a/base/socketaddress.cc
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/socketaddress.h"
-
-#ifdef POSIX
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#if defined(OPENBSD)
-#include <netinet/in_systm.h>
-#endif
-#if !defined(__native_client__)
-#include <netinet/ip.h>
-#endif
-#include <arpa/inet.h>
-#include <netdb.h>
-#include <unistd.h>
-#endif
-
-#include <sstream>
-
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/nethelpers.h"
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif
-
-namespace talk_base {
-
-SocketAddress::SocketAddress() {
- Clear();
-}
-
-SocketAddress::SocketAddress(const std::string& hostname, int port) {
- SetIP(hostname);
- SetPort(port);
-}
-
-SocketAddress::SocketAddress(uint32 ip_as_host_order_integer, int port) {
- SetIP(IPAddress(ip_as_host_order_integer));
- SetPort(port);
-}
-
-SocketAddress::SocketAddress(const IPAddress& ip, int port) {
- SetIP(ip);
- SetPort(port);
-}
-
-SocketAddress::SocketAddress(const SocketAddress& addr) {
- this->operator=(addr);
-}
-
-void SocketAddress::Clear() {
- hostname_.clear();
- literal_ = false;
- ip_ = IPAddress();
- port_ = 0;
- scope_id_ = 0;
-}
-
-bool SocketAddress::IsNil() const {
- return hostname_.empty() && IPIsUnspec(ip_) && 0 == port_;
-}
-
-bool SocketAddress::IsComplete() const {
- return (!IPIsAny(ip_)) && (0 != port_);
-}
-
-SocketAddress& SocketAddress::operator=(const SocketAddress& addr) {
- hostname_ = addr.hostname_;
- ip_ = addr.ip_;
- port_ = addr.port_;
- literal_ = addr.literal_;
- scope_id_ = addr.scope_id_;
- return *this;
-}
-
-void SocketAddress::SetIP(uint32 ip_as_host_order_integer) {
- hostname_.clear();
- literal_ = false;
- ip_ = IPAddress(ip_as_host_order_integer);
- scope_id_ = 0;
-}
-
-void SocketAddress::SetIP(const IPAddress& ip) {
- hostname_.clear();
- literal_ = false;
- ip_ = ip;
- scope_id_ = 0;
-}
-
-void SocketAddress::SetIP(const std::string& hostname) {
- hostname_ = hostname;
- literal_ = IPFromString(hostname, &ip_);
- if (!literal_) {
- ip_ = IPAddress();
- }
- scope_id_ = 0;
-}
-
-void SocketAddress::SetResolvedIP(uint32 ip_as_host_order_integer) {
- ip_ = IPAddress(ip_as_host_order_integer);
- scope_id_ = 0;
-}
-
-void SocketAddress::SetResolvedIP(const IPAddress& ip) {
- ip_ = ip;
- scope_id_ = 0;
-}
-
-void SocketAddress::SetPort(int port) {
- ASSERT((0 <= port) && (port < 65536));
- port_ = port;
-}
-
-uint32 SocketAddress::ip() const {
- return ip_.v4AddressAsHostOrderInteger();
-}
-
-const IPAddress& SocketAddress::ipaddr() const {
- return ip_;
-}
-
-uint16 SocketAddress::port() const {
- return port_;
-}
-
-std::string SocketAddress::HostAsURIString() const {
- // If the hostname was a literal IP string, it may need to have square
- // brackets added (for SocketAddress::ToString()).
- if (!literal_ && !hostname_.empty())
- return hostname_;
- if (ip_.family() == AF_INET6) {
- return "[" + ip_.ToString() + "]";
- } else {
- return ip_.ToString();
- }
-}
-
-std::string SocketAddress::HostAsSensitiveURIString() const {
- // If the hostname was a literal IP string, it may need to have square
- // brackets added (for SocketAddress::ToString()).
- if (!literal_ && !hostname_.empty())
- return hostname_;
- if (ip_.family() == AF_INET6) {
- return "[" + ip_.ToSensitiveString() + "]";
- } else {
- return ip_.ToSensitiveString();
- }
-}
-
-std::string SocketAddress::PortAsString() const {
- std::ostringstream ost;
- ost << port_;
- return ost.str();
-}
-
-std::string SocketAddress::ToString() const {
- std::ostringstream ost;
- ost << *this;
- return ost.str();
-}
-
-std::string SocketAddress::ToSensitiveString() const {
- std::ostringstream ost;
- ost << HostAsSensitiveURIString() << ":" << port();
- return ost.str();
-}
-
-bool SocketAddress::FromString(const std::string& str) {
- if (str.at(0) == '[') {
- std::string::size_type closebracket = str.rfind(']');
- if (closebracket != std::string::npos) {
- std::string::size_type colon = str.find(':', closebracket);
- if (colon != std::string::npos && colon > closebracket) {
- SetPort(strtoul(str.substr(colon + 1).c_str(), NULL, 10));
- SetIP(str.substr(1, closebracket - 1));
- } else {
- return false;
- }
- }
- } else {
- std::string::size_type pos = str.find(':');
- if (std::string::npos == pos)
- return false;
- SetPort(strtoul(str.substr(pos + 1).c_str(), NULL, 10));
- SetIP(str.substr(0, pos));
- }
- return true;
-}
-
-std::ostream& operator<<(std::ostream& os, const SocketAddress& addr) {
- os << addr.HostAsURIString() << ":" << addr.port();
- return os;
-}
-
-bool SocketAddress::IsAnyIP() const {
- return IPIsAny(ip_);
-}
-
-bool SocketAddress::IsLoopbackIP() const {
- return IPIsLoopback(ip_) || (IPIsAny(ip_) &&
- 0 == strcmp(hostname_.c_str(), "localhost"));
-}
-
-bool SocketAddress::IsPrivateIP() const {
- return IPIsPrivate(ip_);
-}
-
-bool SocketAddress::IsUnresolvedIP() const {
- return IPIsUnspec(ip_) && !literal_ && !hostname_.empty();
-}
-
-bool SocketAddress::operator==(const SocketAddress& addr) const {
- return EqualIPs(addr) && EqualPorts(addr);
-}
-
-bool SocketAddress::operator<(const SocketAddress& addr) const {
- if (ip_ < addr.ip_)
- return true;
- else if (addr.ip_ < ip_)
- return false;
-
- // We only check hostnames if both IPs are zero. This matches EqualIPs()
- if (addr.IsAnyIP()) {
- if (hostname_ < addr.hostname_)
- return true;
- else if (addr.hostname_ < hostname_)
- return false;
- }
-
- return port_ < addr.port_;
-}
-
-bool SocketAddress::EqualIPs(const SocketAddress& addr) const {
- return (ip_ == addr.ip_) &&
- ((!IPIsAny(ip_)) || (hostname_ == addr.hostname_));
-}
-
-bool SocketAddress::EqualPorts(const SocketAddress& addr) const {
- return (port_ == addr.port_);
-}
-
-size_t SocketAddress::Hash() const {
- size_t h = 0;
- h ^= HashIP(ip_);
- h ^= port_ | (port_ << 16);
- return h;
-}
-
-void SocketAddress::ToSockAddr(sockaddr_in* saddr) const {
- memset(saddr, 0, sizeof(*saddr));
- if (ip_.family() != AF_INET) {
- saddr->sin_family = AF_UNSPEC;
- return;
- }
- saddr->sin_family = AF_INET;
- saddr->sin_port = HostToNetwork16(port_);
- if (IPIsAny(ip_)) {
- saddr->sin_addr.s_addr = INADDR_ANY;
- } else {
- saddr->sin_addr = ip_.ipv4_address();
- }
-}
-
-bool SocketAddress::FromSockAddr(const sockaddr_in& saddr) {
- if (saddr.sin_family != AF_INET)
- return false;
- SetIP(NetworkToHost32(saddr.sin_addr.s_addr));
- SetPort(NetworkToHost16(saddr.sin_port));
- literal_ = false;
- return true;
-}
-
-static size_t ToSockAddrStorageHelper(sockaddr_storage* addr,
- IPAddress ip, int port, int scope_id) {
- memset(addr, 0, sizeof(sockaddr_storage));
- addr->ss_family = ip.family();
- if (addr->ss_family == AF_INET6) {
- sockaddr_in6* saddr = reinterpret_cast<sockaddr_in6*>(addr);
- saddr->sin6_addr = ip.ipv6_address();
- saddr->sin6_port = HostToNetwork16(port);
- saddr->sin6_scope_id = scope_id;
- return sizeof(sockaddr_in6);
- } else if (addr->ss_family == AF_INET) {
- sockaddr_in* saddr = reinterpret_cast<sockaddr_in*>(addr);
- saddr->sin_addr = ip.ipv4_address();
- saddr->sin_port = HostToNetwork16(port);
- return sizeof(sockaddr_in);
- }
- return 0;
-}
-
-size_t SocketAddress::ToDualStackSockAddrStorage(sockaddr_storage *addr) const {
- return ToSockAddrStorageHelper(addr, ip_.AsIPv6Address(), port_, scope_id_);
-}
-
-size_t SocketAddress::ToSockAddrStorage(sockaddr_storage* addr) const {
- return ToSockAddrStorageHelper(addr, ip_, port_, scope_id_);
-}
-
-std::string SocketAddress::IPToString(uint32 ip_as_host_order_integer) {
- return IPAddress(ip_as_host_order_integer).ToString();
-}
-
-std::string IPToSensitiveString(uint32 ip_as_host_order_integer) {
- return IPAddress(ip_as_host_order_integer).ToSensitiveString();
-}
-
-bool SocketAddress::StringToIP(const std::string& hostname, uint32* ip) {
- in_addr addr;
- if (talk_base::inet_pton(AF_INET, hostname.c_str(), &addr) == 0)
- return false;
- *ip = NetworkToHost32(addr.s_addr);
- return true;
-}
-
-bool SocketAddress::StringToIP(const std::string& hostname, IPAddress* ip) {
- in_addr addr4;
- if (talk_base::inet_pton(AF_INET, hostname.c_str(), &addr4) > 0) {
- if (ip) {
- *ip = IPAddress(addr4);
- }
- return true;
- }
-
- in6_addr addr6;
- if (talk_base::inet_pton(AF_INET6, hostname.c_str(), &addr6) > 0) {
- if (ip) {
- *ip = IPAddress(addr6);
- }
- return true;
- }
- return false;
-}
-
-uint32 SocketAddress::StringToIP(const std::string& hostname) {
- uint32 ip = 0;
- StringToIP(hostname, &ip);
- return ip;
-}
-
-bool SocketAddressFromSockAddrStorage(const sockaddr_storage& addr,
- SocketAddress* out) {
- if (!out) {
- return false;
- }
- if (addr.ss_family == AF_INET) {
- const sockaddr_in* saddr = reinterpret_cast<const sockaddr_in*>(&addr);
- *out = SocketAddress(IPAddress(saddr->sin_addr),
- NetworkToHost16(saddr->sin_port));
- return true;
- } else if (addr.ss_family == AF_INET6) {
- const sockaddr_in6* saddr = reinterpret_cast<const sockaddr_in6*>(&addr);
- *out = SocketAddress(IPAddress(saddr->sin6_addr),
- NetworkToHost16(saddr->sin6_port));
- out->SetScopeID(saddr->sin6_scope_id);
- return true;
- }
- return false;
-}
-
-SocketAddress EmptySocketAddressWithFamily(int family) {
- if (family == AF_INET) {
- return SocketAddress(IPAddress(INADDR_ANY), 0);
- } else if (family == AF_INET6) {
- return SocketAddress(IPAddress(in6addr_any), 0);
- }
- return SocketAddress();
-}
-
-} // namespace talk_base
diff --git a/base/socketaddress.h b/base/socketaddress.h
deleted file mode 100644
index 08f2659..0000000
--- a/base/socketaddress.h
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKETADDRESS_H_
-#define TALK_BASE_SOCKETADDRESS_H_
-
-#include <string>
-#include <vector>
-#include <iosfwd>
-#include "talk/base/basictypes.h"
-#include "talk/base/ipaddress.h"
-
-#undef SetPort
-
-struct sockaddr_in;
-struct sockaddr_storage;
-
-namespace talk_base {
-
-// Records an IP address and port.
-class SocketAddress {
- public:
- // Creates a nil address.
- SocketAddress();
-
- // Creates the address with the given host and port. Host may be a
- // literal IP string or a hostname to be resolved later.
- SocketAddress(const std::string& hostname, int port);
-
- // Creates the address with the given IP and port.
- // IP is given as an integer in host byte order. V4 only, to be deprecated.
- SocketAddress(uint32 ip_as_host_order_integer, int port);
-
- // Creates the address with the given IP and port.
- SocketAddress(const IPAddress& ip, int port);
-
- // Creates a copy of the given address.
- SocketAddress(const SocketAddress& addr);
-
- // Resets to the nil address.
- void Clear();
-
- // Determines if this is a nil address (empty hostname, any IP, null port)
- bool IsNil() const;
-
- // Returns true if ip and port are set.
- bool IsComplete() const;
-
- // Replaces our address with the given one.
- SocketAddress& operator=(const SocketAddress& addr);
-
- // Changes the IP of this address to the given one, and clears the hostname
- // IP is given as an integer in host byte order. V4 only, to be deprecated..
- void SetIP(uint32 ip_as_host_order_integer);
-
- // Changes the IP of this address to the given one, and clears the hostname.
- void SetIP(const IPAddress& ip);
-
- // Changes the hostname of this address to the given one.
- // Does not resolve the address; use Resolve to do so.
- void SetIP(const std::string& hostname);
-
- // Sets the IP address while retaining the hostname. Useful for bypassing
- // DNS for a pre-resolved IP.
- // IP is given as an integer in host byte order. V4 only, to be deprecated.
- void SetResolvedIP(uint32 ip_as_host_order_integer);
-
- // Sets the IP address while retaining the hostname. Useful for bypassing
- // DNS for a pre-resolved IP.
- void SetResolvedIP(const IPAddress& ip);
-
- // Changes the port of this address to the given one.
- void SetPort(int port);
-
- // Returns the hostname.
- const std::string& hostname() const { return hostname_; }
-
- // Returns the IP address as a host byte order integer.
- // Returns 0 for non-v4 addresses.
- uint32 ip() const;
-
- const IPAddress& ipaddr() const;
-
- int family() const {return ip_.family(); }
-
- // Returns the port part of this address.
- uint16 port() const;
-
- // Returns the scope ID associated with this address. Scope IDs are a
- // necessary addition to IPv6 link-local addresses, with different network
- // interfaces having different scope-ids for their link-local addresses.
- // IPv4 address do not have scope_ids and sockaddr_in structures do not have
- // a field for them.
- int scope_id() const {return scope_id_; }
- void SetScopeID(int id) { scope_id_ = id; }
-
- // Returns the 'host' portion of the address (hostname or IP) in a form
- // suitable for use in a URI. If both IP and hostname are present, hostname
- // is preferred. IPv6 addresses are enclosed in square brackets ('[' and ']').
- std::string HostAsURIString() const;
-
- // Same as HostAsURIString but anonymizes IP addresses by hiding the last
- // part.
- std::string HostAsSensitiveURIString() const;
-
- // Returns the port as a string.
- std::string PortAsString() const;
-
- // Returns hostname:port or [hostname]:port.
- std::string ToString() const;
-
- // Same as ToString but anonymizes it by hiding the last part.
- std::string ToSensitiveString() const;
-
- // Parses hostname:port and [hostname]:port.
- bool FromString(const std::string& str);
-
- friend std::ostream& operator<<(std::ostream& os, const SocketAddress& addr);
-
- // Determines whether this represents a missing / any IP address.
- // That is, 0.0.0.0 or ::.
- // Hostname and/or port may be set.
- bool IsAnyIP() const;
- inline bool IsAny() const { return IsAnyIP(); } // deprecated
-
- // Determines whether the IP address refers to a loopback address.
- // For v4 addresses this means the address is in the range 127.0.0.0/8.
- // For v6 addresses this means the address is ::1.
- bool IsLoopbackIP() const;
-
- // Determines whether the IP address is in one of the private ranges:
- // For v4: 127.0.0.0/8 10.0.0.0/8 192.168.0.0/16 172.16.0.0/12.
- // For v6: FE80::/16 and ::1.
- bool IsPrivateIP() const;
-
- // Determines whether the hostname has been resolved to an IP.
- bool IsUnresolvedIP() const;
- inline bool IsUnresolved() const { return IsUnresolvedIP(); } // deprecated
-
- // Determines whether this address is identical to the given one.
- bool operator ==(const SocketAddress& addr) const;
- inline bool operator !=(const SocketAddress& addr) const {
- return !this->operator ==(addr);
- }
-
- // Compares based on IP and then port.
- bool operator <(const SocketAddress& addr) const;
-
- // Determines whether this address has the same IP as the one given.
- bool EqualIPs(const SocketAddress& addr) const;
-
- // Determines whether this address has the same port as the one given.
- bool EqualPorts(const SocketAddress& addr) const;
-
- // Hashes this address into a small number.
- size_t Hash() const;
-
- // Write this address to a sockaddr_in.
- // If IPv6, will zero out the sockaddr_in and sets family to AF_UNSPEC.
- void ToSockAddr(sockaddr_in* saddr) const;
-
- // Read this address from a sockaddr_in.
- bool FromSockAddr(const sockaddr_in& saddr);
-
- // Read and write the address to/from a sockaddr_storage.
- // Dual stack version always sets family to AF_INET6, and maps v4 addresses.
- // The other version doesn't map, and outputs an AF_INET address for
- // v4 or mapped addresses, and AF_INET6 addresses for others.
- // Returns the size of the sockaddr_in or sockaddr_in6 structure that is
- // written to the sockaddr_storage, or zero on failure.
- size_t ToDualStackSockAddrStorage(sockaddr_storage* saddr) const;
- size_t ToSockAddrStorage(sockaddr_storage* saddr) const;
-
- // Converts the IP address given in 'compact form' into dotted form.
- // IP is given as an integer in host byte order. V4 only, to be deprecated.
- // TODO: Deprecate this.
- static std::string IPToString(uint32 ip_as_host_order_integer);
-
- // Same as IPToString but anonymizes it by hiding the last part.
- // TODO: Deprecate this.
- static std::string IPToSensitiveString(uint32 ip_as_host_order_integer);
-
- // Converts the IP address given in dotted form into compact form.
- // Only dotted names (A.B.C.D) are converted.
- // Output integer is returned in host byte order.
- // TODO: Deprecate, replace wth agnostic versions.
- static bool StringToIP(const std::string& str, uint32* ip);
- static uint32 StringToIP(const std::string& str);
-
- // Converts the IP address given in printable form into an IPAddress.
- static bool StringToIP(const std::string& str, IPAddress* ip);
-
- private:
- std::string hostname_;
- IPAddress ip_;
- uint16 port_;
- int scope_id_;
- bool literal_; // Indicates that 'hostname_' contains a literal IP string.
-};
-
-bool SocketAddressFromSockAddrStorage(const sockaddr_storage& saddr,
- SocketAddress* out);
-SocketAddress EmptySocketAddressWithFamily(int family);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKETADDRESS_H_
diff --git a/base/socketaddress_unittest.cc b/base/socketaddress_unittest.cc
deleted file mode 100644
index c57db8d..0000000
--- a/base/socketaddress_unittest.cc
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef POSIX
-#include <netinet/in.h> // for sockaddr_in
-#endif
-
-#include "talk/base/gunit.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/ipaddress.h"
-
-namespace talk_base {
-
-const in6_addr kTestV6Addr = { { {0x20, 0x01, 0x0d, 0xb8,
- 0x10, 0x20, 0x30, 0x40,
- 0x50, 0x60, 0x70, 0x80,
- 0x90, 0xA0, 0xB0, 0xC0} } };
-const in6_addr kMappedV4Addr = { { {0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0xFF, 0xFF,
- 0x01, 0x02, 0x03, 0x04} } };
-const std::string kTestV6AddrString = "2001:db8:1020:3040:5060:7080:90a0:b0c0";
-const std::string kTestV6AddrAnonymizedString = "2001:db8:1020::";
-const std::string kTestV6AddrFullString =
- "[2001:db8:1020:3040:5060:7080:90a0:b0c0]:5678";
-const std::string kTestV6AddrFullAnonymizedString = "[2001:db8:1020::]:5678";
-
-TEST(SocketAddressTest, TestDefaultCtor) {
- SocketAddress addr;
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(), addr.ipaddr());
- EXPECT_EQ(0, addr.port());
- EXPECT_EQ("", addr.hostname());
-}
-
-TEST(SocketAddressTest, TestIPPortCtor) {
- SocketAddress addr(IPAddress(0x01020304), 5678);
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestIPv4StringPortCtor) {
- SocketAddress addr("1.2.3.4", 5678);
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("1.2.3.4", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestIPv6StringPortCtor) {
- SocketAddress addr2(kTestV6AddrString, 1234);
- IPAddress tocheck(kTestV6Addr);
-
- EXPECT_FALSE(addr2.IsUnresolvedIP());
- EXPECT_EQ(tocheck, addr2.ipaddr());
- EXPECT_EQ(1234, addr2.port());
- EXPECT_EQ(kTestV6AddrString, addr2.hostname());
- EXPECT_EQ("[" + kTestV6AddrString + "]:1234", addr2.ToString());
-}
-
-TEST(SocketAddressTest, TestSpecialStringPortCtor) {
- // inet_addr doesn't handle this address properly.
- SocketAddress addr("255.255.255.255", 5678);
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0xFFFFFFFFU), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("255.255.255.255", addr.hostname());
- EXPECT_EQ("255.255.255.255:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestHostnamePortCtor) {
- SocketAddress addr("a.b.com", 5678);
- EXPECT_TRUE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("a.b.com", addr.hostname());
- EXPECT_EQ("a.b.com:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestCopyCtor) {
- SocketAddress from("1.2.3.4", 5678);
- SocketAddress addr(from);
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("1.2.3.4", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestAssign) {
- SocketAddress from("1.2.3.4", 5678);
- SocketAddress addr(IPAddress(0x88888888), 9999);
- addr = from;
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("1.2.3.4", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestSetIPPort) {
- SocketAddress addr(IPAddress(0x88888888), 9999);
- addr.SetIP(IPAddress(0x01020304));
- addr.SetPort(5678);
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestSetIPFromString) {
- SocketAddress addr(IPAddress(0x88888888), 9999);
- addr.SetIP("1.2.3.4");
- addr.SetPort(5678);
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("1.2.3.4", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestSetIPFromHostname) {
- SocketAddress addr(IPAddress(0x88888888), 9999);
- addr.SetIP("a.b.com");
- addr.SetPort(5678);
- EXPECT_TRUE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("a.b.com", addr.hostname());
- EXPECT_EQ("a.b.com:5678", addr.ToString());
- addr.SetResolvedIP(IPAddress(0x01020304));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ("a.b.com", addr.hostname());
- EXPECT_EQ("a.b.com:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestFromIPv4String) {
- SocketAddress addr;
- EXPECT_TRUE(addr.FromString("1.2.3.4:5678"));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("1.2.3.4", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestFromIPv6String) {
- SocketAddress addr;
- EXPECT_TRUE(addr.FromString(kTestV6AddrFullString));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ(kTestV6AddrString, addr.hostname());
- EXPECT_EQ(kTestV6AddrFullString, addr.ToString());
-}
-
-TEST(SocketAddressTest, TestFromHostname) {
- SocketAddress addr;
- EXPECT_TRUE(addr.FromString("a.b.com:5678"));
- EXPECT_TRUE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("a.b.com", addr.hostname());
- EXPECT_EQ("a.b.com:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestToFromSockAddr) {
- SocketAddress from("1.2.3.4", 5678), addr;
- sockaddr_in addr_in;
- from.ToSockAddr(&addr_in);
- EXPECT_TRUE(addr.FromSockAddr(addr_in));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-}
-
-TEST(SocketAddressTest, TestToFromSockAddrStorage) {
- SocketAddress from("1.2.3.4", 5678), addr;
- sockaddr_storage addr_storage;
- from.ToSockAddrStorage(&addr_storage);
- EXPECT_TRUE(SocketAddressFromSockAddrStorage(addr_storage, &addr));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(0x01020304U), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("", addr.hostname());
- EXPECT_EQ("1.2.3.4:5678", addr.ToString());
-
- addr.Clear();
- from.ToDualStackSockAddrStorage(&addr_storage);
- EXPECT_TRUE(SocketAddressFromSockAddrStorage(addr_storage, &addr));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(kMappedV4Addr), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("", addr.hostname());
- EXPECT_EQ("[::ffff:1.2.3.4]:5678", addr.ToString());
-
- addr.Clear();
- memset(&addr_storage, 0, sizeof(sockaddr_storage));
- from = SocketAddress(kTestV6AddrString, 5678);
- from.SetScopeID(6);
- from.ToSockAddrStorage(&addr_storage);
- EXPECT_TRUE(SocketAddressFromSockAddrStorage(addr_storage, &addr));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(kTestV6Addr), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("", addr.hostname());
- EXPECT_EQ(kTestV6AddrFullString, addr.ToString());
- EXPECT_EQ(6, addr.scope_id());
-
- addr.Clear();
- from.ToDualStackSockAddrStorage(&addr_storage);
- EXPECT_TRUE(SocketAddressFromSockAddrStorage(addr_storage, &addr));
- EXPECT_FALSE(addr.IsUnresolvedIP());
- EXPECT_EQ(IPAddress(kTestV6Addr), addr.ipaddr());
- EXPECT_EQ(5678, addr.port());
- EXPECT_EQ("", addr.hostname());
- EXPECT_EQ(kTestV6AddrFullString, addr.ToString());
- EXPECT_EQ(6, addr.scope_id());
-
- addr = from;
- addr_storage.ss_family = AF_UNSPEC;
- EXPECT_FALSE(SocketAddressFromSockAddrStorage(addr_storage, &addr));
- EXPECT_EQ(from, addr);
-
- EXPECT_FALSE(SocketAddressFromSockAddrStorage(addr_storage, NULL));
-}
-
-bool AreEqual(const SocketAddress& addr1,
- const SocketAddress& addr2) {
- return addr1 == addr2 && addr2 == addr1 &&
- !(addr1 != addr2) && !(addr2 != addr1);
-}
-
-bool AreUnequal(const SocketAddress& addr1,
- const SocketAddress& addr2) {
- return !(addr1 == addr2) && !(addr2 == addr1) &&
- addr1 != addr2 && addr2 != addr1;
-}
-
-TEST(SocketAddressTest, TestEqualityOperators) {
- SocketAddress addr1("1.2.3.4", 5678);
- SocketAddress addr2("1.2.3.4", 5678);
- EXPECT_PRED2(AreEqual, addr1, addr2);
-
- addr2 = SocketAddress("0.0.0.1", 5678);
- EXPECT_PRED2(AreUnequal, addr1, addr2);
-
- addr2 = SocketAddress("1.2.3.4", 1234);
- EXPECT_PRED2(AreUnequal, addr1, addr2);
-
- addr2 = SocketAddress(kTestV6AddrString, 5678);
- EXPECT_PRED2(AreUnequal, addr1, addr2);
-
- addr1 = SocketAddress(kTestV6AddrString, 5678);
- EXPECT_PRED2(AreEqual, addr1, addr2);
-
- addr2 = SocketAddress(kTestV6AddrString, 1234);
- EXPECT_PRED2(AreUnequal, addr1, addr2);
-
- addr2 = SocketAddress("fe80::1", 5678);
- EXPECT_PRED2(AreUnequal, addr1, addr2);
-}
-
-bool IsLessThan(const SocketAddress& addr1,
- const SocketAddress& addr2) {
- return addr1 < addr2 &&
- !(addr2 < addr1) &&
- !(addr1 == addr2);
-}
-
-TEST(SocketAddressTest, TestComparisonOperator) {
- SocketAddress addr1("1.2.3.4", 5678);
- SocketAddress addr2("1.2.3.4", 5678);
-
- EXPECT_FALSE(addr1 < addr2);
- EXPECT_FALSE(addr2 < addr1);
-
- addr2 = SocketAddress("1.2.3.4", 5679);
- EXPECT_PRED2(IsLessThan, addr1, addr2);
-
- addr2 = SocketAddress("2.2.3.4", 49152);
- EXPECT_PRED2(IsLessThan, addr1, addr2);
-
- addr2 = SocketAddress(kTestV6AddrString, 5678);
- EXPECT_PRED2(IsLessThan, addr1, addr2);
-
- addr1 = SocketAddress("fe80::1", 5678);
- EXPECT_PRED2(IsLessThan, addr2, addr1);
-
- addr2 = SocketAddress("fe80::1", 5679);
- EXPECT_PRED2(IsLessThan, addr1, addr2);
-
- addr2 = SocketAddress("fe80::1", 5678);
- EXPECT_FALSE(addr1 < addr2);
- EXPECT_FALSE(addr2 < addr1);
-}
-
-TEST(SocketAddressTest, TestToSensitiveString) {
- SocketAddress addr_v4("1.2.3.4", 5678);
- EXPECT_EQ("1.2.3.4", addr_v4.HostAsURIString());
- EXPECT_EQ("1.2.3.4:5678", addr_v4.ToString());
- EXPECT_EQ("1.2.3.4", addr_v4.HostAsSensitiveURIString());
- EXPECT_EQ("1.2.3.4:5678", addr_v4.ToSensitiveString());
- IPAddress::set_strip_sensitive(true);
- EXPECT_EQ("1.2.3.x", addr_v4.HostAsSensitiveURIString());
- EXPECT_EQ("1.2.3.x:5678", addr_v4.ToSensitiveString());
- IPAddress::set_strip_sensitive(false);
-
- SocketAddress addr_v6(kTestV6AddrString, 5678);
- EXPECT_EQ("[" + kTestV6AddrString + "]", addr_v6.HostAsURIString());
- EXPECT_EQ(kTestV6AddrFullString, addr_v6.ToString());
- EXPECT_EQ("[" + kTestV6AddrString + "]", addr_v6.HostAsSensitiveURIString());
- EXPECT_EQ(kTestV6AddrFullString, addr_v6.ToSensitiveString());
- IPAddress::set_strip_sensitive(true);
- EXPECT_EQ("[" + kTestV6AddrAnonymizedString + "]",
- addr_v6.HostAsSensitiveURIString());
- EXPECT_EQ(kTestV6AddrFullAnonymizedString, addr_v6.ToSensitiveString());
- IPAddress::set_strip_sensitive(false);
-}
-
-} // namespace talk_base
diff --git a/base/socketaddresspair.cc b/base/socketaddresspair.cc
deleted file mode 100644
index 7f190a9..0000000
--- a/base/socketaddresspair.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/socketaddresspair.h"
-
-namespace talk_base {
-
-SocketAddressPair::SocketAddressPair(
- const SocketAddress& src, const SocketAddress& dest)
- : src_(src), dest_(dest) {
-}
-
-
-bool SocketAddressPair::operator ==(const SocketAddressPair& p) const {
- return (src_ == p.src_) && (dest_ == p.dest_);
-}
-
-bool SocketAddressPair::operator <(const SocketAddressPair& p) const {
- if (src_ < p.src_)
- return true;
- if (p.src_ < src_)
- return false;
- if (dest_ < p.dest_)
- return true;
- if (p.dest_ < dest_)
- return false;
- return false;
-}
-
-size_t SocketAddressPair::Hash() const {
- return src_.Hash() ^ dest_.Hash();
-}
-
-} // namespace talk_base
diff --git a/base/socketaddresspair.h b/base/socketaddresspair.h
deleted file mode 100644
index 10f5d30..0000000
--- a/base/socketaddresspair.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKETADDRESSPAIR_H__
-#define TALK_BASE_SOCKETADDRESSPAIR_H__
-
-#include "talk/base/socketaddress.h"
-
-namespace talk_base {
-
-// Records a pair (source,destination) of socket addresses. The two addresses
-// identify a connection between two machines. (For UDP, this "connection" is
-// not maintained explicitly in a socket.)
-class SocketAddressPair {
-public:
- SocketAddressPair() {}
- SocketAddressPair(const SocketAddress& srs, const SocketAddress& dest);
-
- const SocketAddress& source() const { return src_; }
- const SocketAddress& destination() const { return dest_; }
-
- bool operator ==(const SocketAddressPair& r) const;
- bool operator <(const SocketAddressPair& r) const;
-
- size_t Hash() const;
-
-private:
- SocketAddress src_;
- SocketAddress dest_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKETADDRESSPAIR_H__
diff --git a/base/socketfactory.h b/base/socketfactory.h
deleted file mode 100644
index 291df60..0000000
--- a/base/socketfactory.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKETFACTORY_H__
-#define TALK_BASE_SOCKETFACTORY_H__
-
-#include "talk/base/socket.h"
-#include "talk/base/asyncsocket.h"
-
-namespace talk_base {
-
-class SocketFactory {
-public:
- virtual ~SocketFactory() {}
-
- // Returns a new socket for blocking communication. The type can be
- // SOCK_DGRAM and SOCK_STREAM.
- // TODO: C++ inheritance rules mean that all users must have both
- // CreateSocket(int) and CreateSocket(int,int). Will remove CreateSocket(int)
- // (and CreateAsyncSocket(int) when all callers are changed.
- virtual Socket* CreateSocket(int type) = 0;
- virtual Socket* CreateSocket(int family, int type) = 0;
- // Returns a new socket for nonblocking communication. The type can be
- // SOCK_DGRAM and SOCK_STREAM.
- virtual AsyncSocket* CreateAsyncSocket(int type) = 0;
- virtual AsyncSocket* CreateAsyncSocket(int family, int type) = 0;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKETFACTORY_H__
diff --git a/base/socketpool.cc b/base/socketpool.cc
deleted file mode 100644
index 10d4303..0000000
--- a/base/socketpool.cc
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <iomanip>
-
-#include "talk/base/asyncsocket.h"
-#include "talk/base/logging.h"
-#include "talk/base/socketfactory.h"
-#include "talk/base/socketpool.h"
-#include "talk/base/socketstream.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamCache - Caches a set of open streams, defers creation to a separate
-// StreamPool.
-///////////////////////////////////////////////////////////////////////////////
-
-StreamCache::StreamCache(StreamPool* pool) : pool_(pool) {
-}
-
-StreamCache::~StreamCache() {
- for (ConnectedList::iterator it = active_.begin(); it != active_.end();
- ++it) {
- delete it->second;
- }
- for (ConnectedList::iterator it = cached_.begin(); it != cached_.end();
- ++it) {
- delete it->second;
- }
-}
-
-StreamInterface* StreamCache::RequestConnectedStream(
- const SocketAddress& remote, int* err) {
- LOG_F(LS_VERBOSE) << "(" << remote << ")";
- for (ConnectedList::iterator it = cached_.begin(); it != cached_.end();
- ++it) {
- if (remote == it->first) {
- it->second->SignalEvent.disconnect(this);
- // Move from cached_ to active_
- active_.push_front(*it);
- cached_.erase(it);
- if (err)
- *err = 0;
- LOG_F(LS_VERBOSE) << "Providing cached stream";
- return active_.front().second;
- }
- }
- if (StreamInterface* stream = pool_->RequestConnectedStream(remote, err)) {
- // We track active streams so that we can remember their address
- active_.push_front(ConnectedStream(remote, stream));
- LOG_F(LS_VERBOSE) << "Providing new stream";
- return active_.front().second;
- }
- return NULL;
-}
-
-void StreamCache::ReturnConnectedStream(StreamInterface* stream) {
- for (ConnectedList::iterator it = active_.begin(); it != active_.end();
- ++it) {
- if (stream == it->second) {
- LOG_F(LS_VERBOSE) << "(" << it->first << ")";
- if (stream->GetState() == SS_CLOSED) {
- // Return closed streams
- LOG_F(LS_VERBOSE) << "Returning closed stream";
- pool_->ReturnConnectedStream(it->second);
- } else {
- // Monitor open streams
- stream->SignalEvent.connect(this, &StreamCache::OnStreamEvent);
- LOG_F(LS_VERBOSE) << "Caching stream";
- cached_.push_front(*it);
- }
- active_.erase(it);
- return;
- }
- }
- ASSERT(false);
-}
-
-void StreamCache::OnStreamEvent(StreamInterface* stream, int events, int err) {
- if ((events & SE_CLOSE) == 0) {
- LOG_F(LS_WARNING) << "(" << events << ", " << err
- << ") received non-close event";
- return;
- }
- for (ConnectedList::iterator it = cached_.begin(); it != cached_.end();
- ++it) {
- if (stream == it->second) {
- LOG_F(LS_VERBOSE) << "(" << it->first << ")";
- // We don't cache closed streams, so return it.
- it->second->SignalEvent.disconnect(this);
- LOG_F(LS_VERBOSE) << "Returning closed stream";
- pool_->ReturnConnectedStream(it->second);
- cached_.erase(it);
- return;
- }
- }
- ASSERT(false);
-}
-
-//////////////////////////////////////////////////////////////////////
-// NewSocketPool
-//////////////////////////////////////////////////////////////////////
-
-NewSocketPool::NewSocketPool(SocketFactory* factory) : factory_(factory) {
-}
-
-NewSocketPool::~NewSocketPool() {
-}
-
-StreamInterface*
-NewSocketPool::RequestConnectedStream(const SocketAddress& remote, int* err) {
- AsyncSocket* socket =
- factory_->CreateAsyncSocket(remote.family(), SOCK_STREAM);
- if (!socket) {
- if (err)
- *err = -1;
- return NULL;
- }
- if ((socket->Connect(remote) != 0) && !socket->IsBlocking()) {
- if (err)
- *err = socket->GetError();
- delete socket;
- return NULL;
- }
- if (err)
- *err = 0;
- return new SocketStream(socket);
-}
-
-void
-NewSocketPool::ReturnConnectedStream(StreamInterface* stream) {
- Thread::Current()->Dispose(stream);
-}
-
-//////////////////////////////////////////////////////////////////////
-// ReuseSocketPool
-//////////////////////////////////////////////////////////////////////
-
-ReuseSocketPool::ReuseSocketPool(SocketFactory* factory)
-: factory_(factory), stream_(NULL), checked_out_(false) {
-}
-
-ReuseSocketPool::~ReuseSocketPool() {
- ASSERT(!checked_out_);
- delete stream_;
-}
-
-StreamInterface*
-ReuseSocketPool::RequestConnectedStream(const SocketAddress& remote, int* err) {
- // Only one socket can be used from this "pool" at a time
- ASSERT(!checked_out_);
- if (!stream_) {
- LOG_F(LS_VERBOSE) << "Creating new socket";
- int family = remote.family();
- // TODO: Deal with this when we/I clean up DNS resolution.
- if (remote.IsUnresolvedIP()) {
- family = AF_INET;
- }
- AsyncSocket* socket =
- factory_->CreateAsyncSocket(family, SOCK_STREAM);
- if (!socket) {
- if (err)
- *err = -1;
- return NULL;
- }
- stream_ = new SocketStream(socket);
- }
- if ((stream_->GetState() == SS_OPEN) && (remote == remote_)) {
- LOG_F(LS_VERBOSE) << "Reusing connection to: " << remote_;
- } else {
- remote_ = remote;
- stream_->Close();
- if ((stream_->GetSocket()->Connect(remote_) != 0)
- && !stream_->GetSocket()->IsBlocking()) {
- if (err)
- *err = stream_->GetSocket()->GetError();
- return NULL;
- } else {
- LOG_F(LS_VERBOSE) << "Opening connection to: " << remote_;
- }
- }
- stream_->SignalEvent.disconnect(this);
- checked_out_ = true;
- if (err)
- *err = 0;
- return stream_;
-}
-
-void
-ReuseSocketPool::ReturnConnectedStream(StreamInterface* stream) {
- ASSERT(stream == stream_);
- ASSERT(checked_out_);
- checked_out_ = false;
- // Until the socket is reused, monitor it to determine if it closes.
- stream_->SignalEvent.connect(this, &ReuseSocketPool::OnStreamEvent);
-}
-
-void
-ReuseSocketPool::OnStreamEvent(StreamInterface* stream, int events, int err) {
- ASSERT(stream == stream_);
- ASSERT(!checked_out_);
-
- // If the stream was written to and then immediately returned to us then
- // we may get a writable notification for it, which we should ignore.
- if (events == SE_WRITE) {
- LOG_F(LS_VERBOSE) << "Pooled Socket unexpectedly writable: ignoring";
- return;
- }
-
- // If the peer sent data, we can't process it, so drop the connection.
- // If the socket has closed, clean it up.
- // In either case, we'll reconnect it the next time it is used.
- ASSERT(0 != (events & (SE_READ|SE_CLOSE)));
- if (0 != (events & SE_CLOSE)) {
- LOG_F(LS_VERBOSE) << "Connection closed with error: " << err;
- } else {
- LOG_F(LS_VERBOSE) << "Pooled Socket unexpectedly readable: closing";
- }
- stream_->Close();
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// LoggingPoolAdapter - Adapts a StreamPool to supply streams with attached
-// LoggingAdapters.
-///////////////////////////////////////////////////////////////////////////////
-
-LoggingPoolAdapter::LoggingPoolAdapter(
- StreamPool* pool, LoggingSeverity level, const std::string& label,
- bool binary_mode)
- : pool_(pool), level_(level), label_(label), binary_mode_(binary_mode) {
-}
-
-LoggingPoolAdapter::~LoggingPoolAdapter() {
- for (StreamList::iterator it = recycle_bin_.begin();
- it != recycle_bin_.end(); ++it) {
- delete *it;
- }
-}
-
-StreamInterface* LoggingPoolAdapter::RequestConnectedStream(
- const SocketAddress& remote, int* err) {
- if (StreamInterface* stream = pool_->RequestConnectedStream(remote, err)) {
- ASSERT(SS_CLOSED != stream->GetState());
- std::stringstream ss;
- ss << label_ << "(0x" << std::setfill('0') << std::hex << std::setw(8)
- << stream << ")";
- LOG_V(level_) << ss.str()
- << ((SS_OPEN == stream->GetState()) ? " Connected"
- : " Connecting")
- << " to " << remote;
- if (recycle_bin_.empty()) {
- return new LoggingAdapter(stream, level_, ss.str(), binary_mode_);
- }
- LoggingAdapter* logging = recycle_bin_.front();
- recycle_bin_.pop_front();
- logging->set_label(ss.str());
- logging->Attach(stream);
- return logging;
- }
- return NULL;
-}
-
-void LoggingPoolAdapter::ReturnConnectedStream(StreamInterface* stream) {
- LoggingAdapter* logging = static_cast<LoggingAdapter*>(stream);
- pool_->ReturnConnectedStream(logging->Detach());
- recycle_bin_.push_back(logging);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/socketpool.h b/base/socketpool.h
deleted file mode 100644
index 847d8ff..0000000
--- a/base/socketpool.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKETPOOL_H_
-#define TALK_BASE_SOCKETPOOL_H_
-
-#include <deque>
-#include <list>
-#include "talk/base/logging.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socketaddress.h"
-
-namespace talk_base {
-
-class AsyncSocket;
-class LoggingAdapter;
-class SocketFactory;
-class SocketStream;
-class StreamInterface;
-
-//////////////////////////////////////////////////////////////////////
-// StreamPool
-//////////////////////////////////////////////////////////////////////
-
-class StreamPool {
-public:
- virtual ~StreamPool() { }
-
- virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote,
- int* err) = 0;
- virtual void ReturnConnectedStream(StreamInterface* stream) = 0;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamCache - Caches a set of open streams, defers creation/destruction to
-// the supplied StreamPool.
-///////////////////////////////////////////////////////////////////////////////
-
-class StreamCache : public StreamPool, public sigslot::has_slots<> {
-public:
- StreamCache(StreamPool* pool);
- virtual ~StreamCache();
-
- // StreamPool Interface
- virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote,
- int* err);
- virtual void ReturnConnectedStream(StreamInterface* stream);
-
-private:
- typedef std::pair<SocketAddress, StreamInterface*> ConnectedStream;
- typedef std::list<ConnectedStream> ConnectedList;
-
- void OnStreamEvent(StreamInterface* stream, int events, int err);
-
- // We delegate stream creation and deletion to this pool.
- StreamPool* pool_;
- // Streams that are in use (returned from RequestConnectedStream).
- ConnectedList active_;
- // Streams which were returned to us, but are still open.
- ConnectedList cached_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// NewSocketPool
-// Creates a new stream on every request
-///////////////////////////////////////////////////////////////////////////////
-
-class NewSocketPool : public StreamPool {
-public:
- NewSocketPool(SocketFactory* factory);
- virtual ~NewSocketPool();
-
- // StreamPool Interface
- virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote,
- int* err);
- virtual void ReturnConnectedStream(StreamInterface* stream);
-
-private:
- SocketFactory* factory_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// ReuseSocketPool
-// Maintains a single socket at a time, and will reuse it without closing if
-// the destination address is the same.
-///////////////////////////////////////////////////////////////////////////////
-
-class ReuseSocketPool : public StreamPool, public sigslot::has_slots<> {
-public:
- ReuseSocketPool(SocketFactory* factory);
- virtual ~ReuseSocketPool();
-
- // StreamPool Interface
- virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote,
- int* err);
- virtual void ReturnConnectedStream(StreamInterface* stream);
-
-private:
- void OnStreamEvent(StreamInterface* stream, int events, int err);
-
- SocketFactory* factory_;
- SocketStream* stream_;
- SocketAddress remote_;
- bool checked_out_; // Whether the stream is currently checked out
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// LoggingPoolAdapter - Adapts a StreamPool to supply streams with attached
-// LoggingAdapters.
-///////////////////////////////////////////////////////////////////////////////
-
-class LoggingPoolAdapter : public StreamPool {
-public:
- LoggingPoolAdapter(StreamPool* pool, LoggingSeverity level,
- const std::string& label, bool binary_mode);
- virtual ~LoggingPoolAdapter();
-
- // StreamPool Interface
- virtual StreamInterface* RequestConnectedStream(const SocketAddress& remote,
- int* err);
- virtual void ReturnConnectedStream(StreamInterface* stream);
-
-private:
- StreamPool* pool_;
- LoggingSeverity level_;
- std::string label_;
- bool binary_mode_;
- typedef std::deque<LoggingAdapter*> StreamList;
- StreamList recycle_bin_;
-};
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKETPOOL_H_
diff --git a/base/socketserver.h b/base/socketserver.h
deleted file mode 100644
index 151ce61..0000000
--- a/base/socketserver.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKETSERVER_H_
-#define TALK_BASE_SOCKETSERVER_H_
-
-#include "talk/base/socketfactory.h"
-
-namespace talk_base {
-
-class MessageQueue;
-
-// Provides the ability to wait for activity on a set of sockets. The Thread
-// class provides a nice wrapper on a socket server.
-//
-// The server is also a socket factory. The sockets it creates will be
-// notified of asynchronous I/O from this server's Wait method.
-class SocketServer : public SocketFactory {
- public:
- // When the socket server is installed into a Thread, this function is
- // called to allow the socket server to use the thread's message queue for
- // any messaging that it might need to perform.
- virtual void SetMessageQueue(MessageQueue* queue) {}
-
- // Sleeps until:
- // 1) cms milliseconds have elapsed (unless cms == kForever)
- // 2) WakeUp() is called
- // While sleeping, I/O is performed if process_io is true.
- virtual bool Wait(int cms, bool process_io) = 0;
-
- // Causes the current wait (if one is in progress) to wake up.
- virtual void WakeUp() = 0;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKETSERVER_H_
diff --git a/base/socketstream.cc b/base/socketstream.cc
deleted file mode 100644
index 3dc5a95..0000000
--- a/base/socketstream.cc
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/socketstream.h"
-
-namespace talk_base {
-
-SocketStream::SocketStream(AsyncSocket* socket) : socket_(NULL) {
- Attach(socket);
-}
-
-SocketStream::~SocketStream() {
- delete socket_;
-}
-
-void SocketStream::Attach(AsyncSocket* socket) {
- if (socket_)
- delete socket_;
- socket_ = socket;
- if (socket_) {
- socket_->SignalConnectEvent.connect(this, &SocketStream::OnConnectEvent);
- socket_->SignalReadEvent.connect(this, &SocketStream::OnReadEvent);
- socket_->SignalWriteEvent.connect(this, &SocketStream::OnWriteEvent);
- socket_->SignalCloseEvent.connect(this, &SocketStream::OnCloseEvent);
- }
-}
-
-AsyncSocket* SocketStream::Detach() {
- AsyncSocket* socket = socket_;
- if (socket_) {
- socket_->SignalConnectEvent.disconnect(this);
- socket_->SignalReadEvent.disconnect(this);
- socket_->SignalWriteEvent.disconnect(this);
- socket_->SignalCloseEvent.disconnect(this);
- socket_ = NULL;
- }
- return socket;
-}
-
-StreamState SocketStream::GetState() const {
- ASSERT(socket_ != NULL);
- switch (socket_->GetState()) {
- case Socket::CS_CONNECTED:
- return SS_OPEN;
- case Socket::CS_CONNECTING:
- return SS_OPENING;
- case Socket::CS_CLOSED:
- default:
- return SS_CLOSED;
- }
-}
-
-StreamResult SocketStream::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- ASSERT(socket_ != NULL);
- int result = socket_->Recv(buffer, buffer_len);
- if (result < 0) {
- if (socket_->IsBlocking())
- return SR_BLOCK;
- if (error)
- *error = socket_->GetError();
- return SR_ERROR;
- }
- if ((result > 0) || (buffer_len == 0)) {
- if (read)
- *read = result;
- return SR_SUCCESS;
- }
- return SR_EOS;
-}
-
-StreamResult SocketStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- ASSERT(socket_ != NULL);
- int result = socket_->Send(data, data_len);
- if (result < 0) {
- if (socket_->IsBlocking())
- return SR_BLOCK;
- if (error)
- *error = socket_->GetError();
- return SR_ERROR;
- }
- if (written)
- *written = result;
- return SR_SUCCESS;
-}
-
-void SocketStream::Close() {
- ASSERT(socket_ != NULL);
- socket_->Close();
-}
-
-void SocketStream::OnConnectEvent(AsyncSocket* socket) {
- ASSERT(socket == socket_);
- SignalEvent(this, SE_OPEN | SE_READ | SE_WRITE, 0);
-}
-
-void SocketStream::OnReadEvent(AsyncSocket* socket) {
- ASSERT(socket == socket_);
- SignalEvent(this, SE_READ, 0);
-}
-
-void SocketStream::OnWriteEvent(AsyncSocket* socket) {
- ASSERT(socket == socket_);
- SignalEvent(this, SE_WRITE, 0);
-}
-
-void SocketStream::OnCloseEvent(AsyncSocket* socket, int err) {
- ASSERT(socket == socket_);
- SignalEvent(this, SE_CLOSE, err);
-}
-
-
-} // namespace talk_base
diff --git a/base/socketstream.h b/base/socketstream.h
deleted file mode 100644
index 591dc4c..0000000
--- a/base/socketstream.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * libjingle
- * Copyright 2005--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SOCKETSTREAM_H_
-#define TALK_BASE_SOCKETSTREAM_H_
-
-#include "talk/base/asyncsocket.h"
-#include "talk/base/common.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-class SocketStream : public StreamInterface, public sigslot::has_slots<> {
- public:
- explicit SocketStream(AsyncSocket* socket);
- virtual ~SocketStream();
-
- void Attach(AsyncSocket* socket);
- AsyncSocket* Detach();
-
- AsyncSocket* GetSocket() { return socket_; }
-
- virtual StreamState GetState() const;
-
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
-
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
-
- virtual void Close();
-
- private:
- void OnConnectEvent(AsyncSocket* socket);
- void OnReadEvent(AsyncSocket* socket);
- void OnWriteEvent(AsyncSocket* socket);
- void OnCloseEvent(AsyncSocket* socket, int err);
-
- AsyncSocket* socket_;
-
- DISALLOW_EVIL_CONSTRUCTORS(SocketStream);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SOCKETSTREAM_H_
diff --git a/base/ssladapter.cc b/base/ssladapter.cc
deleted file mode 100644
index 5bcb619..0000000
--- a/base/ssladapter.cc
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#include "talk/base/ssladapter.h"
-
-#include "talk/base/sslconfig.h"
-
-#if SSL_USE_SCHANNEL
-
-#include "schanneladapter.h"
-
-#elif SSL_USE_OPENSSL // && !SSL_USE_SCHANNEL
-
-#include "openssladapter.h"
-
-#elif SSL_USE_NSS // && !SSL_USE_CHANNEL && !SSL_USE_OPENSSL
-
-#include "nssstreamadapter.h"
-
-#endif // SSL_USE_OPENSSL && !SSL_USE_SCHANNEL && !SSL_USE_NSS
-
-///////////////////////////////////////////////////////////////////////////////
-
-namespace talk_base {
-
-SSLAdapter*
-SSLAdapter::Create(AsyncSocket* socket) {
-#if SSL_USE_SCHANNEL
- return new SChannelAdapter(socket);
-#elif SSL_USE_OPENSSL // && !SSL_USE_SCHANNEL
- return new OpenSSLAdapter(socket);
-#else // !SSL_USE_OPENSSL && !SSL_USE_SCHANNEL
- delete socket;
- return NULL;
-#endif // !SSL_USE_OPENSSL && !SSL_USE_SCHANNEL
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-#if SSL_USE_OPENSSL
-
-bool InitializeSSL(VerificationCallback callback) {
- return OpenSSLAdapter::InitializeSSL(callback);
-}
-
-bool InitializeSSLThread() {
- return OpenSSLAdapter::InitializeSSLThread();
-}
-
-bool CleanupSSL() {
- return OpenSSLAdapter::CleanupSSL();
-}
-
-#elif SSL_USE_NSS // !SSL_USE_OPENSSL
-
-bool InitializeSSL(VerificationCallback callback) {
- return NSSContext::InitializeSSL(callback);
-}
-
-bool InitializeSSLThread() {
- return NSSContext::InitializeSSLThread();
-}
-
-bool CleanupSSL() {
- return NSSContext::CleanupSSL();
-}
-
-#else // !SSL_USE_OPENSSL && !SSL_USE_NSS
-
-bool InitializeSSL(VerificationCallback callback) {
- return true;
-}
-
-bool InitializeSSLThread() {
- return true;
-}
-
-bool CleanupSSL() {
- return true;
-}
-
-#endif // !SSL_USE_OPENSSL && !SSL_USE_NSS
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/ssladapter.h b/base/ssladapter.h
deleted file mode 100644
index 4d2dbcd..0000000
--- a/base/ssladapter.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SSLADAPTER_H_
-#define TALK_BASE_SSLADAPTER_H_
-
-#include "talk/base/asyncsocket.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-class SSLAdapter : public AsyncSocketAdapter {
- public:
- explicit SSLAdapter(AsyncSocket* socket)
- : AsyncSocketAdapter(socket), ignore_bad_cert_(false) { }
-
- bool ignore_bad_cert() const { return ignore_bad_cert_; }
- void set_ignore_bad_cert(bool ignore) { ignore_bad_cert_ = ignore; }
-
- // StartSSL returns 0 if successful.
- // If StartSSL is called while the socket is closed or connecting, the SSL
- // negotiation will begin as soon as the socket connects.
- virtual int StartSSL(const char* hostname, bool restartable) = 0;
-
- // Create the default SSL adapter for this platform. On failure, returns NULL
- // and deletes |socket|. Otherwise, the returned SSLAdapter takes ownership
- // of |socket|.
- static SSLAdapter* Create(AsyncSocket* socket);
-
- private:
- // If true, the server certificate need not match the configured hostname.
- bool ignore_bad_cert_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-typedef bool (*VerificationCallback)(void* cert);
-
-// Call this on the main thread, before using SSL.
-// Call CleanupSSLThread when finished with SSL.
-bool InitializeSSL(VerificationCallback callback = NULL);
-
-// Call to initialize additional threads.
-bool InitializeSSLThread();
-
-// Call to cleanup additional threads, and also the main thread.
-bool CleanupSSL();
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SSLADAPTER_H_
diff --git a/base/sslconfig.h b/base/sslconfig.h
deleted file mode 100644
index cc3a733..0000000
--- a/base/sslconfig.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SSLCONFIG_H_
-#define TALK_BASE_SSLCONFIG_H_
-
-// If no preference has been indicated, default to SChannel on Windows and
-// OpenSSL everywhere else, if it is available.
-#if !defined(SSL_USE_SCHANNEL) && !defined(SSL_USE_OPENSSL) && \
- !defined(SSL_USE_NSS)
-#if defined(WIN32)
-
-#define SSL_USE_SCHANNEL 1
-
-#else // defined(WIN32)
-
-#if defined(HAVE_OPENSSL_SSL_H)
-#define SSL_USE_OPENSSL 1
-#elif defined(HAVE_NSS_SSL_H)
-#define SSL_USE_NSS 1
-#endif
-
-#endif // !defined(WIN32)
-#endif
-
-#endif // TALK_BASE_SSLCONFIG_H_
diff --git a/base/sslfingerprint.cc b/base/sslfingerprint.cc
deleted file mode 100644
index dfd5551..0000000
--- a/base/sslfingerprint.cc
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- * Copyright 2012, RTFM Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/sslfingerprint.h"
-
-#include <ctype.h>
-#include <string>
-
-#include "talk/base/helpers.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/stringencode.h"
-
-namespace talk_base {
-
-SSLFingerprint* SSLFingerprint::Create(
- const std::string& algorithm, const talk_base::SSLIdentity* identity) {
- if (!identity) {
- return NULL;
- }
-
- return Create(algorithm, &(identity->certificate()));
-}
-
-SSLFingerprint* SSLFingerprint::Create(
- const std::string& algorithm, const talk_base::SSLCertificate* cert) {
- uint8 digest_val[64];
- size_t digest_len;
- bool ret = cert->ComputeDigest(
- algorithm, digest_val, sizeof(digest_val), &digest_len);
- if (!ret) {
- return NULL;
- }
-
- return new SSLFingerprint(algorithm, digest_val, digest_len);
-}
-
-SSLFingerprint* SSLFingerprint::CreateFromRfc4572(
- const std::string& algorithm, const std::string& fingerprint) {
- if (algorithm.empty() || !talk_base::IsFips180DigestAlgorithm(algorithm))
- return NULL;
-
- if (fingerprint.empty())
- return NULL;
-
- size_t value_len;
- char value[talk_base::MessageDigest::kMaxSize];
- value_len = talk_base::hex_decode_with_delimiter(value, sizeof(value),
- fingerprint.c_str(),
- fingerprint.length(),
- ':');
- if (!value_len)
- return NULL;
-
- return new SSLFingerprint(algorithm,
- reinterpret_cast<uint8*>(value),
- value_len);
-}
-
-SSLFingerprint::SSLFingerprint(
- const std::string& algorithm, const uint8* digest_in, size_t digest_len)
- : algorithm(algorithm) {
- digest.SetData(digest_in, digest_len);
-}
-
-SSLFingerprint::SSLFingerprint(const SSLFingerprint& from)
- : algorithm(from.algorithm), digest(from.digest) {}
-
-bool SSLFingerprint::operator==(const SSLFingerprint& other) const {
- return algorithm == other.algorithm &&
- digest == other.digest;
-}
-
-std::string SSLFingerprint::GetRfc4572Fingerprint() const {
- std::string fingerprint =
- talk_base::hex_encode_with_delimiter(
- digest.data(), digest.length(), ':');
- std::transform(fingerprint.begin(), fingerprint.end(),
- fingerprint.begin(), ::toupper);
- return fingerprint;
-}
-
-std::string SSLFingerprint::ToString() {
- std::string fp_str = algorithm;
- fp_str.append(" ");
- fp_str.append(GetRfc4572Fingerprint());
- return fp_str;
-}
-
-} // namespace talk_base
diff --git a/base/sslfingerprint.h b/base/sslfingerprint.h
deleted file mode 100644
index a803d21..0000000
--- a/base/sslfingerprint.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * libjingle
- * Copyright 2012, Google Inc.
- * Copyright 2012, RTFM Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SSLFINGERPRINT_H_
-#define TALK_BASE_SSLFINGERPRINT_H_
-
-#include <string>
-
-#include "talk/base/buffer.h"
-#include "talk/base/sslidentity.h"
-
-namespace talk_base {
-
-class SSLCertificate;
-
-struct SSLFingerprint {
- static SSLFingerprint* Create(const std::string& algorithm,
- const talk_base::SSLIdentity* identity);
-
- static SSLFingerprint* Create(const std::string& algorithm,
- const talk_base::SSLCertificate* cert);
-
- static SSLFingerprint* CreateFromRfc4572(const std::string& algorithm,
- const std::string& fingerprint);
-
- SSLFingerprint(const std::string& algorithm, const uint8* digest_in,
- size_t digest_len);
-
- SSLFingerprint(const SSLFingerprint& from);
-
- bool operator==(const SSLFingerprint& other) const;
-
- std::string GetRfc4572Fingerprint() const;
-
- std::string ToString();
-
- std::string algorithm;
- talk_base::Buffer digest;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SSLFINGERPRINT_H_
diff --git a/base/sslidentity.cc b/base/sslidentity.cc
deleted file mode 100644
index d2d2b11..0000000
--- a/base/sslidentity.cc
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Handling of certificates and keypairs for SSLStreamAdapter's peer mode.
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#include "talk/base/sslidentity.h"
-
-#include <string>
-
-#include "talk/base/base64.h"
-#include "talk/base/logging.h"
-#include "talk/base/sslconfig.h"
-
-#if SSL_USE_SCHANNEL
-
-#elif SSL_USE_OPENSSL // !SSL_USE_SCHANNEL
-
-#include "talk/base/opensslidentity.h"
-
-#elif SSL_USE_NSS // !SSL_USE_SCHANNEL && !SSL_USE_OPENSSL
-
-#include "talk/base/nssidentity.h"
-
-#endif // SSL_USE_SCHANNEL
-
-namespace talk_base {
-
-const char kPemTypeCertificate[] = "CERTIFICATE";
-const char kPemTypeRsaPrivateKey[] = "RSA PRIVATE KEY";
-
-bool SSLIdentity::PemToDer(const std::string& pem_type,
- const std::string& pem_string,
- std::string* der) {
- // Find the inner body. We need this to fulfill the contract of
- // returning pem_length.
- size_t header = pem_string.find("-----BEGIN " + pem_type + "-----");
- if (header == std::string::npos)
- return false;
-
- size_t body = pem_string.find("\n", header);
- if (body == std::string::npos)
- return false;
-
- size_t trailer = pem_string.find("-----END " + pem_type + "-----");
- if (trailer == std::string::npos)
- return false;
-
- std::string inner = pem_string.substr(body + 1, trailer - (body + 1));
-
- *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE |
- Base64::DO_PAD_ANY |
- Base64::DO_TERM_BUFFER);
- return true;
-}
-
-std::string SSLIdentity::DerToPem(const std::string& pem_type,
- const unsigned char* data,
- size_t length) {
- std::stringstream result;
-
- result << "-----BEGIN " << pem_type << "-----\n";
-
- std::string b64_encoded;
- Base64::EncodeFromArray(data, length, &b64_encoded);
-
- // Divide the Base-64 encoded data into 64-character chunks, as per
- // 4.3.2.4 of RFC 1421.
- static const size_t kChunkSize = 64;
- size_t chunks = (b64_encoded.size() + (kChunkSize - 1)) / kChunkSize;
- for (size_t i = 0, chunk_offset = 0; i < chunks;
- ++i, chunk_offset += kChunkSize) {
- result << b64_encoded.substr(chunk_offset, kChunkSize);
- result << "\n";
- }
-
- result << "-----END " << pem_type << "-----\n";
-
- return result.str();
-}
-
-#if SSL_USE_SCHANNEL
-
-SSLCertificate* SSLCertificate::FromPEMString(const std::string& pem_string) {
- return NULL;
-}
-
-SSLIdentity* SSLIdentity::Generate(const std::string& common_name) {
- return NULL;
-}
-
-SSLIdentity* GenerateForTest(const SSLIdentityParams& params) {
- return NULL;
-}
-
-SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key,
- const std::string& certificate) {
- return NULL;
-}
-
-#elif SSL_USE_OPENSSL // !SSL_USE_SCHANNEL
-
-SSLCertificate* SSLCertificate::FromPEMString(const std::string& pem_string) {
- return OpenSSLCertificate::FromPEMString(pem_string);
-}
-
-SSLIdentity* SSLIdentity::Generate(const std::string& common_name) {
- return OpenSSLIdentity::Generate(common_name);
-}
-
-SSLIdentity* SSLIdentity::GenerateForTest(const SSLIdentityParams& params) {
- return OpenSSLIdentity::GenerateForTest(params);
-}
-
-SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key,
- const std::string& certificate) {
- return OpenSSLIdentity::FromPEMStrings(private_key, certificate);
-}
-
-#elif SSL_USE_NSS // !SSL_USE_OPENSSL && !SSL_USE_SCHANNEL
-
-SSLCertificate* SSLCertificate::FromPEMString(const std::string& pem_string) {
- return NSSCertificate::FromPEMString(pem_string);
-}
-
-SSLIdentity* SSLIdentity::Generate(const std::string& common_name) {
- return NSSIdentity::Generate(common_name);
-}
-
-SSLIdentity* SSLIdentity::GenerateForTest(const SSLIdentityParams& params) {
- return NSSIdentity::GenerateForTest(params);
-}
-
-SSLIdentity* SSLIdentity::FromPEMStrings(const std::string& private_key,
- const std::string& certificate) {
- return NSSIdentity::FromPEMStrings(private_key, certificate);
-}
-
-#else // !SSL_USE_OPENSSL && !SSL_USE_SCHANNEL && !SSL_USE_NSS
-
-#error "No SSL implementation"
-
-#endif // SSL_USE_SCHANNEL
-
-} // namespace talk_base
diff --git a/base/sslidentity.h b/base/sslidentity.h
deleted file mode 100644
index b930f06..0000000
--- a/base/sslidentity.h
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Handling of certificates and keypairs for SSLStreamAdapter's peer mode.
-
-#ifndef TALK_BASE_SSLIDENTITY_H_
-#define TALK_BASE_SSLIDENTITY_H_
-
-#include <algorithm>
-#include <string>
-#include <vector>
-
-#include "talk/base/buffer.h"
-#include "talk/base/messagedigest.h"
-
-namespace talk_base {
-
-// Forward declaration due to circular dependency with SSLCertificate.
-class SSLCertChain;
-
-// Abstract interface overridden by SSL library specific
-// implementations.
-
-// A somewhat opaque type used to encapsulate a certificate.
-// Wraps the SSL library's notion of a certificate, with reference counting.
-// The SSLCertificate object is pretty much immutable once created.
-// (The OpenSSL implementation only does reference counting and
-// possibly caching of intermediate results.)
-class SSLCertificate {
- public:
- // Parses and build a certificate from a PEM encoded string.
- // Returns NULL on failure.
- // The length of the string representation of the certificate is
- // stored in *pem_length if it is non-NULL, and only if
- // parsing was successful.
- // Caller is responsible for freeing the returned object.
- static SSLCertificate* FromPEMString(const std::string& pem_string);
- virtual ~SSLCertificate() {}
-
- // Returns a new SSLCertificate object instance wrapping the same
- // underlying certificate, including its chain if present.
- // Caller is responsible for freeing the returned object.
- virtual SSLCertificate* GetReference() const = 0;
-
- // Provides the cert chain, or returns false. The caller owns the chain.
- // The chain includes a copy of each certificate, excluding the leaf.
- virtual bool GetChain(SSLCertChain** chain) const = 0;
-
- // Returns a PEM encoded string representation of the certificate.
- virtual std::string ToPEMString() const = 0;
-
- // Provides a DER encoded binary representation of the certificate.
- virtual void ToDER(Buffer* der_buffer) const = 0;
-
- // Gets the name of the digest algorithm that was used to compute this
- // certificate's signature.
- virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0;
-
- // Compute the digest of the certificate given algorithm
- virtual bool ComputeDigest(const std::string& algorithm,
- unsigned char* digest,
- size_t size,
- size_t* length) const = 0;
-};
-
-// SSLCertChain is a simple wrapper for a vector of SSLCertificates. It serves
-// primarily to ensure proper memory management (especially deletion) of the
-// SSLCertificate pointers.
-class SSLCertChain {
- public:
- // These constructors copy the provided SSLCertificate(s), so the caller
- // retains ownership.
- explicit SSLCertChain(const std::vector<SSLCertificate*>& certs) {
- ASSERT(!certs.empty());
- certs_.resize(certs.size());
- std::transform(certs.begin(), certs.end(), certs_.begin(), DupCert);
- }
- explicit SSLCertChain(const SSLCertificate* cert) {
- certs_.push_back(cert->GetReference());
- }
-
- ~SSLCertChain() {
- std::for_each(certs_.begin(), certs_.end(), DeleteCert);
- }
-
- // Vector access methods.
- size_t GetSize() const { return certs_.size(); }
-
- // Returns a temporary reference, only valid until the chain is destroyed.
- const SSLCertificate& Get(size_t pos) const { return *(certs_[pos]); }
-
- // Returns a new SSLCertChain object instance wrapping the same underlying
- // certificate chain. Caller is responsible for freeing the returned object.
- SSLCertChain* Copy() const {
- return new SSLCertChain(certs_);
- }
-
- private:
- // Helper function for duplicating a vector of certificates.
- static SSLCertificate* DupCert(const SSLCertificate* cert) {
- return cert->GetReference();
- }
-
- // Helper function for deleting a vector of certificates.
- static void DeleteCert(SSLCertificate* cert) { delete cert; }
-
- std::vector<SSLCertificate*> certs_;
-
- DISALLOW_COPY_AND_ASSIGN(SSLCertChain);
-};
-
-// Parameters for generating an identity for testing. If common_name is
-// non-empty, it will be used for the certificate's subject and issuer name,
-// otherwise a random string will be used. |not_before| and |not_after| are
-// offsets to the current time in number of seconds.
-struct SSLIdentityParams {
- std::string common_name;
- int not_before; // in seconds.
- int not_after; // in seconds.
-};
-
-// Our identity in an SSL negotiation: a keypair and certificate (both
-// with the same public key).
-// This too is pretty much immutable once created.
-class SSLIdentity {
- public:
- // Generates an identity (keypair and self-signed certificate). If
- // common_name is non-empty, it will be used for the certificate's
- // subject and issuer name, otherwise a random string will be used.
- // Returns NULL on failure.
- // Caller is responsible for freeing the returned object.
- static SSLIdentity* Generate(const std::string& common_name);
-
- // Generates an identity with the specified validity period.
- static SSLIdentity* GenerateForTest(const SSLIdentityParams& params);
-
- // Construct an identity from a private key and a certificate.
- static SSLIdentity* FromPEMStrings(const std::string& private_key,
- const std::string& certificate);
-
- virtual ~SSLIdentity() {}
-
- // Returns a new SSLIdentity object instance wrapping the same
- // identity information.
- // Caller is responsible for freeing the returned object.
- virtual SSLIdentity* GetReference() const = 0;
-
- // Returns a temporary reference to the certificate.
- virtual const SSLCertificate& certificate() const = 0;
-
- // Helpers for parsing converting between PEM and DER format.
- static bool PemToDer(const std::string& pem_type,
- const std::string& pem_string,
- std::string* der);
- static std::string DerToPem(const std::string& pem_type,
- const unsigned char* data,
- size_t length);
-};
-
-extern const char kPemTypeCertificate[];
-extern const char kPemTypeRsaPrivateKey[];
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SSLIDENTITY_H_
diff --git a/base/sslidentity_unittest.cc b/base/sslidentity_unittest.cc
deleted file mode 100644
index fdb165c..0000000
--- a/base/sslidentity_unittest.cc
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- * Portions Copyright 2011, RTFM, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/gunit.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslidentity.h"
-
-using talk_base::SSLIdentity;
-
-const char kTestCertificate[] = "-----BEGIN CERTIFICATE-----\n"
- "MIIB6TCCAVICAQYwDQYJKoZIhvcNAQEEBQAwWzELMAkGA1UEBhMCQVUxEzARBgNV\n"
- "BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMRswGQYD\n"
- "VQQDExJUZXN0IENBICgxMDI0IGJpdCkwHhcNMDAxMDE2MjIzMTAzWhcNMDMwMTE0\n"
- "MjIzMTAzWjBjMQswCQYDVQQGEwJBVTETMBEGA1UECBMKUXVlZW5zbGFuZDEaMBgG\n"
- "A1UEChMRQ3J5cHRTb2Z0IFB0eSBMdGQxIzAhBgNVBAMTGlNlcnZlciB0ZXN0IGNl\n"
- "cnQgKDUxMiBiaXQpMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ+zw4Qnlf8SMVIP\n"
- "Fe9GEcStgOY2Ww/dgNdhjeD8ckUJNP5VZkVDTGiXav6ooKXfX3j/7tdkuD8Ey2//\n"
- "Kv7+ue0CAwEAATANBgkqhkiG9w0BAQQFAAOBgQCT0grFQeZaqYb5EYfk20XixZV4\n"
- "GmyAbXMftG1Eo7qGiMhYzRwGNWxEYojf5PZkYZXvSqZ/ZXHXa4g59jK/rJNnaVGM\n"
- "k+xIX8mxQvlV0n5O9PIha5BX5teZnkHKgL8aKKLKW1BK7YTngsfSzzaeame5iKfz\n"
- "itAE+OjGF+PFKbwX8Q==\n"
- "-----END CERTIFICATE-----\n";
-
-const unsigned char kTestCertSha1[] = {0xA6, 0xC8, 0x59, 0xEA,
- 0xC3, 0x7E, 0x6D, 0x33,
- 0xCF, 0xE2, 0x69, 0x9D,
- 0x74, 0xE6, 0xF6, 0x8A,
- 0x9E, 0x47, 0xA7, 0xCA};
-
-class SSLIdentityTest : public testing::Test {
- public:
- SSLIdentityTest() :
- identity1_(), identity2_() {
- }
-
- ~SSLIdentityTest() {
- }
-
- static void SetUpTestCase() {
- talk_base::InitializeSSL();
- }
-
- static void TearDownTestCase() {
- talk_base::CleanupSSL();
- }
-
- virtual void SetUp() {
- identity1_.reset(SSLIdentity::Generate("test1"));
- identity2_.reset(SSLIdentity::Generate("test2"));
-
- ASSERT_TRUE(identity1_);
- ASSERT_TRUE(identity2_);
-
- test_cert_.reset(
- talk_base::SSLCertificate::FromPEMString(kTestCertificate));
- ASSERT_TRUE(test_cert_);
- }
-
- void TestGetSignatureDigestAlgorithm() {
- std::string digest_algorithm;
- // Both NSSIdentity::Generate and OpenSSLIdentity::Generate are
- // hard-coded to generate RSA-SHA1 certificates.
- ASSERT_TRUE(identity1_->certificate().GetSignatureDigestAlgorithm(
- &digest_algorithm));
- ASSERT_EQ(talk_base::DIGEST_SHA_1, digest_algorithm);
- ASSERT_TRUE(identity2_->certificate().GetSignatureDigestAlgorithm(
- &digest_algorithm));
- ASSERT_EQ(talk_base::DIGEST_SHA_1, digest_algorithm);
-
- // The test certificate has an MD5-based signature.
- ASSERT_TRUE(test_cert_->GetSignatureDigestAlgorithm(&digest_algorithm));
- ASSERT_EQ(talk_base::DIGEST_MD5, digest_algorithm);
- }
-
- void TestDigest(const std::string &algorithm, size_t expected_len,
- const unsigned char *expected_digest = NULL) {
- unsigned char digest1[64];
- unsigned char digest1b[64];
- unsigned char digest2[64];
- size_t digest1_len;
- size_t digest1b_len;
- size_t digest2_len;
- bool rv;
-
- rv = identity1_->certificate().ComputeDigest(algorithm,
- digest1, sizeof(digest1),
- &digest1_len);
- EXPECT_TRUE(rv);
- EXPECT_EQ(expected_len, digest1_len);
-
- rv = identity1_->certificate().ComputeDigest(algorithm,
- digest1b, sizeof(digest1b),
- &digest1b_len);
- EXPECT_TRUE(rv);
- EXPECT_EQ(expected_len, digest1b_len);
- EXPECT_EQ(0, memcmp(digest1, digest1b, expected_len));
-
-
- rv = identity2_->certificate().ComputeDigest(algorithm,
- digest2, sizeof(digest2),
- &digest2_len);
- EXPECT_TRUE(rv);
- EXPECT_EQ(expected_len, digest2_len);
- EXPECT_NE(0, memcmp(digest1, digest2, expected_len));
-
- // If we have an expected hash for the test cert, check it.
- if (expected_digest) {
- unsigned char digest3[64];
- size_t digest3_len;
-
- rv = test_cert_->ComputeDigest(algorithm, digest3, sizeof(digest3),
- &digest3_len);
- EXPECT_TRUE(rv);
- EXPECT_EQ(expected_len, digest3_len);
- EXPECT_EQ(0, memcmp(digest3, expected_digest, expected_len));
- }
- }
-
- private:
- talk_base::scoped_ptr<SSLIdentity> identity1_;
- talk_base::scoped_ptr<SSLIdentity> identity2_;
- talk_base::scoped_ptr<talk_base::SSLCertificate> test_cert_;
-};
-
-TEST_F(SSLIdentityTest, DigestSHA1) {
- TestDigest(talk_base::DIGEST_SHA_1, 20, kTestCertSha1);
-}
-
-// HASH_AlgSHA224 is not supported in the chromium linux build.
-#if SSL_USE_NSS
-TEST_F(SSLIdentityTest, DISABLED_DigestSHA224) {
-#else
-TEST_F(SSLIdentityTest, DigestSHA224) {
-#endif
- TestDigest(talk_base::DIGEST_SHA_224, 28);
-}
-
-TEST_F(SSLIdentityTest, DigestSHA256) {
- TestDigest(talk_base::DIGEST_SHA_256, 32);
-}
-
-TEST_F(SSLIdentityTest, DigestSHA384) {
- TestDigest(talk_base::DIGEST_SHA_384, 48);
-}
-
-TEST_F(SSLIdentityTest, DigestSHA512) {
- TestDigest(talk_base::DIGEST_SHA_512, 64);
-}
-
-TEST_F(SSLIdentityTest, FromPEMStrings) {
- static const char kRSA_PRIVATE_KEY_PEM[] =
- "-----BEGIN RSA PRIVATE KEY-----\n"
- "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMYRkbhmI7kVA/rM\n"
- "czsZ+6JDhDvnkF+vn6yCAGuRPV03zuRqZtDy4N4to7PZu9PjqrRl7nDMXrG3YG9y\n"
- "rlIAZ72KjcKKFAJxQyAKLCIdawKRyp8RdK3LEySWEZb0AV58IadqPZDTNHHRX8dz\n"
- "5aTSMsbbkZ+C/OzTnbiMqLL/vg6jAgMBAAECgYAvgOs4FJcgvp+TuREx7YtiYVsH\n"
- "mwQPTum2z/8VzWGwR8BBHBvIpVe1MbD/Y4seyI2aco/7UaisatSgJhsU46/9Y4fq\n"
- "2TwXH9QANf4at4d9n/R6rzwpAJOpgwZgKvdQjkfrKTtgLV+/dawvpxUYkRH4JZM1\n"
- "CVGukMfKNrSVH4Ap4QJBAOJmGV1ASPnB4r4nc99at7JuIJmd7fmuVUwUgYi4XgaR\n"
- "WhScBsgYwZ/JoywdyZJgnbcrTDuVcWG56B3vXbhdpMsCQQDf9zeJrjnPZ3Cqm79y\n"
- "kdqANep0uwZciiNiWxsQrCHztywOvbFhdp8iYVFG9EK8DMY41Y5TxUwsHD+67zao\n"
- "ZNqJAkEA1suLUP/GvL8IwuRneQd2tWDqqRQ/Td3qq03hP7e77XtF/buya3Ghclo5\n"
- "54czUR89QyVfJEC6278nzA7n2h1uVQJAcG6mztNL6ja/dKZjYZye2CY44QjSlLo0\n"
- "MTgTSjdfg/28fFn2Jjtqf9Pi/X+50LWI/RcYMC2no606wRk9kyOuIQJBAK6VSAim\n"
- "1pOEjsYQn0X5KEIrz1G3bfCbB848Ime3U2/FWlCHMr6ch8kCZ5d1WUeJD3LbwMNG\n"
- "UCXiYxSsu20QNVw=\n"
- "-----END RSA PRIVATE KEY-----\n";
-
- static const char kCERT_PEM[] =
- "-----BEGIN CERTIFICATE-----\n"
- "MIIBmTCCAQKgAwIBAgIEbzBSAjANBgkqhkiG9w0BAQsFADARMQ8wDQYDVQQDEwZX\n"
- "ZWJSVEMwHhcNMTQwMTAyMTgyNDQ3WhcNMTQwMjAxMTgyNDQ3WjARMQ8wDQYDVQQD\n"
- "EwZXZWJSVEMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMYRkbhmI7kVA/rM\n"
- "czsZ+6JDhDvnkF+vn6yCAGuRPV03zuRqZtDy4N4to7PZu9PjqrRl7nDMXrG3YG9y\n"
- "rlIAZ72KjcKKFAJxQyAKLCIdawKRyp8RdK3LEySWEZb0AV58IadqPZDTNHHRX8dz\n"
- "5aTSMsbbkZ+C/OzTnbiMqLL/vg6jAgMBAAEwDQYJKoZIhvcNAQELBQADgYEAUflI\n"
- "VUe5Krqf5RVa5C3u/UTAOAUJBiDS3VANTCLBxjuMsvqOG0WvaYWP3HYPgrz0jXK2\n"
- "LJE/mGw3MyFHEqi81jh95J+ypl6xKW6Rm8jKLR87gUvCaVYn/Z4/P3AqcQTB7wOv\n"
- "UD0A8qfhfDM+LK6rPAnCsVN0NRDY3jvd6rzix9M=\n"
- "-----END CERTIFICATE-----\n";
-
- talk_base::scoped_ptr<SSLIdentity> identity(
- SSLIdentity::FromPEMStrings(kRSA_PRIVATE_KEY_PEM, kCERT_PEM));
- EXPECT_TRUE(identity);
- EXPECT_EQ(kCERT_PEM, identity->certificate().ToPEMString());
-}
-
-TEST_F(SSLIdentityTest, PemDerConversion) {
- std::string der;
- EXPECT_TRUE(SSLIdentity::PemToDer("CERTIFICATE", kTestCertificate, &der));
-
- EXPECT_EQ(kTestCertificate, SSLIdentity::DerToPem(
- "CERTIFICATE",
- reinterpret_cast<const unsigned char*>(der.data()), der.length()));
-}
-
-TEST_F(SSLIdentityTest, GetSignatureDigestAlgorithm) {
- TestGetSignatureDigestAlgorithm();
-}
diff --git a/base/sslroots.h b/base/sslroots.h
deleted file mode 100644
index 0f983cd..0000000
--- a/base/sslroots.h
+++ /dev/null
@@ -1,4930 +0,0 @@
-// This file is the root certificates in C form that are needed to connect to
-// Google.
-
-// It was generated with the following command line:
-// > python //depot/googleclient/talk/tools/generate_sslroots.py
-// //depot/google3/security/cacerts/for_connecting_to_google/roots.pem
-
-/* subject:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root */
-/* issuer :/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root */
-
-
-const unsigned char AddTrust_External_Root_certificate[1082]={
-0x30,0x82,0x04,0x36,0x30,0x82,0x03,0x1E,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x6F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,0x14,
-0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,0x73,
-0x74,0x20,0x41,0x42,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,0x13,0x1D,0x41,
-0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x45,0x78,0x74,0x65,0x72,0x6E,0x61,0x6C,
-0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x22,0x30,0x20,
-0x06,0x03,0x55,0x04,0x03,0x13,0x19,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,
-0x45,0x78,0x74,0x65,0x72,0x6E,0x61,0x6C,0x20,0x43,0x41,0x20,0x52,0x6F,0x6F,0x74,
-0x30,0x1E,0x17,0x0D,0x30,0x30,0x30,0x35,0x33,0x30,0x31,0x30,0x34,0x38,0x33,0x38,
-0x5A,0x17,0x0D,0x32,0x30,0x30,0x35,0x33,0x30,0x31,0x30,0x34,0x38,0x33,0x38,0x5A,
-0x30,0x6F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,
-0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,
-0x73,0x74,0x20,0x41,0x42,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,0x13,0x1D,
-0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x45,0x78,0x74,0x65,0x72,0x6E,0x61,
-0x6C,0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x22,0x30,
-0x20,0x06,0x03,0x55,0x04,0x03,0x13,0x19,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,
-0x20,0x45,0x78,0x74,0x65,0x72,0x6E,0x61,0x6C,0x20,0x43,0x41,0x20,0x52,0x6F,0x6F,
-0x74,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,
-0x01,0x00,0xB7,0xF7,0x1A,0x33,0xE6,0xF2,0x00,0x04,0x2D,0x39,0xE0,0x4E,0x5B,0xED,
-0x1F,0xBC,0x6C,0x0F,0xCD,0xB5,0xFA,0x23,0xB6,0xCE,0xDE,0x9B,0x11,0x33,0x97,0xA4,
-0x29,0x4C,0x7D,0x93,0x9F,0xBD,0x4A,0xBC,0x93,0xED,0x03,0x1A,0xE3,0x8F,0xCF,0xE5,
-0x6D,0x50,0x5A,0xD6,0x97,0x29,0x94,0x5A,0x80,0xB0,0x49,0x7A,0xDB,0x2E,0x95,0xFD,
-0xB8,0xCA,0xBF,0x37,0x38,0x2D,0x1E,0x3E,0x91,0x41,0xAD,0x70,0x56,0xC7,0xF0,0x4F,
-0x3F,0xE8,0x32,0x9E,0x74,0xCA,0xC8,0x90,0x54,0xE9,0xC6,0x5F,0x0F,0x78,0x9D,0x9A,
-0x40,0x3C,0x0E,0xAC,0x61,0xAA,0x5E,0x14,0x8F,0x9E,0x87,0xA1,0x6A,0x50,0xDC,0xD7,
-0x9A,0x4E,0xAF,0x05,0xB3,0xA6,0x71,0x94,0x9C,0x71,0xB3,0x50,0x60,0x0A,0xC7,0x13,
-0x9D,0x38,0x07,0x86,0x02,0xA8,0xE9,0xA8,0x69,0x26,0x18,0x90,0xAB,0x4C,0xB0,0x4F,
-0x23,0xAB,0x3A,0x4F,0x84,0xD8,0xDF,0xCE,0x9F,0xE1,0x69,0x6F,0xBB,0xD7,0x42,0xD7,
-0x6B,0x44,0xE4,0xC7,0xAD,0xEE,0x6D,0x41,0x5F,0x72,0x5A,0x71,0x08,0x37,0xB3,0x79,
-0x65,0xA4,0x59,0xA0,0x94,0x37,0xF7,0x00,0x2F,0x0D,0xC2,0x92,0x72,0xDA,0xD0,0x38,
-0x72,0xDB,0x14,0xA8,0x45,0xC4,0x5D,0x2A,0x7D,0xB7,0xB4,0xD6,0xC4,0xEE,0xAC,0xCD,
-0x13,0x44,0xB7,0xC9,0x2B,0xDD,0x43,0x00,0x25,0xFA,0x61,0xB9,0x69,0x6A,0x58,0x23,
-0x11,0xB7,0xA7,0x33,0x8F,0x56,0x75,0x59,0xF5,0xCD,0x29,0xD7,0x46,0xB7,0x0A,0x2B,
-0x65,0xB6,0xD3,0x42,0x6F,0x15,0xB2,0xB8,0x7B,0xFB,0xEF,0xE9,0x5D,0x53,0xD5,0x34,
-0x5A,0x27,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0xDC,0x30,0x81,0xD9,0x30,0x1D,0x06,
-0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xAD,0xBD,0x98,0x7A,0x34,0xB4,0x26,0xF7,
-0xFA,0xC4,0x26,0x54,0xEF,0x03,0xBD,0xE0,0x24,0xCB,0x54,0x1A,0x30,0x0B,0x06,0x03,
-0x55,0x1D,0x0F,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,
-0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x81,0x99,0x06,0x03,0x55,
-0x1D,0x23,0x04,0x81,0x91,0x30,0x81,0x8E,0x80,0x14,0xAD,0xBD,0x98,0x7A,0x34,0xB4,
-0x26,0xF7,0xFA,0xC4,0x26,0x54,0xEF,0x03,0xBD,0xE0,0x24,0xCB,0x54,0x1A,0xA1,0x73,
-0xA4,0x71,0x30,0x6F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,
-0x45,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,
-0x72,0x75,0x73,0x74,0x20,0x41,0x42,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,
-0x13,0x1D,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x45,0x78,0x74,0x65,0x72,
-0x6E,0x61,0x6C,0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,
-0x22,0x30,0x20,0x06,0x03,0x55,0x04,0x03,0x13,0x19,0x41,0x64,0x64,0x54,0x72,0x75,
-0x73,0x74,0x20,0x45,0x78,0x74,0x65,0x72,0x6E,0x61,0x6C,0x20,0x43,0x41,0x20,0x52,
-0x6F,0x6F,0x74,0x82,0x01,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0xB0,0x9B,0xE0,0x85,0x25,0xC2,
-0xD6,0x23,0xE2,0x0F,0x96,0x06,0x92,0x9D,0x41,0x98,0x9C,0xD9,0x84,0x79,0x81,0xD9,
-0x1E,0x5B,0x14,0x07,0x23,0x36,0x65,0x8F,0xB0,0xD8,0x77,0xBB,0xAC,0x41,0x6C,0x47,
-0x60,0x83,0x51,0xB0,0xF9,0x32,0x3D,0xE7,0xFC,0xF6,0x26,0x13,0xC7,0x80,0x16,0xA5,
-0xBF,0x5A,0xFC,0x87,0xCF,0x78,0x79,0x89,0x21,0x9A,0xE2,0x4C,0x07,0x0A,0x86,0x35,
-0xBC,0xF2,0xDE,0x51,0xC4,0xD2,0x96,0xB7,0xDC,0x7E,0x4E,0xEE,0x70,0xFD,0x1C,0x39,
-0xEB,0x0C,0x02,0x51,0x14,0x2D,0x8E,0xBD,0x16,0xE0,0xC1,0xDF,0x46,0x75,0xE7,0x24,
-0xAD,0xEC,0xF4,0x42,0xB4,0x85,0x93,0x70,0x10,0x67,0xBA,0x9D,0x06,0x35,0x4A,0x18,
-0xD3,0x2B,0x7A,0xCC,0x51,0x42,0xA1,0x7A,0x63,0xD1,0xE6,0xBB,0xA1,0xC5,0x2B,0xC2,
-0x36,0xBE,0x13,0x0D,0xE6,0xBD,0x63,0x7E,0x79,0x7B,0xA7,0x09,0x0D,0x40,0xAB,0x6A,
-0xDD,0x8F,0x8A,0xC3,0xF6,0xF6,0x8C,0x1A,0x42,0x05,0x51,0xD4,0x45,0xF5,0x9F,0xA7,
-0x62,0x21,0x68,0x15,0x20,0x43,0x3C,0x99,0xE7,0x7C,0xBD,0x24,0xD8,0xA9,0x91,0x17,
-0x73,0x88,0x3F,0x56,0x1B,0x31,0x38,0x18,0xB4,0x71,0x0F,0x9A,0xCD,0xC8,0x0E,0x9E,
-0x8E,0x2E,0x1B,0xE1,0x8C,0x98,0x83,0xCB,0x1F,0x31,0xF1,0x44,0x4C,0xC6,0x04,0x73,
-0x49,0x76,0x60,0x0F,0xC7,0xF8,0xBD,0x17,0x80,0x6B,0x2E,0xE9,0xCC,0x4C,0x0E,0x5A,
-0x9A,0x79,0x0F,0x20,0x0A,0x2E,0xD5,0x9E,0x63,0x26,0x1E,0x55,0x92,0x94,0xD8,0x82,
-0x17,0x5A,0x7B,0xD0,0xBC,0xC7,0x8F,0x4E,0x86,0x04,
-};
-
-
-/* subject:/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Class 1 CA Root */
-/* issuer :/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Class 1 CA Root */
-
-
-const unsigned char AddTrust_Low_Value_Services_Root_certificate[1052]={
-0x30,0x82,0x04,0x18,0x30,0x82,0x03,0x00,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x65,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,0x14,
-0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,0x73,
-0x74,0x20,0x41,0x42,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x0B,0x13,0x14,0x41,
-0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,
-0x6F,0x72,0x6B,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x41,0x64,
-0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x31,0x20,0x43,
-0x41,0x20,0x52,0x6F,0x6F,0x74,0x30,0x1E,0x17,0x0D,0x30,0x30,0x30,0x35,0x33,0x30,
-0x31,0x30,0x33,0x38,0x33,0x31,0x5A,0x17,0x0D,0x32,0x30,0x30,0x35,0x33,0x30,0x31,
-0x30,0x33,0x38,0x33,0x31,0x5A,0x30,0x65,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x06,0x13,0x02,0x53,0x45,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,
-0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x41,0x42,0x31,0x1D,0x30,0x1B,0x06,
-0x03,0x55,0x04,0x0B,0x13,0x14,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x54,
-0x54,0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x21,0x30,0x1F,0x06,0x03,
-0x55,0x04,0x03,0x13,0x18,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x43,0x6C,
-0x61,0x73,0x73,0x20,0x31,0x20,0x43,0x41,0x20,0x52,0x6F,0x6F,0x74,0x30,0x82,0x01,
-0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,
-0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0x96,0x96,
-0xD4,0x21,0x49,0x60,0xE2,0x6B,0xE8,0x41,0x07,0x0C,0xDE,0xC4,0xE0,0xDC,0x13,0x23,
-0xCD,0xC1,0x35,0xC7,0xFB,0xD6,0x4E,0x11,0x0A,0x67,0x5E,0xF5,0x06,0x5B,0x6B,0xA5,
-0x08,0x3B,0x5B,0x29,0x16,0x3A,0xE7,0x87,0xB2,0x34,0x06,0xC5,0xBC,0x05,0xA5,0x03,
-0x7C,0x82,0xCB,0x29,0x10,0xAE,0xE1,0x88,0x81,0xBD,0xD6,0x9E,0xD3,0xFE,0x2D,0x56,
-0xC1,0x15,0xCE,0xE3,0x26,0x9D,0x15,0x2E,0x10,0xFB,0x06,0x8F,0x30,0x04,0xDE,0xA7,
-0xB4,0x63,0xB4,0xFF,0xB1,0x9C,0xAE,0x3C,0xAF,0x77,0xB6,0x56,0xC5,0xB5,0xAB,0xA2,
-0xE9,0x69,0x3A,0x3D,0x0E,0x33,0x79,0x32,0x3F,0x70,0x82,0x92,0x99,0x61,0x6D,0x8D,
-0x30,0x08,0x8F,0x71,0x3F,0xA6,0x48,0x57,0x19,0xF8,0x25,0xDC,0x4B,0x66,0x5C,0xA5,
-0x74,0x8F,0x98,0xAE,0xC8,0xF9,0xC0,0x06,0x22,0xE7,0xAC,0x73,0xDF,0xA5,0x2E,0xFB,
-0x52,0xDC,0xB1,0x15,0x65,0x20,0xFA,0x35,0x66,0x69,0xDE,0xDF,0x2C,0xF1,0x6E,0xBC,
-0x30,0xDB,0x2C,0x24,0x12,0xDB,0xEB,0x35,0x35,0x68,0x90,0xCB,0x00,0xB0,0x97,0x21,
-0x3D,0x74,0x21,0x23,0x65,0x34,0x2B,0xBB,0x78,0x59,0xA3,0xD6,0xE1,0x76,0x39,0x9A,
-0xA4,0x49,0x8E,0x8C,0x74,0xAF,0x6E,0xA4,0x9A,0xA3,0xD9,0x9B,0xD2,0x38,0x5C,0x9B,
-0xA2,0x18,0xCC,0x75,0x23,0x84,0xBE,0xEB,0xE2,0x4D,0x33,0x71,0x8E,0x1A,0xF0,0xC2,
-0xF8,0xC7,0x1D,0xA2,0xAD,0x03,0x97,0x2C,0xF8,0xCF,0x25,0xC6,0xF6,0xB8,0x24,0x31,
-0xB1,0x63,0x5D,0x92,0x7F,0x63,0xF0,0x25,0xC9,0x53,0x2E,0x1F,0xBF,0x4D,0x02,0x03,
-0x01,0x00,0x01,0xA3,0x81,0xD2,0x30,0x81,0xCF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,
-0x04,0x16,0x04,0x14,0x95,0xB1,0xB4,0xF0,0x94,0xB6,0xBD,0xC7,0xDA,0xD1,0x11,0x09,
-0x21,0xBE,0xC1,0xAF,0x49,0xFD,0x10,0x7B,0x30,0x0B,0x06,0x03,0x55,0x1D,0x0F,0x04,
-0x04,0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,
-0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x81,0x8F,0x06,0x03,0x55,0x1D,0x23,0x04,0x81,
-0x87,0x30,0x81,0x84,0x80,0x14,0x95,0xB1,0xB4,0xF0,0x94,0xB6,0xBD,0xC7,0xDA,0xD1,
-0x11,0x09,0x21,0xBE,0xC1,0xAF,0x49,0xFD,0x10,0x7B,0xA1,0x69,0xA4,0x67,0x30,0x65,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,0x14,0x30,
-0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,
-0x20,0x41,0x42,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x0B,0x13,0x14,0x41,0x64,
-0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,
-0x72,0x6B,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x41,0x64,0x64,
-0x54,0x72,0x75,0x73,0x74,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x31,0x20,0x43,0x41,
-0x20,0x52,0x6F,0x6F,0x74,0x82,0x01,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x2C,0x6D,0x64,0x1B,
-0x1F,0xCD,0x0D,0xDD,0xB9,0x01,0xFA,0x96,0x63,0x34,0x32,0x48,0x47,0x99,0xAE,0x97,
-0xED,0xFD,0x72,0x16,0xA6,0x73,0x47,0x5A,0xF4,0xEB,0xDD,0xE9,0xF5,0xD6,0xFB,0x45,
-0xCC,0x29,0x89,0x44,0x5D,0xBF,0x46,0x39,0x3D,0xE8,0xEE,0xBC,0x4D,0x54,0x86,0x1E,
-0x1D,0x6C,0xE3,0x17,0x27,0x43,0xE1,0x89,0x56,0x2B,0xA9,0x6F,0x72,0x4E,0x49,0x33,
-0xE3,0x72,0x7C,0x2A,0x23,0x9A,0xBC,0x3E,0xFF,0x28,0x2A,0xED,0xA3,0xFF,0x1C,0x23,
-0xBA,0x43,0x57,0x09,0x67,0x4D,0x4B,0x62,0x06,0x2D,0xF8,0xFF,0x6C,0x9D,0x60,0x1E,
-0xD8,0x1C,0x4B,0x7D,0xB5,0x31,0x2F,0xD9,0xD0,0x7C,0x5D,0xF8,0xDE,0x6B,0x83,0x18,
-0x78,0x37,0x57,0x2F,0xE8,0x33,0x07,0x67,0xDF,0x1E,0xC7,0x6B,0x2A,0x95,0x76,0xAE,
-0x8F,0x57,0xA3,0xF0,0xF4,0x52,0xB4,0xA9,0x53,0x08,0xCF,0xE0,0x4F,0xD3,0x7A,0x53,
-0x8B,0xFD,0xBB,0x1C,0x56,0x36,0xF2,0xFE,0xB2,0xB6,0xE5,0x76,0xBB,0xD5,0x22,0x65,
-0xA7,0x3F,0xFE,0xD1,0x66,0xAD,0x0B,0xBC,0x6B,0x99,0x86,0xEF,0x3F,0x7D,0xF3,0x18,
-0x32,0xCA,0x7B,0xC6,0xE3,0xAB,0x64,0x46,0x95,0xF8,0x26,0x69,0xD9,0x55,0x83,0x7B,
-0x2C,0x96,0x07,0xFF,0x59,0x2C,0x44,0xA3,0xC6,0xE5,0xE9,0xA9,0xDC,0xA1,0x63,0x80,
-0x5A,0x21,0x5E,0x21,0xCF,0x53,0x54,0xF0,0xBA,0x6F,0x89,0xDB,0xA8,0xAA,0x95,0xCF,
-0x8B,0xE3,0x71,0xCC,0x1E,0x1B,0x20,0x44,0x08,0xC0,0x7A,0xB6,0x40,0xFD,0xC4,0xE4,
-0x35,0xE1,0x1D,0x16,0x1C,0xD0,0xBC,0x2B,0x8E,0xD6,0x71,0xD9,
-};
-
-
-/* subject:/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Public CA Root */
-/* issuer :/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Public CA Root */
-
-
-const unsigned char AddTrust_Public_Services_Root_certificate[1049]={
-0x30,0x82,0x04,0x15,0x30,0x82,0x02,0xFD,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x64,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,0x14,
-0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,0x73,
-0x74,0x20,0x41,0x42,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x0B,0x13,0x14,0x41,
-0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,
-0x6F,0x72,0x6B,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,0x17,0x41,0x64,
-0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,0x43,0x41,
-0x20,0x52,0x6F,0x6F,0x74,0x30,0x1E,0x17,0x0D,0x30,0x30,0x30,0x35,0x33,0x30,0x31,
-0x30,0x34,0x31,0x35,0x30,0x5A,0x17,0x0D,0x32,0x30,0x30,0x35,0x33,0x30,0x31,0x30,
-0x34,0x31,0x35,0x30,0x5A,0x30,0x64,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,
-0x13,0x02,0x53,0x45,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,
-0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x41,0x42,0x31,0x1D,0x30,0x1B,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x14,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x54,0x54,
-0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,
-0x04,0x03,0x13,0x17,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x50,0x75,0x62,
-0x6C,0x69,0x63,0x20,0x43,0x41,0x20,0x52,0x6F,0x6F,0x74,0x30,0x82,0x01,0x22,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,
-0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xE9,0x1A,0x30,0x8F,
-0x83,0x88,0x14,0xC1,0x20,0xD8,0x3C,0x9B,0x8F,0x1B,0x7E,0x03,0x74,0xBB,0xDA,0x69,
-0xD3,0x46,0xA5,0xF8,0x8E,0xC2,0x0C,0x11,0x90,0x51,0xA5,0x2F,0x66,0x54,0x40,0x55,
-0xEA,0xDB,0x1F,0x4A,0x56,0xEE,0x9F,0x23,0x6E,0xF4,0x39,0xCB,0xA1,0xB9,0x6F,0xF2,
-0x7E,0xF9,0x5D,0x87,0x26,0x61,0x9E,0x1C,0xF8,0xE2,0xEC,0xA6,0x81,0xF8,0x21,0xC5,
-0x24,0xCC,0x11,0x0C,0x3F,0xDB,0x26,0x72,0x7A,0xC7,0x01,0x97,0x07,0x17,0xF9,0xD7,
-0x18,0x2C,0x30,0x7D,0x0E,0x7A,0x1E,0x62,0x1E,0xC6,0x4B,0xC0,0xFD,0x7D,0x62,0x77,
-0xD3,0x44,0x1E,0x27,0xF6,0x3F,0x4B,0x44,0xB3,0xB7,0x38,0xD9,0x39,0x1F,0x60,0xD5,
-0x51,0x92,0x73,0x03,0xB4,0x00,0x69,0xE3,0xF3,0x14,0x4E,0xEE,0xD1,0xDC,0x09,0xCF,
-0x77,0x34,0x46,0x50,0xB0,0xF8,0x11,0xF2,0xFE,0x38,0x79,0xF7,0x07,0x39,0xFE,0x51,
-0x92,0x97,0x0B,0x5B,0x08,0x5F,0x34,0x86,0x01,0xAD,0x88,0x97,0xEB,0x66,0xCD,0x5E,
-0xD1,0xFF,0xDC,0x7D,0xF2,0x84,0xDA,0xBA,0x77,0xAD,0xDC,0x80,0x08,0xC7,0xA7,0x87,
-0xD6,0x55,0x9F,0x97,0x6A,0xE8,0xC8,0x11,0x64,0xBA,0xE7,0x19,0x29,0x3F,0x11,0xB3,
-0x78,0x90,0x84,0x20,0x52,0x5B,0x11,0xEF,0x78,0xD0,0x83,0xF6,0xD5,0x48,0x90,0xD0,
-0x30,0x1C,0xCF,0x80,0xF9,0x60,0xFE,0x79,0xE4,0x88,0xF2,0xDD,0x00,0xEB,0x94,0x45,
-0xEB,0x65,0x94,0x69,0x40,0xBA,0xC0,0xD5,0xB4,0xB8,0xBA,0x7D,0x04,0x11,0xA8,0xEB,
-0x31,0x05,0x96,0x94,0x4E,0x58,0x21,0x8E,0x9F,0xD0,0x60,0xFD,0x02,0x03,0x01,0x00,
-0x01,0xA3,0x81,0xD1,0x30,0x81,0xCE,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,
-0x04,0x14,0x81,0x3E,0x37,0xD8,0x92,0xB0,0x1F,0x77,0x9F,0x5C,0xB4,0xAB,0x73,0xAA,
-0xE7,0xF6,0x34,0x60,0x2F,0xFA,0x30,0x0B,0x06,0x03,0x55,0x1D,0x0F,0x04,0x04,0x03,
-0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x81,0x8E,0x06,0x03,0x55,0x1D,0x23,0x04,0x81,0x86,0x30,
-0x81,0x83,0x80,0x14,0x81,0x3E,0x37,0xD8,0x92,0xB0,0x1F,0x77,0x9F,0x5C,0xB4,0xAB,
-0x73,0xAA,0xE7,0xF6,0x34,0x60,0x2F,0xFA,0xA1,0x68,0xA4,0x66,0x30,0x64,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,0x14,0x30,0x12,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x41,
-0x42,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x0B,0x13,0x14,0x41,0x64,0x64,0x54,
-0x72,0x75,0x73,0x74,0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,
-0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,0x17,0x41,0x64,0x64,0x54,0x72,
-0x75,0x73,0x74,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,0x43,0x41,0x20,0x52,0x6F,
-0x6F,0x74,0x82,0x01,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x03,0xF7,0x15,0x4A,0xF8,0x24,0xDA,
-0x23,0x56,0x16,0x93,0x76,0xDD,0x36,0x28,0xB9,0xAE,0x1B,0xB8,0xC3,0xF1,0x64,0xBA,
-0x20,0x18,0x78,0x95,0x29,0x27,0x57,0x05,0xBC,0x7C,0x2A,0xF4,0xB9,0x51,0x55,0xDA,
-0x87,0x02,0xDE,0x0F,0x16,0x17,0x31,0xF8,0xAA,0x79,0x2E,0x09,0x13,0xBB,0xAF,0xB2,
-0x20,0x19,0x12,0xE5,0x93,0xF9,0x4B,0xF9,0x83,0xE8,0x44,0xD5,0xB2,0x41,0x25,0xBF,
-0x88,0x75,0x6F,0xFF,0x10,0xFC,0x4A,0x54,0xD0,0x5F,0xF0,0xFA,0xEF,0x36,0x73,0x7D,
-0x1B,0x36,0x45,0xC6,0x21,0x6D,0xB4,0x15,0xB8,0x4E,0xCF,0x9C,0x5C,0xA5,0x3D,0x5A,
-0x00,0x8E,0x06,0xE3,0x3C,0x6B,0x32,0x7B,0xF2,0x9F,0xF0,0xB6,0xFD,0xDF,0xF0,0x28,
-0x18,0x48,0xF0,0xC6,0xBC,0xD0,0xBF,0x34,0x80,0x96,0xC2,0x4A,0xB1,0x6D,0x8E,0xC7,
-0x90,0x45,0xDE,0x2F,0x67,0xAC,0x45,0x04,0xA3,0x7A,0xDC,0x55,0x92,0xC9,0x47,0x66,
-0xD8,0x1A,0x8C,0xC7,0xED,0x9C,0x4E,0x9A,0xE0,0x12,0xBB,0xB5,0x6A,0x4C,0x84,0xE1,
-0xE1,0x22,0x0D,0x87,0x00,0x64,0xFE,0x8C,0x7D,0x62,0x39,0x65,0xA6,0xEF,0x42,0xB6,
-0x80,0x25,0x12,0x61,0x01,0xA8,0x24,0x13,0x70,0x00,0x11,0x26,0x5F,0xFA,0x35,0x50,
-0xC5,0x48,0xCC,0x06,0x47,0xE8,0x27,0xD8,0x70,0x8D,0x5F,0x64,0xE6,0xA1,0x44,0x26,
-0x5E,0x22,0xEC,0x92,0xCD,0xFF,0x42,0x9A,0x44,0x21,0x6D,0x5C,0xC5,0xE3,0x22,0x1D,
-0x5F,0x47,0x12,0xE7,0xCE,0x5F,0x5D,0xFA,0xD8,0xAA,0xB1,0x33,0x2D,0xD9,0x76,0xF2,
-0x4E,0x3A,0x33,0x0C,0x2B,0xB3,0x2D,0x90,0x06,
-};
-
-
-/* subject:/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Qualified CA Root */
-/* issuer :/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Qualified CA Root */
-
-
-const unsigned char AddTrust_Qualified_Certificates_Root_certificate[1058]={
-0x30,0x82,0x04,0x1E,0x30,0x82,0x03,0x06,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x67,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,0x14,
-0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,0x73,
-0x74,0x20,0x41,0x42,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x0B,0x13,0x14,0x41,
-0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,
-0x6F,0x72,0x6B,0x31,0x23,0x30,0x21,0x06,0x03,0x55,0x04,0x03,0x13,0x1A,0x41,0x64,
-0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x51,0x75,0x61,0x6C,0x69,0x66,0x69,0x65,0x64,
-0x20,0x43,0x41,0x20,0x52,0x6F,0x6F,0x74,0x30,0x1E,0x17,0x0D,0x30,0x30,0x30,0x35,
-0x33,0x30,0x31,0x30,0x34,0x34,0x35,0x30,0x5A,0x17,0x0D,0x32,0x30,0x30,0x35,0x33,
-0x30,0x31,0x30,0x34,0x34,0x35,0x30,0x5A,0x30,0x67,0x31,0x0B,0x30,0x09,0x06,0x03,
-0x55,0x04,0x06,0x13,0x02,0x53,0x45,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,
-0x13,0x0B,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x41,0x42,0x31,0x1D,0x30,
-0x1B,0x06,0x03,0x55,0x04,0x0B,0x13,0x14,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,
-0x20,0x54,0x54,0x50,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x23,0x30,0x21,
-0x06,0x03,0x55,0x04,0x03,0x13,0x1A,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,
-0x51,0x75,0x61,0x6C,0x69,0x66,0x69,0x65,0x64,0x20,0x43,0x41,0x20,0x52,0x6F,0x6F,
-0x74,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,
-0x01,0x00,0xE4,0x1E,0x9A,0xFE,0xDC,0x09,0x5A,0x87,0xA4,0x9F,0x47,0xBE,0x11,0x5F,
-0xAF,0x84,0x34,0xDB,0x62,0x3C,0x79,0x78,0xB7,0xE9,0x30,0xB5,0xEC,0x0C,0x1C,0x2A,
-0xC4,0x16,0xFF,0xE0,0xEC,0x71,0xEB,0x8A,0xF5,0x11,0x6E,0xED,0x4F,0x0D,0x91,0xD2,
-0x12,0x18,0x2D,0x49,0x15,0x01,0xC2,0xA4,0x22,0x13,0xC7,0x11,0x64,0xFF,0x22,0x12,
-0x9A,0xB9,0x8E,0x5C,0x2F,0x08,0xCF,0x71,0x6A,0xB3,0x67,0x01,0x59,0xF1,0x5D,0x46,
-0xF3,0xB0,0x78,0xA5,0xF6,0x0E,0x42,0x7A,0xE3,0x7F,0x1B,0xCC,0xD0,0xF0,0xB7,0x28,
-0xFD,0x2A,0xEA,0x9E,0xB3,0xB0,0xB9,0x04,0xAA,0xFD,0xF6,0xC7,0xB4,0xB1,0xB8,0x2A,
-0xA0,0xFB,0x58,0xF1,0x19,0xA0,0x6F,0x70,0x25,0x7E,0x3E,0x69,0x4A,0x7F,0x0F,0x22,
-0xD8,0xEF,0xAD,0x08,0x11,0x9A,0x29,0x99,0xE1,0xAA,0x44,0x45,0x9A,0x12,0x5E,0x3E,
-0x9D,0x6D,0x52,0xFC,0xE7,0xA0,0x3D,0x68,0x2F,0xF0,0x4B,0x70,0x7C,0x13,0x38,0xAD,
-0xBC,0x15,0x25,0xF1,0xD6,0xCE,0xAB,0xA2,0xC0,0x31,0xD6,0x2F,0x9F,0xE0,0xFF,0x14,
-0x59,0xFC,0x84,0x93,0xD9,0x87,0x7C,0x4C,0x54,0x13,0xEB,0x9F,0xD1,0x2D,0x11,0xF8,
-0x18,0x3A,0x3A,0xDE,0x25,0xD9,0xF7,0xD3,0x40,0xED,0xA4,0x06,0x12,0xC4,0x3B,0xE1,
-0x91,0xC1,0x56,0x35,0xF0,0x14,0xDC,0x65,0x36,0x09,0x6E,0xAB,0xA4,0x07,0xC7,0x35,
-0xD1,0xC2,0x03,0x33,0x36,0x5B,0x75,0x26,0x6D,0x42,0xF1,0x12,0x6B,0x43,0x6F,0x4B,
-0x71,0x94,0xFA,0x34,0x1D,0xED,0x13,0x6E,0xCA,0x80,0x7F,0x98,0x2F,0x6C,0xB9,0x65,
-0xD8,0xE9,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0xD4,0x30,0x81,0xD1,0x30,0x1D,0x06,
-0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x39,0x95,0x8B,0x62,0x8B,0x5C,0xC9,0xD4,
-0x80,0xBA,0x58,0x0F,0x97,0x3F,0x15,0x08,0x43,0xCC,0x98,0xA7,0x30,0x0B,0x06,0x03,
-0x55,0x1D,0x0F,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,
-0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x81,0x91,0x06,0x03,0x55,
-0x1D,0x23,0x04,0x81,0x89,0x30,0x81,0x86,0x80,0x14,0x39,0x95,0x8B,0x62,0x8B,0x5C,
-0xC9,0xD4,0x80,0xBA,0x58,0x0F,0x97,0x3F,0x15,0x08,0x43,0xCC,0x98,0xA7,0xA1,0x6B,
-0xA4,0x69,0x30,0x67,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x53,
-0x45,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x41,0x64,0x64,0x54,
-0x72,0x75,0x73,0x74,0x20,0x41,0x42,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x0B,
-0x13,0x14,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x54,0x54,0x50,0x20,0x4E,
-0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x23,0x30,0x21,0x06,0x03,0x55,0x04,0x03,0x13,
-0x1A,0x41,0x64,0x64,0x54,0x72,0x75,0x73,0x74,0x20,0x51,0x75,0x61,0x6C,0x69,0x66,
-0x69,0x65,0x64,0x20,0x43,0x41,0x20,0x52,0x6F,0x6F,0x74,0x82,0x01,0x01,0x30,0x0D,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,
-0x01,0x00,0x19,0xAB,0x75,0xEA,0xF8,0x8B,0x65,0x61,0x95,0x13,0xBA,0x69,0x04,0xEF,
-0x86,0xCA,0x13,0xA0,0xC7,0xAA,0x4F,0x64,0x1B,0x3F,0x18,0xF6,0xA8,0x2D,0x2C,0x55,
-0x8F,0x05,0xB7,0x30,0xEA,0x42,0x6A,0x1D,0xC0,0x25,0x51,0x2D,0xA7,0xBF,0x0C,0xB3,
-0xED,0xEF,0x08,0x7F,0x6C,0x3C,0x46,0x1A,0xEA,0x18,0x43,0xDF,0x76,0xCC,0xF9,0x66,
-0x86,0x9C,0x2C,0x68,0xF5,0xE9,0x17,0xF8,0x31,0xB3,0x18,0xC4,0xD6,0x48,0x7D,0x23,
-0x4C,0x68,0xC1,0x7E,0xBB,0x01,0x14,0x6F,0xC5,0xD9,0x6E,0xDE,0xBB,0x04,0x42,0x6A,
-0xF8,0xF6,0x5C,0x7D,0xE5,0xDA,0xFA,0x87,0xEB,0x0D,0x35,0x52,0x67,0xD0,0x9E,0x97,
-0x76,0x05,0x93,0x3F,0x95,0xC7,0x01,0xE6,0x69,0x55,0x38,0x7F,0x10,0x61,0x99,0xC9,
-0xE3,0x5F,0xA6,0xCA,0x3E,0x82,0x63,0x48,0xAA,0xE2,0x08,0x48,0x3E,0xAA,0xF2,0xB2,
-0x85,0x62,0xA6,0xB4,0xA7,0xD9,0xBD,0x37,0x9C,0x68,0xB5,0x2D,0x56,0x7D,0xB0,0xB7,
-0x3F,0xA0,0xB1,0x07,0xD6,0xE9,0x4F,0xDC,0xDE,0x45,0x71,0x30,0x32,0x7F,0x1B,0x2E,
-0x09,0xF9,0xBF,0x52,0xA1,0xEE,0xC2,0x80,0x3E,0x06,0x5C,0x2E,0x55,0x40,0xC1,0x1B,
-0xF5,0x70,0x45,0xB0,0xDC,0x5D,0xFA,0xF6,0x72,0x5A,0x77,0xD2,0x63,0xCD,0xCF,0x58,
-0x89,0x00,0x42,0x63,0x3F,0x79,0x39,0xD0,0x44,0xB0,0x82,0x6E,0x41,0x19,0xE8,0xDD,
-0xE0,0xC1,0x88,0x5A,0xD1,0x1E,0x71,0x93,0x1F,0x24,0x30,0x74,0xE5,0x1E,0xA8,0xDE,
-0x3C,0x27,0x37,0x7F,0x83,0xAE,0x9E,0x77,0xCF,0xF0,0x30,0xB1,0xFF,0x4B,0x99,0xE8,
-0xC6,0xA1,
-};
-
-
-/* subject:/C=US/O=AffirmTrust/CN=AffirmTrust Commercial */
-/* issuer :/C=US/O=AffirmTrust/CN=AffirmTrust Commercial */
-
-
-const unsigned char AffirmTrust_Commercial_certificate[848]={
-0x30,0x82,0x03,0x4C,0x30,0x82,0x02,0x34,0xA0,0x03,0x02,0x01,0x02,0x02,0x08,0x77,
-0x77,0x06,0x27,0x26,0xA9,0xB1,0x7C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,0x44,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x0C,0x0B,
-0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x31,0x1F,0x30,0x1D,0x06,
-0x03,0x55,0x04,0x03,0x0C,0x16,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,
-0x74,0x20,0x43,0x6F,0x6D,0x6D,0x65,0x72,0x63,0x69,0x61,0x6C,0x30,0x1E,0x17,0x0D,
-0x31,0x30,0x30,0x31,0x32,0x39,0x31,0x34,0x30,0x36,0x30,0x36,0x5A,0x17,0x0D,0x33,
-0x30,0x31,0x32,0x33,0x31,0x31,0x34,0x30,0x36,0x30,0x36,0x5A,0x30,0x44,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,
-0x03,0x55,0x04,0x0A,0x0C,0x0B,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,
-0x74,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x0C,0x16,0x41,0x66,0x66,0x69,
-0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x20,0x43,0x6F,0x6D,0x6D,0x65,0x72,0x63,0x69,
-0x61,0x6C,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,
-0x01,0x01,0x00,0xF6,0x1B,0x4F,0x67,0x07,0x2B,0xA1,0x15,0xF5,0x06,0x22,0xCB,0x1F,
-0x01,0xB2,0xE3,0x73,0x45,0x06,0x44,0x49,0x2C,0xBB,0x49,0x25,0x14,0xD6,0xCE,0xC3,
-0xB7,0xAB,0x2C,0x4F,0xC6,0x41,0x32,0x94,0x57,0xFA,0x12,0xA7,0x5B,0x0E,0xE2,0x8F,
-0x1F,0x1E,0x86,0x19,0xA7,0xAA,0xB5,0x2D,0xB9,0x5F,0x0D,0x8A,0xC2,0xAF,0x85,0x35,
-0x79,0x32,0x2D,0xBB,0x1C,0x62,0x37,0xF2,0xB1,0x5B,0x4A,0x3D,0xCA,0xCD,0x71,0x5F,
-0xE9,0x42,0xBE,0x94,0xE8,0xC8,0xDE,0xF9,0x22,0x48,0x64,0xC6,0xE5,0xAB,0xC6,0x2B,
-0x6D,0xAD,0x05,0xF0,0xFA,0xD5,0x0B,0xCF,0x9A,0xE5,0xF0,0x50,0xA4,0x8B,0x3B,0x47,
-0xA5,0x23,0x5B,0x7A,0x7A,0xF8,0x33,0x3F,0xB8,0xEF,0x99,0x97,0xE3,0x20,0xC1,0xD6,
-0x28,0x89,0xCF,0x94,0xFB,0xB9,0x45,0xED,0xE3,0x40,0x17,0x11,0xD4,0x74,0xF0,0x0B,
-0x31,0xE2,0x2B,0x26,0x6A,0x9B,0x4C,0x57,0xAE,0xAC,0x20,0x3E,0xBA,0x45,0x7A,0x05,
-0xF3,0xBD,0x9B,0x69,0x15,0xAE,0x7D,0x4E,0x20,0x63,0xC4,0x35,0x76,0x3A,0x07,0x02,
-0xC9,0x37,0xFD,0xC7,0x47,0xEE,0xE8,0xF1,0x76,0x1D,0x73,0x15,0xF2,0x97,0xA4,0xB5,
-0xC8,0x7A,0x79,0xD9,0x42,0xAA,0x2B,0x7F,0x5C,0xFE,0xCE,0x26,0x4F,0xA3,0x66,0x81,
-0x35,0xAF,0x44,0xBA,0x54,0x1E,0x1C,0x30,0x32,0x65,0x9D,0xE6,0x3C,0x93,0x5E,0x50,
-0x4E,0x7A,0xE3,0x3A,0xD4,0x6E,0xCC,0x1A,0xFB,0xF9,0xD2,0x37,0xAE,0x24,0x2A,0xAB,
-0x57,0x03,0x22,0x28,0x0D,0x49,0x75,0x7F,0xB7,0x28,0xDA,0x75,0xBF,0x8E,0xE3,0xDC,
-0x0E,0x79,0x31,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,0x1D,0x06,0x03,
-0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x9D,0x93,0xC6,0x53,0x8B,0x5E,0xCA,0xAF,0x3F,
-0x9F,0x1E,0x0F,0xE5,0x99,0x95,0xBC,0x24,0xF6,0x94,0x8F,0x30,0x0F,0x06,0x03,0x55,
-0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,
-0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,0x01,0x01,0x00,
-0x58,0xAC,0xF4,0x04,0x0E,0xCD,0xC0,0x0D,0xFF,0x0A,0xFD,0xD4,0xBA,0x16,0x5F,0x29,
-0xBD,0x7B,0x68,0x99,0x58,0x49,0xD2,0xB4,0x1D,0x37,0x4D,0x7F,0x27,0x7D,0x46,0x06,
-0x5D,0x43,0xC6,0x86,0x2E,0x3E,0x73,0xB2,0x26,0x7D,0x4F,0x93,0xA9,0xB6,0xC4,0x2A,
-0x9A,0xAB,0x21,0x97,0x14,0xB1,0xDE,0x8C,0xD3,0xAB,0x89,0x15,0xD8,0x6B,0x24,0xD4,
-0xF1,0x16,0xAE,0xD8,0xA4,0x5C,0xD4,0x7F,0x51,0x8E,0xED,0x18,0x01,0xB1,0x93,0x63,
-0xBD,0xBC,0xF8,0x61,0x80,0x9A,0x9E,0xB1,0xCE,0x42,0x70,0xE2,0xA9,0x7D,0x06,0x25,
-0x7D,0x27,0xA1,0xFE,0x6F,0xEC,0xB3,0x1E,0x24,0xDA,0xE3,0x4B,0x55,0x1A,0x00,0x3B,
-0x35,0xB4,0x3B,0xD9,0xD7,0x5D,0x30,0xFD,0x81,0x13,0x89,0xF2,0xC2,0x06,0x2B,0xED,
-0x67,0xC4,0x8E,0xC9,0x43,0xB2,0x5C,0x6B,0x15,0x89,0x02,0xBC,0x62,0xFC,0x4E,0xF2,
-0xB5,0x33,0xAA,0xB2,0x6F,0xD3,0x0A,0xA2,0x50,0xE3,0xF6,0x3B,0xE8,0x2E,0x44,0xC2,
-0xDB,0x66,0x38,0xA9,0x33,0x56,0x48,0xF1,0x6D,0x1B,0x33,0x8D,0x0D,0x8C,0x3F,0x60,
-0x37,0x9D,0xD3,0xCA,0x6D,0x7E,0x34,0x7E,0x0D,0x9F,0x72,0x76,0x8B,0x1B,0x9F,0x72,
-0xFD,0x52,0x35,0x41,0x45,0x02,0x96,0x2F,0x1C,0xB2,0x9A,0x73,0x49,0x21,0xB1,0x49,
-0x47,0x45,0x47,0xB4,0xEF,0x6A,0x34,0x11,0xC9,0x4D,0x9A,0xCC,0x59,0xB7,0xD6,0x02,
-0x9E,0x5A,0x4E,0x65,0xB5,0x94,0xAE,0x1B,0xDF,0x29,0xB0,0x16,0xF1,0xBF,0x00,0x9E,
-0x07,0x3A,0x17,0x64,0xB5,0x04,0xB5,0x23,0x21,0x99,0x0A,0x95,0x3B,0x97,0x7C,0xEF,
-};
-
-
-/* subject:/C=US/O=AffirmTrust/CN=AffirmTrust Networking */
-/* issuer :/C=US/O=AffirmTrust/CN=AffirmTrust Networking */
-
-
-const unsigned char AffirmTrust_Networking_certificate[848]={
-0x30,0x82,0x03,0x4C,0x30,0x82,0x02,0x34,0xA0,0x03,0x02,0x01,0x02,0x02,0x08,0x7C,
-0x4F,0x04,0x39,0x1C,0xD4,0x99,0x2D,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x44,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x0C,0x0B,
-0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x31,0x1F,0x30,0x1D,0x06,
-0x03,0x55,0x04,0x03,0x0C,0x16,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,
-0x74,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x69,0x6E,0x67,0x30,0x1E,0x17,0x0D,
-0x31,0x30,0x30,0x31,0x32,0x39,0x31,0x34,0x30,0x38,0x32,0x34,0x5A,0x17,0x0D,0x33,
-0x30,0x31,0x32,0x33,0x31,0x31,0x34,0x30,0x38,0x32,0x34,0x5A,0x30,0x44,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,
-0x03,0x55,0x04,0x0A,0x0C,0x0B,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,
-0x74,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x0C,0x16,0x41,0x66,0x66,0x69,
-0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x69,
-0x6E,0x67,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,
-0x01,0x01,0x00,0xB4,0x84,0xCC,0x33,0x17,0x2E,0x6B,0x94,0x6C,0x6B,0x61,0x52,0xA0,
-0xEB,0xA3,0xCF,0x79,0x94,0x4C,0xE5,0x94,0x80,0x99,0xCB,0x55,0x64,0x44,0x65,0x8F,
-0x67,0x64,0xE2,0x06,0xE3,0x5C,0x37,0x49,0xF6,0x2F,0x9B,0x84,0x84,0x1E,0x2D,0xF2,
-0x60,0x9D,0x30,0x4E,0xCC,0x84,0x85,0xE2,0x2C,0xCF,0x1E,0x9E,0xFE,0x36,0xAB,0x33,
-0x77,0x35,0x44,0xD8,0x35,0x96,0x1A,0x3D,0x36,0xE8,0x7A,0x0E,0xD8,0xD5,0x47,0xA1,
-0x6A,0x69,0x8B,0xD9,0xFC,0xBB,0x3A,0xAE,0x79,0x5A,0xD5,0xF4,0xD6,0x71,0xBB,0x9A,
-0x90,0x23,0x6B,0x9A,0xB7,0x88,0x74,0x87,0x0C,0x1E,0x5F,0xB9,0x9E,0x2D,0xFA,0xAB,
-0x53,0x2B,0xDC,0xBB,0x76,0x3E,0x93,0x4C,0x08,0x08,0x8C,0x1E,0xA2,0x23,0x1C,0xD4,
-0x6A,0xAD,0x22,0xBA,0x99,0x01,0x2E,0x6D,0x65,0xCB,0xBE,0x24,0x66,0x55,0x24,0x4B,
-0x40,0x44,0xB1,0x1B,0xD7,0xE1,0xC2,0x85,0xC0,0xDE,0x10,0x3F,0x3D,0xED,0xB8,0xFC,
-0xF1,0xF1,0x23,0x53,0xDC,0xBF,0x65,0x97,0x6F,0xD9,0xF9,0x40,0x71,0x8D,0x7D,0xBD,
-0x95,0xD4,0xCE,0xBE,0xA0,0x5E,0x27,0x23,0xDE,0xFD,0xA6,0xD0,0x26,0x0E,0x00,0x29,
-0xEB,0x3C,0x46,0xF0,0x3D,0x60,0xBF,0x3F,0x50,0xD2,0xDC,0x26,0x41,0x51,0x9E,0x14,
-0x37,0x42,0x04,0xA3,0x70,0x57,0xA8,0x1B,0x87,0xED,0x2D,0xFA,0x7B,0xEE,0x8C,0x0A,
-0xE3,0xA9,0x66,0x89,0x19,0xCB,0x41,0xF9,0xDD,0x44,0x36,0x61,0xCF,0xE2,0x77,0x46,
-0xC8,0x7D,0xF6,0xF4,0x92,0x81,0x36,0xFD,0xDB,0x34,0xF1,0x72,0x7E,0xF3,0x0C,0x16,
-0xBD,0xB4,0x15,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,0x1D,0x06,0x03,
-0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x07,0x1F,0xD2,0xE7,0x9C,0xDA,0xC2,0x6E,0xA2,
-0x40,0xB4,0xB0,0x7A,0x50,0x10,0x50,0x74,0xC4,0xC8,0xBD,0x30,0x0F,0x06,0x03,0x55,
-0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,
-0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,
-0x89,0x57,0xB2,0x16,0x7A,0xA8,0xC2,0xFD,0xD6,0xD9,0x9B,0x9B,0x34,0xC2,0x9C,0xB4,
-0x32,0x14,0x4D,0xA7,0xA4,0xDF,0xEC,0xBE,0xA7,0xBE,0xF8,0x43,0xDB,0x91,0x37,0xCE,
-0xB4,0x32,0x2E,0x50,0x55,0x1A,0x35,0x4E,0x76,0x43,0x71,0x20,0xEF,0x93,0x77,0x4E,
-0x15,0x70,0x2E,0x87,0xC3,0xC1,0x1D,0x6D,0xDC,0xCB,0xB5,0x27,0xD4,0x2C,0x56,0xD1,
-0x52,0x53,0x3A,0x44,0xD2,0x73,0xC8,0xC4,0x1B,0x05,0x65,0x5A,0x62,0x92,0x9C,0xEE,
-0x41,0x8D,0x31,0xDB,0xE7,0x34,0xEA,0x59,0x21,0xD5,0x01,0x7A,0xD7,0x64,0xB8,0x64,
-0x39,0xCD,0xC9,0xED,0xAF,0xED,0x4B,0x03,0x48,0xA7,0xA0,0x99,0x01,0x80,0xDC,0x65,
-0xA3,0x36,0xAE,0x65,0x59,0x48,0x4F,0x82,0x4B,0xC8,0x65,0xF1,0x57,0x1D,0xE5,0x59,
-0x2E,0x0A,0x3F,0x6C,0xD8,0xD1,0xF5,0xE5,0x09,0xB4,0x6C,0x54,0x00,0x0A,0xE0,0x15,
-0x4D,0x87,0x75,0x6D,0xB7,0x58,0x96,0x5A,0xDD,0x6D,0xD2,0x00,0xA0,0xF4,0x9B,0x48,
-0xBE,0xC3,0x37,0xA4,0xBA,0x36,0xE0,0x7C,0x87,0x85,0x97,0x1A,0x15,0xA2,0xDE,0x2E,
-0xA2,0x5B,0xBD,0xAF,0x18,0xF9,0x90,0x50,0xCD,0x70,0x59,0xF8,0x27,0x67,0x47,0xCB,
-0xC7,0xA0,0x07,0x3A,0x7D,0xD1,0x2C,0x5D,0x6C,0x19,0x3A,0x66,0xB5,0x7D,0xFD,0x91,
-0x6F,0x82,0xB1,0xBE,0x08,0x93,0xDB,0x14,0x47,0xF1,0xA2,0x37,0xC7,0x45,0x9E,0x3C,
-0xC7,0x77,0xAF,0x64,0xA8,0x93,0xDF,0xF6,0x69,0x83,0x82,0x60,0xF2,0x49,0x42,0x34,
-0xED,0x5A,0x00,0x54,0x85,0x1C,0x16,0x36,0x92,0x0C,0x5C,0xFA,0xA6,0xAD,0xBF,0xDB,
-};
-
-
-/* subject:/C=US/O=AffirmTrust/CN=AffirmTrust Premium */
-/* issuer :/C=US/O=AffirmTrust/CN=AffirmTrust Premium */
-
-
-const unsigned char AffirmTrust_Premium_certificate[1354]={
-0x30,0x82,0x05,0x46,0x30,0x82,0x03,0x2E,0xA0,0x03,0x02,0x01,0x02,0x02,0x08,0x6D,
-0x8C,0x14,0x46,0xB1,0xA6,0x0A,0xEE,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x0C,0x05,0x00,0x30,0x41,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x0C,0x0B,
-0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x31,0x1C,0x30,0x1A,0x06,
-0x03,0x55,0x04,0x03,0x0C,0x13,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,
-0x74,0x20,0x50,0x72,0x65,0x6D,0x69,0x75,0x6D,0x30,0x1E,0x17,0x0D,0x31,0x30,0x30,
-0x31,0x32,0x39,0x31,0x34,0x31,0x30,0x33,0x36,0x5A,0x17,0x0D,0x34,0x30,0x31,0x32,
-0x33,0x31,0x31,0x34,0x31,0x30,0x33,0x36,0x5A,0x30,0x41,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,
-0x0A,0x0C,0x0B,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x31,0x1C,
-0x30,0x1A,0x06,0x03,0x55,0x04,0x03,0x0C,0x13,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,
-0x72,0x75,0x73,0x74,0x20,0x50,0x72,0x65,0x6D,0x69,0x75,0x6D,0x30,0x82,0x02,0x22,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,
-0x82,0x02,0x0F,0x00,0x30,0x82,0x02,0x0A,0x02,0x82,0x02,0x01,0x00,0xC4,0x12,0xDF,
-0xA9,0x5F,0xFE,0x41,0xDD,0xDD,0xF5,0x9F,0x8A,0xE3,0xF6,0xAC,0xE1,0x3C,0x78,0x9A,
-0xBC,0xD8,0xF0,0x7F,0x7A,0xA0,0x33,0x2A,0xDC,0x8D,0x20,0x5B,0xAE,0x2D,0x6F,0xE7,
-0x93,0xD9,0x36,0x70,0x6A,0x68,0xCF,0x8E,0x51,0xA3,0x85,0x5B,0x67,0x04,0xA0,0x10,
-0x24,0x6F,0x5D,0x28,0x82,0xC1,0x97,0x57,0xD8,0x48,0x29,0x13,0xB6,0xE1,0xBE,0x91,
-0x4D,0xDF,0x85,0x0C,0x53,0x18,0x9A,0x1E,0x24,0xA2,0x4F,0x8F,0xF0,0xA2,0x85,0x0B,
-0xCB,0xF4,0x29,0x7F,0xD2,0xA4,0x58,0xEE,0x26,0x4D,0xC9,0xAA,0xA8,0x7B,0x9A,0xD9,
-0xFA,0x38,0xDE,0x44,0x57,0x15,0xE5,0xF8,0x8C,0xC8,0xD9,0x48,0xE2,0x0D,0x16,0x27,
-0x1D,0x1E,0xC8,0x83,0x85,0x25,0xB7,0xBA,0xAA,0x55,0x41,0xCC,0x03,0x22,0x4B,0x2D,
-0x91,0x8D,0x8B,0xE6,0x89,0xAF,0x66,0xC7,0xE9,0xFF,0x2B,0xE9,0x3C,0xAC,0xDA,0xD2,
-0xB3,0xC3,0xE1,0x68,0x9C,0x89,0xF8,0x7A,0x00,0x56,0xDE,0xF4,0x55,0x95,0x6C,0xFB,
-0xBA,0x64,0xDD,0x62,0x8B,0xDF,0x0B,0x77,0x32,0xEB,0x62,0xCC,0x26,0x9A,0x9B,0xBB,
-0xAA,0x62,0x83,0x4C,0xB4,0x06,0x7A,0x30,0xC8,0x29,0xBF,0xED,0x06,0x4D,0x97,0xB9,
-0x1C,0xC4,0x31,0x2B,0xD5,0x5F,0xBC,0x53,0x12,0x17,0x9C,0x99,0x57,0x29,0x66,0x77,
-0x61,0x21,0x31,0x07,0x2E,0x25,0x49,0x9D,0x18,0xF2,0xEE,0xF3,0x2B,0x71,0x8C,0xB5,
-0xBA,0x39,0x07,0x49,0x77,0xFC,0xEF,0x2E,0x92,0x90,0x05,0x8D,0x2D,0x2F,0x77,0x7B,
-0xEF,0x43,0xBF,0x35,0xBB,0x9A,0xD8,0xF9,0x73,0xA7,0x2C,0xF2,0xD0,0x57,0xEE,0x28,
-0x4E,0x26,0x5F,0x8F,0x90,0x68,0x09,0x2F,0xB8,0xF8,0xDC,0x06,0xE9,0x2E,0x9A,0x3E,
-0x51,0xA7,0xD1,0x22,0xC4,0x0A,0xA7,0x38,0x48,0x6C,0xB3,0xF9,0xFF,0x7D,0xAB,0x86,
-0x57,0xE3,0xBA,0xD6,0x85,0x78,0x77,0xBA,0x43,0xEA,0x48,0x7F,0xF6,0xD8,0xBE,0x23,
-0x6D,0x1E,0xBF,0xD1,0x36,0x6C,0x58,0x5C,0xF1,0xEE,0xA4,0x19,0x54,0x1A,0xF5,0x03,
-0xD2,0x76,0xE6,0xE1,0x8C,0xBD,0x3C,0xB3,0xD3,0x48,0x4B,0xE2,0xC8,0xF8,0x7F,0x92,
-0xA8,0x76,0x46,0x9C,0x42,0x65,0x3E,0xA4,0x1E,0xC1,0x07,0x03,0x5A,0x46,0x2D,0xB8,
-0x97,0xF3,0xB7,0xD5,0xB2,0x55,0x21,0xEF,0xBA,0xDC,0x4C,0x00,0x97,0xFB,0x14,0x95,
-0x27,0x33,0xBF,0xE8,0x43,0x47,0x46,0xD2,0x08,0x99,0x16,0x60,0x3B,0x9A,0x7E,0xD2,
-0xE6,0xED,0x38,0xEA,0xEC,0x01,0x1E,0x3C,0x48,0x56,0x49,0x09,0xC7,0x4C,0x37,0x00,
-0x9E,0x88,0x0E,0xC0,0x73,0xE1,0x6F,0x66,0xE9,0x72,0x47,0x30,0x3E,0x10,0xE5,0x0B,
-0x03,0xC9,0x9A,0x42,0x00,0x6C,0xC5,0x94,0x7E,0x61,0xC4,0x8A,0xDF,0x7F,0x82,0x1A,
-0x0B,0x59,0xC4,0x59,0x32,0x77,0xB3,0xBC,0x60,0x69,0x56,0x39,0xFD,0xB4,0x06,0x7B,
-0x2C,0xD6,0x64,0x36,0xD9,0xBD,0x48,0xED,0x84,0x1F,0x7E,0xA5,0x22,0x8F,0x2A,0xB8,
-0x42,0xF4,0x82,0xB7,0xD4,0x53,0x90,0x78,0x4E,0x2D,0x1A,0xFD,0x81,0x6F,0x44,0xD7,
-0x3B,0x01,0x74,0x96,0x42,0xE0,0x00,0xE2,0x2E,0x6B,0xEA,0xC5,0xEE,0x72,0xAC,0xBB,
-0xBF,0xFE,0xEA,0xAA,0xA8,0xF8,0xDC,0xF6,0xB2,0x79,0x8A,0xB6,0x67,0x02,0x03,0x01,
-0x00,0x01,0xA3,0x42,0x30,0x40,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,
-0x14,0x9D,0xC0,0x67,0xA6,0x0C,0x22,0xD9,0x26,0xF5,0x45,0xAB,0xA6,0x65,0x52,0x11,
-0x27,0xD8,0x45,0xAC,0x63,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,
-0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,
-0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x0C,0x05,0x00,0x03,0x82,0x02,0x01,0x00,0xB3,0x57,0x4D,0x10,0x62,0x4E,
-0x3A,0xE4,0xAC,0xEA,0xB8,0x1C,0xAF,0x32,0x23,0xC8,0xB3,0x49,0x5A,0x51,0x9C,0x76,
-0x28,0x8D,0x79,0xAA,0x57,0x46,0x17,0xD5,0xF5,0x52,0xF6,0xB7,0x44,0xE8,0x08,0x44,
-0xBF,0x18,0x84,0xD2,0x0B,0x80,0xCD,0xC5,0x12,0xFD,0x00,0x55,0x05,0x61,0x87,0x41,
-0xDC,0xB5,0x24,0x9E,0x3C,0xC4,0xD8,0xC8,0xFB,0x70,0x9E,0x2F,0x78,0x96,0x83,0x20,
-0x36,0xDE,0x7C,0x0F,0x69,0x13,0x88,0xA5,0x75,0x36,0x98,0x08,0xA6,0xC6,0xDF,0xAC,
-0xCE,0xE3,0x58,0xD6,0xB7,0x3E,0xDE,0xBA,0xF3,0xEB,0x34,0x40,0xD8,0xA2,0x81,0xF5,
-0x78,0x3F,0x2F,0xD5,0xA5,0xFC,0xD9,0xA2,0xD4,0x5E,0x04,0x0E,0x17,0xAD,0xFE,0x41,
-0xF0,0xE5,0xB2,0x72,0xFA,0x44,0x82,0x33,0x42,0xE8,0x2D,0x58,0xF7,0x56,0x8C,0x62,
-0x3F,0xBA,0x42,0xB0,0x9C,0x0C,0x5C,0x7E,0x2E,0x65,0x26,0x5C,0x53,0x4F,0x00,0xB2,
-0x78,0x7E,0xA1,0x0D,0x99,0x2D,0x8D,0xB8,0x1D,0x8E,0xA2,0xC4,0xB0,0xFD,0x60,0xD0,
-0x30,0xA4,0x8E,0xC8,0x04,0x62,0xA9,0xC4,0xED,0x35,0xDE,0x7A,0x97,0xED,0x0E,0x38,
-0x5E,0x92,0x2F,0x93,0x70,0xA5,0xA9,0x9C,0x6F,0xA7,0x7D,0x13,0x1D,0x7E,0xC6,0x08,
-0x48,0xB1,0x5E,0x67,0xEB,0x51,0x08,0x25,0xE9,0xE6,0x25,0x6B,0x52,0x29,0x91,0x9C,
-0xD2,0x39,0x73,0x08,0x57,0xDE,0x99,0x06,0xB4,0x5B,0x9D,0x10,0x06,0xE1,0xC2,0x00,
-0xA8,0xB8,0x1C,0x4A,0x02,0x0A,0x14,0xD0,0xC1,0x41,0xCA,0xFB,0x8C,0x35,0x21,0x7D,
-0x82,0x38,0xF2,0xA9,0x54,0x91,0x19,0x35,0x93,0x94,0x6D,0x6A,0x3A,0xC5,0xB2,0xD0,
-0xBB,0x89,0x86,0x93,0xE8,0x9B,0xC9,0x0F,0x3A,0xA7,0x7A,0xB8,0xA1,0xF0,0x78,0x46,
-0xFA,0xFC,0x37,0x2F,0xE5,0x8A,0x84,0xF3,0xDF,0xFE,0x04,0xD9,0xA1,0x68,0xA0,0x2F,
-0x24,0xE2,0x09,0x95,0x06,0xD5,0x95,0xCA,0xE1,0x24,0x96,0xEB,0x7C,0xF6,0x93,0x05,
-0xBB,0xED,0x73,0xE9,0x2D,0xD1,0x75,0x39,0xD7,0xE7,0x24,0xDB,0xD8,0x4E,0x5F,0x43,
-0x8F,0x9E,0xD0,0x14,0x39,0xBF,0x55,0x70,0x48,0x99,0x57,0x31,0xB4,0x9C,0xEE,0x4A,
-0x98,0x03,0x96,0x30,0x1F,0x60,0x06,0xEE,0x1B,0x23,0xFE,0x81,0x60,0x23,0x1A,0x47,
-0x62,0x85,0xA5,0xCC,0x19,0x34,0x80,0x6F,0xB3,0xAC,0x1A,0xE3,0x9F,0xF0,0x7B,0x48,
-0xAD,0xD5,0x01,0xD9,0x67,0xB6,0xA9,0x72,0x93,0xEA,0x2D,0x66,0xB5,0xB2,0xB8,0xE4,
-0x3D,0x3C,0xB2,0xEF,0x4C,0x8C,0xEA,0xEB,0x07,0xBF,0xAB,0x35,0x9A,0x55,0x86,0xBC,
-0x18,0xA6,0xB5,0xA8,0x5E,0xB4,0x83,0x6C,0x6B,0x69,0x40,0xD3,0x9F,0xDC,0xF1,0xC3,
-0x69,0x6B,0xB9,0xE1,0x6D,0x09,0xF4,0xF1,0xAA,0x50,0x76,0x0A,0x7A,0x7D,0x7A,0x17,
-0xA1,0x55,0x96,0x42,0x99,0x31,0x09,0xDD,0x60,0x11,0x8D,0x05,0x30,0x7E,0xE6,0x8E,
-0x46,0xD1,0x9D,0x14,0xDA,0xC7,0x17,0xE4,0x05,0x96,0x8C,0xC4,0x24,0xB5,0x1B,0xCF,
-0x14,0x07,0xB2,0x40,0xF8,0xA3,0x9E,0x41,0x86,0xBC,0x04,0xD0,0x6B,0x96,0xC8,0x2A,
-0x80,0x34,0xFD,0xBF,0xEF,0x06,0xA3,0xDD,0x58,0xC5,0x85,0x3D,0x3E,0x8F,0xFE,0x9E,
-0x29,0xE0,0xB6,0xB8,0x09,0x68,0x19,0x1C,0x18,0x43,
-};
-
-
-/* subject:/C=US/O=AffirmTrust/CN=AffirmTrust Premium ECC */
-/* issuer :/C=US/O=AffirmTrust/CN=AffirmTrust Premium ECC */
-
-
-const unsigned char AffirmTrust_Premium_ECC_certificate[514]={
-0x30,0x82,0x01,0xFE,0x30,0x82,0x01,0x85,0xA0,0x03,0x02,0x01,0x02,0x02,0x08,0x74,
-0x97,0x25,0x8A,0xC7,0x3F,0x7A,0x54,0x30,0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,
-0x04,0x03,0x03,0x30,0x45,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,
-0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x0C,0x0B,0x41,0x66,0x66,
-0x69,0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,
-0x03,0x0C,0x17,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x20,0x50,
-0x72,0x65,0x6D,0x69,0x75,0x6D,0x20,0x45,0x43,0x43,0x30,0x1E,0x17,0x0D,0x31,0x30,
-0x30,0x31,0x32,0x39,0x31,0x34,0x32,0x30,0x32,0x34,0x5A,0x17,0x0D,0x34,0x30,0x31,
-0x32,0x33,0x31,0x31,0x34,0x32,0x30,0x32,0x34,0x5A,0x30,0x45,0x31,0x0B,0x30,0x09,
-0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,
-0x04,0x0A,0x0C,0x0B,0x41,0x66,0x66,0x69,0x72,0x6D,0x54,0x72,0x75,0x73,0x74,0x31,
-0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x0C,0x17,0x41,0x66,0x66,0x69,0x72,0x6D,
-0x54,0x72,0x75,0x73,0x74,0x20,0x50,0x72,0x65,0x6D,0x69,0x75,0x6D,0x20,0x45,0x43,
-0x43,0x30,0x76,0x30,0x10,0x06,0x07,0x2A,0x86,0x48,0xCE,0x3D,0x02,0x01,0x06,0x05,
-0x2B,0x81,0x04,0x00,0x22,0x03,0x62,0x00,0x04,0x0D,0x30,0x5E,0x1B,0x15,0x9D,0x03,
-0xD0,0xA1,0x79,0x35,0xB7,0x3A,0x3C,0x92,0x7A,0xCA,0x15,0x1C,0xCD,0x62,0xF3,0x9C,
-0x26,0x5C,0x07,0x3D,0xE5,0x54,0xFA,0xA3,0xD6,0xCC,0x12,0xEA,0xF4,0x14,0x5F,0xE8,
-0x8E,0x19,0xAB,0x2F,0x2E,0x48,0xE6,0xAC,0x18,0x43,0x78,0xAC,0xD0,0x37,0xC3,0xBD,
-0xB2,0xCD,0x2C,0xE6,0x47,0xE2,0x1A,0xE6,0x63,0xB8,0x3D,0x2E,0x2F,0x78,0xC4,0x4F,
-0xDB,0xF4,0x0F,0xA4,0x68,0x4C,0x55,0x72,0x6B,0x95,0x1D,0x4E,0x18,0x42,0x95,0x78,
-0xCC,0x37,0x3C,0x91,0xE2,0x9B,0x65,0x2B,0x29,0xA3,0x42,0x30,0x40,0x30,0x1D,0x06,
-0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x9A,0xAF,0x29,0x7A,0xC0,0x11,0x35,0x35,
-0x26,0x51,0x30,0x00,0xC3,0x6A,0xFE,0x40,0xD5,0xAE,0xD6,0x3C,0x30,0x0F,0x06,0x03,
-0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,
-0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0A,0x06,
-0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x03,0x03,0x67,0x00,0x30,0x64,0x02,0x30,
-0x17,0x09,0xF3,0x87,0x88,0x50,0x5A,0xAF,0xC8,0xC0,0x42,0xBF,0x47,0x5F,0xF5,0x6C,
-0x6A,0x86,0xE0,0xC4,0x27,0x74,0xE4,0x38,0x53,0xD7,0x05,0x7F,0x1B,0x34,0xE3,0xC6,
-0x2F,0xB3,0xCA,0x09,0x3C,0x37,0x9D,0xD7,0xE7,0xB8,0x46,0xF1,0xFD,0xA1,0xE2,0x71,
-0x02,0x30,0x42,0x59,0x87,0x43,0xD4,0x51,0xDF,0xBA,0xD3,0x09,0x32,0x5A,0xCE,0x88,
-0x7E,0x57,0x3D,0x9C,0x5F,0x42,0x6B,0xF5,0x07,0x2D,0xB5,0xF0,0x82,0x93,0xF9,0x59,
-0x6F,0xAE,0x64,0xFA,0x58,0xE5,0x8B,0x1E,0xE3,0x63,0xBE,0xB5,0x81,0xCD,0x6F,0x02,
-0x8C,0x79,
-};
-
-
-/* subject:/C=US/O=America Online Inc./CN=America Online Root Certification Authority 1 */
-/* issuer :/C=US/O=America Online Inc./CN=America Online Root Certification Authority 1 */
-
-
-const unsigned char America_Online_Root_Certification_Authority_1_certificate[936]={
-0x30,0x82,0x03,0xA4,0x30,0x82,0x02,0x8C,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x63,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x1C,
-0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x41,0x6D,0x65,0x72,0x69,0x63,0x61,
-0x20,0x4F,0x6E,0x6C,0x69,0x6E,0x65,0x20,0x49,0x6E,0x63,0x2E,0x31,0x36,0x30,0x34,
-0x06,0x03,0x55,0x04,0x03,0x13,0x2D,0x41,0x6D,0x65,0x72,0x69,0x63,0x61,0x20,0x4F,
-0x6E,0x6C,0x69,0x6E,0x65,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x20,0x31,0x30,0x1E,0x17,0x0D,0x30,0x32,0x30,0x35,0x32,0x38,0x30,0x36,
-0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x37,0x31,0x31,0x31,0x39,0x32,0x30,0x34,
-0x33,0x30,0x30,0x5A,0x30,0x63,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x55,0x53,0x31,0x1C,0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x41,0x6D,
-0x65,0x72,0x69,0x63,0x61,0x20,0x4F,0x6E,0x6C,0x69,0x6E,0x65,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x36,0x30,0x34,0x06,0x03,0x55,0x04,0x03,0x13,0x2D,0x41,0x6D,0x65,0x72,
-0x69,0x63,0x61,0x20,0x4F,0x6E,0x6C,0x69,0x6E,0x65,0x20,0x52,0x6F,0x6F,0x74,0x20,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,
-0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x31,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,
-0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xA8,0x2F,0xE8,0xA4,0x69,0x06,
-0x03,0x47,0xC3,0xE9,0x2A,0x98,0xFF,0x19,0xA2,0x70,0x9A,0xC6,0x50,0xB2,0x7E,0xA5,
-0xDF,0x68,0x4D,0x1B,0x7C,0x0F,0xB6,0x97,0x68,0x7D,0x2D,0xA6,0x8B,0x97,0xE9,0x64,
-0x86,0xC9,0xA3,0xEF,0xA0,0x86,0xBF,0x60,0x65,0x9C,0x4B,0x54,0x88,0xC2,0x48,0xC5,
-0x4A,0x39,0xBF,0x14,0xE3,0x59,0x55,0xE5,0x19,0xB4,0x74,0xC8,0xB4,0x05,0x39,0x5C,
-0x16,0xA5,0xE2,0x95,0x05,0xE0,0x12,0xAE,0x59,0x8B,0xA2,0x33,0x68,0x58,0x1C,0xA6,
-0xD4,0x15,0xB7,0xD8,0x9F,0xD7,0xDC,0x71,0xAB,0x7E,0x9A,0xBF,0x9B,0x8E,0x33,0x0F,
-0x22,0xFD,0x1F,0x2E,0xE7,0x07,0x36,0xEF,0x62,0x39,0xC5,0xDD,0xCB,0xBA,0x25,0x14,
-0x23,0xDE,0x0C,0xC6,0x3D,0x3C,0xCE,0x82,0x08,0xE6,0x66,0x3E,0xDA,0x51,0x3B,0x16,
-0x3A,0xA3,0x05,0x7F,0xA0,0xDC,0x87,0xD5,0x9C,0xFC,0x72,0xA9,0xA0,0x7D,0x78,0xE4,
-0xB7,0x31,0x55,0x1E,0x65,0xBB,0xD4,0x61,0xB0,0x21,0x60,0xED,0x10,0x32,0x72,0xC5,
-0x92,0x25,0x1E,0xF8,0x90,0x4A,0x18,0x78,0x47,0xDF,0x7E,0x30,0x37,0x3E,0x50,0x1B,
-0xDB,0x1C,0xD3,0x6B,0x9A,0x86,0x53,0x07,0xB0,0xEF,0xAC,0x06,0x78,0xF8,0x84,0x99,
-0xFE,0x21,0x8D,0x4C,0x80,0xB6,0x0C,0x82,0xF6,0x66,0x70,0x79,0x1A,0xD3,0x4F,0xA3,
-0xCF,0xF1,0xCF,0x46,0xB0,0x4B,0x0F,0x3E,0xDD,0x88,0x62,0xB8,0x8C,0xA9,0x09,0x28,
-0x3B,0x7A,0xC7,0x97,0xE1,0x1E,0xE5,0xF4,0x9F,0xC0,0xC0,0xAE,0x24,0xA0,0xC8,0xA1,
-0xD9,0x0F,0xD6,0x7B,0x26,0x82,0x69,0x32,0x3D,0xA7,0x02,0x03,0x01,0x00,0x01,0xA3,
-0x63,0x30,0x61,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x00,
-0xAD,0xD9,0xA3,0xF6,0x79,0xF6,0x6E,0x74,0xA9,0x7F,0x33,0x3D,0x81,0x17,0xD7,0x4C,
-0xCF,0x33,0xDE,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,
-0x00,0xAD,0xD9,0xA3,0xF6,0x79,0xF6,0x6E,0x74,0xA9,0x7F,0x33,0x3D,0x81,0x17,0xD7,
-0x4C,0xCF,0x33,0xDE,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,
-0x03,0x02,0x01,0x86,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x7C,0x8A,0xD1,0x1F,0x18,0x37,0x82,0xE0,
-0xB8,0xB0,0xA3,0xED,0x56,0x95,0xC8,0x62,0x61,0x9C,0x05,0xA2,0xCD,0xC2,0x62,0x26,
-0x61,0xCD,0x10,0x16,0xD7,0xCC,0xB4,0x65,0x34,0xD0,0x11,0x8A,0xAD,0xA8,0xA9,0x05,
-0x66,0xEF,0x74,0xF3,0x6D,0x5F,0x9D,0x99,0xAF,0xF6,0x8B,0xFB,0xEB,0x52,0xB2,0x05,
-0x98,0xA2,0x6F,0x2A,0xC5,0x54,0xBD,0x25,0xBD,0x5F,0xAE,0xC8,0x86,0xEA,0x46,0x2C,
-0xC1,0xB3,0xBD,0xC1,0xE9,0x49,0x70,0x18,0x16,0x97,0x08,0x13,0x8C,0x20,0xE0,0x1B,
-0x2E,0x3A,0x47,0xCB,0x1E,0xE4,0x00,0x30,0x95,0x5B,0xF4,0x45,0xA3,0xC0,0x1A,0xB0,
-0x01,0x4E,0xAB,0xBD,0xC0,0x23,0x6E,0x63,0x3F,0x80,0x4A,0xC5,0x07,0xED,0xDC,0xE2,
-0x6F,0xC7,0xC1,0x62,0xF1,0xE3,0x72,0xD6,0x04,0xC8,0x74,0x67,0x0B,0xFA,0x88,0xAB,
-0xA1,0x01,0xC8,0x6F,0xF0,0x14,0xAF,0xD2,0x99,0xCD,0x51,0x93,0x7E,0xED,0x2E,0x38,
-0xC7,0xBD,0xCE,0x46,0x50,0x3D,0x72,0xE3,0x79,0x25,0x9D,0x9B,0x88,0x2B,0x10,0x20,
-0xDD,0xA5,0xB8,0x32,0x9F,0x8D,0xE0,0x29,0xDF,0x21,0x74,0x86,0x82,0xDB,0x2F,0x82,
-0x30,0xC6,0xC7,0x35,0x86,0xB3,0xF9,0x96,0x5F,0x46,0xDB,0x0C,0x45,0xFD,0xF3,0x50,
-0xC3,0x6F,0xC6,0xC3,0x48,0xAD,0x46,0xA6,0xE1,0x27,0x47,0x0A,0x1D,0x0E,0x9B,0xB6,
-0xC2,0x77,0x7F,0x63,0xF2,0xE0,0x7D,0x1A,0xBE,0xFC,0xE0,0xDF,0xD7,0xC7,0xA7,0x6C,
-0xB0,0xF9,0xAE,0xBA,0x3C,0xFD,0x74,0xB4,0x11,0xE8,0x58,0x0D,0x80,0xBC,0xD3,0xA8,
-0x80,0x3A,0x99,0xED,0x75,0xCC,0x46,0x7B,
-};
-
-
-/* subject:/C=US/O=America Online Inc./CN=America Online Root Certification Authority 2 */
-/* issuer :/C=US/O=America Online Inc./CN=America Online Root Certification Authority 2 */
-
-
-const unsigned char America_Online_Root_Certification_Authority_2_certificate[1448]={
-0x30,0x82,0x05,0xA4,0x30,0x82,0x03,0x8C,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x63,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x1C,
-0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x41,0x6D,0x65,0x72,0x69,0x63,0x61,
-0x20,0x4F,0x6E,0x6C,0x69,0x6E,0x65,0x20,0x49,0x6E,0x63,0x2E,0x31,0x36,0x30,0x34,
-0x06,0x03,0x55,0x04,0x03,0x13,0x2D,0x41,0x6D,0x65,0x72,0x69,0x63,0x61,0x20,0x4F,
-0x6E,0x6C,0x69,0x6E,0x65,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x20,0x32,0x30,0x1E,0x17,0x0D,0x30,0x32,0x30,0x35,0x32,0x38,0x30,0x36,
-0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x37,0x30,0x39,0x32,0x39,0x31,0x34,0x30,
-0x38,0x30,0x30,0x5A,0x30,0x63,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x55,0x53,0x31,0x1C,0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x41,0x6D,
-0x65,0x72,0x69,0x63,0x61,0x20,0x4F,0x6E,0x6C,0x69,0x6E,0x65,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x36,0x30,0x34,0x06,0x03,0x55,0x04,0x03,0x13,0x2D,0x41,0x6D,0x65,0x72,
-0x69,0x63,0x61,0x20,0x4F,0x6E,0x6C,0x69,0x6E,0x65,0x20,0x52,0x6F,0x6F,0x74,0x20,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,
-0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x32,0x30,0x82,0x02,0x22,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x02,0x0F,
-0x00,0x30,0x82,0x02,0x0A,0x02,0x82,0x02,0x01,0x00,0xCC,0x41,0x45,0x1D,0xE9,0x3D,
-0x4D,0x10,0xF6,0x8C,0xB1,0x41,0xC9,0xE0,0x5E,0xCB,0x0D,0xB7,0xBF,0x47,0x73,0xD3,
-0xF0,0x55,0x4D,0xDD,0xC6,0x0C,0xFA,0xB1,0x66,0x05,0x6A,0xCD,0x78,0xB4,0xDC,0x02,
-0xDB,0x4E,0x81,0xF3,0xD7,0xA7,0x7C,0x71,0xBC,0x75,0x63,0xA0,0x5D,0xE3,0x07,0x0C,
-0x48,0xEC,0x25,0xC4,0x03,0x20,0xF4,0xFF,0x0E,0x3B,0x12,0xFF,0x9B,0x8D,0xE1,0xC6,
-0xD5,0x1B,0xB4,0x6D,0x22,0xE3,0xB1,0xDB,0x7F,0x21,0x64,0xAF,0x86,0xBC,0x57,0x22,
-0x2A,0xD6,0x47,0x81,0x57,0x44,0x82,0x56,0x53,0xBD,0x86,0x14,0x01,0x0B,0xFC,0x7F,
-0x74,0xA4,0x5A,0xAE,0xF1,0xBA,0x11,0xB5,0x9B,0x58,0x5A,0x80,0xB4,0x37,0x78,0x09,
-0x33,0x7C,0x32,0x47,0x03,0x5C,0xC4,0xA5,0x83,0x48,0xF4,0x57,0x56,0x6E,0x81,0x36,
-0x27,0x18,0x4F,0xEC,0x9B,0x28,0xC2,0xD4,0xB4,0xD7,0x7C,0x0C,0x3E,0x0C,0x2B,0xDF,
-0xCA,0x04,0xD7,0xC6,0x8E,0xEA,0x58,0x4E,0xA8,0xA4,0xA5,0x18,0x1C,0x6C,0x45,0x98,
-0xA3,0x41,0xD1,0x2D,0xD2,0xC7,0x6D,0x8D,0x19,0xF1,0xAD,0x79,0xB7,0x81,0x3F,0xBD,
-0x06,0x82,0x27,0x2D,0x10,0x58,0x05,0xB5,0x78,0x05,0xB9,0x2F,0xDB,0x0C,0x6B,0x90,
-0x90,0x7E,0x14,0x59,0x38,0xBB,0x94,0x24,0x13,0xE5,0xD1,0x9D,0x14,0xDF,0xD3,0x82,
-0x4D,0x46,0xF0,0x80,0x39,0x52,0x32,0x0F,0xE3,0x84,0xB2,0x7A,0x43,0xF2,0x5E,0xDE,
-0x5F,0x3F,0x1D,0xDD,0xE3,0xB2,0x1B,0xA0,0xA1,0x2A,0x23,0x03,0x6E,0x2E,0x01,0x15,
-0x87,0x5C,0xA6,0x75,0x75,0xC7,0x97,0x61,0xBE,0xDE,0x86,0xDC,0xD4,0x48,0xDB,0xBD,
-0x2A,0xBF,0x4A,0x55,0xDA,0xE8,0x7D,0x50,0xFB,0xB4,0x80,0x17,0xB8,0x94,0xBF,0x01,
-0x3D,0xEA,0xDA,0xBA,0x7C,0xE0,0x58,0x67,0x17,0xB9,0x58,0xE0,0x88,0x86,0x46,0x67,
-0x6C,0x9D,0x10,0x47,0x58,0x32,0xD0,0x35,0x7C,0x79,0x2A,0x90,0xA2,0x5A,0x10,0x11,
-0x23,0x35,0xAD,0x2F,0xCC,0xE4,0x4A,0x5B,0xA7,0xC8,0x27,0xF2,0x83,0xDE,0x5E,0xBB,
-0x5E,0x77,0xE7,0xE8,0xA5,0x6E,0x63,0xC2,0x0D,0x5D,0x61,0xD0,0x8C,0xD2,0x6C,0x5A,
-0x21,0x0E,0xCA,0x28,0xA3,0xCE,0x2A,0xE9,0x95,0xC7,0x48,0xCF,0x96,0x6F,0x1D,0x92,
-0x25,0xC8,0xC6,0xC6,0xC1,0xC1,0x0C,0x05,0xAC,0x26,0xC4,0xD2,0x75,0xD2,0xE1,0x2A,
-0x67,0xC0,0x3D,0x5B,0xA5,0x9A,0xEB,0xCF,0x7B,0x1A,0xA8,0x9D,0x14,0x45,0xE5,0x0F,
-0xA0,0x9A,0x65,0xDE,0x2F,0x28,0xBD,0xCE,0x6F,0x94,0x66,0x83,0x48,0x29,0xD8,0xEA,
-0x65,0x8C,0xAF,0x93,0xD9,0x64,0x9F,0x55,0x57,0x26,0xBF,0x6F,0xCB,0x37,0x31,0x99,
-0xA3,0x60,0xBB,0x1C,0xAD,0x89,0x34,0x32,0x62,0xB8,0x43,0x21,0x06,0x72,0x0C,0xA1,
-0x5C,0x6D,0x46,0xC5,0xFA,0x29,0xCF,0x30,0xDE,0x89,0xDC,0x71,0x5B,0xDD,0xB6,0x37,
-0x3E,0xDF,0x50,0xF5,0xB8,0x07,0x25,0x26,0xE5,0xBC,0xB5,0xFE,0x3C,0x02,0xB3,0xB7,
-0xF8,0xBE,0x43,0xC1,0x87,0x11,0x94,0x9E,0x23,0x6C,0x17,0x8A,0xB8,0x8A,0x27,0x0C,
-0x54,0x47,0xF0,0xA9,0xB3,0xC0,0x80,0x8C,0xA0,0x27,0xEB,0x1D,0x19,0xE3,0x07,0x8E,
-0x77,0x70,0xCA,0x2B,0xF4,0x7D,0x76,0xE0,0x78,0x67,0x02,0x03,0x01,0x00,0x01,0xA3,
-0x63,0x30,0x61,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x4D,
-0x45,0xC1,0x68,0x38,0xBB,0x73,0xA9,0x69,0xA1,0x20,0xE7,0xED,0xF5,0x22,0xA1,0x23,
-0x14,0xD7,0x9E,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,
-0x4D,0x45,0xC1,0x68,0x38,0xBB,0x73,0xA9,0x69,0xA1,0x20,0xE7,0xED,0xF5,0x22,0xA1,
-0x23,0x14,0xD7,0x9E,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,
-0x03,0x02,0x01,0x86,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x05,0x05,0x00,0x03,0x82,0x02,0x01,0x00,0x67,0x6B,0x06,0xB9,0x5F,0x45,0x3B,0x2A,
-0x4B,0x33,0xB3,0xE6,0x1B,0x6B,0x59,0x4E,0x22,0xCC,0xB9,0xB7,0xA4,0x25,0xC9,0xA7,
-0xC4,0xF0,0x54,0x96,0x0B,0x64,0xF3,0xB1,0x58,0x4F,0x5E,0x51,0xFC,0xB2,0x97,0x7B,
-0x27,0x65,0xC2,0xE5,0xCA,0xE7,0x0D,0x0C,0x25,0x7B,0x62,0xE3,0xFA,0x9F,0xB4,0x87,
-0xB7,0x45,0x46,0xAF,0x83,0xA5,0x97,0x48,0x8C,0xA5,0xBD,0xF1,0x16,0x2B,0x9B,0x76,
-0x2C,0x7A,0x35,0x60,0x6C,0x11,0x80,0x97,0xCC,0xA9,0x92,0x52,0xE6,0x2B,0xE6,0x69,
-0xED,0xA9,0xF8,0x36,0x2D,0x2C,0x77,0xBF,0x61,0x48,0xD1,0x63,0x0B,0xB9,0x5B,0x52,
-0xED,0x18,0xB0,0x43,0x42,0x22,0xA6,0xB1,0x77,0xAE,0xDE,0x69,0xC5,0xCD,0xC7,0x1C,
-0xA1,0xB1,0xA5,0x1C,0x10,0xFB,0x18,0xBE,0x1A,0x70,0xDD,0xC1,0x92,0x4B,0xBE,0x29,
-0x5A,0x9D,0x3F,0x35,0xBE,0xE5,0x7D,0x51,0xF8,0x55,0xE0,0x25,0x75,0x23,0x87,0x1E,
-0x5C,0xDC,0xBA,0x9D,0xB0,0xAC,0xB3,0x69,0xDB,0x17,0x83,0xC9,0xF7,0xDE,0x0C,0xBC,
-0x08,0xDC,0x91,0x9E,0xA8,0xD0,0xD7,0x15,0x37,0x73,0xA5,0x35,0xB8,0xFC,0x7E,0xC5,
-0x44,0x40,0x06,0xC3,0xEB,0xF8,0x22,0x80,0x5C,0x47,0xCE,0x02,0xE3,0x11,0x9F,0x44,
-0xFF,0xFD,0x9A,0x32,0xCC,0x7D,0x64,0x51,0x0E,0xEB,0x57,0x26,0x76,0x3A,0xE3,0x1E,
-0x22,0x3C,0xC2,0xA6,0x36,0xDD,0x19,0xEF,0xA7,0xFC,0x12,0xF3,0x26,0xC0,0x59,0x31,
-0x85,0x4C,0x9C,0xD8,0xCF,0xDF,0xA4,0xCC,0xCC,0x29,0x93,0xFF,0x94,0x6D,0x76,0x5C,
-0x13,0x08,0x97,0xF2,0xED,0xA5,0x0B,0x4D,0xDD,0xE8,0xC9,0x68,0x0E,0x66,0xD3,0x00,
-0x0E,0x33,0x12,0x5B,0xBC,0x95,0xE5,0x32,0x90,0xA8,0xB3,0xC6,0x6C,0x83,0xAD,0x77,
-0xEE,0x8B,0x7E,0x7E,0xB1,0xA9,0xAB,0xD3,0xE1,0xF1,0xB6,0xC0,0xB1,0xEA,0x88,0xC0,
-0xE7,0xD3,0x90,0xE9,0x28,0x92,0x94,0x7B,0x68,0x7B,0x97,0x2A,0x0A,0x67,0x2D,0x85,
-0x02,0x38,0x10,0xE4,0x03,0x61,0xD4,0xDA,0x25,0x36,0xC7,0x08,0x58,0x2D,0xA1,0xA7,
-0x51,0xAF,0x30,0x0A,0x49,0xF5,0xA6,0x69,0x87,0x07,0x2D,0x44,0x46,0x76,0x8E,0x2A,
-0xE5,0x9A,0x3B,0xD7,0x18,0xA2,0xFC,0x9C,0x38,0x10,0xCC,0xC6,0x3B,0xD2,0xB5,0x17,
-0x3A,0x6F,0xFD,0xAE,0x25,0xBD,0xF5,0x72,0x59,0x64,0xB1,0x74,0x2A,0x38,0x5F,0x18,
-0x4C,0xDF,0xCF,0x71,0x04,0x5A,0x36,0xD4,0xBF,0x2F,0x99,0x9C,0xE8,0xD9,0xBA,0xB1,
-0x95,0xE6,0x02,0x4B,0x21,0xA1,0x5B,0xD5,0xC1,0x4F,0x8F,0xAE,0x69,0x6D,0x53,0xDB,
-0x01,0x93,0xB5,0x5C,0x1E,0x18,0xDD,0x64,0x5A,0xCA,0x18,0x28,0x3E,0x63,0x04,0x11,
-0xFD,0x1C,0x8D,0x00,0x0F,0xB8,0x37,0xDF,0x67,0x8A,0x9D,0x66,0xA9,0x02,0x6A,0x91,
-0xFF,0x13,0xCA,0x2F,0x5D,0x83,0xBC,0x87,0x93,0x6C,0xDC,0x24,0x51,0x16,0x04,0x25,
-0x66,0xFA,0xB3,0xD9,0xC2,0xBA,0x29,0xBE,0x9A,0x48,0x38,0x82,0x99,0xF4,0xBF,0x3B,
-0x4A,0x31,0x19,0xF9,0xBF,0x8E,0x21,0x33,0x14,0xCA,0x4F,0x54,0x5F,0xFB,0xCE,0xFB,
-0x8F,0x71,0x7F,0xFD,0x5E,0x19,0xA0,0x0F,0x4B,0x91,0xB8,0xC4,0x54,0xBC,0x06,0xB0,
-0x45,0x8F,0x26,0x91,0xA2,0x8E,0xFE,0xA9,
-};
-
-
-/* subject:/C=IE/O=Baltimore/OU=CyberTrust/CN=Baltimore CyberTrust Root */
-/* issuer :/C=IE/O=Baltimore/OU=CyberTrust/CN=Baltimore CyberTrust Root */
-
-
-const unsigned char Baltimore_CyberTrust_Root_certificate[891]={
-0x30,0x82,0x03,0x77,0x30,0x82,0x02,0x5F,0xA0,0x03,0x02,0x01,0x02,0x02,0x04,0x02,
-0x00,0x00,0xB9,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x30,0x5A,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x49,
-0x45,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04,0x0A,0x13,0x09,0x42,0x61,0x6C,0x74,
-0x69,0x6D,0x6F,0x72,0x65,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x0B,0x13,0x0A,
-0x43,0x79,0x62,0x65,0x72,0x54,0x72,0x75,0x73,0x74,0x31,0x22,0x30,0x20,0x06,0x03,
-0x55,0x04,0x03,0x13,0x19,0x42,0x61,0x6C,0x74,0x69,0x6D,0x6F,0x72,0x65,0x20,0x43,
-0x79,0x62,0x65,0x72,0x54,0x72,0x75,0x73,0x74,0x20,0x52,0x6F,0x6F,0x74,0x30,0x1E,
-0x17,0x0D,0x30,0x30,0x30,0x35,0x31,0x32,0x31,0x38,0x34,0x36,0x30,0x30,0x5A,0x17,
-0x0D,0x32,0x35,0x30,0x35,0x31,0x32,0x32,0x33,0x35,0x39,0x30,0x30,0x5A,0x30,0x5A,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x49,0x45,0x31,0x12,0x30,
-0x10,0x06,0x03,0x55,0x04,0x0A,0x13,0x09,0x42,0x61,0x6C,0x74,0x69,0x6D,0x6F,0x72,
-0x65,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x0B,0x13,0x0A,0x43,0x79,0x62,0x65,
-0x72,0x54,0x72,0x75,0x73,0x74,0x31,0x22,0x30,0x20,0x06,0x03,0x55,0x04,0x03,0x13,
-0x19,0x42,0x61,0x6C,0x74,0x69,0x6D,0x6F,0x72,0x65,0x20,0x43,0x79,0x62,0x65,0x72,
-0x54,0x72,0x75,0x73,0x74,0x20,0x52,0x6F,0x6F,0x74,0x30,0x82,0x01,0x22,0x30,0x0D,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,
-0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xA3,0x04,0xBB,0x22,0xAB,
-0x98,0x3D,0x57,0xE8,0x26,0x72,0x9A,0xB5,0x79,0xD4,0x29,0xE2,0xE1,0xE8,0x95,0x80,
-0xB1,0xB0,0xE3,0x5B,0x8E,0x2B,0x29,0x9A,0x64,0xDF,0xA1,0x5D,0xED,0xB0,0x09,0x05,
-0x6D,0xDB,0x28,0x2E,0xCE,0x62,0xA2,0x62,0xFE,0xB4,0x88,0xDA,0x12,0xEB,0x38,0xEB,
-0x21,0x9D,0xC0,0x41,0x2B,0x01,0x52,0x7B,0x88,0x77,0xD3,0x1C,0x8F,0xC7,0xBA,0xB9,
-0x88,0xB5,0x6A,0x09,0xE7,0x73,0xE8,0x11,0x40,0xA7,0xD1,0xCC,0xCA,0x62,0x8D,0x2D,
-0xE5,0x8F,0x0B,0xA6,0x50,0xD2,0xA8,0x50,0xC3,0x28,0xEA,0xF5,0xAB,0x25,0x87,0x8A,
-0x9A,0x96,0x1C,0xA9,0x67,0xB8,0x3F,0x0C,0xD5,0xF7,0xF9,0x52,0x13,0x2F,0xC2,0x1B,
-0xD5,0x70,0x70,0xF0,0x8F,0xC0,0x12,0xCA,0x06,0xCB,0x9A,0xE1,0xD9,0xCA,0x33,0x7A,
-0x77,0xD6,0xF8,0xEC,0xB9,0xF1,0x68,0x44,0x42,0x48,0x13,0xD2,0xC0,0xC2,0xA4,0xAE,
-0x5E,0x60,0xFE,0xB6,0xA6,0x05,0xFC,0xB4,0xDD,0x07,0x59,0x02,0xD4,0x59,0x18,0x98,
-0x63,0xF5,0xA5,0x63,0xE0,0x90,0x0C,0x7D,0x5D,0xB2,0x06,0x7A,0xF3,0x85,0xEA,0xEB,
-0xD4,0x03,0xAE,0x5E,0x84,0x3E,0x5F,0xFF,0x15,0xED,0x69,0xBC,0xF9,0x39,0x36,0x72,
-0x75,0xCF,0x77,0x52,0x4D,0xF3,0xC9,0x90,0x2C,0xB9,0x3D,0xE5,0xC9,0x23,0x53,0x3F,
-0x1F,0x24,0x98,0x21,0x5C,0x07,0x99,0x29,0xBD,0xC6,0x3A,0xEC,0xE7,0x6E,0x86,0x3A,
-0x6B,0x97,0x74,0x63,0x33,0xBD,0x68,0x18,0x31,0xF0,0x78,0x8D,0x76,0xBF,0xFC,0x9E,
-0x8E,0x5D,0x2A,0x86,0xA7,0x4D,0x90,0xDC,0x27,0x1A,0x39,0x02,0x03,0x01,0x00,0x01,
-0xA3,0x45,0x30,0x43,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xE5,
-0x9D,0x59,0x30,0x82,0x47,0x58,0xCC,0xAC,0xFA,0x08,0x54,0x36,0x86,0x7B,0x3A,0xB5,
-0x04,0x4D,0xF0,0x30,0x12,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x08,0x30,
-0x06,0x01,0x01,0xFF,0x02,0x01,0x03,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,
-0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x85,0x0C,0x5D,0x8E,0xE4,
-0x6F,0x51,0x68,0x42,0x05,0xA0,0xDD,0xBB,0x4F,0x27,0x25,0x84,0x03,0xBD,0xF7,0x64,
-0xFD,0x2D,0xD7,0x30,0xE3,0xA4,0x10,0x17,0xEB,0xDA,0x29,0x29,0xB6,0x79,0x3F,0x76,
-0xF6,0x19,0x13,0x23,0xB8,0x10,0x0A,0xF9,0x58,0xA4,0xD4,0x61,0x70,0xBD,0x04,0x61,
-0x6A,0x12,0x8A,0x17,0xD5,0x0A,0xBD,0xC5,0xBC,0x30,0x7C,0xD6,0xE9,0x0C,0x25,0x8D,
-0x86,0x40,0x4F,0xEC,0xCC,0xA3,0x7E,0x38,0xC6,0x37,0x11,0x4F,0xED,0xDD,0x68,0x31,
-0x8E,0x4C,0xD2,0xB3,0x01,0x74,0xEE,0xBE,0x75,0x5E,0x07,0x48,0x1A,0x7F,0x70,0xFF,
-0x16,0x5C,0x84,0xC0,0x79,0x85,0xB8,0x05,0xFD,0x7F,0xBE,0x65,0x11,0xA3,0x0F,0xC0,
-0x02,0xB4,0xF8,0x52,0x37,0x39,0x04,0xD5,0xA9,0x31,0x7A,0x18,0xBF,0xA0,0x2A,0xF4,
-0x12,0x99,0xF7,0xA3,0x45,0x82,0xE3,0x3C,0x5E,0xF5,0x9D,0x9E,0xB5,0xC8,0x9E,0x7C,
-0x2E,0xC8,0xA4,0x9E,0x4E,0x08,0x14,0x4B,0x6D,0xFD,0x70,0x6D,0x6B,0x1A,0x63,0xBD,
-0x64,0xE6,0x1F,0xB7,0xCE,0xF0,0xF2,0x9F,0x2E,0xBB,0x1B,0xB7,0xF2,0x50,0x88,0x73,
-0x92,0xC2,0xE2,0xE3,0x16,0x8D,0x9A,0x32,0x02,0xAB,0x8E,0x18,0xDD,0xE9,0x10,0x11,
-0xEE,0x7E,0x35,0xAB,0x90,0xAF,0x3E,0x30,0x94,0x7A,0xD0,0x33,0x3D,0xA7,0x65,0x0F,
-0xF5,0xFC,0x8E,0x9E,0x62,0xCF,0x47,0x44,0x2C,0x01,0x5D,0xBB,0x1D,0xB5,0x32,0xD2,
-0x47,0xD2,0x38,0x2E,0xD0,0xFE,0x81,0xDC,0x32,0x6A,0x1E,0xB5,0xEE,0x3C,0xD5,0xFC,
-0xE7,0x81,0x1D,0x19,0xC3,0x24,0x42,0xEA,0x63,0x39,0xA9,
-};
-
-
-/* subject:/C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=AAA Certificate Services */
-/* issuer :/C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=AAA Certificate Services */
-
-
-const unsigned char Comodo_AAA_Services_root_certificate[1078]={
-0x30,0x82,0x04,0x32,0x30,0x82,0x03,0x1A,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x7B,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,0x1B,
-0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x0C,0x12,0x47,0x72,0x65,0x61,0x74,0x65,0x72,
-0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,0x06,
-0x03,0x55,0x04,0x07,0x0C,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,0x30,
-0x18,0x06,0x03,0x55,0x04,0x0A,0x0C,0x11,0x43,0x6F,0x6D,0x6F,0x64,0x6F,0x20,0x43,
-0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,
-0x04,0x03,0x0C,0x18,0x41,0x41,0x41,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,
-0x61,0x74,0x65,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x30,0x1E,0x17,0x0D,
-0x30,0x34,0x30,0x31,0x30,0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,
-0x38,0x31,0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x7B,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,0x1B,0x30,0x19,0x06,
-0x03,0x55,0x04,0x08,0x0C,0x12,0x47,0x72,0x65,0x61,0x74,0x65,0x72,0x20,0x4D,0x61,
-0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,
-0x07,0x0C,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,0x30,0x18,0x06,0x03,
-0x55,0x04,0x0A,0x0C,0x11,0x43,0x6F,0x6D,0x6F,0x64,0x6F,0x20,0x43,0x41,0x20,0x4C,
-0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x0C,
-0x18,0x41,0x41,0x41,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,
-0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,
-0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xBE,0x40,0x9D,0xF4,0x6E,0xE1,
-0xEA,0x76,0x87,0x1C,0x4D,0x45,0x44,0x8E,0xBE,0x46,0xC8,0x83,0x06,0x9D,0xC1,0x2A,
-0xFE,0x18,0x1F,0x8E,0xE4,0x02,0xFA,0xF3,0xAB,0x5D,0x50,0x8A,0x16,0x31,0x0B,0x9A,
-0x06,0xD0,0xC5,0x70,0x22,0xCD,0x49,0x2D,0x54,0x63,0xCC,0xB6,0x6E,0x68,0x46,0x0B,
-0x53,0xEA,0xCB,0x4C,0x24,0xC0,0xBC,0x72,0x4E,0xEA,0xF1,0x15,0xAE,0xF4,0x54,0x9A,
-0x12,0x0A,0xC3,0x7A,0xB2,0x33,0x60,0xE2,0xDA,0x89,0x55,0xF3,0x22,0x58,0xF3,0xDE,
-0xDC,0xCF,0xEF,0x83,0x86,0xA2,0x8C,0x94,0x4F,0x9F,0x68,0xF2,0x98,0x90,0x46,0x84,
-0x27,0xC7,0x76,0xBF,0xE3,0xCC,0x35,0x2C,0x8B,0x5E,0x07,0x64,0x65,0x82,0xC0,0x48,
-0xB0,0xA8,0x91,0xF9,0x61,0x9F,0x76,0x20,0x50,0xA8,0x91,0xC7,0x66,0xB5,0xEB,0x78,
-0x62,0x03,0x56,0xF0,0x8A,0x1A,0x13,0xEA,0x31,0xA3,0x1E,0xA0,0x99,0xFD,0x38,0xF6,
-0xF6,0x27,0x32,0x58,0x6F,0x07,0xF5,0x6B,0xB8,0xFB,0x14,0x2B,0xAF,0xB7,0xAA,0xCC,
-0xD6,0x63,0x5F,0x73,0x8C,0xDA,0x05,0x99,0xA8,0x38,0xA8,0xCB,0x17,0x78,0x36,0x51,
-0xAC,0xE9,0x9E,0xF4,0x78,0x3A,0x8D,0xCF,0x0F,0xD9,0x42,0xE2,0x98,0x0C,0xAB,0x2F,
-0x9F,0x0E,0x01,0xDE,0xEF,0x9F,0x99,0x49,0xF1,0x2D,0xDF,0xAC,0x74,0x4D,0x1B,0x98,
-0xB5,0x47,0xC5,0xE5,0x29,0xD1,0xF9,0x90,0x18,0xC7,0x62,0x9C,0xBE,0x83,0xC7,0x26,
-0x7B,0x3E,0x8A,0x25,0xC7,0xC0,0xDD,0x9D,0xE6,0x35,0x68,0x10,0x20,0x9D,0x8F,0xD8,
-0xDE,0xD2,0xC3,0x84,0x9C,0x0D,0x5E,0xE8,0x2F,0xC9,0x02,0x03,0x01,0x00,0x01,0xA3,
-0x81,0xC0,0x30,0x81,0xBD,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,
-0xA0,0x11,0x0A,0x23,0x3E,0x96,0xF1,0x07,0xEC,0xE2,0xAF,0x29,0xEF,0x82,0xA5,0x7F,
-0xD0,0x30,0xA4,0xB4,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,
-0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,
-0x30,0x03,0x01,0x01,0xFF,0x30,0x7B,0x06,0x03,0x55,0x1D,0x1F,0x04,0x74,0x30,0x72,
-0x30,0x38,0xA0,0x36,0xA0,0x34,0x86,0x32,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,
-0x72,0x6C,0x2E,0x63,0x6F,0x6D,0x6F,0x64,0x6F,0x63,0x61,0x2E,0x63,0x6F,0x6D,0x2F,
-0x41,0x41,0x41,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x53,0x65,
-0x72,0x76,0x69,0x63,0x65,0x73,0x2E,0x63,0x72,0x6C,0x30,0x36,0xA0,0x34,0xA0,0x32,
-0x86,0x30,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x63,0x6F,0x6D,
-0x6F,0x64,0x6F,0x2E,0x6E,0x65,0x74,0x2F,0x41,0x41,0x41,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x65,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x2E,0x63,
-0x72,0x6C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,
-0x00,0x03,0x82,0x01,0x01,0x00,0x08,0x56,0xFC,0x02,0xF0,0x9B,0xE8,0xFF,0xA4,0xFA,
-0xD6,0x7B,0xC6,0x44,0x80,0xCE,0x4F,0xC4,0xC5,0xF6,0x00,0x58,0xCC,0xA6,0xB6,0xBC,
-0x14,0x49,0x68,0x04,0x76,0xE8,0xE6,0xEE,0x5D,0xEC,0x02,0x0F,0x60,0xD6,0x8D,0x50,
-0x18,0x4F,0x26,0x4E,0x01,0xE3,0xE6,0xB0,0xA5,0xEE,0xBF,0xBC,0x74,0x54,0x41,0xBF,
-0xFD,0xFC,0x12,0xB8,0xC7,0x4F,0x5A,0xF4,0x89,0x60,0x05,0x7F,0x60,0xB7,0x05,0x4A,
-0xF3,0xF6,0xF1,0xC2,0xBF,0xC4,0xB9,0x74,0x86,0xB6,0x2D,0x7D,0x6B,0xCC,0xD2,0xF3,
-0x46,0xDD,0x2F,0xC6,0xE0,0x6A,0xC3,0xC3,0x34,0x03,0x2C,0x7D,0x96,0xDD,0x5A,0xC2,
-0x0E,0xA7,0x0A,0x99,0xC1,0x05,0x8B,0xAB,0x0C,0x2F,0xF3,0x5C,0x3A,0xCF,0x6C,0x37,
-0x55,0x09,0x87,0xDE,0x53,0x40,0x6C,0x58,0xEF,0xFC,0xB6,0xAB,0x65,0x6E,0x04,0xF6,
-0x1B,0xDC,0x3C,0xE0,0x5A,0x15,0xC6,0x9E,0xD9,0xF1,0x59,0x48,0x30,0x21,0x65,0x03,
-0x6C,0xEC,0xE9,0x21,0x73,0xEC,0x9B,0x03,0xA1,0xE0,0x37,0xAD,0xA0,0x15,0x18,0x8F,
-0xFA,0xBA,0x02,0xCE,0xA7,0x2C,0xA9,0x10,0x13,0x2C,0xD4,0xE5,0x08,0x26,0xAB,0x22,
-0x97,0x60,0xF8,0x90,0x5E,0x74,0xD4,0xA2,0x9A,0x53,0xBD,0xF2,0xA9,0x68,0xE0,0xA2,
-0x6E,0xC2,0xD7,0x6C,0xB1,0xA3,0x0F,0x9E,0xBF,0xEB,0x68,0xE7,0x56,0xF2,0xAE,0xF2,
-0xE3,0x2B,0x38,0x3A,0x09,0x81,0xB5,0x6B,0x85,0xD7,0xBE,0x2D,0xED,0x3F,0x1A,0xB7,
-0xB2,0x63,0xE2,0xF5,0x62,0x2C,0x82,0xD4,0x6A,0x00,0x41,0x50,0xF1,0x39,0x83,0x9F,
-0x95,0xE9,0x36,0x96,0x98,0x6E,
-};
-
-
-/* subject:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO Certification Authority */
-/* issuer :/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO Certification Authority */
-
-
-const unsigned char COMODO_Certification_Authority_certificate[1057]={
-0x30,0x82,0x04,0x1D,0x30,0x82,0x03,0x05,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x4E,
-0x81,0x2D,0x8A,0x82,0x65,0xE0,0x0B,0x02,0xEE,0x3E,0x35,0x02,0x46,0xE5,0x3D,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,
-0x81,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,0x1B,
-0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x13,0x12,0x47,0x72,0x65,0x61,0x74,0x65,0x72,
-0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,0x06,
-0x03,0x55,0x04,0x07,0x13,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,0x30,
-0x18,0x06,0x03,0x55,0x04,0x0A,0x13,0x11,0x43,0x4F,0x4D,0x4F,0x44,0x4F,0x20,0x43,
-0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x27,0x30,0x25,0x06,0x03,0x55,
-0x04,0x03,0x13,0x1E,0x43,0x4F,0x4D,0x4F,0x44,0x4F,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x32,0x30,0x31,0x30,0x30,0x30,0x30,
-0x30,0x30,0x5A,0x17,0x0D,0x32,0x39,0x31,0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,
-0x39,0x5A,0x30,0x81,0x81,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,
-0x47,0x42,0x31,0x1B,0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x13,0x12,0x47,0x72,0x65,
-0x61,0x74,0x65,0x72,0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,
-0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x07,0x13,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,
-0x64,0x31,0x1A,0x30,0x18,0x06,0x03,0x55,0x04,0x0A,0x13,0x11,0x43,0x4F,0x4D,0x4F,
-0x44,0x4F,0x20,0x43,0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x27,0x30,
-0x25,0x06,0x03,0x55,0x04,0x03,0x13,0x1E,0x43,0x4F,0x4D,0x4F,0x44,0x4F,0x20,0x43,
-0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,
-0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xD0,0x40,0x8B,0x8B,0x72,0xE3,0x91,0x1B,0xF7,
-0x51,0xC1,0x1B,0x54,0x04,0x98,0xD3,0xA9,0xBF,0xC1,0xE6,0x8A,0x5D,0x3B,0x87,0xFB,
-0xBB,0x88,0xCE,0x0D,0xE3,0x2F,0x3F,0x06,0x96,0xF0,0xA2,0x29,0x50,0x99,0xAE,0xDB,
-0x3B,0xA1,0x57,0xB0,0x74,0x51,0x71,0xCD,0xED,0x42,0x91,0x4D,0x41,0xFE,0xA9,0xC8,
-0xD8,0x6A,0x86,0x77,0x44,0xBB,0x59,0x66,0x97,0x50,0x5E,0xB4,0xD4,0x2C,0x70,0x44,
-0xCF,0xDA,0x37,0x95,0x42,0x69,0x3C,0x30,0xC4,0x71,0xB3,0x52,0xF0,0x21,0x4D,0xA1,
-0xD8,0xBA,0x39,0x7C,0x1C,0x9E,0xA3,0x24,0x9D,0xF2,0x83,0x16,0x98,0xAA,0x16,0x7C,
-0x43,0x9B,0x15,0x5B,0xB7,0xAE,0x34,0x91,0xFE,0xD4,0x62,0x26,0x18,0x46,0x9A,0x3F,
-0xEB,0xC1,0xF9,0xF1,0x90,0x57,0xEB,0xAC,0x7A,0x0D,0x8B,0xDB,0x72,0x30,0x6A,0x66,
-0xD5,0xE0,0x46,0xA3,0x70,0xDC,0x68,0xD9,0xFF,0x04,0x48,0x89,0x77,0xDE,0xB5,0xE9,
-0xFB,0x67,0x6D,0x41,0xE9,0xBC,0x39,0xBD,0x32,0xD9,0x62,0x02,0xF1,0xB1,0xA8,0x3D,
-0x6E,0x37,0x9C,0xE2,0x2F,0xE2,0xD3,0xA2,0x26,0x8B,0xC6,0xB8,0x55,0x43,0x88,0xE1,
-0x23,0x3E,0xA5,0xD2,0x24,0x39,0x6A,0x47,0xAB,0x00,0xD4,0xA1,0xB3,0xA9,0x25,0xFE,
-0x0D,0x3F,0xA7,0x1D,0xBA,0xD3,0x51,0xC1,0x0B,0xA4,0xDA,0xAC,0x38,0xEF,0x55,0x50,
-0x24,0x05,0x65,0x46,0x93,0x34,0x4F,0x2D,0x8D,0xAD,0xC6,0xD4,0x21,0x19,0xD2,0x8E,
-0xCA,0x05,0x61,0x71,0x07,0x73,0x47,0xE5,0x8A,0x19,0x12,0xBD,0x04,0x4D,0xCE,0x4E,
-0x9C,0xA5,0x48,0xAC,0xBB,0x26,0xF7,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0x8E,0x30,
-0x81,0x8B,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x0B,0x58,0xE5,
-0x8B,0xC6,0x4C,0x15,0x37,0xA4,0x40,0xA9,0x30,0xA9,0x21,0xBE,0x47,0x36,0x5A,0x56,
-0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,
-0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,
-0x01,0xFF,0x30,0x49,0x06,0x03,0x55,0x1D,0x1F,0x04,0x42,0x30,0x40,0x30,0x3E,0xA0,
-0x3C,0xA0,0x3A,0x86,0x38,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,
-0x63,0x6F,0x6D,0x6F,0x64,0x6F,0x63,0x61,0x2E,0x63,0x6F,0x6D,0x2F,0x43,0x4F,0x4D,
-0x4F,0x44,0x4F,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,
-0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x2E,0x63,0x72,0x6C,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,
-0x00,0x3E,0x98,0x9E,0x9B,0xF6,0x1B,0xE9,0xD7,0x39,0xB7,0x78,0xAE,0x1D,0x72,0x18,
-0x49,0xD3,0x87,0xE4,0x43,0x82,0xEB,0x3F,0xC9,0xAA,0xF5,0xA8,0xB5,0xEF,0x55,0x7C,
-0x21,0x52,0x65,0xF9,0xD5,0x0D,0xE1,0x6C,0xF4,0x3E,0x8C,0x93,0x73,0x91,0x2E,0x02,
-0xC4,0x4E,0x07,0x71,0x6F,0xC0,0x8F,0x38,0x61,0x08,0xA8,0x1E,0x81,0x0A,0xC0,0x2F,
-0x20,0x2F,0x41,0x8B,0x91,0xDC,0x48,0x45,0xBC,0xF1,0xC6,0xDE,0xBA,0x76,0x6B,0x33,
-0xC8,0x00,0x2D,0x31,0x46,0x4C,0xED,0xE7,0x9D,0xCF,0x88,0x94,0xFF,0x33,0xC0,0x56,
-0xE8,0x24,0x86,0x26,0xB8,0xD8,0x38,0x38,0xDF,0x2A,0x6B,0xDD,0x12,0xCC,0xC7,0x3F,
-0x47,0x17,0x4C,0xA2,0xC2,0x06,0x96,0x09,0xD6,0xDB,0xFE,0x3F,0x3C,0x46,0x41,0xDF,
-0x58,0xE2,0x56,0x0F,0x3C,0x3B,0xC1,0x1C,0x93,0x35,0xD9,0x38,0x52,0xAC,0xEE,0xC8,
-0xEC,0x2E,0x30,0x4E,0x94,0x35,0xB4,0x24,0x1F,0x4B,0x78,0x69,0xDA,0xF2,0x02,0x38,
-0xCC,0x95,0x52,0x93,0xF0,0x70,0x25,0x59,0x9C,0x20,0x67,0xC4,0xEE,0xF9,0x8B,0x57,
-0x61,0xF4,0x92,0x76,0x7D,0x3F,0x84,0x8D,0x55,0xB7,0xE8,0xE5,0xAC,0xD5,0xF1,0xF5,
-0x19,0x56,0xA6,0x5A,0xFB,0x90,0x1C,0xAF,0x93,0xEB,0xE5,0x1C,0xD4,0x67,0x97,0x5D,
-0x04,0x0E,0xBE,0x0B,0x83,0xA6,0x17,0x83,0xB9,0x30,0x12,0xA0,0xC5,0x33,0x15,0x05,
-0xB9,0x0D,0xFB,0xC7,0x05,0x76,0xE3,0xD8,0x4A,0x8D,0xFC,0x34,0x17,0xA3,0xC6,0x21,
-0x28,0xBE,0x30,0x45,0x31,0x1E,0xC7,0x78,0xBE,0x58,0x61,0x38,0xAC,0x3B,0xE2,0x01,
-0x65,
-};
-
-
-/* subject:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO ECC Certification Authority */
-/* issuer :/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO ECC Certification Authority */
-
-
-const unsigned char COMODO_ECC_Certification_Authority_certificate[653]={
-0x30,0x82,0x02,0x89,0x30,0x82,0x02,0x0F,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x1F,
-0x47,0xAF,0xAA,0x62,0x00,0x70,0x50,0x54,0x4C,0x01,0x9E,0x9B,0x63,0x99,0x2A,0x30,
-0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x03,0x30,0x81,0x85,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,0x1B,0x30,0x19,0x06,
-0x03,0x55,0x04,0x08,0x13,0x12,0x47,0x72,0x65,0x61,0x74,0x65,0x72,0x20,0x4D,0x61,
-0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,
-0x07,0x13,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,0x30,0x18,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x11,0x43,0x4F,0x4D,0x4F,0x44,0x4F,0x20,0x43,0x41,0x20,0x4C,
-0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x2B,0x30,0x29,0x06,0x03,0x55,0x04,0x03,0x13,
-0x22,0x43,0x4F,0x4D,0x4F,0x44,0x4F,0x20,0x45,0x43,0x43,0x20,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x38,0x30,0x33,0x30,0x36,0x30,0x30,0x30,
-0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x38,0x30,0x31,0x31,0x38,0x32,0x33,0x35,0x39,
-0x35,0x39,0x5A,0x30,0x81,0x85,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x47,0x42,0x31,0x1B,0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x13,0x12,0x47,0x72,
-0x65,0x61,0x74,0x65,0x72,0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,
-0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x07,0x13,0x07,0x53,0x61,0x6C,0x66,0x6F,
-0x72,0x64,0x31,0x1A,0x30,0x18,0x06,0x03,0x55,0x04,0x0A,0x13,0x11,0x43,0x4F,0x4D,
-0x4F,0x44,0x4F,0x20,0x43,0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x2B,
-0x30,0x29,0x06,0x03,0x55,0x04,0x03,0x13,0x22,0x43,0x4F,0x4D,0x4F,0x44,0x4F,0x20,
-0x45,0x43,0x43,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,
-0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x76,0x30,0x10,0x06,
-0x07,0x2A,0x86,0x48,0xCE,0x3D,0x02,0x01,0x06,0x05,0x2B,0x81,0x04,0x00,0x22,0x03,
-0x62,0x00,0x04,0x03,0x47,0x7B,0x2F,0x75,0xC9,0x82,0x15,0x85,0xFB,0x75,0xE4,0x91,
-0x16,0xD4,0xAB,0x62,0x99,0xF5,0x3E,0x52,0x0B,0x06,0xCE,0x41,0x00,0x7F,0x97,0xE1,
-0x0A,0x24,0x3C,0x1D,0x01,0x04,0xEE,0x3D,0xD2,0x8D,0x09,0x97,0x0C,0xE0,0x75,0xE4,
-0xFA,0xFB,0x77,0x8A,0x2A,0xF5,0x03,0x60,0x4B,0x36,0x8B,0x16,0x23,0x16,0xAD,0x09,
-0x71,0xF4,0x4A,0xF4,0x28,0x50,0xB4,0xFE,0x88,0x1C,0x6E,0x3F,0x6C,0x2F,0x2F,0x09,
-0x59,0x5B,0xA5,0x5B,0x0B,0x33,0x99,0xE2,0xC3,0x3D,0x89,0xF9,0x6A,0x2C,0xEF,0xB2,
-0xD3,0x06,0xE9,0xA3,0x42,0x30,0x40,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,
-0x04,0x14,0x75,0x71,0xA7,0x19,0x48,0x19,0xBC,0x9D,0x9D,0xEA,0x41,0x47,0xDF,0x94,
-0xC4,0x48,0x77,0x99,0xD3,0x79,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,
-0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,
-0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,
-0x04,0x03,0x03,0x03,0x68,0x00,0x30,0x65,0x02,0x31,0x00,0xEF,0x03,0x5B,0x7A,0xAC,
-0xB7,0x78,0x0A,0x72,0xB7,0x88,0xDF,0xFF,0xB5,0x46,0x14,0x09,0x0A,0xFA,0xA0,0xE6,
-0x7D,0x08,0xC6,0x1A,0x87,0xBD,0x18,0xA8,0x73,0xBD,0x26,0xCA,0x60,0x0C,0x9D,0xCE,
-0x99,0x9F,0xCF,0x5C,0x0F,0x30,0xE1,0xBE,0x14,0x31,0xEA,0x02,0x30,0x14,0xF4,0x93,
-0x3C,0x49,0xA7,0x33,0x7A,0x90,0x46,0x47,0xB3,0x63,0x7D,0x13,0x9B,0x4E,0xB7,0x6F,
-0x18,0x37,0x80,0x53,0xFE,0xDD,0x20,0xE0,0x35,0x9A,0x36,0xD1,0xC7,0x01,0xB9,0xE6,
-0xDC,0xDD,0xF3,0xFF,0x1D,0x2C,0x3A,0x16,0x57,0xD9,0x92,0x39,0xD6,
-};
-
-
-/* subject:/C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=Secure Certificate Services */
-/* issuer :/C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=Secure Certificate Services */
-
-
-const unsigned char Comodo_Secure_Services_root_certificate[1091]={
-0x30,0x82,0x04,0x3F,0x30,0x82,0x03,0x27,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x7E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,0x1B,
-0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x0C,0x12,0x47,0x72,0x65,0x61,0x74,0x65,0x72,
-0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,0x06,
-0x03,0x55,0x04,0x07,0x0C,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,0x30,
-0x18,0x06,0x03,0x55,0x04,0x0A,0x0C,0x11,0x43,0x6F,0x6D,0x6F,0x64,0x6F,0x20,0x43,
-0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x24,0x30,0x22,0x06,0x03,0x55,
-0x04,0x03,0x0C,0x1B,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x30,
-0x1E,0x17,0x0D,0x30,0x34,0x30,0x31,0x30,0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,
-0x17,0x0D,0x32,0x38,0x31,0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,
-0x7E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,0x1B,
-0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x0C,0x12,0x47,0x72,0x65,0x61,0x74,0x65,0x72,
-0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,0x06,
-0x03,0x55,0x04,0x07,0x0C,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,0x30,
-0x18,0x06,0x03,0x55,0x04,0x0A,0x0C,0x11,0x43,0x6F,0x6D,0x6F,0x64,0x6F,0x20,0x43,
-0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x24,0x30,0x22,0x06,0x03,0x55,
-0x04,0x03,0x0C,0x1B,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x30,
-0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,
-0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,
-0xC0,0x71,0x33,0x82,0x8A,0xD0,0x70,0xEB,0x73,0x87,0x82,0x40,0xD5,0x1D,0xE4,0xCB,
-0xC9,0x0E,0x42,0x90,0xF9,0xDE,0x34,0xB9,0xA1,0xBA,0x11,0xF4,0x25,0x85,0xF3,0xCC,
-0x72,0x6D,0xF2,0x7B,0x97,0x6B,0xB3,0x07,0xF1,0x77,0x24,0x91,0x5F,0x25,0x8F,0xF6,
-0x74,0x3D,0xE4,0x80,0xC2,0xF8,0x3C,0x0D,0xF3,0xBF,0x40,0xEA,0xF7,0xC8,0x52,0xD1,
-0x72,0x6F,0xEF,0xC8,0xAB,0x41,0xB8,0x6E,0x2E,0x17,0x2A,0x95,0x69,0x0C,0xCD,0xD2,
-0x1E,0x94,0x7B,0x2D,0x94,0x1D,0xAA,0x75,0xD7,0xB3,0x98,0xCB,0xAC,0xBC,0x64,0x53,
-0x40,0xBC,0x8F,0xAC,0xAC,0x36,0xCB,0x5C,0xAD,0xBB,0xDD,0xE0,0x94,0x17,0xEC,0xD1,
-0x5C,0xD0,0xBF,0xEF,0xA5,0x95,0xC9,0x90,0xC5,0xB0,0xAC,0xFB,0x1B,0x43,0xDF,0x7A,
-0x08,0x5D,0xB7,0xB8,0xF2,0x40,0x1B,0x2B,0x27,0x9E,0x50,0xCE,0x5E,0x65,0x82,0x88,
-0x8C,0x5E,0xD3,0x4E,0x0C,0x7A,0xEA,0x08,0x91,0xB6,0x36,0xAA,0x2B,0x42,0xFB,0xEA,
-0xC2,0xA3,0x39,0xE5,0xDB,0x26,0x38,0xAD,0x8B,0x0A,0xEE,0x19,0x63,0xC7,0x1C,0x24,
-0xDF,0x03,0x78,0xDA,0xE6,0xEA,0xC1,0x47,0x1A,0x0B,0x0B,0x46,0x09,0xDD,0x02,0xFC,
-0xDE,0xCB,0x87,0x5F,0xD7,0x30,0x63,0x68,0xA1,0xAE,0xDC,0x32,0xA1,0xBA,0xBE,0xFE,
-0x44,0xAB,0x68,0xB6,0xA5,0x17,0x15,0xFD,0xBD,0xD5,0xA7,0xA7,0x9A,0xE4,0x44,0x33,
-0xE9,0x88,0x8E,0xFC,0xED,0x51,0xEB,0x93,0x71,0x4E,0xAD,0x01,0xE7,0x44,0x8E,0xAB,
-0x2D,0xCB,0xA8,0xFE,0x01,0x49,0x48,0xF0,0xC0,0xDD,0xC7,0x68,0xD8,0x92,0xFE,0x3D,
-0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0xC7,0x30,0x81,0xC4,0x30,0x1D,0x06,0x03,0x55,
-0x1D,0x0E,0x04,0x16,0x04,0x14,0x3C,0xD8,0x93,0x88,0xC2,0xC0,0x82,0x09,0xCC,0x01,
-0x99,0x06,0x93,0x20,0xE9,0x9E,0x70,0x09,0x63,0x4F,0x30,0x0E,0x06,0x03,0x55,0x1D,
-0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,
-0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x81,0x81,0x06,0x03,
-0x55,0x1D,0x1F,0x04,0x7A,0x30,0x78,0x30,0x3B,0xA0,0x39,0xA0,0x37,0x86,0x35,0x68,
-0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x63,0x6F,0x6D,0x6F,0x64,0x6F,
-0x63,0x61,0x2E,0x63,0x6F,0x6D,0x2F,0x53,0x65,0x63,0x75,0x72,0x65,0x43,0x65,0x72,
-0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,
-0x2E,0x63,0x72,0x6C,0x30,0x39,0xA0,0x37,0xA0,0x35,0x86,0x33,0x68,0x74,0x74,0x70,
-0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x63,0x6F,0x6D,0x6F,0x64,0x6F,0x2E,0x6E,0x65,
-0x74,0x2F,0x53,0x65,0x63,0x75,0x72,0x65,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,
-0x61,0x74,0x65,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x2E,0x63,0x72,0x6C,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,
-0x01,0x01,0x00,0x87,0x01,0x6D,0x23,0x1D,0x7E,0x5B,0x17,0x7D,0xC1,0x61,0x32,0xCF,
-0x8F,0xE7,0xF3,0x8A,0x94,0x59,0x66,0xE0,0x9E,0x28,0xA8,0x5E,0xD3,0xB7,0xF4,0x34,
-0xE6,0xAA,0x39,0xB2,0x97,0x16,0xC5,0x82,0x6F,0x32,0xA4,0xE9,0x8C,0xE7,0xAF,0xFD,
-0xEF,0xC2,0xE8,0xB9,0x4B,0xAA,0xA3,0xF4,0xE6,0xDA,0x8D,0x65,0x21,0xFB,0xBA,0x80,
-0xEB,0x26,0x28,0x85,0x1A,0xFE,0x39,0x8C,0xDE,0x5B,0x04,0x04,0xB4,0x54,0xF9,0xA3,
-0x67,0x9E,0x41,0xFA,0x09,0x52,0xCC,0x05,0x48,0xA8,0xC9,0x3F,0x21,0x04,0x1E,0xCE,
-0x48,0x6B,0xFC,0x85,0xE8,0xC2,0x7B,0xAF,0x7F,0xB7,0xCC,0xF8,0x5F,0x3A,0xFD,0x35,
-0xC6,0x0D,0xEF,0x97,0xDC,0x4C,0xAB,0x11,0xE1,0x6B,0xCB,0x31,0xD1,0x6C,0xFB,0x48,
-0x80,0xAB,0xDC,0x9C,0x37,0xB8,0x21,0x14,0x4B,0x0D,0x71,0x3D,0xEC,0x83,0x33,0x6E,
-0xD1,0x6E,0x32,0x16,0xEC,0x98,0xC7,0x16,0x8B,0x59,0xA6,0x34,0xAB,0x05,0x57,0x2D,
-0x93,0xF7,0xAA,0x13,0xCB,0xD2,0x13,0xE2,0xB7,0x2E,0x3B,0xCD,0x6B,0x50,0x17,0x09,
-0x68,0x3E,0xB5,0x26,0x57,0xEE,0xB6,0xE0,0xB6,0xDD,0xB9,0x29,0x80,0x79,0x7D,0x8F,
-0xA3,0xF0,0xA4,0x28,0xA4,0x15,0xC4,0x85,0xF4,0x27,0xD4,0x6B,0xBF,0xE5,0x5C,0xE4,
-0x65,0x02,0x76,0x54,0xB4,0xE3,0x37,0x66,0x24,0xD3,0x19,0x61,0xC8,0x52,0x10,0xE5,
-0x8B,0x37,0x9A,0xB9,0xA9,0xF9,0x1D,0xBF,0xEA,0x99,0x92,0x61,0x96,0xFF,0x01,0xCD,
-0xA1,0x5F,0x0D,0xBC,0x71,0xBC,0x0E,0xAC,0x0B,0x1D,0x47,0x45,0x1D,0xC1,0xEC,0x7C,
-0xEC,0xFD,0x29,
-};
-
-
-/* subject:/C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=Trusted Certificate Services */
-/* issuer :/C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=Trusted Certificate Services */
-
-
-const unsigned char Comodo_Trusted_Services_root_certificate[1095]={
-0x30,0x82,0x04,0x43,0x30,0x82,0x03,0x2B,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x7F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,0x1B,
-0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x0C,0x12,0x47,0x72,0x65,0x61,0x74,0x65,0x72,
-0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,0x06,
-0x03,0x55,0x04,0x07,0x0C,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,0x30,
-0x18,0x06,0x03,0x55,0x04,0x0A,0x0C,0x11,0x43,0x6F,0x6D,0x6F,0x64,0x6F,0x20,0x43,
-0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x25,0x30,0x23,0x06,0x03,0x55,
-0x04,0x03,0x0C,0x1C,0x54,0x72,0x75,0x73,0x74,0x65,0x64,0x20,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,
-0x30,0x1E,0x17,0x0D,0x30,0x34,0x30,0x31,0x30,0x31,0x30,0x30,0x30,0x30,0x30,0x30,
-0x5A,0x17,0x0D,0x32,0x38,0x31,0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,
-0x30,0x7F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x47,0x42,0x31,
-0x1B,0x30,0x19,0x06,0x03,0x55,0x04,0x08,0x0C,0x12,0x47,0x72,0x65,0x61,0x74,0x65,
-0x72,0x20,0x4D,0x61,0x6E,0x63,0x68,0x65,0x73,0x74,0x65,0x72,0x31,0x10,0x30,0x0E,
-0x06,0x03,0x55,0x04,0x07,0x0C,0x07,0x53,0x61,0x6C,0x66,0x6F,0x72,0x64,0x31,0x1A,
-0x30,0x18,0x06,0x03,0x55,0x04,0x0A,0x0C,0x11,0x43,0x6F,0x6D,0x6F,0x64,0x6F,0x20,
-0x43,0x41,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x25,0x30,0x23,0x06,0x03,
-0x55,0x04,0x03,0x0C,0x1C,0x54,0x72,0x75,0x73,0x74,0x65,0x64,0x20,0x43,0x65,0x72,
-0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,
-0x73,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,
-0x01,0x00,0xDF,0x71,0x6F,0x36,0x58,0x53,0x5A,0xF2,0x36,0x54,0x57,0x80,0xC4,0x74,
-0x08,0x20,0xED,0x18,0x7F,0x2A,0x1D,0xE6,0x35,0x9A,0x1E,0x25,0xAC,0x9C,0xE5,0x96,
-0x7E,0x72,0x52,0xA0,0x15,0x42,0xDB,0x59,0xDD,0x64,0x7A,0x1A,0xD0,0xB8,0x7B,0xDD,
-0x39,0x15,0xBC,0x55,0x48,0xC4,0xED,0x3A,0x00,0xEA,0x31,0x11,0xBA,0xF2,0x71,0x74,
-0x1A,0x67,0xB8,0xCF,0x33,0xCC,0xA8,0x31,0xAF,0xA3,0xE3,0xD7,0x7F,0xBF,0x33,0x2D,
-0x4C,0x6A,0x3C,0xEC,0x8B,0xC3,0x92,0xD2,0x53,0x77,0x24,0x74,0x9C,0x07,0x6E,0x70,
-0xFC,0xBD,0x0B,0x5B,0x76,0xBA,0x5F,0xF2,0xFF,0xD7,0x37,0x4B,0x4A,0x60,0x78,0xF7,
-0xF0,0xFA,0xCA,0x70,0xB4,0xEA,0x59,0xAA,0xA3,0xCE,0x48,0x2F,0xA9,0xC3,0xB2,0x0B,
-0x7E,0x17,0x72,0x16,0x0C,0xA6,0x07,0x0C,0x1B,0x38,0xCF,0xC9,0x62,0xB7,0x3F,0xA0,
-0x93,0xA5,0x87,0x41,0xF2,0xB7,0x70,0x40,0x77,0xD8,0xBE,0x14,0x7C,0xE3,0xA8,0xC0,
-0x7A,0x8E,0xE9,0x63,0x6A,0xD1,0x0F,0x9A,0xC6,0xD2,0xF4,0x8B,0x3A,0x14,0x04,0x56,
-0xD4,0xED,0xB8,0xCC,0x6E,0xF5,0xFB,0xE2,0x2C,0x58,0xBD,0x7F,0x4F,0x6B,0x2B,0xF7,
-0x60,0x24,0x58,0x24,0xCE,0x26,0xEF,0x34,0x91,0x3A,0xD5,0xE3,0x81,0xD0,0xB2,0xF0,
-0x04,0x02,0xD7,0x5B,0xB7,0x3E,0x92,0xAC,0x6B,0x12,0x8A,0xF9,0xE4,0x05,0xB0,0x3B,
-0x91,0x49,0x5C,0xB2,0xEB,0x53,0xEA,0xF8,0x9F,0x47,0x86,0xEE,0xBF,0x95,0xC0,0xC0,
-0x06,0x9F,0xD2,0x5B,0x5E,0x11,0x1B,0xF4,0xC7,0x04,0x35,0x29,0xD2,0x55,0x5C,0xE4,
-0xED,0xEB,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0xC9,0x30,0x81,0xC6,0x30,0x1D,0x06,
-0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xC5,0x7B,0x58,0xBD,0xED,0xDA,0x25,0x69,
-0xD2,0xF7,0x59,0x16,0xA8,0xB3,0x32,0xC0,0x7B,0x27,0x5B,0xF4,0x30,0x0E,0x06,0x03,
-0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,
-0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x81,0x83,
-0x06,0x03,0x55,0x1D,0x1F,0x04,0x7C,0x30,0x7A,0x30,0x3C,0xA0,0x3A,0xA0,0x38,0x86,
-0x36,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x63,0x6F,0x6D,0x6F,
-0x64,0x6F,0x63,0x61,0x2E,0x63,0x6F,0x6D,0x2F,0x54,0x72,0x75,0x73,0x74,0x65,0x64,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x53,0x65,0x72,0x76,0x69,
-0x63,0x65,0x73,0x2E,0x63,0x72,0x6C,0x30,0x3A,0xA0,0x38,0xA0,0x36,0x86,0x34,0x68,
-0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x63,0x6F,0x6D,0x6F,0x64,0x6F,
-0x2E,0x6E,0x65,0x74,0x2F,0x54,0x72,0x75,0x73,0x74,0x65,0x64,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x2E,
-0x63,0x72,0x6C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x03,0x82,0x01,0x01,0x00,0xC8,0x93,0x81,0x3B,0x89,0xB4,0xAF,0xB8,0x84,
-0x12,0x4C,0x8D,0xD2,0xF0,0xDB,0x70,0xBA,0x57,0x86,0x15,0x34,0x10,0xB9,0x2F,0x7F,
-0x1E,0xB0,0xA8,0x89,0x60,0xA1,0x8A,0xC2,0x77,0x0C,0x50,0x4A,0x9B,0x00,0x8B,0xD8,
-0x8B,0xF4,0x41,0xE2,0xD0,0x83,0x8A,0x4A,0x1C,0x14,0x06,0xB0,0xA3,0x68,0x05,0x70,
-0x31,0x30,0xA7,0x53,0x9B,0x0E,0xE9,0x4A,0xA0,0x58,0x69,0x67,0x0E,0xAE,0x9D,0xF6,
-0xA5,0x2C,0x41,0xBF,0x3C,0x06,0x6B,0xE4,0x59,0xCC,0x6D,0x10,0xF1,0x96,0x6F,0x1F,
-0xDF,0xF4,0x04,0x02,0xA4,0x9F,0x45,0x3E,0xC8,0xD8,0xFA,0x36,0x46,0x44,0x50,0x3F,
-0x82,0x97,0x91,0x1F,0x28,0xDB,0x18,0x11,0x8C,0x2A,0xE4,0x65,0x83,0x57,0x12,0x12,
-0x8C,0x17,0x3F,0x94,0x36,0xFE,0x5D,0xB0,0xC0,0x04,0x77,0x13,0xB8,0xF4,0x15,0xD5,
-0x3F,0x38,0xCC,0x94,0x3A,0x55,0xD0,0xAC,0x98,0xF5,0xBA,0x00,0x5F,0xE0,0x86,0x19,
-0x81,0x78,0x2F,0x28,0xC0,0x7E,0xD3,0xCC,0x42,0x0A,0xF5,0xAE,0x50,0xA0,0xD1,0x3E,
-0xC6,0xA1,0x71,0xEC,0x3F,0xA0,0x20,0x8C,0x66,0x3A,0x89,0xB4,0x8E,0xD4,0xD8,0xB1,
-0x4D,0x25,0x47,0xEE,0x2F,0x88,0xC8,0xB5,0xE1,0x05,0x45,0xC0,0xBE,0x14,0x71,0xDE,
-0x7A,0xFD,0x8E,0x7B,0x7D,0x4D,0x08,0x96,0xA5,0x12,0x73,0xF0,0x2D,0xCA,0x37,0x27,
-0x74,0x12,0x27,0x4C,0xCB,0xB6,0x97,0xE9,0xD9,0xAE,0x08,0x6D,0x5A,0x39,0x40,0xDD,
-0x05,0x47,0x75,0x6A,0x5A,0x21,0xB3,0xA3,0x18,0xCF,0x4E,0xF7,0x2E,0x57,0xB7,0x98,
-0x70,0x5E,0xC8,0xC4,0x78,0xB0,0x62,
-};
-
-
-/* subject:/O=Cybertrust, Inc/CN=Cybertrust Global Root */
-/* issuer :/O=Cybertrust, Inc/CN=Cybertrust Global Root */
-
-
-const unsigned char Cybertrust_Global_Root_certificate[933]={
-0x30,0x82,0x03,0xA1,0x30,0x82,0x02,0x89,0xA0,0x03,0x02,0x01,0x02,0x02,0x0B,0x04,
-0x00,0x00,0x00,0x00,0x01,0x0F,0x85,0xAA,0x2D,0x48,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x3B,0x31,0x18,0x30,0x16,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0F,0x43,0x79,0x62,0x65,0x72,0x74,0x72,0x75,0x73,0x74,
-0x2C,0x20,0x49,0x6E,0x63,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,
-0x43,0x79,0x62,0x65,0x72,0x74,0x72,0x75,0x73,0x74,0x20,0x47,0x6C,0x6F,0x62,0x61,
-0x6C,0x20,0x52,0x6F,0x6F,0x74,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x32,0x31,0x35,
-0x30,0x38,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x31,0x31,0x32,0x31,0x35,0x30,
-0x38,0x30,0x30,0x30,0x30,0x5A,0x30,0x3B,0x31,0x18,0x30,0x16,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x0F,0x43,0x79,0x62,0x65,0x72,0x74,0x72,0x75,0x73,0x74,0x2C,0x20,0x49,
-0x6E,0x63,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,0x43,0x79,0x62,
-0x65,0x72,0x74,0x72,0x75,0x73,0x74,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x52,
-0x6F,0x6F,0x74,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,
-0x82,0x01,0x01,0x00,0xF8,0xC8,0xBC,0xBD,0x14,0x50,0x66,0x13,0xFF,0xF0,0xD3,0x79,
-0xEC,0x23,0xF2,0xB7,0x1A,0xC7,0x8E,0x85,0xF1,0x12,0x73,0xA6,0x19,0xAA,0x10,0xDB,
-0x9C,0xA2,0x65,0x74,0x5A,0x77,0x3E,0x51,0x7D,0x56,0xF6,0xDC,0x23,0xB6,0xD4,0xED,
-0x5F,0x58,0xB1,0x37,0x4D,0xD5,0x49,0x0E,0x6E,0xF5,0x6A,0x87,0xD6,0xD2,0x8C,0xD2,
-0x27,0xC6,0xE2,0xFF,0x36,0x9F,0x98,0x65,0xA0,0x13,0x4E,0xC6,0x2A,0x64,0x9B,0xD5,
-0x90,0x12,0xCF,0x14,0x06,0xF4,0x3B,0xE3,0xD4,0x28,0xBE,0xE8,0x0E,0xF8,0xAB,0x4E,
-0x48,0x94,0x6D,0x8E,0x95,0x31,0x10,0x5C,0xED,0xA2,0x2D,0xBD,0xD5,0x3A,0x6D,0xB2,
-0x1C,0xBB,0x60,0xC0,0x46,0x4B,0x01,0xF5,0x49,0xAE,0x7E,0x46,0x8A,0xD0,0x74,0x8D,
-0xA1,0x0C,0x02,0xCE,0xEE,0xFC,0xE7,0x8F,0xB8,0x6B,0x66,0xF3,0x7F,0x44,0x00,0xBF,
-0x66,0x25,0x14,0x2B,0xDD,0x10,0x30,0x1D,0x07,0x96,0x3F,0x4D,0xF6,0x6B,0xB8,0x8F,
-0xB7,0x7B,0x0C,0xA5,0x38,0xEB,0xDE,0x47,0xDB,0xD5,0x5D,0x39,0xFC,0x88,0xA7,0xF3,
-0xD7,0x2A,0x74,0xF1,0xE8,0x5A,0xA2,0x3B,0x9F,0x50,0xBA,0xA6,0x8C,0x45,0x35,0xC2,
-0x50,0x65,0x95,0xDC,0x63,0x82,0xEF,0xDD,0xBF,0x77,0x4D,0x9C,0x62,0xC9,0x63,0x73,
-0x16,0xD0,0x29,0x0F,0x49,0xA9,0x48,0xF0,0xB3,0xAA,0xB7,0x6C,0xC5,0xA7,0x30,0x39,
-0x40,0x5D,0xAE,0xC4,0xE2,0x5D,0x26,0x53,0xF0,0xCE,0x1C,0x23,0x08,0x61,0xA8,0x94,
-0x19,0xBA,0x04,0x62,0x40,0xEC,0x1F,0x38,0x70,0x77,0x12,0x06,0x71,0xA7,0x30,0x18,
-0x5D,0x25,0x27,0xA5,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0xA5,0x30,0x81,0xA2,0x30,
-0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,
-0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,
-0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xB6,0x08,0x7B,0x0D,0x7A,
-0xCC,0xAC,0x20,0x4C,0x86,0x56,0x32,0x5E,0xCF,0xAB,0x6E,0x85,0x2D,0x70,0x57,0x30,
-0x3F,0x06,0x03,0x55,0x1D,0x1F,0x04,0x38,0x30,0x36,0x30,0x34,0xA0,0x32,0xA0,0x30,
-0x86,0x2E,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x32,0x2E,0x70,0x75,
-0x62,0x6C,0x69,0x63,0x2D,0x74,0x72,0x75,0x73,0x74,0x2E,0x63,0x6F,0x6D,0x2F,0x63,
-0x72,0x6C,0x2F,0x63,0x74,0x2F,0x63,0x74,0x72,0x6F,0x6F,0x74,0x2E,0x63,0x72,0x6C,
-0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0xB6,0x08,0x7B,
-0x0D,0x7A,0xCC,0xAC,0x20,0x4C,0x86,0x56,0x32,0x5E,0xCF,0xAB,0x6E,0x85,0x2D,0x70,
-0x57,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,
-0x03,0x82,0x01,0x01,0x00,0x56,0xEF,0x0A,0x23,0xA0,0x54,0x4E,0x95,0x97,0xC9,0xF8,
-0x89,0xDA,0x45,0xC1,0xD4,0xA3,0x00,0x25,0xF4,0x1F,0x13,0xAB,0xB7,0xA3,0x85,0x58,
-0x69,0xC2,0x30,0xAD,0xD8,0x15,0x8A,0x2D,0xE3,0xC9,0xCD,0x81,0x5A,0xF8,0x73,0x23,
-0x5A,0xA7,0x7C,0x05,0xF3,0xFD,0x22,0x3B,0x0E,0xD1,0x06,0xC4,0xDB,0x36,0x4C,0x73,
-0x04,0x8E,0xE5,0xB0,0x22,0xE4,0xC5,0xF3,0x2E,0xA5,0xD9,0x23,0xE3,0xB8,0x4E,0x4A,
-0x20,0xA7,0x6E,0x02,0x24,0x9F,0x22,0x60,0x67,0x7B,0x8B,0x1D,0x72,0x09,0xC5,0x31,
-0x5C,0xE9,0x79,0x9F,0x80,0x47,0x3D,0xAD,0xA1,0x0B,0x07,0x14,0x3D,0x47,0xFF,0x03,
-0x69,0x1A,0x0C,0x0B,0x44,0xE7,0x63,0x25,0xA7,0x7F,0xB2,0xC9,0xB8,0x76,0x84,0xED,
-0x23,0xF6,0x7D,0x07,0xAB,0x45,0x7E,0xD3,0xDF,0xB3,0xBF,0xE9,0x8A,0xB6,0xCD,0xA8,
-0xA2,0x67,0x2B,0x52,0xD5,0xB7,0x65,0xF0,0x39,0x4C,0x63,0xA0,0x91,0x79,0x93,0x52,
-0x0F,0x54,0xDD,0x83,0xBB,0x9F,0xD1,0x8F,0xA7,0x53,0x73,0xC3,0xCB,0xFF,0x30,0xEC,
-0x7C,0x04,0xB8,0xD8,0x44,0x1F,0x93,0x5F,0x71,0x09,0x22,0xB7,0x6E,0x3E,0xEA,0x1C,
-0x03,0x4E,0x9D,0x1A,0x20,0x61,0xFB,0x81,0x37,0xEC,0x5E,0xFC,0x0A,0x45,0xAB,0xD7,
-0xE7,0x17,0x55,0xD0,0xA0,0xEA,0x60,0x9B,0xA6,0xF6,0xE3,0x8C,0x5B,0x29,0xC2,0x06,
-0x60,0x14,0x9D,0x2D,0x97,0x4C,0xA9,0x93,0x15,0x9D,0x61,0xC4,0x01,0x5F,0x48,0xD6,
-0x58,0xBD,0x56,0x31,0x12,0x4E,0x11,0xC8,0x21,0xE0,0xB3,0x11,0x91,0x65,0xDB,0xB4,
-0xA6,0x88,0x38,0xCE,0x55,
-};
-
-
-/* subject:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Assured ID Root CA */
-/* issuer :/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Assured ID Root CA */
-
-
-const unsigned char DigiCert_Assured_ID_Root_CA_certificate[955]={
-0x30,0x82,0x03,0xB7,0x30,0x82,0x02,0x9F,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x0C,
-0xE7,0xE0,0xE5,0x17,0xD8,0x46,0xFE,0x8F,0xE5,0x60,0xFC,0x1B,0xF0,0x30,0x39,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x65,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,0x30,
-0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x44,0x69,0x67,0x69,0x43,0x65,0x72,0x74,
-0x20,0x49,0x6E,0x63,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,0x0B,0x13,0x10,0x77,
-0x77,0x77,0x2E,0x64,0x69,0x67,0x69,0x63,0x65,0x72,0x74,0x2E,0x63,0x6F,0x6D,0x31,
-0x24,0x30,0x22,0x06,0x03,0x55,0x04,0x03,0x13,0x1B,0x44,0x69,0x67,0x69,0x43,0x65,
-0x72,0x74,0x20,0x41,0x73,0x73,0x75,0x72,0x65,0x64,0x20,0x49,0x44,0x20,0x52,0x6F,
-0x6F,0x74,0x20,0x43,0x41,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x31,0x31,0x30,0x30,
-0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x31,0x31,0x31,0x31,0x30,0x30,0x30,
-0x30,0x30,0x30,0x30,0x5A,0x30,0x65,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,
-0x13,0x02,0x55,0x53,0x31,0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x44,
-0x69,0x67,0x69,0x43,0x65,0x72,0x74,0x20,0x49,0x6E,0x63,0x31,0x19,0x30,0x17,0x06,
-0x03,0x55,0x04,0x0B,0x13,0x10,0x77,0x77,0x77,0x2E,0x64,0x69,0x67,0x69,0x63,0x65,
-0x72,0x74,0x2E,0x63,0x6F,0x6D,0x31,0x24,0x30,0x22,0x06,0x03,0x55,0x04,0x03,0x13,
-0x1B,0x44,0x69,0x67,0x69,0x43,0x65,0x72,0x74,0x20,0x41,0x73,0x73,0x75,0x72,0x65,
-0x64,0x20,0x49,0x44,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x82,0x01,0x22,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,
-0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xAD,0x0E,0x15,
-0xCE,0xE4,0x43,0x80,0x5C,0xB1,0x87,0xF3,0xB7,0x60,0xF9,0x71,0x12,0xA5,0xAE,0xDC,
-0x26,0x94,0x88,0xAA,0xF4,0xCE,0xF5,0x20,0x39,0x28,0x58,0x60,0x0C,0xF8,0x80,0xDA,
-0xA9,0x15,0x95,0x32,0x61,0x3C,0xB5,0xB1,0x28,0x84,0x8A,0x8A,0xDC,0x9F,0x0A,0x0C,
-0x83,0x17,0x7A,0x8F,0x90,0xAC,0x8A,0xE7,0x79,0x53,0x5C,0x31,0x84,0x2A,0xF6,0x0F,
-0x98,0x32,0x36,0x76,0xCC,0xDE,0xDD,0x3C,0xA8,0xA2,0xEF,0x6A,0xFB,0x21,0xF2,0x52,
-0x61,0xDF,0x9F,0x20,0xD7,0x1F,0xE2,0xB1,0xD9,0xFE,0x18,0x64,0xD2,0x12,0x5B,0x5F,
-0xF9,0x58,0x18,0x35,0xBC,0x47,0xCD,0xA1,0x36,0xF9,0x6B,0x7F,0xD4,0xB0,0x38,0x3E,
-0xC1,0x1B,0xC3,0x8C,0x33,0xD9,0xD8,0x2F,0x18,0xFE,0x28,0x0F,0xB3,0xA7,0x83,0xD6,
-0xC3,0x6E,0x44,0xC0,0x61,0x35,0x96,0x16,0xFE,0x59,0x9C,0x8B,0x76,0x6D,0xD7,0xF1,
-0xA2,0x4B,0x0D,0x2B,0xFF,0x0B,0x72,0xDA,0x9E,0x60,0xD0,0x8E,0x90,0x35,0xC6,0x78,
-0x55,0x87,0x20,0xA1,0xCF,0xE5,0x6D,0x0A,0xC8,0x49,0x7C,0x31,0x98,0x33,0x6C,0x22,
-0xE9,0x87,0xD0,0x32,0x5A,0xA2,0xBA,0x13,0x82,0x11,0xED,0x39,0x17,0x9D,0x99,0x3A,
-0x72,0xA1,0xE6,0xFA,0xA4,0xD9,0xD5,0x17,0x31,0x75,0xAE,0x85,0x7D,0x22,0xAE,0x3F,
-0x01,0x46,0x86,0xF6,0x28,0x79,0xC8,0xB1,0xDA,0xE4,0x57,0x17,0xC4,0x7E,0x1C,0x0E,
-0xB0,0xB4,0x92,0xA6,0x56,0xB3,0xBD,0xB2,0x97,0xED,0xAA,0xA7,0xF0,0xB7,0xC5,0xA8,
-0x3F,0x95,0x16,0xD0,0xFF,0xA1,0x96,0xEB,0x08,0x5F,0x18,0x77,0x4F,0x02,0x03,0x01,
-0x00,0x01,0xA3,0x63,0x30,0x61,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,
-0x04,0x04,0x03,0x02,0x01,0x86,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,
-0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,
-0x04,0x14,0x45,0xEB,0xA2,0xAF,0xF4,0x92,0xCB,0x82,0x31,0x2D,0x51,0x8B,0xA7,0xA7,
-0x21,0x9D,0xF3,0x6D,0xC8,0x0F,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,
-0x16,0x80,0x14,0x45,0xEB,0xA2,0xAF,0xF4,0x92,0xCB,0x82,0x31,0x2D,0x51,0x8B,0xA7,
-0xA7,0x21,0x9D,0xF3,0x6D,0xC8,0x0F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0xA2,0x0E,0xBC,0xDF,0xE2,
-0xED,0xF0,0xE3,0x72,0x73,0x7A,0x64,0x94,0xBF,0xF7,0x72,0x66,0xD8,0x32,0xE4,0x42,
-0x75,0x62,0xAE,0x87,0xEB,0xF2,0xD5,0xD9,0xDE,0x56,0xB3,0x9F,0xCC,0xCE,0x14,0x28,
-0xB9,0x0D,0x97,0x60,0x5C,0x12,0x4C,0x58,0xE4,0xD3,0x3D,0x83,0x49,0x45,0x58,0x97,
-0x35,0x69,0x1A,0xA8,0x47,0xEA,0x56,0xC6,0x79,0xAB,0x12,0xD8,0x67,0x81,0x84,0xDF,
-0x7F,0x09,0x3C,0x94,0xE6,0xB8,0x26,0x2C,0x20,0xBD,0x3D,0xB3,0x28,0x89,0xF7,0x5F,
-0xFF,0x22,0xE2,0x97,0x84,0x1F,0xE9,0x65,0xEF,0x87,0xE0,0xDF,0xC1,0x67,0x49,0xB3,
-0x5D,0xEB,0xB2,0x09,0x2A,0xEB,0x26,0xED,0x78,0xBE,0x7D,0x3F,0x2B,0xF3,0xB7,0x26,
-0x35,0x6D,0x5F,0x89,0x01,0xB6,0x49,0x5B,0x9F,0x01,0x05,0x9B,0xAB,0x3D,0x25,0xC1,
-0xCC,0xB6,0x7F,0xC2,0xF1,0x6F,0x86,0xC6,0xFA,0x64,0x68,0xEB,0x81,0x2D,0x94,0xEB,
-0x42,0xB7,0xFA,0x8C,0x1E,0xDD,0x62,0xF1,0xBE,0x50,0x67,0xB7,0x6C,0xBD,0xF3,0xF1,
-0x1F,0x6B,0x0C,0x36,0x07,0x16,0x7F,0x37,0x7C,0xA9,0x5B,0x6D,0x7A,0xF1,0x12,0x46,
-0x60,0x83,0xD7,0x27,0x04,0xBE,0x4B,0xCE,0x97,0xBE,0xC3,0x67,0x2A,0x68,0x11,0xDF,
-0x80,0xE7,0x0C,0x33,0x66,0xBF,0x13,0x0D,0x14,0x6E,0xF3,0x7F,0x1F,0x63,0x10,0x1E,
-0xFA,0x8D,0x1B,0x25,0x6D,0x6C,0x8F,0xA5,0xB7,0x61,0x01,0xB1,0xD2,0xA3,0x26,0xA1,
-0x10,0x71,0x9D,0xAD,0xE2,0xC3,0xF9,0xC3,0x99,0x51,0xB7,0x2B,0x07,0x08,0xCE,0x2E,
-0xE6,0x50,0xB2,0xA7,0xFA,0x0A,0x45,0x2F,0xA2,0xF0,0xF2,
-};
-
-
-/* subject:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root CA */
-/* issuer :/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Global Root CA */
-
-
-const unsigned char DigiCert_Global_Root_CA_certificate[947]={
-0x30,0x82,0x03,0xAF,0x30,0x82,0x02,0x97,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x08,
-0x3B,0xE0,0x56,0x90,0x42,0x46,0xB1,0xA1,0x75,0x6A,0xC9,0x59,0x91,0xC7,0x4A,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x61,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,0x30,
-0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x44,0x69,0x67,0x69,0x43,0x65,0x72,0x74,
-0x20,0x49,0x6E,0x63,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,0x0B,0x13,0x10,0x77,
-0x77,0x77,0x2E,0x64,0x69,0x67,0x69,0x63,0x65,0x72,0x74,0x2E,0x63,0x6F,0x6D,0x31,
-0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,0x17,0x44,0x69,0x67,0x69,0x43,0x65,
-0x72,0x74,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,
-0x41,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x31,0x31,0x30,0x30,0x30,0x30,0x30,0x30,
-0x30,0x5A,0x17,0x0D,0x33,0x31,0x31,0x31,0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x30,
-0x5A,0x30,0x61,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,
-0x31,0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x44,0x69,0x67,0x69,0x43,
-0x65,0x72,0x74,0x20,0x49,0x6E,0x63,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,0x0B,
-0x13,0x10,0x77,0x77,0x77,0x2E,0x64,0x69,0x67,0x69,0x63,0x65,0x72,0x74,0x2E,0x63,
-0x6F,0x6D,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,0x17,0x44,0x69,0x67,
-0x69,0x43,0x65,0x72,0x74,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x52,0x6F,0x6F,
-0x74,0x20,0x43,0x41,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,
-0x02,0x82,0x01,0x01,0x00,0xE2,0x3B,0xE1,0x11,0x72,0xDE,0xA8,0xA4,0xD3,0xA3,0x57,
-0xAA,0x50,0xA2,0x8F,0x0B,0x77,0x90,0xC9,0xA2,0xA5,0xEE,0x12,0xCE,0x96,0x5B,0x01,
-0x09,0x20,0xCC,0x01,0x93,0xA7,0x4E,0x30,0xB7,0x53,0xF7,0x43,0xC4,0x69,0x00,0x57,
-0x9D,0xE2,0x8D,0x22,0xDD,0x87,0x06,0x40,0x00,0x81,0x09,0xCE,0xCE,0x1B,0x83,0xBF,
-0xDF,0xCD,0x3B,0x71,0x46,0xE2,0xD6,0x66,0xC7,0x05,0xB3,0x76,0x27,0x16,0x8F,0x7B,
-0x9E,0x1E,0x95,0x7D,0xEE,0xB7,0x48,0xA3,0x08,0xDA,0xD6,0xAF,0x7A,0x0C,0x39,0x06,
-0x65,0x7F,0x4A,0x5D,0x1F,0xBC,0x17,0xF8,0xAB,0xBE,0xEE,0x28,0xD7,0x74,0x7F,0x7A,
-0x78,0x99,0x59,0x85,0x68,0x6E,0x5C,0x23,0x32,0x4B,0xBF,0x4E,0xC0,0xE8,0x5A,0x6D,
-0xE3,0x70,0xBF,0x77,0x10,0xBF,0xFC,0x01,0xF6,0x85,0xD9,0xA8,0x44,0x10,0x58,0x32,
-0xA9,0x75,0x18,0xD5,0xD1,0xA2,0xBE,0x47,0xE2,0x27,0x6A,0xF4,0x9A,0x33,0xF8,0x49,
-0x08,0x60,0x8B,0xD4,0x5F,0xB4,0x3A,0x84,0xBF,0xA1,0xAA,0x4A,0x4C,0x7D,0x3E,0xCF,
-0x4F,0x5F,0x6C,0x76,0x5E,0xA0,0x4B,0x37,0x91,0x9E,0xDC,0x22,0xE6,0x6D,0xCE,0x14,
-0x1A,0x8E,0x6A,0xCB,0xFE,0xCD,0xB3,0x14,0x64,0x17,0xC7,0x5B,0x29,0x9E,0x32,0xBF,
-0xF2,0xEE,0xFA,0xD3,0x0B,0x42,0xD4,0xAB,0xB7,0x41,0x32,0xDA,0x0C,0xD4,0xEF,0xF8,
-0x81,0xD5,0xBB,0x8D,0x58,0x3F,0xB5,0x1B,0xE8,0x49,0x28,0xA2,0x70,0xDA,0x31,0x04,
-0xDD,0xF7,0xB2,0x16,0xF2,0x4C,0x0A,0x4E,0x07,0xA8,0xED,0x4A,0x3D,0x5E,0xB5,0x7F,
-0xA3,0x90,0xC3,0xAF,0x27,0x02,0x03,0x01,0x00,0x01,0xA3,0x63,0x30,0x61,0x30,0x0E,
-0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x86,0x30,0x0F,
-0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,
-0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x03,0xDE,0x50,0x35,0x56,0xD1,
-0x4C,0xBB,0x66,0xF0,0xA3,0xE2,0x1B,0x1B,0xC3,0x97,0xB2,0x3D,0xD1,0x55,0x30,0x1F,
-0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x03,0xDE,0x50,0x35,0x56,
-0xD1,0x4C,0xBB,0x66,0xF0,0xA3,0xE2,0x1B,0x1B,0xC3,0x97,0xB2,0x3D,0xD1,0x55,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,
-0x01,0x01,0x00,0xCB,0x9C,0x37,0xAA,0x48,0x13,0x12,0x0A,0xFA,0xDD,0x44,0x9C,0x4F,
-0x52,0xB0,0xF4,0xDF,0xAE,0x04,0xF5,0x79,0x79,0x08,0xA3,0x24,0x18,0xFC,0x4B,0x2B,
-0x84,0xC0,0x2D,0xB9,0xD5,0xC7,0xFE,0xF4,0xC1,0x1F,0x58,0xCB,0xB8,0x6D,0x9C,0x7A,
-0x74,0xE7,0x98,0x29,0xAB,0x11,0xB5,0xE3,0x70,0xA0,0xA1,0xCD,0x4C,0x88,0x99,0x93,
-0x8C,0x91,0x70,0xE2,0xAB,0x0F,0x1C,0xBE,0x93,0xA9,0xFF,0x63,0xD5,0xE4,0x07,0x60,
-0xD3,0xA3,0xBF,0x9D,0x5B,0x09,0xF1,0xD5,0x8E,0xE3,0x53,0xF4,0x8E,0x63,0xFA,0x3F,
-0xA7,0xDB,0xB4,0x66,0xDF,0x62,0x66,0xD6,0xD1,0x6E,0x41,0x8D,0xF2,0x2D,0xB5,0xEA,
-0x77,0x4A,0x9F,0x9D,0x58,0xE2,0x2B,0x59,0xC0,0x40,0x23,0xED,0x2D,0x28,0x82,0x45,
-0x3E,0x79,0x54,0x92,0x26,0x98,0xE0,0x80,0x48,0xA8,0x37,0xEF,0xF0,0xD6,0x79,0x60,
-0x16,0xDE,0xAC,0xE8,0x0E,0xCD,0x6E,0xAC,0x44,0x17,0x38,0x2F,0x49,0xDA,0xE1,0x45,
-0x3E,0x2A,0xB9,0x36,0x53,0xCF,0x3A,0x50,0x06,0xF7,0x2E,0xE8,0xC4,0x57,0x49,0x6C,
-0x61,0x21,0x18,0xD5,0x04,0xAD,0x78,0x3C,0x2C,0x3A,0x80,0x6B,0xA7,0xEB,0xAF,0x15,
-0x14,0xE9,0xD8,0x89,0xC1,0xB9,0x38,0x6C,0xE2,0x91,0x6C,0x8A,0xFF,0x64,0xB9,0x77,
-0x25,0x57,0x30,0xC0,0x1B,0x24,0xA3,0xE1,0xDC,0xE9,0xDF,0x47,0x7C,0xB5,0xB4,0x24,
-0x08,0x05,0x30,0xEC,0x2D,0xBD,0x0B,0xBF,0x45,0xBF,0x50,0xB9,0xA9,0xF3,0xEB,0x98,
-0x01,0x12,0xAD,0xC8,0x88,0xC6,0x98,0x34,0x5F,0x8D,0x0A,0x3C,0xC6,0xE9,0xD5,0x95,
-0x95,0x6D,0xDE,
-};
-
-
-/* subject:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA */
-/* issuer :/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA */
-
-
-const unsigned char DigiCert_High_Assurance_EV_Root_CA_certificate[969]={
-0x30,0x82,0x03,0xC5,0x30,0x82,0x02,0xAD,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x02,
-0xAC,0x5C,0x26,0x6A,0x0B,0x40,0x9B,0x8F,0x0B,0x79,0xF2,0xAE,0x46,0x25,0x77,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x6C,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,0x30,
-0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x44,0x69,0x67,0x69,0x43,0x65,0x72,0x74,
-0x20,0x49,0x6E,0x63,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,0x0B,0x13,0x10,0x77,
-0x77,0x77,0x2E,0x64,0x69,0x67,0x69,0x63,0x65,0x72,0x74,0x2E,0x63,0x6F,0x6D,0x31,
-0x2B,0x30,0x29,0x06,0x03,0x55,0x04,0x03,0x13,0x22,0x44,0x69,0x67,0x69,0x43,0x65,
-0x72,0x74,0x20,0x48,0x69,0x67,0x68,0x20,0x41,0x73,0x73,0x75,0x72,0x61,0x6E,0x63,
-0x65,0x20,0x45,0x56,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x1E,0x17,0x0D,
-0x30,0x36,0x31,0x31,0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,
-0x31,0x31,0x31,0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x30,0x6C,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,0x30,0x13,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0C,0x44,0x69,0x67,0x69,0x43,0x65,0x72,0x74,0x20,0x49,
-0x6E,0x63,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,0x0B,0x13,0x10,0x77,0x77,0x77,
-0x2E,0x64,0x69,0x67,0x69,0x63,0x65,0x72,0x74,0x2E,0x63,0x6F,0x6D,0x31,0x2B,0x30,
-0x29,0x06,0x03,0x55,0x04,0x03,0x13,0x22,0x44,0x69,0x67,0x69,0x43,0x65,0x72,0x74,
-0x20,0x48,0x69,0x67,0x68,0x20,0x41,0x73,0x73,0x75,0x72,0x61,0x6E,0x63,0x65,0x20,
-0x45,0x56,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x82,0x01,0x22,0x30,0x0D,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,
-0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xC6,0xCC,0xE5,0x73,0xE6,
-0xFB,0xD4,0xBB,0xE5,0x2D,0x2D,0x32,0xA6,0xDF,0xE5,0x81,0x3F,0xC9,0xCD,0x25,0x49,
-0xB6,0x71,0x2A,0xC3,0xD5,0x94,0x34,0x67,0xA2,0x0A,0x1C,0xB0,0x5F,0x69,0xA6,0x40,
-0xB1,0xC4,0xB7,0xB2,0x8F,0xD0,0x98,0xA4,0xA9,0x41,0x59,0x3A,0xD3,0xDC,0x94,0xD6,
-0x3C,0xDB,0x74,0x38,0xA4,0x4A,0xCC,0x4D,0x25,0x82,0xF7,0x4A,0xA5,0x53,0x12,0x38,
-0xEE,0xF3,0x49,0x6D,0x71,0x91,0x7E,0x63,0xB6,0xAB,0xA6,0x5F,0xC3,0xA4,0x84,0xF8,
-0x4F,0x62,0x51,0xBE,0xF8,0xC5,0xEC,0xDB,0x38,0x92,0xE3,0x06,0xE5,0x08,0x91,0x0C,
-0xC4,0x28,0x41,0x55,0xFB,0xCB,0x5A,0x89,0x15,0x7E,0x71,0xE8,0x35,0xBF,0x4D,0x72,
-0x09,0x3D,0xBE,0x3A,0x38,0x50,0x5B,0x77,0x31,0x1B,0x8D,0xB3,0xC7,0x24,0x45,0x9A,
-0xA7,0xAC,0x6D,0x00,0x14,0x5A,0x04,0xB7,0xBA,0x13,0xEB,0x51,0x0A,0x98,0x41,0x41,
-0x22,0x4E,0x65,0x61,0x87,0x81,0x41,0x50,0xA6,0x79,0x5C,0x89,0xDE,0x19,0x4A,0x57,
-0xD5,0x2E,0xE6,0x5D,0x1C,0x53,0x2C,0x7E,0x98,0xCD,0x1A,0x06,0x16,0xA4,0x68,0x73,
-0xD0,0x34,0x04,0x13,0x5C,0xA1,0x71,0xD3,0x5A,0x7C,0x55,0xDB,0x5E,0x64,0xE1,0x37,
-0x87,0x30,0x56,0x04,0xE5,0x11,0xB4,0x29,0x80,0x12,0xF1,0x79,0x39,0x88,0xA2,0x02,
-0x11,0x7C,0x27,0x66,0xB7,0x88,0xB7,0x78,0xF2,0xCA,0x0A,0xA8,0x38,0xAB,0x0A,0x64,
-0xC2,0xBF,0x66,0x5D,0x95,0x84,0xC1,0xA1,0x25,0x1E,0x87,0x5D,0x1A,0x50,0x0B,0x20,
-0x12,0xCC,0x41,0xBB,0x6E,0x0B,0x51,0x38,0xB8,0x4B,0xCB,0x02,0x03,0x01,0x00,0x01,
-0xA3,0x63,0x30,0x61,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,
-0x03,0x02,0x01,0x86,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,
-0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,
-0xB1,0x3E,0xC3,0x69,0x03,0xF8,0xBF,0x47,0x01,0xD4,0x98,0x26,0x1A,0x08,0x02,0xEF,
-0x63,0x64,0x2B,0xC3,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,
-0x14,0xB1,0x3E,0xC3,0x69,0x03,0xF8,0xBF,0x47,0x01,0xD4,0x98,0x26,0x1A,0x08,0x02,
-0xEF,0x63,0x64,0x2B,0xC3,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x1C,0x1A,0x06,0x97,0xDC,0xD7,0x9C,
-0x9F,0x3C,0x88,0x66,0x06,0x08,0x57,0x21,0xDB,0x21,0x47,0xF8,0x2A,0x67,0xAA,0xBF,
-0x18,0x32,0x76,0x40,0x10,0x57,0xC1,0x8A,0xF3,0x7A,0xD9,0x11,0x65,0x8E,0x35,0xFA,
-0x9E,0xFC,0x45,0xB5,0x9E,0xD9,0x4C,0x31,0x4B,0xB8,0x91,0xE8,0x43,0x2C,0x8E,0xB3,
-0x78,0xCE,0xDB,0xE3,0x53,0x79,0x71,0xD6,0xE5,0x21,0x94,0x01,0xDA,0x55,0x87,0x9A,
-0x24,0x64,0xF6,0x8A,0x66,0xCC,0xDE,0x9C,0x37,0xCD,0xA8,0x34,0xB1,0x69,0x9B,0x23,
-0xC8,0x9E,0x78,0x22,0x2B,0x70,0x43,0xE3,0x55,0x47,0x31,0x61,0x19,0xEF,0x58,0xC5,
-0x85,0x2F,0x4E,0x30,0xF6,0xA0,0x31,0x16,0x23,0xC8,0xE7,0xE2,0x65,0x16,0x33,0xCB,
-0xBF,0x1A,0x1B,0xA0,0x3D,0xF8,0xCA,0x5E,0x8B,0x31,0x8B,0x60,0x08,0x89,0x2D,0x0C,
-0x06,0x5C,0x52,0xB7,0xC4,0xF9,0x0A,0x98,0xD1,0x15,0x5F,0x9F,0x12,0xBE,0x7C,0x36,
-0x63,0x38,0xBD,0x44,0xA4,0x7F,0xE4,0x26,0x2B,0x0A,0xC4,0x97,0x69,0x0D,0xE9,0x8C,
-0xE2,0xC0,0x10,0x57,0xB8,0xC8,0x76,0x12,0x91,0x55,0xF2,0x48,0x69,0xD8,0xBC,0x2A,
-0x02,0x5B,0x0F,0x44,0xD4,0x20,0x31,0xDB,0xF4,0xBA,0x70,0x26,0x5D,0x90,0x60,0x9E,
-0xBC,0x4B,0x17,0x09,0x2F,0xB4,0xCB,0x1E,0x43,0x68,0xC9,0x07,0x27,0xC1,0xD2,0x5C,
-0xF7,0xEA,0x21,0xB9,0x68,0x12,0x9C,0x3C,0x9C,0xBF,0x9E,0xFC,0x80,0x5C,0x9B,0x63,
-0xCD,0xEC,0x47,0xAA,0x25,0x27,0x67,0xA0,0x37,0xF3,0x00,0x82,0x7D,0x54,0xD7,0xA9,
-0xF8,0xE9,0x2E,0x13,0xA3,0x77,0xE8,0x1F,0x4A,
-};
-
-
-/* subject:/O=Entrust.net/OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/OU=(c) 1999 Entrust.net Limited/CN=Entrust.net Certification Authority (2048) */
-/* issuer :/O=Entrust.net/OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/OU=(c) 1999 Entrust.net Limited/CN=Entrust.net Certification Authority (2048) */
-
-
-const unsigned char Entrust_net_Premium_2048_Secure_Server_CA_certificate[1120]={
-0x30,0x82,0x04,0x5C,0x30,0x82,0x03,0x44,0xA0,0x03,0x02,0x01,0x02,0x02,0x04,0x38,
-0x63,0xB9,0x66,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x30,0x81,0xB4,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,
-0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x31,0x40,0x30,0x3E,0x06,
-0x03,0x55,0x04,0x0B,0x14,0x37,0x77,0x77,0x77,0x2E,0x65,0x6E,0x74,0x72,0x75,0x73,
-0x74,0x2E,0x6E,0x65,0x74,0x2F,0x43,0x50,0x53,0x5F,0x32,0x30,0x34,0x38,0x20,0x69,
-0x6E,0x63,0x6F,0x72,0x70,0x2E,0x20,0x62,0x79,0x20,0x72,0x65,0x66,0x2E,0x20,0x28,
-0x6C,0x69,0x6D,0x69,0x74,0x73,0x20,0x6C,0x69,0x61,0x62,0x2E,0x29,0x31,0x25,0x30,
-0x23,0x06,0x03,0x55,0x04,0x0B,0x13,0x1C,0x28,0x63,0x29,0x20,0x31,0x39,0x39,0x39,
-0x20,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x20,0x4C,0x69,0x6D,
-0x69,0x74,0x65,0x64,0x31,0x33,0x30,0x31,0x06,0x03,0x55,0x04,0x03,0x13,0x2A,0x45,
-0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x20,0x28,0x32,0x30,0x34,0x38,0x29,0x30,0x1E,0x17,0x0D,0x39,0x39,0x31,
-0x32,0x32,0x34,0x31,0x37,0x35,0x30,0x35,0x31,0x5A,0x17,0x0D,0x31,0x39,0x31,0x32,
-0x32,0x34,0x31,0x38,0x32,0x30,0x35,0x31,0x5A,0x30,0x81,0xB4,0x31,0x14,0x30,0x12,
-0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,
-0x65,0x74,0x31,0x40,0x30,0x3E,0x06,0x03,0x55,0x04,0x0B,0x14,0x37,0x77,0x77,0x77,
-0x2E,0x65,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x2F,0x43,0x50,0x53,
-0x5F,0x32,0x30,0x34,0x38,0x20,0x69,0x6E,0x63,0x6F,0x72,0x70,0x2E,0x20,0x62,0x79,
-0x20,0x72,0x65,0x66,0x2E,0x20,0x28,0x6C,0x69,0x6D,0x69,0x74,0x73,0x20,0x6C,0x69,
-0x61,0x62,0x2E,0x29,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x0B,0x13,0x1C,0x28,
-0x63,0x29,0x20,0x31,0x39,0x39,0x39,0x20,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,
-0x6E,0x65,0x74,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x33,0x30,0x31,0x06,
-0x03,0x55,0x04,0x03,0x13,0x2A,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,
-0x74,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,
-0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x28,0x32,0x30,0x34,0x38,0x29,
-0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,
-0x00,0xAD,0x4D,0x4B,0xA9,0x12,0x86,0xB2,0xEA,0xA3,0x20,0x07,0x15,0x16,0x64,0x2A,
-0x2B,0x4B,0xD1,0xBF,0x0B,0x4A,0x4D,0x8E,0xED,0x80,0x76,0xA5,0x67,0xB7,0x78,0x40,
-0xC0,0x73,0x42,0xC8,0x68,0xC0,0xDB,0x53,0x2B,0xDD,0x5E,0xB8,0x76,0x98,0x35,0x93,
-0x8B,0x1A,0x9D,0x7C,0x13,0x3A,0x0E,0x1F,0x5B,0xB7,0x1E,0xCF,0xE5,0x24,0x14,0x1E,
-0xB1,0x81,0xA9,0x8D,0x7D,0xB8,0xCC,0x6B,0x4B,0x03,0xF1,0x02,0x0C,0xDC,0xAB,0xA5,
-0x40,0x24,0x00,0x7F,0x74,0x94,0xA1,0x9D,0x08,0x29,0xB3,0x88,0x0B,0xF5,0x87,0x77,
-0x9D,0x55,0xCD,0xE4,0xC3,0x7E,0xD7,0x6A,0x64,0xAB,0x85,0x14,0x86,0x95,0x5B,0x97,
-0x32,0x50,0x6F,0x3D,0xC8,0xBA,0x66,0x0C,0xE3,0xFC,0xBD,0xB8,0x49,0xC1,0x76,0x89,
-0x49,0x19,0xFD,0xC0,0xA8,0xBD,0x89,0xA3,0x67,0x2F,0xC6,0x9F,0xBC,0x71,0x19,0x60,
-0xB8,0x2D,0xE9,0x2C,0xC9,0x90,0x76,0x66,0x7B,0x94,0xE2,0xAF,0x78,0xD6,0x65,0x53,
-0x5D,0x3C,0xD6,0x9C,0xB2,0xCF,0x29,0x03,0xF9,0x2F,0xA4,0x50,0xB2,0xD4,0x48,0xCE,
-0x05,0x32,0x55,0x8A,0xFD,0xB2,0x64,0x4C,0x0E,0xE4,0x98,0x07,0x75,0xDB,0x7F,0xDF,
-0xB9,0x08,0x55,0x60,0x85,0x30,0x29,0xF9,0x7B,0x48,0xA4,0x69,0x86,0xE3,0x35,0x3F,
-0x1E,0x86,0x5D,0x7A,0x7A,0x15,0xBD,0xEF,0x00,0x8E,0x15,0x22,0x54,0x17,0x00,0x90,
-0x26,0x93,0xBC,0x0E,0x49,0x68,0x91,0xBF,0xF8,0x47,0xD3,0x9D,0x95,0x42,0xC1,0x0E,
-0x4D,0xDF,0x6F,0x26,0xCF,0xC3,0x18,0x21,0x62,0x66,0x43,0x70,0xD6,0xD5,0xC0,0x07,
-0xE1,0x02,0x03,0x01,0x00,0x01,0xA3,0x74,0x30,0x72,0x30,0x11,0x06,0x09,0x60,0x86,
-0x48,0x01,0x86,0xF8,0x42,0x01,0x01,0x04,0x04,0x03,0x02,0x00,0x07,0x30,0x1F,0x06,
-0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x55,0xE4,0x81,0xD1,0x11,0x80,
-0xBE,0xD8,0x89,0xB9,0x08,0xA3,0x31,0xF9,0xA1,0x24,0x09,0x16,0xB9,0x70,0x30,0x1D,
-0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x55,0xE4,0x81,0xD1,0x11,0x80,0xBE,
-0xD8,0x89,0xB9,0x08,0xA3,0x31,0xF9,0xA1,0x24,0x09,0x16,0xB9,0x70,0x30,0x1D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF6,0x7D,0x07,0x41,0x00,0x04,0x10,0x30,0x0E,0x1B,0x08,
-0x56,0x35,0x2E,0x30,0x3A,0x34,0x2E,0x30,0x03,0x02,0x04,0x90,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,
-0x59,0x47,0xAC,0x21,0x84,0x8A,0x17,0xC9,0x9C,0x89,0x53,0x1E,0xBA,0x80,0x85,0x1A,
-0xC6,0x3C,0x4E,0x3E,0xB1,0x9C,0xB6,0x7C,0xC6,0x92,0x5D,0x18,0x64,0x02,0xE3,0xD3,
-0x06,0x08,0x11,0x61,0x7C,0x63,0xE3,0x2B,0x9D,0x31,0x03,0x70,0x76,0xD2,0xA3,0x28,
-0xA0,0xF4,0xBB,0x9A,0x63,0x73,0xED,0x6D,0xE5,0x2A,0xDB,0xED,0x14,0xA9,0x2B,0xC6,
-0x36,0x11,0xD0,0x2B,0xEB,0x07,0x8B,0xA5,0xDA,0x9E,0x5C,0x19,0x9D,0x56,0x12,0xF5,
-0x54,0x29,0xC8,0x05,0xED,0xB2,0x12,0x2A,0x8D,0xF4,0x03,0x1B,0xFF,0xE7,0x92,0x10,
-0x87,0xB0,0x3A,0xB5,0xC3,0x9D,0x05,0x37,0x12,0xA3,0xC7,0xF4,0x15,0xB9,0xD5,0xA4,
-0x39,0x16,0x9B,0x53,0x3A,0x23,0x91,0xF1,0xA8,0x82,0xA2,0x6A,0x88,0x68,0xC1,0x79,
-0x02,0x22,0xBC,0xAA,0xA6,0xD6,0xAE,0xDF,0xB0,0x14,0x5F,0xB8,0x87,0xD0,0xDD,0x7C,
-0x7F,0x7B,0xFF,0xAF,0x1C,0xCF,0xE6,0xDB,0x07,0xAD,0x5E,0xDB,0x85,0x9D,0xD0,0x2B,
-0x0D,0x33,0xDB,0x04,0xD1,0xE6,0x49,0x40,0x13,0x2B,0x76,0xFB,0x3E,0xE9,0x9C,0x89,
-0x0F,0x15,0xCE,0x18,0xB0,0x85,0x78,0x21,0x4F,0x6B,0x4F,0x0E,0xFA,0x36,0x67,0xCD,
-0x07,0xF2,0xFF,0x08,0xD0,0xE2,0xDE,0xD9,0xBF,0x2A,0xAF,0xB8,0x87,0x86,0x21,0x3C,
-0x04,0xCA,0xB7,0x94,0x68,0x7F,0xCF,0x3C,0xE9,0x98,0xD7,0x38,0xFF,0xEC,0xC0,0xD9,
-0x50,0xF0,0x2E,0x4B,0x58,0xAE,0x46,0x6F,0xD0,0x2E,0xC3,0x60,0xDA,0x72,0x55,0x72,
-0xBD,0x4C,0x45,0x9E,0x61,0xBA,0xBF,0x84,0x81,0x92,0x03,0xD1,0xD2,0x69,0x7C,0xC5,
-};
-
-
-/* subject:/C=US/O=Entrust.net/OU=www.entrust.net/CPS incorp. by ref. (limits liab.)/OU=(c) 1999 Entrust.net Limited/CN=Entrust.net Secure Server Certification Authority */
-/* issuer :/C=US/O=Entrust.net/OU=www.entrust.net/CPS incorp. by ref. (limits liab.)/OU=(c) 1999 Entrust.net Limited/CN=Entrust.net Secure Server Certification Authority */
-
-
-const unsigned char Entrust_net_Secure_Server_CA_certificate[1244]={
-0x30,0x82,0x04,0xD8,0x30,0x82,0x04,0x41,0xA0,0x03,0x02,0x01,0x02,0x02,0x04,0x37,
-0x4A,0xD2,0x43,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x30,0x81,0xC3,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,
-0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,0x0B,0x45,0x6E,0x74,
-0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x31,0x3B,0x30,0x39,0x06,0x03,0x55,0x04,
-0x0B,0x13,0x32,0x77,0x77,0x77,0x2E,0x65,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,
-0x65,0x74,0x2F,0x43,0x50,0x53,0x20,0x69,0x6E,0x63,0x6F,0x72,0x70,0x2E,0x20,0x62,
-0x79,0x20,0x72,0x65,0x66,0x2E,0x20,0x28,0x6C,0x69,0x6D,0x69,0x74,0x73,0x20,0x6C,
-0x69,0x61,0x62,0x2E,0x29,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x0B,0x13,0x1C,
-0x28,0x63,0x29,0x20,0x31,0x39,0x39,0x39,0x20,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,
-0x2E,0x6E,0x65,0x74,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x31,0x3A,0x30,0x38,
-0x06,0x03,0x55,0x04,0x03,0x13,0x31,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,
-0x65,0x74,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x53,0x65,0x72,0x76,0x65,0x72,
-0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,
-0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x35,
-0x32,0x35,0x31,0x36,0x30,0x39,0x34,0x30,0x5A,0x17,0x0D,0x31,0x39,0x30,0x35,0x32,
-0x35,0x31,0x36,0x33,0x39,0x34,0x30,0x5A,0x30,0x81,0xC3,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x0B,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x31,0x3B,
-0x30,0x39,0x06,0x03,0x55,0x04,0x0B,0x13,0x32,0x77,0x77,0x77,0x2E,0x65,0x6E,0x74,
-0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x2F,0x43,0x50,0x53,0x20,0x69,0x6E,0x63,
-0x6F,0x72,0x70,0x2E,0x20,0x62,0x79,0x20,0x72,0x65,0x66,0x2E,0x20,0x28,0x6C,0x69,
-0x6D,0x69,0x74,0x73,0x20,0x6C,0x69,0x61,0x62,0x2E,0x29,0x31,0x25,0x30,0x23,0x06,
-0x03,0x55,0x04,0x0B,0x13,0x1C,0x28,0x63,0x29,0x20,0x31,0x39,0x39,0x39,0x20,0x45,
-0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x20,0x4C,0x69,0x6D,0x69,0x74,
-0x65,0x64,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x03,0x13,0x31,0x45,0x6E,0x74,
-0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,
-0x53,0x65,0x72,0x76,0x65,0x72,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,
-0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x81,
-0x9D,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,
-0x03,0x81,0x8B,0x00,0x30,0x81,0x87,0x02,0x81,0x81,0x00,0xCD,0x28,0x83,0x34,0x54,
-0x1B,0x89,0xF3,0x0F,0xAF,0x37,0x91,0x31,0xFF,0xAF,0x31,0x60,0xC9,0xA8,0xE8,0xB2,
-0x10,0x68,0xED,0x9F,0xE7,0x93,0x36,0xF1,0x0A,0x64,0xBB,0x47,0xF5,0x04,0x17,0x3F,
-0x23,0x47,0x4D,0xC5,0x27,0x19,0x81,0x26,0x0C,0x54,0x72,0x0D,0x88,0x2D,0xD9,0x1F,
-0x9A,0x12,0x9F,0xBC,0xB3,0x71,0xD3,0x80,0x19,0x3F,0x47,0x66,0x7B,0x8C,0x35,0x28,
-0xD2,0xB9,0x0A,0xDF,0x24,0xDA,0x9C,0xD6,0x50,0x79,0x81,0x7A,0x5A,0xD3,0x37,0xF7,
-0xC2,0x4A,0xD8,0x29,0x92,0x26,0x64,0xD1,0xE4,0x98,0x6C,0x3A,0x00,0x8A,0xF5,0x34,
-0x9B,0x65,0xF8,0xED,0xE3,0x10,0xFF,0xFD,0xB8,0x49,0x58,0xDC,0xA0,0xDE,0x82,0x39,
-0x6B,0x81,0xB1,0x16,0x19,0x61,0xB9,0x54,0xB6,0xE6,0x43,0x02,0x01,0x03,0xA3,0x82,
-0x01,0xD7,0x30,0x82,0x01,0xD3,0x30,0x11,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,
-0x42,0x01,0x01,0x04,0x04,0x03,0x02,0x00,0x07,0x30,0x82,0x01,0x19,0x06,0x03,0x55,
-0x1D,0x1F,0x04,0x82,0x01,0x10,0x30,0x82,0x01,0x0C,0x30,0x81,0xDE,0xA0,0x81,0xDB,
-0xA0,0x81,0xD8,0xA4,0x81,0xD5,0x30,0x81,0xD2,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,
-0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x0A,0x13,
-0x0B,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x31,0x3B,0x30,0x39,
-0x06,0x03,0x55,0x04,0x0B,0x13,0x32,0x77,0x77,0x77,0x2E,0x65,0x6E,0x74,0x72,0x75,
-0x73,0x74,0x2E,0x6E,0x65,0x74,0x2F,0x43,0x50,0x53,0x20,0x69,0x6E,0x63,0x6F,0x72,
-0x70,0x2E,0x20,0x62,0x79,0x20,0x72,0x65,0x66,0x2E,0x20,0x28,0x6C,0x69,0x6D,0x69,
-0x74,0x73,0x20,0x6C,0x69,0x61,0x62,0x2E,0x29,0x31,0x25,0x30,0x23,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x1C,0x28,0x63,0x29,0x20,0x31,0x39,0x39,0x39,0x20,0x45,0x6E,0x74,
-0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x20,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,
-0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x03,0x13,0x31,0x45,0x6E,0x74,0x72,0x75,
-0x73,0x74,0x2E,0x6E,0x65,0x74,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x53,0x65,
-0x72,0x76,0x65,0x72,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,
-0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x31,0x0D,0x30,0x0B,
-0x06,0x03,0x55,0x04,0x03,0x13,0x04,0x43,0x52,0x4C,0x31,0x30,0x29,0xA0,0x27,0xA0,
-0x25,0x86,0x23,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x65,0x6E,
-0x74,0x72,0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x2F,0x43,0x52,0x4C,0x2F,0x6E,0x65,
-0x74,0x31,0x2E,0x63,0x72,0x6C,0x30,0x2B,0x06,0x03,0x55,0x1D,0x10,0x04,0x24,0x30,
-0x22,0x80,0x0F,0x31,0x39,0x39,0x39,0x30,0x35,0x32,0x35,0x31,0x36,0x30,0x39,0x34,
-0x30,0x5A,0x81,0x0F,0x32,0x30,0x31,0x39,0x30,0x35,0x32,0x35,0x31,0x36,0x30,0x39,
-0x34,0x30,0x5A,0x30,0x0B,0x06,0x03,0x55,0x1D,0x0F,0x04,0x04,0x03,0x02,0x01,0x06,
-0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0xF0,0x17,0x62,
-0x13,0x55,0x3D,0xB3,0xFF,0x0A,0x00,0x6B,0xFB,0x50,0x84,0x97,0xF3,0xED,0x62,0xD0,
-0x1A,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xF0,0x17,0x62,0x13,
-0x55,0x3D,0xB3,0xFF,0x0A,0x00,0x6B,0xFB,0x50,0x84,0x97,0xF3,0xED,0x62,0xD0,0x1A,
-0x30,0x0C,0x06,0x03,0x55,0x1D,0x13,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x19,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF6,0x7D,0x07,0x41,0x00,0x04,0x0C,0x30,0x0A,0x1B,
-0x04,0x56,0x34,0x2E,0x30,0x03,0x02,0x04,0x90,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x81,0x81,0x00,0x90,0xDC,0x30,0x02,
-0xFA,0x64,0x74,0xC2,0xA7,0x0A,0xA5,0x7C,0x21,0x8D,0x34,0x17,0xA8,0xFB,0x47,0x0E,
-0xFF,0x25,0x7C,0x8D,0x13,0x0A,0xFB,0xE4,0x98,0xB5,0xEF,0x8C,0xF8,0xC5,0x10,0x0D,
-0xF7,0x92,0xBE,0xF1,0xC3,0xD5,0xD5,0x95,0x6A,0x04,0xBB,0x2C,0xCE,0x26,0x36,0x65,
-0xC8,0x31,0xC6,0xE7,0xEE,0x3F,0xE3,0x57,0x75,0x84,0x7A,0x11,0xEF,0x46,0x4F,0x18,
-0xF4,0xD3,0x98,0xBB,0xA8,0x87,0x32,0xBA,0x72,0xF6,0x3C,0xE2,0x3D,0x9F,0xD7,0x1D,
-0xD9,0xC3,0x60,0x43,0x8C,0x58,0x0E,0x22,0x96,0x2F,0x62,0xA3,0x2C,0x1F,0xBA,0xAD,
-0x05,0xEF,0xAB,0x32,0x78,0x87,0xA0,0x54,0x73,0x19,0xB5,0x5C,0x05,0xF9,0x52,0x3E,
-0x6D,0x2D,0x45,0x0B,0xF7,0x0A,0x93,0xEA,0xED,0x06,0xF9,0xB2,
-};
-
-
-/* subject:/C=US/O=Entrust, Inc./OU=www.entrust.net/CPS is incorporated by reference/OU=(c) 2006 Entrust, Inc./CN=Entrust Root Certification Authority */
-/* issuer :/C=US/O=Entrust, Inc./OU=www.entrust.net/CPS is incorporated by reference/OU=(c) 2006 Entrust, Inc./CN=Entrust Root Certification Authority */
-
-
-const unsigned char Entrust_Root_Certification_Authority_certificate[1173]={
-0x30,0x82,0x04,0x91,0x30,0x82,0x03,0x79,0xA0,0x03,0x02,0x01,0x02,0x02,0x04,0x45,
-0x6B,0x50,0x54,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x30,0x81,0xB0,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,
-0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x45,0x6E,0x74,
-0x72,0x75,0x73,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x39,0x30,0x37,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x30,0x77,0x77,0x77,0x2E,0x65,0x6E,0x74,0x72,0x75,0x73,0x74,
-0x2E,0x6E,0x65,0x74,0x2F,0x43,0x50,0x53,0x20,0x69,0x73,0x20,0x69,0x6E,0x63,0x6F,
-0x72,0x70,0x6F,0x72,0x61,0x74,0x65,0x64,0x20,0x62,0x79,0x20,0x72,0x65,0x66,0x65,
-0x72,0x65,0x6E,0x63,0x65,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,
-0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x36,0x20,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,
-0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,0x04,0x03,0x13,
-0x24,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,
-0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,
-0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x31,0x32,0x37,0x32,
-0x30,0x32,0x33,0x34,0x32,0x5A,0x17,0x0D,0x32,0x36,0x31,0x31,0x32,0x37,0x32,0x30,
-0x35,0x33,0x34,0x32,0x5A,0x30,0x81,0xB0,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,
-0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x39,0x30,
-0x37,0x06,0x03,0x55,0x04,0x0B,0x13,0x30,0x77,0x77,0x77,0x2E,0x65,0x6E,0x74,0x72,
-0x75,0x73,0x74,0x2E,0x6E,0x65,0x74,0x2F,0x43,0x50,0x53,0x20,0x69,0x73,0x20,0x69,
-0x6E,0x63,0x6F,0x72,0x70,0x6F,0x72,0x61,0x74,0x65,0x64,0x20,0x62,0x79,0x20,0x72,
-0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,
-0x0B,0x13,0x16,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x36,0x20,0x45,0x6E,0x74,0x72,
-0x75,0x73,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,
-0x04,0x03,0x13,0x24,0x45,0x6E,0x74,0x72,0x75,0x73,0x74,0x20,0x52,0x6F,0x6F,0x74,
-0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,
-0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,
-0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xB6,0x95,0xB6,0x43,0x42,0xFA,0xC6,
-0x6D,0x2A,0x6F,0x48,0xDF,0x94,0x4C,0x39,0x57,0x05,0xEE,0xC3,0x79,0x11,0x41,0x68,
-0x36,0xED,0xEC,0xFE,0x9A,0x01,0x8F,0xA1,0x38,0x28,0xFC,0xF7,0x10,0x46,0x66,0x2E,
-0x4D,0x1E,0x1A,0xB1,0x1A,0x4E,0xC6,0xD1,0xC0,0x95,0x88,0xB0,0xC9,0xFF,0x31,0x8B,
-0x33,0x03,0xDB,0xB7,0x83,0x7B,0x3E,0x20,0x84,0x5E,0xED,0xB2,0x56,0x28,0xA7,0xF8,
-0xE0,0xB9,0x40,0x71,0x37,0xC5,0xCB,0x47,0x0E,0x97,0x2A,0x68,0xC0,0x22,0x95,0x62,
-0x15,0xDB,0x47,0xD9,0xF5,0xD0,0x2B,0xFF,0x82,0x4B,0xC9,0xAD,0x3E,0xDE,0x4C,0xDB,
-0x90,0x80,0x50,0x3F,0x09,0x8A,0x84,0x00,0xEC,0x30,0x0A,0x3D,0x18,0xCD,0xFB,0xFD,
-0x2A,0x59,0x9A,0x23,0x95,0x17,0x2C,0x45,0x9E,0x1F,0x6E,0x43,0x79,0x6D,0x0C,0x5C,
-0x98,0xFE,0x48,0xA7,0xC5,0x23,0x47,0x5C,0x5E,0xFD,0x6E,0xE7,0x1E,0xB4,0xF6,0x68,
-0x45,0xD1,0x86,0x83,0x5B,0xA2,0x8A,0x8D,0xB1,0xE3,0x29,0x80,0xFE,0x25,0x71,0x88,
-0xAD,0xBE,0xBC,0x8F,0xAC,0x52,0x96,0x4B,0xAA,0x51,0x8D,0xE4,0x13,0x31,0x19,0xE8,
-0x4E,0x4D,0x9F,0xDB,0xAC,0xB3,0x6A,0xD5,0xBC,0x39,0x54,0x71,0xCA,0x7A,0x7A,0x7F,
-0x90,0xDD,0x7D,0x1D,0x80,0xD9,0x81,0xBB,0x59,0x26,0xC2,0x11,0xFE,0xE6,0x93,0xE2,
-0xF7,0x80,0xE4,0x65,0xFB,0x34,0x37,0x0E,0x29,0x80,0x70,0x4D,0xAF,0x38,0x86,0x2E,
-0x9E,0x7F,0x57,0xAF,0x9E,0x17,0xAE,0xEB,0x1C,0xCB,0x28,0x21,0x5F,0xB6,0x1C,0xD8,
-0xE7,0xA2,0x04,0x22,0xF9,0xD3,0xDA,0xD8,0xCB,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,
-0xB0,0x30,0x81,0xAD,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,
-0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,
-0x30,0x03,0x01,0x01,0xFF,0x30,0x2B,0x06,0x03,0x55,0x1D,0x10,0x04,0x24,0x30,0x22,
-0x80,0x0F,0x32,0x30,0x30,0x36,0x31,0x31,0x32,0x37,0x32,0x30,0x32,0x33,0x34,0x32,
-0x5A,0x81,0x0F,0x32,0x30,0x32,0x36,0x31,0x31,0x32,0x37,0x32,0x30,0x35,0x33,0x34,
-0x32,0x5A,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x68,
-0x90,0xE4,0x67,0xA4,0xA6,0x53,0x80,0xC7,0x86,0x66,0xA4,0xF1,0xF7,0x4B,0x43,0xFB,
-0x84,0xBD,0x6D,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x68,0x90,
-0xE4,0x67,0xA4,0xA6,0x53,0x80,0xC7,0x86,0x66,0xA4,0xF1,0xF7,0x4B,0x43,0xFB,0x84,
-0xBD,0x6D,0x30,0x1D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF6,0x7D,0x07,0x41,0x00,0x04,
-0x10,0x30,0x0E,0x1B,0x08,0x56,0x37,0x2E,0x31,0x3A,0x34,0x2E,0x30,0x03,0x02,0x04,
-0x90,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,
-0x03,0x82,0x01,0x01,0x00,0x93,0xD4,0x30,0xB0,0xD7,0x03,0x20,0x2A,0xD0,0xF9,0x63,
-0xE8,0x91,0x0C,0x05,0x20,0xA9,0x5F,0x19,0xCA,0x7B,0x72,0x4E,0xD4,0xB1,0xDB,0xD0,
-0x96,0xFB,0x54,0x5A,0x19,0x2C,0x0C,0x08,0xF7,0xB2,0xBC,0x85,0xA8,0x9D,0x7F,0x6D,
-0x3B,0x52,0xB3,0x2A,0xDB,0xE7,0xD4,0x84,0x8C,0x63,0xF6,0x0F,0xCB,0x26,0x01,0x91,
-0x50,0x6C,0xF4,0x5F,0x14,0xE2,0x93,0x74,0xC0,0x13,0x9E,0x30,0x3A,0x50,0xE3,0xB4,
-0x60,0xC5,0x1C,0xF0,0x22,0x44,0x8D,0x71,0x47,0xAC,0xC8,0x1A,0xC9,0xE9,0x9B,0x9A,
-0x00,0x60,0x13,0xFF,0x70,0x7E,0x5F,0x11,0x4D,0x49,0x1B,0xB3,0x15,0x52,0x7B,0xC9,
-0x54,0xDA,0xBF,0x9D,0x95,0xAF,0x6B,0x9A,0xD8,0x9E,0xE9,0xF1,0xE4,0x43,0x8D,0xE2,
-0x11,0x44,0x3A,0xBF,0xAF,0xBD,0x83,0x42,0x73,0x52,0x8B,0xAA,0xBB,0xA7,0x29,0xCF,
-0xF5,0x64,0x1C,0x0A,0x4D,0xD1,0xBC,0xAA,0xAC,0x9F,0x2A,0xD0,0xFF,0x7F,0x7F,0xDA,
-0x7D,0xEA,0xB1,0xED,0x30,0x25,0xC1,0x84,0xDA,0x34,0xD2,0x5B,0x78,0x83,0x56,0xEC,
-0x9C,0x36,0xC3,0x26,0xE2,0x11,0xF6,0x67,0x49,0x1D,0x92,0xAB,0x8C,0xFB,0xEB,0xFF,
-0x7A,0xEE,0x85,0x4A,0xA7,0x50,0x80,0xF0,0xA7,0x5C,0x4A,0x94,0x2E,0x5F,0x05,0x99,
-0x3C,0x52,0x41,0xE0,0xCD,0xB4,0x63,0xCF,0x01,0x43,0xBA,0x9C,0x83,0xDC,0x8F,0x60,
-0x3B,0xF3,0x5A,0xB4,0xB4,0x7B,0xAE,0xDA,0x0B,0x90,0x38,0x75,0xEF,0x81,0x1D,0x66,
-0xD2,0xF7,0x57,0x70,0x36,0xB3,0xBF,0xFC,0x28,0xAF,0x71,0x25,0x85,0x5B,0x13,0xFE,
-0x1E,0x7F,0x5A,0xB4,0x3C,
-};
-
-
-/* subject:/C=US/O=Equifax/OU=Equifax Secure Certificate Authority */
-/* issuer :/C=US/O=Equifax/OU=Equifax Secure Certificate Authority */
-
-
-const unsigned char Equifax_Secure_CA_certificate[804]={
-0x30,0x82,0x03,0x20,0x30,0x82,0x02,0x89,0xA0,0x03,0x02,0x01,0x02,0x02,0x04,0x35,
-0xDE,0xF4,0xCF,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x30,0x4E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,
-0x53,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x0A,0x13,0x07,0x45,0x71,0x75,0x69,
-0x66,0x61,0x78,0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,0x04,0x0B,0x13,0x24,0x45,0x71,
-0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x43,0x65,0x72,
-0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x30,0x1E,0x17,0x0D,0x39,0x38,0x30,0x38,0x32,0x32,0x31,0x36,0x34,0x31,
-0x35,0x31,0x5A,0x17,0x0D,0x31,0x38,0x30,0x38,0x32,0x32,0x31,0x36,0x34,0x31,0x35,
-0x31,0x5A,0x30,0x4E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,
-0x53,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x0A,0x13,0x07,0x45,0x71,0x75,0x69,
-0x66,0x61,0x78,0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,0x04,0x0B,0x13,0x24,0x45,0x71,
-0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x43,0x65,0x72,
-0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,0x02,0x81,0x81,0x00,0xC1,
-0x5D,0xB1,0x58,0x67,0x08,0x62,0xEE,0xA0,0x9A,0x2D,0x1F,0x08,0x6D,0x91,0x14,0x68,
-0x98,0x0A,0x1E,0xFE,0xDA,0x04,0x6F,0x13,0x84,0x62,0x21,0xC3,0xD1,0x7C,0xCE,0x9F,
-0x05,0xE0,0xB8,0x01,0xF0,0x4E,0x34,0xEC,0xE2,0x8A,0x95,0x04,0x64,0xAC,0xF1,0x6B,
-0x53,0x5F,0x05,0xB3,0xCB,0x67,0x80,0xBF,0x42,0x02,0x8E,0xFE,0xDD,0x01,0x09,0xEC,
-0xE1,0x00,0x14,0x4F,0xFC,0xFB,0xF0,0x0C,0xDD,0x43,0xBA,0x5B,0x2B,0xE1,0x1F,0x80,
-0x70,0x99,0x15,0x57,0x93,0x16,0xF1,0x0F,0x97,0x6A,0xB7,0xC2,0x68,0x23,0x1C,0xCC,
-0x4D,0x59,0x30,0xAC,0x51,0x1E,0x3B,0xAF,0x2B,0xD6,0xEE,0x63,0x45,0x7B,0xC5,0xD9,
-0x5F,0x50,0xD2,0xE3,0x50,0x0F,0x3A,0x88,0xE7,0xBF,0x14,0xFD,0xE0,0xC7,0xB9,0x02,
-0x03,0x01,0x00,0x01,0xA3,0x82,0x01,0x09,0x30,0x82,0x01,0x05,0x30,0x70,0x06,0x03,
-0x55,0x1D,0x1F,0x04,0x69,0x30,0x67,0x30,0x65,0xA0,0x63,0xA0,0x61,0xA4,0x5F,0x30,
-0x5D,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x10,
-0x30,0x0E,0x06,0x03,0x55,0x04,0x0A,0x13,0x07,0x45,0x71,0x75,0x69,0x66,0x61,0x78,
-0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,0x04,0x0B,0x13,0x24,0x45,0x71,0x75,0x69,0x66,
-0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x43,0x65,0x72,0x74,0x69,0x66,
-0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x31,
-0x0D,0x30,0x0B,0x06,0x03,0x55,0x04,0x03,0x13,0x04,0x43,0x52,0x4C,0x31,0x30,0x1A,
-0x06,0x03,0x55,0x1D,0x10,0x04,0x13,0x30,0x11,0x81,0x0F,0x32,0x30,0x31,0x38,0x30,
-0x38,0x32,0x32,0x31,0x36,0x34,0x31,0x35,0x31,0x5A,0x30,0x0B,0x06,0x03,0x55,0x1D,
-0x0F,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,
-0x30,0x16,0x80,0x14,0x48,0xE6,0x68,0xF9,0x2B,0xD2,0xB2,0x95,0xD7,0x47,0xD8,0x23,
-0x20,0x10,0x4F,0x33,0x98,0x90,0x9F,0xD4,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,
-0x16,0x04,0x14,0x48,0xE6,0x68,0xF9,0x2B,0xD2,0xB2,0x95,0xD7,0x47,0xD8,0x23,0x20,
-0x10,0x4F,0x33,0x98,0x90,0x9F,0xD4,0x30,0x0C,0x06,0x03,0x55,0x1D,0x13,0x04,0x05,
-0x30,0x03,0x01,0x01,0xFF,0x30,0x1A,0x06,0x09,0x2A,0x86,0x48,0x86,0xF6,0x7D,0x07,
-0x41,0x00,0x04,0x0D,0x30,0x0B,0x1B,0x05,0x56,0x33,0x2E,0x30,0x63,0x03,0x02,0x06,
-0xC0,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,
-0x03,0x81,0x81,0x00,0x58,0xCE,0x29,0xEA,0xFC,0xF7,0xDE,0xB5,0xCE,0x02,0xB9,0x17,
-0xB5,0x85,0xD1,0xB9,0xE3,0xE0,0x95,0xCC,0x25,0x31,0x0D,0x00,0xA6,0x92,0x6E,0x7F,
-0xB6,0x92,0x63,0x9E,0x50,0x95,0xD1,0x9A,0x6F,0xE4,0x11,0xDE,0x63,0x85,0x6E,0x98,
-0xEE,0xA8,0xFF,0x5A,0xC8,0xD3,0x55,0xB2,0x66,0x71,0x57,0xDE,0xC0,0x21,0xEB,0x3D,
-0x2A,0xA7,0x23,0x49,0x01,0x04,0x86,0x42,0x7B,0xFC,0xEE,0x7F,0xA2,0x16,0x52,0xB5,
-0x67,0x67,0xD3,0x40,0xDB,0x3B,0x26,0x58,0xB2,0x28,0x77,0x3D,0xAE,0x14,0x77,0x61,
-0xD6,0xFA,0x2A,0x66,0x27,0xA0,0x0D,0xFA,0xA7,0x73,0x5C,0xEA,0x70,0xF1,0x94,0x21,
-0x65,0x44,0x5F,0xFA,0xFC,0xEF,0x29,0x68,0xA9,0xA2,0x87,0x79,0xEF,0x79,0xEF,0x4F,
-0xAC,0x07,0x77,0x38,
-};
-
-
-/* subject:/C=US/O=Equifax Secure Inc./CN=Equifax Secure eBusiness CA-1 */
-/* issuer :/C=US/O=Equifax Secure Inc./CN=Equifax Secure eBusiness CA-1 */
-
-
-const unsigned char Equifax_Secure_eBusiness_CA_1_certificate[646]={
-0x30,0x82,0x02,0x82,0x30,0x82,0x01,0xEB,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x04,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,
-0x53,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x1C,
-0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x45,0x71,0x75,0x69,0x66,0x61,0x78,
-0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x49,0x6E,0x63,0x2E,0x31,0x26,0x30,0x24,
-0x06,0x03,0x55,0x04,0x03,0x13,0x1D,0x45,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53,
-0x65,0x63,0x75,0x72,0x65,0x20,0x65,0x42,0x75,0x73,0x69,0x6E,0x65,0x73,0x73,0x20,
-0x43,0x41,0x2D,0x31,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x36,0x32,0x31,0x30,0x34,
-0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x30,0x30,0x36,0x32,0x31,0x30,0x34,0x30,
-0x30,0x30,0x30,0x5A,0x30,0x53,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x55,0x53,0x31,0x1C,0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x45,0x71,
-0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x03,0x13,0x1D,0x45,0x71,0x75,0x69,
-0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x65,0x42,0x75,0x73,0x69,
-0x6E,0x65,0x73,0x73,0x20,0x43,0x41,0x2D,0x31,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,
-0x81,0x89,0x02,0x81,0x81,0x00,0xCE,0x2F,0x19,0xBC,0x17,0xB7,0x77,0xDE,0x93,0xA9,
-0x5F,0x5A,0x0D,0x17,0x4F,0x34,0x1A,0x0C,0x98,0xF4,0x22,0xD9,0x59,0xD4,0xC4,0x68,
-0x46,0xF0,0xB4,0x35,0xC5,0x85,0x03,0x20,0xC6,0xAF,0x45,0xA5,0x21,0x51,0x45,0x41,
-0xEB,0x16,0x58,0x36,0x32,0x6F,0xE2,0x50,0x62,0x64,0xF9,0xFD,0x51,0x9C,0xAA,0x24,
-0xD9,0xF4,0x9D,0x83,0x2A,0x87,0x0A,0x21,0xD3,0x12,0x38,0x34,0x6C,0x8D,0x00,0x6E,
-0x5A,0xA0,0xD9,0x42,0xEE,0x1A,0x21,0x95,0xF9,0x52,0x4C,0x55,0x5A,0xC5,0x0F,0x38,
-0x4F,0x46,0xFA,0x6D,0xF8,0x2E,0x35,0xD6,0x1D,0x7C,0xEB,0xE2,0xF0,0xB0,0x75,0x80,
-0xC8,0xA9,0x13,0xAC,0xBE,0x88,0xEF,0x3A,0x6E,0xAB,0x5F,0x2A,0x38,0x62,0x02,0xB0,
-0x12,0x7B,0xFE,0x8F,0xA6,0x03,0x02,0x03,0x01,0x00,0x01,0xA3,0x66,0x30,0x64,0x30,
-0x11,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x42,0x01,0x01,0x04,0x04,0x03,0x02,
-0x00,0x07,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,
-0x01,0x01,0xFF,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,
-0x4A,0x78,0x32,0x52,0x11,0xDB,0x59,0x16,0x36,0x5E,0xDF,0xC1,0x14,0x36,0x40,0x6A,
-0x47,0x7C,0x4C,0xA1,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x4A,
-0x78,0x32,0x52,0x11,0xDB,0x59,0x16,0x36,0x5E,0xDF,0xC1,0x14,0x36,0x40,0x6A,0x47,
-0x7C,0x4C,0xA1,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,
-0x05,0x00,0x03,0x81,0x81,0x00,0x75,0x5B,0xA8,0x9B,0x03,0x11,0xE6,0xE9,0x56,0x4C,
-0xCD,0xF9,0xA9,0x4C,0xC0,0x0D,0x9A,0xF3,0xCC,0x65,0x69,0xE6,0x25,0x76,0xCC,0x59,
-0xB7,0xD6,0x54,0xC3,0x1D,0xCD,0x99,0xAC,0x19,0xDD,0xB4,0x85,0xD5,0xE0,0x3D,0xFC,
-0x62,0x20,0xA7,0x84,0x4B,0x58,0x65,0xF1,0xE2,0xF9,0x95,0x21,0x3F,0xF5,0xD4,0x7E,
-0x58,0x1E,0x47,0x87,0x54,0x3E,0x58,0xA1,0xB5,0xB5,0xF8,0x2A,0xEF,0x71,0xE7,0xBC,
-0xC3,0xF6,0xB1,0x49,0x46,0xE2,0xD7,0xA0,0x6B,0xE5,0x56,0x7A,0x9A,0x27,0x98,0x7C,
-0x46,0x62,0x14,0xE7,0xC9,0xFC,0x6E,0x03,0x12,0x79,0x80,0x38,0x1D,0x48,0x82,0x8D,
-0xFC,0x17,0xFE,0x2A,0x96,0x2B,0xB5,0x62,0xA6,0xA6,0x3D,0xBD,0x7F,0x92,0x59,0xCD,
-0x5A,0x2A,0x82,0xB2,0x37,0x79,
-};
-
-
-/* subject:/C=US/O=Equifax Secure/OU=Equifax Secure eBusiness CA-2 */
-/* issuer :/C=US/O=Equifax Secure/OU=Equifax Secure eBusiness CA-2 */
-
-
-const unsigned char Equifax_Secure_eBusiness_CA_2_certificate[804]={
-0x30,0x82,0x03,0x20,0x30,0x82,0x02,0x89,0xA0,0x03,0x02,0x01,0x02,0x02,0x04,0x37,
-0x70,0xCF,0xB5,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x30,0x4E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,
-0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x45,0x71,0x75,0x69,
-0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x31,0x26,0x30,0x24,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x1D,0x45,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,
-0x75,0x72,0x65,0x20,0x65,0x42,0x75,0x73,0x69,0x6E,0x65,0x73,0x73,0x20,0x43,0x41,
-0x2D,0x32,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x36,0x32,0x33,0x31,0x32,0x31,0x34,
-0x34,0x35,0x5A,0x17,0x0D,0x31,0x39,0x30,0x36,0x32,0x33,0x31,0x32,0x31,0x34,0x34,
-0x35,0x5A,0x30,0x4E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,
-0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x45,0x71,0x75,0x69,
-0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x31,0x26,0x30,0x24,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x1D,0x45,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,
-0x75,0x72,0x65,0x20,0x65,0x42,0x75,0x73,0x69,0x6E,0x65,0x73,0x73,0x20,0x43,0x41,
-0x2D,0x32,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,0x02,0x81,0x81,0x00,0xE4,
-0x39,0x39,0x93,0x1E,0x52,0x06,0x1B,0x28,0x36,0xF8,0xB2,0xA3,0x29,0xC5,0xED,0x8E,
-0xB2,0x11,0xBD,0xFE,0xEB,0xE7,0xB4,0x74,0xC2,0x8F,0xFF,0x05,0xE7,0xD9,0x9D,0x06,
-0xBF,0x12,0xC8,0x3F,0x0E,0xF2,0xD6,0xD1,0x24,0xB2,0x11,0xDE,0xD1,0x73,0x09,0x8A,
-0xD4,0xB1,0x2C,0x98,0x09,0x0D,0x1E,0x50,0x46,0xB2,0x83,0xA6,0x45,0x8D,0x62,0x68,
-0xBB,0x85,0x1B,0x20,0x70,0x32,0xAA,0x40,0xCD,0xA6,0x96,0x5F,0xC4,0x71,0x37,0x3F,
-0x04,0xF3,0xB7,0x41,0x24,0x39,0x07,0x1A,0x1E,0x2E,0x61,0x58,0xA0,0x12,0x0B,0xE5,
-0xA5,0xDF,0xC5,0xAB,0xEA,0x37,0x71,0xCC,0x1C,0xC8,0x37,0x3A,0xB9,0x97,0x52,0xA7,
-0xAC,0xC5,0x6A,0x24,0x94,0x4E,0x9C,0x7B,0xCF,0xC0,0x6A,0xD6,0xDF,0x21,0xBD,0x02,
-0x03,0x01,0x00,0x01,0xA3,0x82,0x01,0x09,0x30,0x82,0x01,0x05,0x30,0x70,0x06,0x03,
-0x55,0x1D,0x1F,0x04,0x69,0x30,0x67,0x30,0x65,0xA0,0x63,0xA0,0x61,0xA4,0x5F,0x30,
-0x5D,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,
-0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x45,0x71,0x75,0x69,0x66,0x61,0x78,
-0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,
-0x13,0x1D,0x45,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,0x65,
-0x20,0x65,0x42,0x75,0x73,0x69,0x6E,0x65,0x73,0x73,0x20,0x43,0x41,0x2D,0x32,0x31,
-0x0D,0x30,0x0B,0x06,0x03,0x55,0x04,0x03,0x13,0x04,0x43,0x52,0x4C,0x31,0x30,0x1A,
-0x06,0x03,0x55,0x1D,0x10,0x04,0x13,0x30,0x11,0x81,0x0F,0x32,0x30,0x31,0x39,0x30,
-0x36,0x32,0x33,0x31,0x32,0x31,0x34,0x34,0x35,0x5A,0x30,0x0B,0x06,0x03,0x55,0x1D,
-0x0F,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,
-0x30,0x16,0x80,0x14,0x50,0x9E,0x0B,0xEA,0xAF,0x5E,0xB9,0x20,0x48,0xA6,0x50,0x6A,
-0xCB,0xFD,0xD8,0x20,0x7A,0xA7,0x82,0x76,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,
-0x16,0x04,0x14,0x50,0x9E,0x0B,0xEA,0xAF,0x5E,0xB9,0x20,0x48,0xA6,0x50,0x6A,0xCB,
-0xFD,0xD8,0x20,0x7A,0xA7,0x82,0x76,0x30,0x0C,0x06,0x03,0x55,0x1D,0x13,0x04,0x05,
-0x30,0x03,0x01,0x01,0xFF,0x30,0x1A,0x06,0x09,0x2A,0x86,0x48,0x86,0xF6,0x7D,0x07,
-0x41,0x00,0x04,0x0D,0x30,0x0B,0x1B,0x05,0x56,0x33,0x2E,0x30,0x63,0x03,0x02,0x06,
-0xC0,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,
-0x03,0x81,0x81,0x00,0x0C,0x86,0x82,0xAD,0xE8,0x4E,0x1A,0xF5,0x8E,0x89,0x27,0xE2,
-0x35,0x58,0x3D,0x29,0xB4,0x07,0x8F,0x36,0x50,0x95,0xBF,0x6E,0xC1,0x9E,0xEB,0xC4,
-0x90,0xB2,0x85,0xA8,0xBB,0xB7,0x42,0xE0,0x0F,0x07,0x39,0xDF,0xFB,0x9E,0x90,0xB2,
-0xD1,0xC1,0x3E,0x53,0x9F,0x03,0x44,0xB0,0x7E,0x4B,0xF4,0x6F,0xE4,0x7C,0x1F,0xE7,
-0xE2,0xB1,0xE4,0xB8,0x9A,0xEF,0xC3,0xBD,0xCE,0xDE,0x0B,0x32,0x34,0xD9,0xDE,0x28,
-0xED,0x33,0x6B,0xC4,0xD4,0xD7,0x3D,0x12,0x58,0xAB,0x7D,0x09,0x2D,0xCB,0x70,0xF5,
-0x13,0x8A,0x94,0xA1,0x27,0xA4,0xD6,0x70,0xC5,0x6D,0x94,0xB5,0xC9,0x7D,0x9D,0xA0,
-0xD2,0xC6,0x08,0x49,0xD9,0x66,0x9B,0xA6,0xD3,0xF4,0x0B,0xDC,0xC5,0x26,0x57,0xE1,
-0x91,0x30,0xEA,0xCD,
-};
-
-
-/* subject:/C=US/O=Equifax Secure Inc./CN=Equifax Secure Global eBusiness CA-1 */
-/* issuer :/C=US/O=Equifax Secure Inc./CN=Equifax Secure Global eBusiness CA-1 */
-
-
-const unsigned char Equifax_Secure_Global_eBusiness_CA_certificate[660]={
-0x30,0x82,0x02,0x90,0x30,0x82,0x01,0xF9,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,
-0x5A,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x1C,
-0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x45,0x71,0x75,0x69,0x66,0x61,0x78,
-0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x49,0x6E,0x63,0x2E,0x31,0x2D,0x30,0x2B,
-0x06,0x03,0x55,0x04,0x03,0x13,0x24,0x45,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53,
-0x65,0x63,0x75,0x72,0x65,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x65,0x42,0x75,
-0x73,0x69,0x6E,0x65,0x73,0x73,0x20,0x43,0x41,0x2D,0x31,0x30,0x1E,0x17,0x0D,0x39,
-0x39,0x30,0x36,0x32,0x31,0x30,0x34,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x30,
-0x30,0x36,0x32,0x31,0x30,0x34,0x30,0x30,0x30,0x30,0x5A,0x30,0x5A,0x31,0x0B,0x30,
-0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x1C,0x30,0x1A,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x13,0x45,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,
-0x75,0x72,0x65,0x20,0x49,0x6E,0x63,0x2E,0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,0x04,
-0x03,0x13,0x24,0x45,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72,
-0x65,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x65,0x42,0x75,0x73,0x69,0x6E,0x65,
-0x73,0x73,0x20,0x43,0x41,0x2D,0x31,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,
-0x02,0x81,0x81,0x00,0xBA,0xE7,0x17,0x90,0x02,0x65,0xB1,0x34,0x55,0x3C,0x49,0xC2,
-0x51,0xD5,0xDF,0xA7,0xD1,0x37,0x8F,0xD1,0xE7,0x81,0x73,0x41,0x52,0x60,0x9B,0x9D,
-0xA1,0x17,0x26,0x78,0xAD,0xC7,0xB1,0xE8,0x26,0x94,0x32,0xB5,0xDE,0x33,0x8D,0x3A,
-0x2F,0xDB,0xF2,0x9A,0x7A,0x5A,0x73,0x98,0xA3,0x5C,0xE9,0xFB,0x8A,0x73,0x1B,0x5C,
-0xE7,0xC3,0xBF,0x80,0x6C,0xCD,0xA9,0xF4,0xD6,0x2B,0xC0,0xF7,0xF9,0x99,0xAA,0x63,
-0xA2,0xB1,0x47,0x02,0x0F,0xD4,0xE4,0x51,0x3A,0x12,0x3C,0x6C,0x8A,0x5A,0x54,0x84,
-0x70,0xDB,0xC1,0xC5,0x90,0xCF,0x72,0x45,0xCB,0xA8,0x59,0xC0,0xCD,0x33,0x9D,0x3F,
-0xA3,0x96,0xEB,0x85,0x33,0x21,0x1C,0x3E,0x1E,0x3E,0x60,0x6E,0x76,0x9C,0x67,0x85,
-0xC5,0xC8,0xC3,0x61,0x02,0x03,0x01,0x00,0x01,0xA3,0x66,0x30,0x64,0x30,0x11,0x06,
-0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x42,0x01,0x01,0x04,0x04,0x03,0x02,0x00,0x07,
-0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,
-0xFF,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0xBE,0xA8,
-0xA0,0x74,0x72,0x50,0x6B,0x44,0xB7,0xC9,0x23,0xD8,0xFB,0xA8,0xFF,0xB3,0x57,0x6B,
-0x68,0x6C,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xBE,0xA8,0xA0,
-0x74,0x72,0x50,0x6B,0x44,0xB7,0xC9,0x23,0xD8,0xFB,0xA8,0xFF,0xB3,0x57,0x6B,0x68,
-0x6C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,
-0x03,0x81,0x81,0x00,0x30,0xE2,0x01,0x51,0xAA,0xC7,0xEA,0x5F,0xDA,0xB9,0xD0,0x65,
-0x0F,0x30,0xD6,0x3E,0xDA,0x0D,0x14,0x49,0x6E,0x91,0x93,0x27,0x14,0x31,0xEF,0xC4,
-0xF7,0x2D,0x45,0xF8,0xEC,0xC7,0xBF,0xA2,0x41,0x0D,0x23,0xB4,0x92,0xF9,0x19,0x00,
-0x67,0xBD,0x01,0xAF,0xCD,0xE0,0x71,0xFC,0x5A,0xCF,0x64,0xC4,0xE0,0x96,0x98,0xD0,
-0xA3,0x40,0xE2,0x01,0x8A,0xEF,0x27,0x07,0xF1,0x65,0x01,0x8A,0x44,0x2D,0x06,0x65,
-0x75,0x52,0xC0,0x86,0x10,0x20,0x21,0x5F,0x6C,0x6B,0x0F,0x6C,0xAE,0x09,0x1C,0xAF,
-0xF2,0xA2,0x18,0x34,0xC4,0x75,0xA4,0x73,0x1C,0xF1,0x8D,0xDC,0xEF,0xAD,0xF9,0xB3,
-0x76,0xB4,0x92,0xBF,0xDC,0x95,0x10,0x1E,0xBE,0xCB,0xC8,0x3B,0x5A,0x84,0x60,0x19,
-0x56,0x94,0xA9,0x55,
-};
-
-
-/* subject:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA */
-/* issuer :/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA */
-
-
-const unsigned char GeoTrust_Global_CA_certificate[856]={
-0x30,0x82,0x03,0x54,0x30,0x82,0x02,0x3C,0xA0,0x03,0x02,0x01,0x02,0x02,0x03,0x02,
-0x34,0x56,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,
-0x00,0x30,0x42,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,
-0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,
-0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1B,0x30,0x19,0x06,0x03,0x55,0x04,
-0x03,0x13,0x12,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x47,0x6C,0x6F,0x62,
-0x61,0x6C,0x20,0x43,0x41,0x30,0x1E,0x17,0x0D,0x30,0x32,0x30,0x35,0x32,0x31,0x30,
-0x34,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x32,0x30,0x35,0x32,0x31,0x30,0x34,
-0x30,0x30,0x30,0x30,0x5A,0x30,0x42,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,
-0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,
-0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1B,0x30,0x19,
-0x06,0x03,0x55,0x04,0x03,0x13,0x12,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,
-0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x43,0x41,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,
-0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xDA,0xCC,0x18,0x63,0x30,0xFD,
-0xF4,0x17,0x23,0x1A,0x56,0x7E,0x5B,0xDF,0x3C,0x6C,0x38,0xE4,0x71,0xB7,0x78,0x91,
-0xD4,0xBC,0xA1,0xD8,0x4C,0xF8,0xA8,0x43,0xB6,0x03,0xE9,0x4D,0x21,0x07,0x08,0x88,
-0xDA,0x58,0x2F,0x66,0x39,0x29,0xBD,0x05,0x78,0x8B,0x9D,0x38,0xE8,0x05,0xB7,0x6A,
-0x7E,0x71,0xA4,0xE6,0xC4,0x60,0xA6,0xB0,0xEF,0x80,0xE4,0x89,0x28,0x0F,0x9E,0x25,
-0xD6,0xED,0x83,0xF3,0xAD,0xA6,0x91,0xC7,0x98,0xC9,0x42,0x18,0x35,0x14,0x9D,0xAD,
-0x98,0x46,0x92,0x2E,0x4F,0xCA,0xF1,0x87,0x43,0xC1,0x16,0x95,0x57,0x2D,0x50,0xEF,
-0x89,0x2D,0x80,0x7A,0x57,0xAD,0xF2,0xEE,0x5F,0x6B,0xD2,0x00,0x8D,0xB9,0x14,0xF8,
-0x14,0x15,0x35,0xD9,0xC0,0x46,0xA3,0x7B,0x72,0xC8,0x91,0xBF,0xC9,0x55,0x2B,0xCD,
-0xD0,0x97,0x3E,0x9C,0x26,0x64,0xCC,0xDF,0xCE,0x83,0x19,0x71,0xCA,0x4E,0xE6,0xD4,
-0xD5,0x7B,0xA9,0x19,0xCD,0x55,0xDE,0xC8,0xEC,0xD2,0x5E,0x38,0x53,0xE5,0x5C,0x4F,
-0x8C,0x2D,0xFE,0x50,0x23,0x36,0xFC,0x66,0xE6,0xCB,0x8E,0xA4,0x39,0x19,0x00,0xB7,
-0x95,0x02,0x39,0x91,0x0B,0x0E,0xFE,0x38,0x2E,0xD1,0x1D,0x05,0x9A,0xF6,0x4D,0x3E,
-0x6F,0x0F,0x07,0x1D,0xAF,0x2C,0x1E,0x8F,0x60,0x39,0xE2,0xFA,0x36,0x53,0x13,0x39,
-0xD4,0x5E,0x26,0x2B,0xDB,0x3D,0xA8,0x14,0xBD,0x32,0xEB,0x18,0x03,0x28,0x52,0x04,
-0x71,0xE5,0xAB,0x33,0x3D,0xE1,0x38,0xBB,0x07,0x36,0x84,0x62,0x9C,0x79,0xEA,0x16,
-0x30,0xF4,0x5F,0xC0,0x2B,0xE8,0x71,0x6B,0xE4,0xF9,0x02,0x03,0x01,0x00,0x01,0xA3,
-0x53,0x30,0x51,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xC0,
-0x7A,0x98,0x68,0x8D,0x89,0xFB,0xAB,0x05,0x64,0x0C,0x11,0x7D,0xAA,0x7D,0x65,0xB8,
-0xCA,0xCC,0x4E,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,
-0xC0,0x7A,0x98,0x68,0x8D,0x89,0xFB,0xAB,0x05,0x64,0x0C,0x11,0x7D,0xAA,0x7D,0x65,
-0xB8,0xCA,0xCC,0x4E,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x35,0xE3,0x29,0x6A,0xE5,0x2F,0x5D,0x54,
-0x8E,0x29,0x50,0x94,0x9F,0x99,0x1A,0x14,0xE4,0x8F,0x78,0x2A,0x62,0x94,0xA2,0x27,
-0x67,0x9E,0xD0,0xCF,0x1A,0x5E,0x47,0xE9,0xC1,0xB2,0xA4,0xCF,0xDD,0x41,0x1A,0x05,
-0x4E,0x9B,0x4B,0xEE,0x4A,0x6F,0x55,0x52,0xB3,0x24,0xA1,0x37,0x0A,0xEB,0x64,0x76,
-0x2A,0x2E,0x2C,0xF3,0xFD,0x3B,0x75,0x90,0xBF,0xFA,0x71,0xD8,0xC7,0x3D,0x37,0xD2,
-0xB5,0x05,0x95,0x62,0xB9,0xA6,0xDE,0x89,0x3D,0x36,0x7B,0x38,0x77,0x48,0x97,0xAC,
-0xA6,0x20,0x8F,0x2E,0xA6,0xC9,0x0C,0xC2,0xB2,0x99,0x45,0x00,0xC7,0xCE,0x11,0x51,
-0x22,0x22,0xE0,0xA5,0xEA,0xB6,0x15,0x48,0x09,0x64,0xEA,0x5E,0x4F,0x74,0xF7,0x05,
-0x3E,0xC7,0x8A,0x52,0x0C,0xDB,0x15,0xB4,0xBD,0x6D,0x9B,0xE5,0xC6,0xB1,0x54,0x68,
-0xA9,0xE3,0x69,0x90,0xB6,0x9A,0xA5,0x0F,0xB8,0xB9,0x3F,0x20,0x7D,0xAE,0x4A,0xB5,
-0xB8,0x9C,0xE4,0x1D,0xB6,0xAB,0xE6,0x94,0xA5,0xC1,0xC7,0x83,0xAD,0xDB,0xF5,0x27,
-0x87,0x0E,0x04,0x6C,0xD5,0xFF,0xDD,0xA0,0x5D,0xED,0x87,0x52,0xB7,0x2B,0x15,0x02,
-0xAE,0x39,0xA6,0x6A,0x74,0xE9,0xDA,0xC4,0xE7,0xBC,0x4D,0x34,0x1E,0xA9,0x5C,0x4D,
-0x33,0x5F,0x92,0x09,0x2F,0x88,0x66,0x5D,0x77,0x97,0xC7,0x1D,0x76,0x13,0xA9,0xD5,
-0xE5,0xF1,0x16,0x09,0x11,0x35,0xD5,0xAC,0xDB,0x24,0x71,0x70,0x2C,0x98,0x56,0x0B,
-0xD9,0x17,0xB4,0xD1,0xE3,0x51,0x2B,0x5E,0x75,0xE8,0xD5,0xD0,0xDC,0x4F,0x34,0xED,
-0xC2,0x05,0x66,0x80,0xA1,0xCB,0xE6,0x33,
-};
-
-
-/* subject:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA 2 */
-/* issuer :/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA 2 */
-
-
-const unsigned char GeoTrust_Global_CA_2_certificate[874]={
-0x30,0x82,0x03,0x66,0x30,0x82,0x02,0x4E,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x44,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,
-0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,
-0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x03,0x13,
-0x14,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,
-0x20,0x43,0x41,0x20,0x32,0x30,0x1E,0x17,0x0D,0x30,0x34,0x30,0x33,0x30,0x34,0x30,
-0x35,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x31,0x39,0x30,0x33,0x30,0x34,0x30,0x35,
-0x30,0x30,0x30,0x30,0x5A,0x30,0x44,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,
-0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,
-0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1D,0x30,0x1B,
-0x06,0x03,0x55,0x04,0x03,0x13,0x14,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,
-0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x43,0x41,0x20,0x32,0x30,0x82,0x01,0x22,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,
-0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xEF,0x3C,0x4D,0x40,
-0x3D,0x10,0xDF,0x3B,0x53,0x00,0xE1,0x67,0xFE,0x94,0x60,0x15,0x3E,0x85,0x88,0xF1,
-0x89,0x0D,0x90,0xC8,0x28,0x23,0x99,0x05,0xE8,0x2B,0x20,0x9D,0xC6,0xF3,0x60,0x46,
-0xD8,0xC1,0xB2,0xD5,0x8C,0x31,0xD9,0xDC,0x20,0x79,0x24,0x81,0xBF,0x35,0x32,0xFC,
-0x63,0x69,0xDB,0xB1,0x2A,0x6B,0xEE,0x21,0x58,0xF2,0x08,0xE9,0x78,0xCB,0x6F,0xCB,
-0xFC,0x16,0x52,0xC8,0x91,0xC4,0xFF,0x3D,0x73,0xDE,0xB1,0x3E,0xA7,0xC2,0x7D,0x66,
-0xC1,0xF5,0x7E,0x52,0x24,0x1A,0xE2,0xD5,0x67,0x91,0xD0,0x82,0x10,0xD7,0x78,0x4B,
-0x4F,0x2B,0x42,0x39,0xBD,0x64,0x2D,0x40,0xA0,0xB0,0x10,0xD3,0x38,0x48,0x46,0x88,
-0xA1,0x0C,0xBB,0x3A,0x33,0x2A,0x62,0x98,0xFB,0x00,0x9D,0x13,0x59,0x7F,0x6F,0x3B,
-0x72,0xAA,0xEE,0xA6,0x0F,0x86,0xF9,0x05,0x61,0xEA,0x67,0x7F,0x0C,0x37,0x96,0x8B,
-0xE6,0x69,0x16,0x47,0x11,0xC2,0x27,0x59,0x03,0xB3,0xA6,0x60,0xC2,0x21,0x40,0x56,
-0xFA,0xA0,0xC7,0x7D,0x3A,0x13,0xE3,0xEC,0x57,0xC7,0xB3,0xD6,0xAE,0x9D,0x89,0x80,
-0xF7,0x01,0xE7,0x2C,0xF6,0x96,0x2B,0x13,0x0D,0x79,0x2C,0xD9,0xC0,0xE4,0x86,0x7B,
-0x4B,0x8C,0x0C,0x72,0x82,0x8A,0xFB,0x17,0xCD,0x00,0x6C,0x3A,0x13,0x3C,0xB0,0x84,
-0x87,0x4B,0x16,0x7A,0x29,0xB2,0x4F,0xDB,0x1D,0xD4,0x0B,0xF3,0x66,0x37,0xBD,0xD8,
-0xF6,0x57,0xBB,0x5E,0x24,0x7A,0xB8,0x3C,0x8B,0xB9,0xFA,0x92,0x1A,0x1A,0x84,0x9E,
-0xD8,0x74,0x8F,0xAA,0x1B,0x7F,0x5E,0xF4,0xFE,0x45,0x22,0x21,0x02,0x03,0x01,0x00,
-0x01,0xA3,0x63,0x30,0x61,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,
-0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,
-0x14,0x71,0x38,0x36,0xF2,0x02,0x31,0x53,0x47,0x2B,0x6E,0xBA,0x65,0x46,0xA9,0x10,
-0x15,0x58,0x20,0x05,0x09,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,
-0x80,0x14,0x71,0x38,0x36,0xF2,0x02,0x31,0x53,0x47,0x2B,0x6E,0xBA,0x65,0x46,0xA9,
-0x10,0x15,0x58,0x20,0x05,0x09,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,
-0x04,0x04,0x03,0x02,0x01,0x86,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x03,0xF7,0xB5,0x2B,0xAB,0x5D,
-0x10,0xFC,0x7B,0xB2,0xB2,0x5E,0xAC,0x9B,0x0E,0x7E,0x53,0x78,0x59,0x3E,0x42,0x04,
-0xFE,0x75,0xA3,0xAD,0xAC,0x81,0x4E,0xD7,0x02,0x8B,0x5E,0xC4,0x2D,0xC8,0x52,0x76,
-0xC7,0x2C,0x1F,0xFC,0x81,0x32,0x98,0xD1,0x4B,0xC6,0x92,0x93,0x33,0x35,0x31,0x2F,
-0xFC,0xD8,0x1D,0x44,0xDD,0xE0,0x81,0x7F,0x9D,0xE9,0x8B,0xE1,0x64,0x91,0x62,0x0B,
-0x39,0x08,0x8C,0xAC,0x74,0x9D,0x59,0xD9,0x7A,0x59,0x52,0x97,0x11,0xB9,0x16,0x7B,
-0x6F,0x45,0xD3,0x96,0xD9,0x31,0x7D,0x02,0x36,0x0F,0x9C,0x3B,0x6E,0xCF,0x2C,0x0D,
-0x03,0x46,0x45,0xEB,0xA0,0xF4,0x7F,0x48,0x44,0xC6,0x08,0x40,0xCC,0xDE,0x1B,0x70,
-0xB5,0x29,0xAD,0xBA,0x8B,0x3B,0x34,0x65,0x75,0x1B,0x71,0x21,0x1D,0x2C,0x14,0x0A,
-0xB0,0x96,0x95,0xB8,0xD6,0xEA,0xF2,0x65,0xFB,0x29,0xBA,0x4F,0xEA,0x91,0x93,0x74,
-0x69,0xB6,0xF2,0xFF,0xE1,0x1A,0xD0,0x0C,0xD1,0x76,0x85,0xCB,0x8A,0x25,0xBD,0x97,
-0x5E,0x2C,0x6F,0x15,0x99,0x26,0xE7,0xB6,0x29,0xFF,0x22,0xEC,0xC9,0x02,0xC7,0x56,
-0x00,0xCD,0x49,0xB9,0xB3,0x6C,0x7B,0x53,0x04,0x1A,0xE2,0xA8,0xC9,0xAA,0x12,0x05,
-0x23,0xC2,0xCE,0xE7,0xBB,0x04,0x02,0xCC,0xC0,0x47,0xA2,0xE4,0xC4,0x29,0x2F,0x5B,
-0x45,0x57,0x89,0x51,0xEE,0x3C,0xEB,0x52,0x08,0xFF,0x07,0x35,0x1E,0x9F,0x35,0x6A,
-0x47,0x4A,0x56,0x98,0xD1,0x5A,0x85,0x1F,0x8C,0xF5,0x22,0xBF,0xAB,0xCE,0x83,0xF3,
-0xE2,0x22,0x29,0xAE,0x7D,0x83,0x40,0xA8,0xBA,0x6C,
-};
-
-
-/* subject:/C=US/O=GeoTrust Inc./CN=GeoTrust Primary Certification Authority */
-/* issuer :/C=US/O=GeoTrust Inc./CN=GeoTrust Primary Certification Authority */
-
-
-const unsigned char GeoTrust_Primary_Certification_Authority_certificate[896]={
-0x30,0x82,0x03,0x7C,0x30,0x82,0x02,0x64,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x18,
-0xAC,0xB5,0x6A,0xFD,0x69,0xB6,0x15,0x3A,0x63,0x6C,0xAF,0xDA,0xFA,0xC4,0xA1,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x58,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,
-0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,
-0x20,0x49,0x6E,0x63,0x2E,0x31,0x31,0x30,0x2F,0x06,0x03,0x55,0x04,0x03,0x13,0x28,
-0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,
-0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,
-0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x31,
-0x32,0x37,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x36,0x30,0x37,0x31,
-0x36,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x58,0x31,0x0B,0x30,0x09,0x06,0x03,
-0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,
-0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,
-0x31,0x30,0x2F,0x06,0x03,0x55,0x04,0x03,0x13,0x28,0x47,0x65,0x6F,0x54,0x72,0x75,
-0x73,0x74,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,
-0x01,0x01,0x00,0xBE,0xB8,0x15,0x7B,0xFF,0xD4,0x7C,0x7D,0x67,0xAD,0x83,0x64,0x7B,
-0xC8,0x42,0x53,0x2D,0xDF,0xF6,0x84,0x08,0x20,0x61,0xD6,0x01,0x59,0x6A,0x9C,0x44,
-0x11,0xAF,0xEF,0x76,0xFD,0x95,0x7E,0xCE,0x61,0x30,0xBB,0x7A,0x83,0x5F,0x02,0xBD,
-0x01,0x66,0xCA,0xEE,0x15,0x8D,0x6F,0xA1,0x30,0x9C,0xBD,0xA1,0x85,0x9E,0x94,0x3A,
-0xF3,0x56,0x88,0x00,0x31,0xCF,0xD8,0xEE,0x6A,0x96,0x02,0xD9,0xED,0x03,0x8C,0xFB,
-0x75,0x6D,0xE7,0xEA,0xB8,0x55,0x16,0x05,0x16,0x9A,0xF4,0xE0,0x5E,0xB1,0x88,0xC0,
-0x64,0x85,0x5C,0x15,0x4D,0x88,0xC7,0xB7,0xBA,0xE0,0x75,0xE9,0xAD,0x05,0x3D,0x9D,
-0xC7,0x89,0x48,0xE0,0xBB,0x28,0xC8,0x03,0xE1,0x30,0x93,0x64,0x5E,0x52,0xC0,0x59,
-0x70,0x22,0x35,0x57,0x88,0x8A,0xF1,0x95,0x0A,0x83,0xD7,0xBC,0x31,0x73,0x01,0x34,
-0xED,0xEF,0x46,0x71,0xE0,0x6B,0x02,0xA8,0x35,0x72,0x6B,0x97,0x9B,0x66,0xE0,0xCB,
-0x1C,0x79,0x5F,0xD8,0x1A,0x04,0x68,0x1E,0x47,0x02,0xE6,0x9D,0x60,0xE2,0x36,0x97,
-0x01,0xDF,0xCE,0x35,0x92,0xDF,0xBE,0x67,0xC7,0x6D,0x77,0x59,0x3B,0x8F,0x9D,0xD6,
-0x90,0x15,0x94,0xBC,0x42,0x34,0x10,0xC1,0x39,0xF9,0xB1,0x27,0x3E,0x7E,0xD6,0x8A,
-0x75,0xC5,0xB2,0xAF,0x96,0xD3,0xA2,0xDE,0x9B,0xE4,0x98,0xBE,0x7D,0xE1,0xE9,0x81,
-0xAD,0xB6,0x6F,0xFC,0xD7,0x0E,0xDA,0xE0,0x34,0xB0,0x0D,0x1A,0x77,0xE7,0xE3,0x08,
-0x98,0xEF,0x58,0xFA,0x9C,0x84,0xB7,0x36,0xAF,0xC2,0xDF,0xAC,0xD2,0xF4,0x10,0x06,
-0x70,0x71,0x35,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,0x0F,0x06,0x03,
-0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,
-0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,
-0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x2C,0xD5,0x50,0x41,0x97,0x15,0x8B,0xF0,
-0x8F,0x36,0x61,0x5B,0x4A,0xFB,0x6B,0xD9,0x99,0xC9,0x33,0x92,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,
-0x5A,0x70,0x7F,0x2C,0xDD,0xB7,0x34,0x4F,0xF5,0x86,0x51,0xA9,0x26,0xBE,0x4B,0xB8,
-0xAA,0xF1,0x71,0x0D,0xDC,0x61,0xC7,0xA0,0xEA,0x34,0x1E,0x7A,0x77,0x0F,0x04,0x35,
-0xE8,0x27,0x8F,0x6C,0x90,0xBF,0x91,0x16,0x24,0x46,0x3E,0x4A,0x4E,0xCE,0x2B,0x16,
-0xD5,0x0B,0x52,0x1D,0xFC,0x1F,0x67,0xA2,0x02,0x45,0x31,0x4F,0xCE,0xF3,0xFA,0x03,
-0xA7,0x79,0x9D,0x53,0x6A,0xD9,0xDA,0x63,0x3A,0xF8,0x80,0xD7,0xD3,0x99,0xE1,0xA5,
-0xE1,0xBE,0xD4,0x55,0x71,0x98,0x35,0x3A,0xBE,0x93,0xEA,0xAE,0xAD,0x42,0xB2,0x90,
-0x6F,0xE0,0xFC,0x21,0x4D,0x35,0x63,0x33,0x89,0x49,0xD6,0x9B,0x4E,0xCA,0xC7,0xE7,
-0x4E,0x09,0x00,0xF7,0xDA,0xC7,0xEF,0x99,0x62,0x99,0x77,0xB6,0x95,0x22,0x5E,0x8A,
-0xA0,0xAB,0xF4,0xB8,0x78,0x98,0xCA,0x38,0x19,0x99,0xC9,0x72,0x9E,0x78,0xCD,0x4B,
-0xAC,0xAF,0x19,0xA0,0x73,0x12,0x2D,0xFC,0xC2,0x41,0xBA,0x81,0x91,0xDA,0x16,0x5A,
-0x31,0xB7,0xF9,0xB4,0x71,0x80,0x12,0x48,0x99,0x72,0x73,0x5A,0x59,0x53,0xC1,0x63,
-0x52,0x33,0xED,0xA7,0xC9,0xD2,0x39,0x02,0x70,0xFA,0xE0,0xB1,0x42,0x66,0x29,0xAA,
-0x9B,0x51,0xED,0x30,0x54,0x22,0x14,0x5F,0xD9,0xAB,0x1D,0xC1,0xE4,0x94,0xF0,0xF8,
-0xF5,0x2B,0xF7,0xEA,0xCA,0x78,0x46,0xD6,0xB8,0x91,0xFD,0xA6,0x0D,0x2B,0x1A,0x14,
-0x01,0x3E,0x80,0xF0,0x42,0xA0,0x95,0x07,0x5E,0x6D,0xCD,0xCC,0x4B,0xA4,0x45,0x8D,
-0xAB,0x12,0xE8,0xB3,0xDE,0x5A,0xE5,0xA0,0x7C,0xE8,0x0F,0x22,0x1D,0x5A,0xE9,0x59,
-};
-
-
-/* subject:/C=US/O=GeoTrust Inc./OU=(c) 2007 GeoTrust Inc. - For authorized use only/CN=GeoTrust Primary Certification Authority - G2 */
-/* issuer :/C=US/O=GeoTrust Inc./OU=(c) 2007 GeoTrust Inc. - For authorized use only/CN=GeoTrust Primary Certification Authority - G2 */
-
-
-const unsigned char GeoTrust_Primary_Certification_Authority___G2_certificate[690]={
-0x30,0x82,0x02,0xAE,0x30,0x82,0x02,0x35,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x3C,
-0xB2,0xF4,0x48,0x0A,0x00,0xE2,0xFE,0xEB,0x24,0x3B,0x5E,0x60,0x3E,0xC3,0x6B,0x30,
-0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x03,0x30,0x81,0x98,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,
-0x6E,0x63,0x2E,0x31,0x39,0x30,0x37,0x06,0x03,0x55,0x04,0x0B,0x13,0x30,0x28,0x63,
-0x29,0x20,0x32,0x30,0x30,0x37,0x20,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,
-0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,
-0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x36,
-0x30,0x34,0x06,0x03,0x55,0x04,0x03,0x13,0x2D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,
-0x74,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,
-0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,
-0x79,0x20,0x2D,0x20,0x47,0x32,0x30,0x1E,0x17,0x0D,0x30,0x37,0x31,0x31,0x30,0x35,
-0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x38,0x30,0x31,0x31,0x38,0x32,
-0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0x98,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,
-0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,
-0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x39,
-0x30,0x37,0x06,0x03,0x55,0x04,0x0B,0x13,0x30,0x28,0x63,0x29,0x20,0x32,0x30,0x30,
-0x37,0x20,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x20,
-0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,
-0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x36,0x30,0x34,0x06,0x03,0x55,
-0x04,0x03,0x13,0x2D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x50,0x72,0x69,
-0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,
-0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x2D,0x20,0x47,
-0x32,0x30,0x76,0x30,0x10,0x06,0x07,0x2A,0x86,0x48,0xCE,0x3D,0x02,0x01,0x06,0x05,
-0x2B,0x81,0x04,0x00,0x22,0x03,0x62,0x00,0x04,0x15,0xB1,0xE8,0xFD,0x03,0x15,0x43,
-0xE5,0xAC,0xEB,0x87,0x37,0x11,0x62,0xEF,0xD2,0x83,0x36,0x52,0x7D,0x45,0x57,0x0B,
-0x4A,0x8D,0x7B,0x54,0x3B,0x3A,0x6E,0x5F,0x15,0x02,0xC0,0x50,0xA6,0xCF,0x25,0x2F,
-0x7D,0xCA,0x48,0xB8,0xC7,0x50,0x63,0x1C,0x2A,0x21,0x08,0x7C,0x9A,0x36,0xD8,0x0B,
-0xFE,0xD1,0x26,0xC5,0x58,0x31,0x30,0x28,0x25,0xF3,0x5D,0x5D,0xA3,0xB8,0xB6,0xA5,
-0xB4,0x92,0xED,0x6C,0x2C,0x9F,0xEB,0xDD,0x43,0x89,0xA2,0x3C,0x4B,0x48,0x91,0x1D,
-0x50,0xEC,0x26,0xDF,0xD6,0x60,0x2E,0xBD,0x21,0xA3,0x42,0x30,0x40,0x30,0x0F,0x06,
-0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,
-0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,
-0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x15,0x5F,0x35,0x57,0x51,0x55,0xFB,
-0x25,0xB2,0xAD,0x03,0x69,0xFC,0x01,0xA3,0xFA,0xBE,0x11,0x55,0xD5,0x30,0x0A,0x06,
-0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x03,0x03,0x67,0x00,0x30,0x64,0x02,0x30,
-0x64,0x96,0x59,0xA6,0xE8,0x09,0xDE,0x8B,0xBA,0xFA,0x5A,0x88,0x88,0xF0,0x1F,0x91,
-0xD3,0x46,0xA8,0xF2,0x4A,0x4C,0x02,0x63,0xFB,0x6C,0x5F,0x38,0xDB,0x2E,0x41,0x93,
-0xA9,0x0E,0xE6,0x9D,0xDC,0x31,0x1C,0xB2,0xA0,0xA7,0x18,0x1C,0x79,0xE1,0xC7,0x36,
-0x02,0x30,0x3A,0x56,0xAF,0x9A,0x74,0x6C,0xF6,0xFB,0x83,0xE0,0x33,0xD3,0x08,0x5F,
-0xA1,0x9C,0xC2,0x5B,0x9F,0x46,0xD6,0xB6,0xCB,0x91,0x06,0x63,0xA2,0x06,0xE7,0x33,
-0xAC,0x3E,0xA8,0x81,0x12,0xD0,0xCB,0xBA,0xD0,0x92,0x0B,0xB6,0x9E,0x96,0xAA,0x04,
-0x0F,0x8A,
-};
-
-
-/* subject:/C=US/O=GeoTrust Inc./OU=(c) 2008 GeoTrust Inc. - For authorized use only/CN=GeoTrust Primary Certification Authority - G3 */
-/* issuer :/C=US/O=GeoTrust Inc./OU=(c) 2008 GeoTrust Inc. - For authorized use only/CN=GeoTrust Primary Certification Authority - G3 */
-
-
-const unsigned char GeoTrust_Primary_Certification_Authority___G3_certificate[1026]={
-0x30,0x82,0x03,0xFE,0x30,0x82,0x02,0xE6,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x15,
-0xAC,0x6E,0x94,0x19,0xB2,0x79,0x4B,0x41,0xF6,0x27,0xA9,0xC3,0x18,0x0F,0x1F,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,0x81,
-0x98,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,
-0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,
-0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x39,0x30,0x37,0x06,0x03,0x55,0x04,0x0B,0x13,
-0x30,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x38,0x20,0x47,0x65,0x6F,0x54,0x72,0x75,
-0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,
-0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,
-0x79,0x31,0x36,0x30,0x34,0x06,0x03,0x55,0x04,0x03,0x13,0x2D,0x47,0x65,0x6F,0x54,
-0x72,0x75,0x73,0x74,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,
-0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,
-0x72,0x69,0x74,0x79,0x20,0x2D,0x20,0x47,0x33,0x30,0x1E,0x17,0x0D,0x30,0x38,0x30,
-0x34,0x30,0x32,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x37,0x31,0x32,
-0x30,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0x98,0x31,0x0B,0x30,0x09,
-0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,
-0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x39,0x30,0x37,0x06,0x03,0x55,0x04,0x0B,0x13,0x30,0x28,0x63,0x29,0x20,
-0x32,0x30,0x30,0x38,0x20,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,
-0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x36,0x30,0x34,
-0x06,0x03,0x55,0x04,0x03,0x13,0x2D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,
-0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,
-0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,
-0x2D,0x20,0x47,0x33,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,
-0x02,0x82,0x01,0x01,0x00,0xDC,0xE2,0x5E,0x62,0x58,0x1D,0x33,0x57,0x39,0x32,0x33,
-0xFA,0xEB,0xCB,0x87,0x8C,0xA7,0xD4,0x4A,0xDD,0x06,0x88,0xEA,0x64,0x8E,0x31,0x98,
-0xA5,0x38,0x90,0x1E,0x98,0xCF,0x2E,0x63,0x2B,0xF0,0x46,0xBC,0x44,0xB2,0x89,0xA1,
-0xC0,0x28,0x0C,0x49,0x70,0x21,0x95,0x9F,0x64,0xC0,0xA6,0x93,0x12,0x02,0x65,0x26,
-0x86,0xC6,0xA5,0x89,0xF0,0xFA,0xD7,0x84,0xA0,0x70,0xAF,0x4F,0x1A,0x97,0x3F,0x06,
-0x44,0xD5,0xC9,0xEB,0x72,0x10,0x7D,0xE4,0x31,0x28,0xFB,0x1C,0x61,0xE6,0x28,0x07,
-0x44,0x73,0x92,0x22,0x69,0xA7,0x03,0x88,0x6C,0x9D,0x63,0xC8,0x52,0xDA,0x98,0x27,
-0xE7,0x08,0x4C,0x70,0x3E,0xB4,0xC9,0x12,0xC1,0xC5,0x67,0x83,0x5D,0x33,0xF3,0x03,
-0x11,0xEC,0x6A,0xD0,0x53,0xE2,0xD1,0xBA,0x36,0x60,0x94,0x80,0xBB,0x61,0x63,0x6C,
-0x5B,0x17,0x7E,0xDF,0x40,0x94,0x1E,0xAB,0x0D,0xC2,0x21,0x28,0x70,0x88,0xFF,0xD6,
-0x26,0x6C,0x6C,0x60,0x04,0x25,0x4E,0x55,0x7E,0x7D,0xEF,0xBF,0x94,0x48,0xDE,0xB7,
-0x1D,0xDD,0x70,0x8D,0x05,0x5F,0x88,0xA5,0x9B,0xF2,0xC2,0xEE,0xEA,0xD1,0x40,0x41,
-0x6D,0x62,0x38,0x1D,0x56,0x06,0xC5,0x03,0x47,0x51,0x20,0x19,0xFC,0x7B,0x10,0x0B,
-0x0E,0x62,0xAE,0x76,0x55,0xBF,0x5F,0x77,0xBE,0x3E,0x49,0x01,0x53,0x3D,0x98,0x25,
-0x03,0x76,0x24,0x5A,0x1D,0xB4,0xDB,0x89,0xEA,0x79,0xE5,0xB6,0xB3,0x3B,0x3F,0xBA,
-0x4C,0x28,0x41,0x7F,0x06,0xAC,0x6A,0x8E,0xC1,0xD0,0xF6,0x05,0x1D,0x7D,0xE6,0x42,
-0x86,0xE3,0xA5,0xD5,0x47,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,0x0F,
-0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,
-0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,
-0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xC4,0x79,0xCA,0x8E,0xA1,0x4E,
-0x03,0x1D,0x1C,0xDC,0x6B,0xDB,0x31,0x5B,0x94,0x3E,0x3F,0x30,0x7F,0x2D,0x30,0x0D,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,0x01,
-0x01,0x00,0x2D,0xC5,0x13,0xCF,0x56,0x80,0x7B,0x7A,0x78,0xBD,0x9F,0xAE,0x2C,0x99,
-0xE7,0xEF,0xDA,0xDF,0x94,0x5E,0x09,0x69,0xA7,0xE7,0x6E,0x68,0x8C,0xBD,0x72,0xBE,
-0x47,0xA9,0x0E,0x97,0x12,0xB8,0x4A,0xF1,0x64,0xD3,0x39,0xDF,0x25,0x34,0xD4,0xC1,
-0xCD,0x4E,0x81,0xF0,0x0F,0x04,0xC4,0x24,0xB3,0x34,0x96,0xC6,0xA6,0xAA,0x30,0xDF,
-0x68,0x61,0x73,0xD7,0xF9,0x8E,0x85,0x89,0xEF,0x0E,0x5E,0x95,0x28,0x4A,0x2A,0x27,
-0x8F,0x10,0x8E,0x2E,0x7C,0x86,0xC4,0x02,0x9E,0xDA,0x0C,0x77,0x65,0x0E,0x44,0x0D,
-0x92,0xFD,0xFD,0xB3,0x16,0x36,0xFA,0x11,0x0D,0x1D,0x8C,0x0E,0x07,0x89,0x6A,0x29,
-0x56,0xF7,0x72,0xF4,0xDD,0x15,0x9C,0x77,0x35,0x66,0x57,0xAB,0x13,0x53,0xD8,0x8E,
-0xC1,0x40,0xC5,0xD7,0x13,0x16,0x5A,0x72,0xC7,0xB7,0x69,0x01,0xC4,0x7A,0xB1,0x83,
-0x01,0x68,0x7D,0x8D,0x41,0xA1,0x94,0x18,0xC1,0x25,0x5C,0xFC,0xF0,0xFE,0x83,0x02,
-0x87,0x7C,0x0D,0x0D,0xCF,0x2E,0x08,0x5C,0x4A,0x40,0x0D,0x3E,0xEC,0x81,0x61,0xE6,
-0x24,0xDB,0xCA,0xE0,0x0E,0x2D,0x07,0xB2,0x3E,0x56,0xDC,0x8D,0xF5,0x41,0x85,0x07,
-0x48,0x9B,0x0C,0x0B,0xCB,0x49,0x3F,0x7D,0xEC,0xB7,0xFD,0xCB,0x8D,0x67,0x89,0x1A,
-0xAB,0xED,0xBB,0x1E,0xA3,0x00,0x08,0x08,0x17,0x2A,0x82,0x5C,0x31,0x5D,0x46,0x8A,
-0x2D,0x0F,0x86,0x9B,0x74,0xD9,0x45,0xFB,0xD4,0x40,0xB1,0x7A,0xAA,0x68,0x2D,0x86,
-0xB2,0x99,0x22,0xE1,0xC1,0x2B,0xC7,0x9C,0xF8,0xF3,0x5F,0xA8,0x82,0x12,0xEB,0x19,
-0x11,0x2D,
-};
-
-
-/* subject:/C=US/O=GeoTrust Inc./CN=GeoTrust Universal CA */
-/* issuer :/C=US/O=GeoTrust Inc./CN=GeoTrust Universal CA */
-
-
-const unsigned char GeoTrust_Universal_CA_certificate[1388]={
-0x30,0x82,0x05,0x68,0x30,0x82,0x03,0x50,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x45,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,
-0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,
-0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1E,0x30,0x1C,0x06,0x03,0x55,0x04,0x03,0x13,
-0x15,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,
-0x73,0x61,0x6C,0x20,0x43,0x41,0x30,0x1E,0x17,0x0D,0x30,0x34,0x30,0x33,0x30,0x34,
-0x30,0x35,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x39,0x30,0x33,0x30,0x34,0x30,
-0x35,0x30,0x30,0x30,0x30,0x5A,0x30,0x45,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,
-0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1E,0x30,
-0x1C,0x06,0x03,0x55,0x04,0x03,0x13,0x15,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,
-0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,0x43,0x41,0x30,0x82,0x02,
-0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,
-0x03,0x82,0x02,0x0F,0x00,0x30,0x82,0x02,0x0A,0x02,0x82,0x02,0x01,0x00,0xA6,0x15,
-0x55,0xA0,0xA3,0xC6,0xE0,0x1F,0x8C,0x9D,0x21,0x50,0xD7,0xC1,0xBE,0x2B,0x5B,0xB5,
-0xA4,0x9E,0xA1,0xD9,0x72,0x58,0xBD,0x00,0x1B,0x4C,0xBF,0x61,0xC9,0x14,0x1D,0x45,
-0x82,0xAB,0xC6,0x1D,0x80,0xD6,0x3D,0xEB,0x10,0x9C,0x3A,0xAF,0x6D,0x24,0xF8,0xBC,
-0x71,0x01,0x9E,0x06,0xF5,0x7C,0x5F,0x1E,0xC1,0x0E,0x55,0xCA,0x83,0x9A,0x59,0x30,
-0xAE,0x19,0xCB,0x30,0x48,0x95,0xED,0x22,0x37,0x8D,0xF4,0x4A,0x9A,0x72,0x66,0x3E,
-0xAD,0x95,0xC0,0xE0,0x16,0x00,0xE0,0x10,0x1F,0x2B,0x31,0x0E,0xD7,0x94,0x54,0xD3,
-0x42,0x33,0xA0,0x34,0x1D,0x1E,0x45,0x76,0xDD,0x4F,0xCA,0x18,0x37,0xEC,0x85,0x15,
-0x7A,0x19,0x08,0xFC,0xD5,0xC7,0x9C,0xF0,0xF2,0xA9,0x2E,0x10,0xA9,0x92,0xE6,0x3D,
-0x58,0x3D,0xA9,0x16,0x68,0x3C,0x2F,0x75,0x21,0x18,0x7F,0x28,0x77,0xA5,0xE1,0x61,
-0x17,0xB7,0xA6,0xE9,0xF8,0x1E,0x99,0xDB,0x73,0x6E,0xF4,0x0A,0xA2,0x21,0x6C,0xEE,
-0xDA,0xAA,0x85,0x92,0x66,0xAF,0xF6,0x7A,0x6B,0x82,0xDA,0xBA,0x22,0x08,0x35,0x0F,
-0xCF,0x42,0xF1,0x35,0xFA,0x6A,0xEE,0x7E,0x2B,0x25,0xCC,0x3A,0x11,0xE4,0x6D,0xAF,
-0x73,0xB2,0x76,0x1D,0xAD,0xD0,0xB2,0x78,0x67,0x1A,0xA4,0x39,0x1C,0x51,0x0B,0x67,
-0x56,0x83,0xFD,0x38,0x5D,0x0D,0xCE,0xDD,0xF0,0xBB,0x2B,0x96,0x1F,0xDE,0x7B,0x32,
-0x52,0xFD,0x1D,0xBB,0xB5,0x06,0xA1,0xB2,0x21,0x5E,0xA5,0xD6,0x95,0x68,0x7F,0xF0,
-0x99,0x9E,0xDC,0x45,0x08,0x3E,0xE7,0xD2,0x09,0x0D,0x35,0x94,0xDD,0x80,0x4E,0x53,
-0x97,0xD7,0xB5,0x09,0x44,0x20,0x64,0x16,0x17,0x03,0x02,0x4C,0x53,0x0D,0x68,0xDE,
-0xD5,0xAA,0x72,0x4D,0x93,0x6D,0x82,0x0E,0xDB,0x9C,0xBD,0xCF,0xB4,0xF3,0x5C,0x5D,
-0x54,0x7A,0x69,0x09,0x96,0xD6,0xDB,0x11,0xC1,0x8D,0x75,0xA8,0xB4,0xCF,0x39,0xC8,
-0xCE,0x3C,0xBC,0x24,0x7C,0xE6,0x62,0xCA,0xE1,0xBD,0x7D,0xA7,0xBD,0x57,0x65,0x0B,
-0xE4,0xFE,0x25,0xED,0xB6,0x69,0x10,0xDC,0x28,0x1A,0x46,0xBD,0x01,0x1D,0xD0,0x97,
-0xB5,0xE1,0x98,0x3B,0xC0,0x37,0x64,0xD6,0x3D,0x94,0xEE,0x0B,0xE1,0xF5,0x28,0xAE,
-0x0B,0x56,0xBF,0x71,0x8B,0x23,0x29,0x41,0x8E,0x86,0xC5,0x4B,0x52,0x7B,0xD8,0x71,
-0xAB,0x1F,0x8A,0x15,0xA6,0x3B,0x83,0x5A,0xD7,0x58,0x01,0x51,0xC6,0x4C,0x41,0xD9,
-0x7F,0xD8,0x41,0x67,0x72,0xA2,0x28,0xDF,0x60,0x83,0xA9,0x9E,0xC8,0x7B,0xFC,0x53,
-0x73,0x72,0x59,0xF5,0x93,0x7A,0x17,0x76,0x0E,0xCE,0xF7,0xE5,0x5C,0xD9,0x0B,0x55,
-0x34,0xA2,0xAA,0x5B,0xB5,0x6A,0x54,0xE7,0x13,0xCA,0x57,0xEC,0x97,0x6D,0xF4,0x5E,
-0x06,0x2F,0x45,0x8B,0x58,0xD4,0x23,0x16,0x92,0xE4,0x16,0x6E,0x28,0x63,0x59,0x30,
-0xDF,0x50,0x01,0x9C,0x63,0x89,0x1A,0x9F,0xDB,0x17,0x94,0x82,0x70,0x37,0xC3,0x24,
-0x9E,0x9A,0x47,0xD6,0x5A,0xCA,0x4E,0xA8,0x69,0x89,0x72,0x1F,0x91,0x6C,0xDB,0x7E,
-0x9E,0x1B,0xAD,0xC7,0x1F,0x73,0xDD,0x2C,0x4F,0x19,0x65,0xFD,0x7F,0x93,0x40,0x10,
-0x2E,0xD2,0xF0,0xED,0x3C,0x9E,0x2E,0x28,0x3E,0x69,0x26,0x33,0xC5,0x7B,0x02,0x03,
-0x01,0x00,0x01,0xA3,0x63,0x30,0x61,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,
-0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,
-0x16,0x04,0x14,0xDA,0xBB,0x2E,0xAA,0xB0,0x0C,0xB8,0x88,0x26,0x51,0x74,0x5C,0x6D,
-0x03,0xD3,0xC0,0xD8,0x8F,0x7A,0xD6,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,
-0x30,0x16,0x80,0x14,0xDA,0xBB,0x2E,0xAA,0xB0,0x0C,0xB8,0x88,0x26,0x51,0x74,0x5C,
-0x6D,0x03,0xD3,0xC0,0xD8,0x8F,0x7A,0xD6,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,
-0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x86,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x02,0x01,0x00,0x31,0x78,0xE6,0xC7,
-0xB5,0xDF,0xB8,0x94,0x40,0xC9,0x71,0xC4,0xA8,0x35,0xEC,0x46,0x1D,0xC2,0x85,0xF3,
-0x28,0x58,0x86,0xB0,0x0B,0xFC,0x8E,0xB2,0x39,0x8F,0x44,0x55,0xAB,0x64,0x84,0x5C,
-0x69,0xA9,0xD0,0x9A,0x38,0x3C,0xFA,0xE5,0x1F,0x35,0xE5,0x44,0xE3,0x80,0x79,0x94,
-0x68,0xA4,0xBB,0xC4,0x9F,0x3D,0xE1,0x34,0xCD,0x30,0x46,0x8B,0x54,0x2B,0x95,0xA5,
-0xEF,0xF7,0x3F,0x99,0x84,0xFD,0x35,0xE6,0xCF,0x31,0xC6,0xDC,0x6A,0xBF,0xA7,0xD7,
-0x23,0x08,0xE1,0x98,0x5E,0xC3,0x5A,0x08,0x76,0xA9,0xA6,0xAF,0x77,0x2F,0xB7,0x60,
-0xBD,0x44,0x46,0x6A,0xEF,0x97,0xFF,0x73,0x95,0xC1,0x8E,0xE8,0x93,0xFB,0xFD,0x31,
-0xB7,0xEC,0x57,0x11,0x11,0x45,0x9B,0x30,0xF1,0x1A,0x88,0x39,0xC1,0x4F,0x3C,0xA7,
-0x00,0xD5,0xC7,0xFC,0xAB,0x6D,0x80,0x22,0x70,0xA5,0x0C,0xE0,0x5D,0x04,0x29,0x02,
-0xFB,0xCB,0xA0,0x91,0xD1,0x7C,0xD6,0xC3,0x7E,0x50,0xD5,0x9D,0x58,0xBE,0x41,0x38,
-0xEB,0xB9,0x75,0x3C,0x15,0xD9,0x9B,0xC9,0x4A,0x83,0x59,0xC0,0xDA,0x53,0xFD,0x33,
-0xBB,0x36,0x18,0x9B,0x85,0x0F,0x15,0xDD,0xEE,0x2D,0xAC,0x76,0x93,0xB9,0xD9,0x01,
-0x8D,0x48,0x10,0xA8,0xFB,0xF5,0x38,0x86,0xF1,0xDB,0x0A,0xC6,0xBD,0x84,0xA3,0x23,
-0x41,0xDE,0xD6,0x77,0x6F,0x85,0xD4,0x85,0x1C,0x50,0xE0,0xAE,0x51,0x8A,0xBA,0x8D,
-0x3E,0x76,0xE2,0xB9,0xCA,0x27,0xF2,0x5F,0x9F,0xEF,0x6E,0x59,0x0D,0x06,0xD8,0x2B,
-0x17,0xA4,0xD2,0x7C,0x6B,0xBB,0x5F,0x14,0x1A,0x48,0x8F,0x1A,0x4C,0xE7,0xB3,0x47,
-0x1C,0x8E,0x4C,0x45,0x2B,0x20,0xEE,0x48,0xDF,0xE7,0xDD,0x09,0x8E,0x18,0xA8,0xDA,
-0x40,0x8D,0x92,0x26,0x11,0x53,0x61,0x73,0x5D,0xEB,0xBD,0xE7,0xC4,0x4D,0x29,0x37,
-0x61,0xEB,0xAC,0x39,0x2D,0x67,0x2E,0x16,0xD6,0xF5,0x00,0x83,0x85,0xA1,0xCC,0x7F,
-0x76,0xC4,0x7D,0xE4,0xB7,0x4B,0x66,0xEF,0x03,0x45,0x60,0x69,0xB6,0x0C,0x52,0x96,
-0x92,0x84,0x5E,0xA6,0xA3,0xB5,0xA4,0x3E,0x2B,0xD9,0xCC,0xD8,0x1B,0x47,0xAA,0xF2,
-0x44,0xDA,0x4F,0xF9,0x03,0xE8,0xF0,0x14,0xCB,0x3F,0xF3,0x83,0xDE,0xD0,0xC1,0x54,
-0xE3,0xB7,0xE8,0x0A,0x37,0x4D,0x8B,0x20,0x59,0x03,0x30,0x19,0xA1,0x2C,0xC8,0xBD,
-0x11,0x1F,0xDF,0xAE,0xC9,0x4A,0xC5,0xF3,0x27,0x66,0x66,0x86,0xAC,0x68,0x91,0xFF,
-0xD9,0xE6,0x53,0x1C,0x0F,0x8B,0x5C,0x69,0x65,0x0A,0x26,0xC8,0x1E,0x34,0xC3,0x5D,
-0x51,0x7B,0xD7,0xA9,0x9C,0x06,0xA1,0x36,0xDD,0xD5,0x89,0x94,0xBC,0xD9,0xE4,0x2D,
-0x0C,0x5E,0x09,0x6C,0x08,0x97,0x7C,0xA3,0x3D,0x7C,0x93,0xFF,0x3F,0xA1,0x14,0xA7,
-0xCF,0xB5,0x5D,0xEB,0xDB,0xDB,0x1C,0xC4,0x76,0xDF,0x88,0xB9,0xBD,0x45,0x05,0x95,
-0x1B,0xAE,0xFC,0x46,0x6A,0x4C,0xAF,0x48,0xE3,0xCE,0xAE,0x0F,0xD2,0x7E,0xEB,0xE6,
-0x6C,0x9C,0x4F,0x81,0x6A,0x7A,0x64,0xAC,0xBB,0x3E,0xD5,0xE7,0xCB,0x76,0x2E,0xC5,
-0xA7,0x48,0xC1,0x5C,0x90,0x0F,0xCB,0xC8,0x3F,0xFA,0xE6,0x32,0xE1,0x8D,0x1B,0x6F,
-0xA4,0xE6,0x8E,0xD8,0xF9,0x29,0x48,0x8A,0xCE,0x73,0xFE,0x2C,
-};
-
-
-/* subject:/C=US/O=GeoTrust Inc./CN=GeoTrust Universal CA 2 */
-/* issuer :/C=US/O=GeoTrust Inc./CN=GeoTrust Universal CA 2 */
-
-
-const unsigned char GeoTrust_Universal_CA_2_certificate[1392]={
-0x30,0x82,0x05,0x6C,0x30,0x82,0x03,0x54,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x47,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,
-0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,
-0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,
-0x17,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,
-0x73,0x61,0x6C,0x20,0x43,0x41,0x20,0x32,0x30,0x1E,0x17,0x0D,0x30,0x34,0x30,0x33,
-0x30,0x34,0x30,0x35,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x39,0x30,0x33,0x30,
-0x34,0x30,0x35,0x30,0x30,0x30,0x30,0x5A,0x30,0x47,0x31,0x0B,0x30,0x09,0x06,0x03,
-0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,
-0x13,0x0D,0x47,0x65,0x6F,0x54,0x72,0x75,0x73,0x74,0x20,0x49,0x6E,0x63,0x2E,0x31,
-0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,0x17,0x47,0x65,0x6F,0x54,0x72,0x75,
-0x73,0x74,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,0x43,0x41,0x20,
-0x32,0x30,0x82,0x02,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x01,0x05,0x00,0x03,0x82,0x02,0x0F,0x00,0x30,0x82,0x02,0x0A,0x02,0x82,0x02,
-0x01,0x00,0xB3,0x54,0x52,0xC1,0xC9,0x3E,0xF2,0xD9,0xDC,0xB1,0x53,0x1A,0x59,0x29,
-0xE7,0xB1,0xC3,0x45,0x28,0xE5,0xD7,0xD1,0xED,0xC5,0xC5,0x4B,0xA1,0xAA,0x74,0x7B,
-0x57,0xAF,0x4A,0x26,0xFC,0xD8,0xF5,0x5E,0xA7,0x6E,0x19,0xDB,0x74,0x0C,0x4F,0x35,
-0x5B,0x32,0x0B,0x01,0xE3,0xDB,0xEB,0x7A,0x77,0x35,0xEA,0xAA,0x5A,0xE0,0xD6,0xE8,
-0xA1,0x57,0x94,0xF0,0x90,0xA3,0x74,0x56,0x94,0x44,0x30,0x03,0x1E,0x5C,0x4E,0x2B,
-0x85,0x26,0x74,0x82,0x7A,0x0C,0x76,0xA0,0x6F,0x4D,0xCE,0x41,0x2D,0xA0,0x15,0x06,
-0x14,0x5F,0xB7,0x42,0xCD,0x7B,0x8F,0x58,0x61,0x34,0xDC,0x2A,0x08,0xF9,0x2E,0xC3,
-0x01,0xA6,0x22,0x44,0x1C,0x4C,0x07,0x82,0xE6,0x5B,0xCE,0xD0,0x4A,0x7C,0x04,0xD3,
-0x19,0x73,0x27,0xF0,0xAA,0x98,0x7F,0x2E,0xAF,0x4E,0xEB,0x87,0x1E,0x24,0x77,0x6A,
-0x5D,0xB6,0xE8,0x5B,0x45,0xBA,0xDC,0xC3,0xA1,0x05,0x6F,0x56,0x8E,0x8F,0x10,0x26,
-0xA5,0x49,0xC3,0x2E,0xD7,0x41,0x87,0x22,0xE0,0x4F,0x86,0xCA,0x60,0xB5,0xEA,0xA1,
-0x63,0xC0,0x01,0x97,0x10,0x79,0xBD,0x00,0x3C,0x12,0x6D,0x2B,0x15,0xB1,0xAC,0x4B,
-0xB1,0xEE,0x18,0xB9,0x4E,0x96,0xDC,0xDC,0x76,0xFF,0x3B,0xBE,0xCF,0x5F,0x03,0xC0,
-0xFC,0x3B,0xE8,0xBE,0x46,0x1B,0xFF,0xDA,0x40,0xC2,0x52,0xF7,0xFE,0xE3,0x3A,0xF7,
-0x6A,0x77,0x35,0xD0,0xDA,0x8D,0xEB,0x5E,0x18,0x6A,0x31,0xC7,0x1E,0xBA,0x3C,0x1B,
-0x28,0xD6,0x6B,0x54,0xC6,0xAA,0x5B,0xD7,0xA2,0x2C,0x1B,0x19,0xCC,0xA2,0x02,0xF6,
-0x9B,0x59,0xBD,0x37,0x6B,0x86,0xB5,0x6D,0x82,0xBA,0xD8,0xEA,0xC9,0x56,0xBC,0xA9,
-0x36,0x58,0xFD,0x3E,0x19,0xF3,0xED,0x0C,0x26,0xA9,0x93,0x38,0xF8,0x4F,0xC1,0x5D,
-0x22,0x06,0xD0,0x97,0xEA,0xE1,0xAD,0xC6,0x55,0xE0,0x81,0x2B,0x28,0x83,0x3A,0xFA,
-0xF4,0x7B,0x21,0x51,0x00,0xBE,0x52,0x38,0xCE,0xCD,0x66,0x79,0xA8,0xF4,0x81,0x56,
-0xE2,0xD0,0x83,0x09,0x47,0x51,0x5B,0x50,0x6A,0xCF,0xDB,0x48,0x1A,0x5D,0x3E,0xF7,
-0xCB,0xF6,0x65,0xF7,0x6C,0xF1,0x95,0xF8,0x02,0x3B,0x32,0x56,0x82,0x39,0x7A,0x5B,
-0xBD,0x2F,0x89,0x1B,0xBF,0xA1,0xB4,0xE8,0xFF,0x7F,0x8D,0x8C,0xDF,0x03,0xF1,0x60,
-0x4E,0x58,0x11,0x4C,0xEB,0xA3,0x3F,0x10,0x2B,0x83,0x9A,0x01,0x73,0xD9,0x94,0x6D,
-0x84,0x00,0x27,0x66,0xAC,0xF0,0x70,0x40,0x09,0x42,0x92,0xAD,0x4F,0x93,0x0D,0x61,
-0x09,0x51,0x24,0xD8,0x92,0xD5,0x0B,0x94,0x61,0xB2,0x87,0xB2,0xED,0xFF,0x9A,0x35,
-0xFF,0x85,0x54,0xCA,0xED,0x44,0x43,0xAC,0x1B,0x3C,0x16,0x6B,0x48,0x4A,0x0A,0x1C,
-0x40,0x88,0x1F,0x92,0xC2,0x0B,0x00,0x05,0xFF,0xF2,0xC8,0x02,0x4A,0xA4,0xAA,0xA9,
-0xCC,0x99,0x96,0x9C,0x2F,0x58,0xE0,0x7D,0xE1,0xBE,0xBB,0x07,0xDC,0x5F,0x04,0x72,
-0x5C,0x31,0x34,0xC3,0xEC,0x5F,0x2D,0xE0,0x3D,0x64,0x90,0x22,0xE6,0xD1,0xEC,0xB8,
-0x2E,0xDD,0x59,0xAE,0xD9,0xA1,0x37,0xBF,0x54,0x35,0xDC,0x73,0x32,0x4F,0x8C,0x04,
-0x1E,0x33,0xB2,0xC9,0x46,0xF1,0xD8,0x5C,0xC8,0x55,0x50,0xC9,0x68,0xBD,0xA8,0xBA,
-0x36,0x09,0x02,0x03,0x01,0x00,0x01,0xA3,0x63,0x30,0x61,0x30,0x0F,0x06,0x03,0x55,
-0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,
-0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x76,0xF3,0x55,0xE1,0xFA,0xA4,0x36,0xFB,0xF0,
-0x9F,0x5C,0x62,0x71,0xED,0x3C,0xF4,0x47,0x38,0x10,0x2B,0x30,0x1F,0x06,0x03,0x55,
-0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x76,0xF3,0x55,0xE1,0xFA,0xA4,0x36,0xFB,
-0xF0,0x9F,0x5C,0x62,0x71,0xED,0x3C,0xF4,0x47,0x38,0x10,0x2B,0x30,0x0E,0x06,0x03,
-0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x86,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x02,0x01,0x00,
-0x66,0xC1,0xC6,0x23,0xF3,0xD9,0xE0,0x2E,0x6E,0x5F,0xE8,0xCF,0xAE,0xB0,0xB0,0x25,
-0x4D,0x2B,0xF8,0x3B,0x58,0x9B,0x40,0x24,0x37,0x5A,0xCB,0xAB,0x16,0x49,0xFF,0xB3,
-0x75,0x79,0x33,0xA1,0x2F,0x6D,0x70,0x17,0x34,0x91,0xFE,0x67,0x7E,0x8F,0xEC,0x9B,
-0xE5,0x5E,0x82,0xA9,0x55,0x1F,0x2F,0xDC,0xD4,0x51,0x07,0x12,0xFE,0xAC,0x16,0x3E,
-0x2C,0x35,0xC6,0x63,0xFC,0xDC,0x10,0xEB,0x0D,0xA3,0xAA,0xD0,0x7C,0xCC,0xD1,0xD0,
-0x2F,0x51,0x2E,0xC4,0x14,0x5A,0xDE,0xE8,0x19,0xE1,0x3E,0xC6,0xCC,0xA4,0x29,0xE7,
-0x2E,0x84,0xAA,0x06,0x30,0x78,0x76,0x54,0x73,0x28,0x98,0x59,0x38,0xE0,0x00,0x0D,
-0x62,0xD3,0x42,0x7D,0x21,0x9F,0xAE,0x3D,0x3A,0x8C,0xD5,0xFA,0x77,0x0D,0x18,0x2B,
-0x16,0x0E,0x5F,0x36,0xE1,0xFC,0x2A,0xB5,0x30,0x24,0xCF,0xE0,0x63,0x0C,0x7B,0x58,
-0x1A,0xFE,0x99,0xBA,0x42,0x12,0xB1,0x91,0xF4,0x7C,0x68,0xE2,0xC8,0xE8,0xAF,0x2C,
-0xEA,0xC9,0x7E,0xAE,0xBB,0x2A,0x3D,0x0D,0x15,0xDC,0x34,0x95,0xB6,0x18,0x74,0xA8,
-0x6A,0x0F,0xC7,0xB4,0xF4,0x13,0xC4,0xE4,0x5B,0xED,0x0A,0xD2,0xA4,0x97,0x4C,0x2A,
-0xED,0x2F,0x6C,0x12,0x89,0x3D,0xF1,0x27,0x70,0xAA,0x6A,0x03,0x52,0x21,0x9F,0x40,
-0xA8,0x67,0x50,0xF2,0xF3,0x5A,0x1F,0xDF,0xDF,0x23,0xF6,0xDC,0x78,0x4E,0xE6,0x98,
-0x4F,0x55,0x3A,0x53,0xE3,0xEF,0xF2,0xF4,0x9F,0xC7,0x7C,0xD8,0x58,0xAF,0x29,0x22,
-0x97,0xB8,0xE0,0xBD,0x91,0x2E,0xB0,0x76,0xEC,0x57,0x11,0xCF,0xEF,0x29,0x44,0xF3,
-0xE9,0x85,0x7A,0x60,0x63,0xE4,0x5D,0x33,0x89,0x17,0xD9,0x31,0xAA,0xDA,0xD6,0xF3,
-0x18,0x35,0x72,0xCF,0x87,0x2B,0x2F,0x63,0x23,0x84,0x5D,0x84,0x8C,0x3F,0x57,0xA0,
-0x88,0xFC,0x99,0x91,0x28,0x26,0x69,0x99,0xD4,0x8F,0x97,0x44,0xBE,0x8E,0xD5,0x48,
-0xB1,0xA4,0x28,0x29,0xF1,0x15,0xB4,0xE1,0xE5,0x9E,0xDD,0xF8,0x8F,0xA6,0x6F,0x26,
-0xD7,0x09,0x3C,0x3A,0x1C,0x11,0x0E,0xA6,0x6C,0x37,0xF7,0xAD,0x44,0x87,0x2C,0x28,
-0xC7,0xD8,0x74,0x82,0xB3,0xD0,0x6F,0x4A,0x57,0xBB,0x35,0x29,0x27,0xA0,0x8B,0xE8,
-0x21,0xA7,0x87,0x64,0x36,0x5D,0xCC,0xD8,0x16,0xAC,0xC7,0xB2,0x27,0x40,0x92,0x55,
-0x38,0x28,0x8D,0x51,0x6E,0xDD,0x14,0x67,0x53,0x6C,0x71,0x5C,0x26,0x84,0x4D,0x75,
-0x5A,0xB6,0x7E,0x60,0x56,0xA9,0x4D,0xAD,0xFB,0x9B,0x1E,0x97,0xF3,0x0D,0xD9,0xD2,
-0x97,0x54,0x77,0xDA,0x3D,0x12,0xB7,0xE0,0x1E,0xEF,0x08,0x06,0xAC,0xF9,0x85,0x87,
-0xE9,0xA2,0xDC,0xAF,0x7E,0x18,0x12,0x83,0xFD,0x56,0x17,0x41,0x2E,0xD5,0x29,0x82,
-0x7D,0x99,0xF4,0x31,0xF6,0x71,0xA9,0xCF,0x2C,0x01,0x27,0xA5,0x05,0xB9,0xAA,0xB2,
-0x48,0x4E,0x2A,0xEF,0x9F,0x93,0x52,0x51,0x95,0x3C,0x52,0x73,0x8E,0x56,0x4C,0x17,
-0x40,0xC0,0x09,0x28,0xE4,0x8B,0x6A,0x48,0x53,0xDB,0xEC,0xCD,0x55,0x55,0xF1,0xC6,
-0xF8,0xE9,0xA2,0x2C,0x4C,0xA6,0xD1,0x26,0x5F,0x7E,0xAF,0x5A,0x4C,0xDA,0x1F,0xA6,
-0xF2,0x1C,0x2C,0x7E,0xAE,0x02,0x16,0xD2,0x56,0xD0,0x2F,0x57,0x53,0x47,0xE8,0x92,
-};
-
-
-/* subject:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA */
-/* issuer :/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA */
-
-
-const unsigned char GlobalSign_Root_CA_certificate[889]={
-0x30,0x82,0x03,0x75,0x30,0x82,0x02,0x5D,0xA0,0x03,0x02,0x01,0x02,0x02,0x0B,0x04,
-0x00,0x00,0x00,0x00,0x01,0x15,0x4B,0x5A,0xC3,0x94,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x57,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x42,0x45,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x10,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,0x20,0x6E,0x76,
-0x2D,0x73,0x61,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x0B,0x13,0x07,0x52,0x6F,
-0x6F,0x74,0x20,0x43,0x41,0x31,0x1B,0x30,0x19,0x06,0x03,0x55,0x04,0x03,0x13,0x12,
-0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,0x20,0x52,0x6F,0x6F,0x74,0x20,
-0x43,0x41,0x30,0x1E,0x17,0x0D,0x39,0x38,0x30,0x39,0x30,0x31,0x31,0x32,0x30,0x30,
-0x30,0x30,0x5A,0x17,0x0D,0x32,0x38,0x30,0x31,0x32,0x38,0x31,0x32,0x30,0x30,0x30,
-0x30,0x5A,0x30,0x57,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x42,
-0x45,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,0x0A,0x13,0x10,0x47,0x6C,0x6F,0x62,
-0x61,0x6C,0x53,0x69,0x67,0x6E,0x20,0x6E,0x76,0x2D,0x73,0x61,0x31,0x10,0x30,0x0E,
-0x06,0x03,0x55,0x04,0x0B,0x13,0x07,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x31,0x1B,
-0x30,0x19,0x06,0x03,0x55,0x04,0x03,0x13,0x12,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,
-0x69,0x67,0x6E,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x82,0x01,0x22,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,
-0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xDA,0x0E,0xE6,0x99,
-0x8D,0xCE,0xA3,0xE3,0x4F,0x8A,0x7E,0xFB,0xF1,0x8B,0x83,0x25,0x6B,0xEA,0x48,0x1F,
-0xF1,0x2A,0xB0,0xB9,0x95,0x11,0x04,0xBD,0xF0,0x63,0xD1,0xE2,0x67,0x66,0xCF,0x1C,
-0xDD,0xCF,0x1B,0x48,0x2B,0xEE,0x8D,0x89,0x8E,0x9A,0xAF,0x29,0x80,0x65,0xAB,0xE9,
-0xC7,0x2D,0x12,0xCB,0xAB,0x1C,0x4C,0x70,0x07,0xA1,0x3D,0x0A,0x30,0xCD,0x15,0x8D,
-0x4F,0xF8,0xDD,0xD4,0x8C,0x50,0x15,0x1C,0xEF,0x50,0xEE,0xC4,0x2E,0xF7,0xFC,0xE9,
-0x52,0xF2,0x91,0x7D,0xE0,0x6D,0xD5,0x35,0x30,0x8E,0x5E,0x43,0x73,0xF2,0x41,0xE9,
-0xD5,0x6A,0xE3,0xB2,0x89,0x3A,0x56,0x39,0x38,0x6F,0x06,0x3C,0x88,0x69,0x5B,0x2A,
-0x4D,0xC5,0xA7,0x54,0xB8,0x6C,0x89,0xCC,0x9B,0xF9,0x3C,0xCA,0xE5,0xFD,0x89,0xF5,
-0x12,0x3C,0x92,0x78,0x96,0xD6,0xDC,0x74,0x6E,0x93,0x44,0x61,0xD1,0x8D,0xC7,0x46,
-0xB2,0x75,0x0E,0x86,0xE8,0x19,0x8A,0xD5,0x6D,0x6C,0xD5,0x78,0x16,0x95,0xA2,0xE9,
-0xC8,0x0A,0x38,0xEB,0xF2,0x24,0x13,0x4F,0x73,0x54,0x93,0x13,0x85,0x3A,0x1B,0xBC,
-0x1E,0x34,0xB5,0x8B,0x05,0x8C,0xB9,0x77,0x8B,0xB1,0xDB,0x1F,0x20,0x91,0xAB,0x09,
-0x53,0x6E,0x90,0xCE,0x7B,0x37,0x74,0xB9,0x70,0x47,0x91,0x22,0x51,0x63,0x16,0x79,
-0xAE,0xB1,0xAE,0x41,0x26,0x08,0xC8,0x19,0x2B,0xD1,0x46,0xAA,0x48,0xD6,0x64,0x2A,
-0xD7,0x83,0x34,0xFF,0x2C,0x2A,0xC1,0x6C,0x19,0x43,0x4A,0x07,0x85,0xE7,0xD3,0x7C,
-0xF6,0x21,0x68,0xEF,0xEA,0xF2,0x52,0x9F,0x7F,0x93,0x90,0xCF,0x02,0x03,0x01,0x00,
-0x01,0xA3,0x42,0x30,0x40,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,
-0x04,0x03,0x02,0x01,0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,
-0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,
-0x14,0x60,0x7B,0x66,0x1A,0x45,0x0D,0x97,0xCA,0x89,0x50,0x2F,0x7D,0x04,0xCD,0x34,
-0xA8,0xFF,0xFC,0xFD,0x4B,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0xD6,0x73,0xE7,0x7C,0x4F,0x76,0xD0,
-0x8D,0xBF,0xEC,0xBA,0xA2,0xBE,0x34,0xC5,0x28,0x32,0xB5,0x7C,0xFC,0x6C,0x9C,0x2C,
-0x2B,0xBD,0x09,0x9E,0x53,0xBF,0x6B,0x5E,0xAA,0x11,0x48,0xB6,0xE5,0x08,0xA3,0xB3,
-0xCA,0x3D,0x61,0x4D,0xD3,0x46,0x09,0xB3,0x3E,0xC3,0xA0,0xE3,0x63,0x55,0x1B,0xF2,
-0xBA,0xEF,0xAD,0x39,0xE1,0x43,0xB9,0x38,0xA3,0xE6,0x2F,0x8A,0x26,0x3B,0xEF,0xA0,
-0x50,0x56,0xF9,0xC6,0x0A,0xFD,0x38,0xCD,0xC4,0x0B,0x70,0x51,0x94,0x97,0x98,0x04,
-0xDF,0xC3,0x5F,0x94,0xD5,0x15,0xC9,0x14,0x41,0x9C,0xC4,0x5D,0x75,0x64,0x15,0x0D,
-0xFF,0x55,0x30,0xEC,0x86,0x8F,0xFF,0x0D,0xEF,0x2C,0xB9,0x63,0x46,0xF6,0xAA,0xFC,
-0xDF,0xBC,0x69,0xFD,0x2E,0x12,0x48,0x64,0x9A,0xE0,0x95,0xF0,0xA6,0xEF,0x29,0x8F,
-0x01,0xB1,0x15,0xB5,0x0C,0x1D,0xA5,0xFE,0x69,0x2C,0x69,0x24,0x78,0x1E,0xB3,0xA7,
-0x1C,0x71,0x62,0xEE,0xCA,0xC8,0x97,0xAC,0x17,0x5D,0x8A,0xC2,0xF8,0x47,0x86,0x6E,
-0x2A,0xC4,0x56,0x31,0x95,0xD0,0x67,0x89,0x85,0x2B,0xF9,0x6C,0xA6,0x5D,0x46,0x9D,
-0x0C,0xAA,0x82,0xE4,0x99,0x51,0xDD,0x70,0xB7,0xDB,0x56,0x3D,0x61,0xE4,0x6A,0xE1,
-0x5C,0xD6,0xF6,0xFE,0x3D,0xDE,0x41,0xCC,0x07,0xAE,0x63,0x52,0xBF,0x53,0x53,0xF4,
-0x2B,0xE9,0xC7,0xFD,0xB6,0xF7,0x82,0x5F,0x85,0xD2,0x41,0x18,0xDB,0x81,0xB3,0x04,
-0x1C,0xC5,0x1F,0xA4,0x80,0x6F,0x15,0x20,0xC9,0xDE,0x0C,0x88,0x0A,0x1D,0xD6,0x66,
-0x55,0xE2,0xFC,0x48,0xC9,0x29,0x26,0x69,0xE0,
-};
-
-
-/* subject:/OU=GlobalSign Root CA - R2/O=GlobalSign/CN=GlobalSign */
-/* issuer :/OU=GlobalSign Root CA - R2/O=GlobalSign/CN=GlobalSign */
-
-
-const unsigned char GlobalSign_Root_CA___R2_certificate[958]={
-0x30,0x82,0x03,0xBA,0x30,0x82,0x02,0xA2,0xA0,0x03,0x02,0x01,0x02,0x02,0x0B,0x04,
-0x00,0x00,0x00,0x00,0x01,0x0F,0x86,0x26,0xE6,0x0D,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x4C,0x31,0x20,0x30,0x1E,0x06,
-0x03,0x55,0x04,0x0B,0x13,0x17,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,
-0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x20,0x2D,0x20,0x52,0x32,0x31,0x13,0x30,
-0x11,0x06,0x03,0x55,0x04,0x0A,0x13,0x0A,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,
-0x67,0x6E,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x03,0x13,0x0A,0x47,0x6C,0x6F,
-0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x32,0x31,
-0x35,0x30,0x38,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x31,0x31,0x32,0x31,0x35,
-0x30,0x38,0x30,0x30,0x30,0x30,0x5A,0x30,0x4C,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x17,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,0x20,0x52,
-0x6F,0x6F,0x74,0x20,0x43,0x41,0x20,0x2D,0x20,0x52,0x32,0x31,0x13,0x30,0x11,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0A,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,
-0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x03,0x13,0x0A,0x47,0x6C,0x6F,0x62,0x61,
-0x6C,0x53,0x69,0x67,0x6E,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,
-0x0A,0x02,0x82,0x01,0x01,0x00,0xA6,0xCF,0x24,0x0E,0xBE,0x2E,0x6F,0x28,0x99,0x45,
-0x42,0xC4,0xAB,0x3E,0x21,0x54,0x9B,0x0B,0xD3,0x7F,0x84,0x70,0xFA,0x12,0xB3,0xCB,
-0xBF,0x87,0x5F,0xC6,0x7F,0x86,0xD3,0xB2,0x30,0x5C,0xD6,0xFD,0xAD,0xF1,0x7B,0xDC,
-0xE5,0xF8,0x60,0x96,0x09,0x92,0x10,0xF5,0xD0,0x53,0xDE,0xFB,0x7B,0x7E,0x73,0x88,
-0xAC,0x52,0x88,0x7B,0x4A,0xA6,0xCA,0x49,0xA6,0x5E,0xA8,0xA7,0x8C,0x5A,0x11,0xBC,
-0x7A,0x82,0xEB,0xBE,0x8C,0xE9,0xB3,0xAC,0x96,0x25,0x07,0x97,0x4A,0x99,0x2A,0x07,
-0x2F,0xB4,0x1E,0x77,0xBF,0x8A,0x0F,0xB5,0x02,0x7C,0x1B,0x96,0xB8,0xC5,0xB9,0x3A,
-0x2C,0xBC,0xD6,0x12,0xB9,0xEB,0x59,0x7D,0xE2,0xD0,0x06,0x86,0x5F,0x5E,0x49,0x6A,
-0xB5,0x39,0x5E,0x88,0x34,0xEC,0xBC,0x78,0x0C,0x08,0x98,0x84,0x6C,0xA8,0xCD,0x4B,
-0xB4,0xA0,0x7D,0x0C,0x79,0x4D,0xF0,0xB8,0x2D,0xCB,0x21,0xCA,0xD5,0x6C,0x5B,0x7D,
-0xE1,0xA0,0x29,0x84,0xA1,0xF9,0xD3,0x94,0x49,0xCB,0x24,0x62,0x91,0x20,0xBC,0xDD,
-0x0B,0xD5,0xD9,0xCC,0xF9,0xEA,0x27,0x0A,0x2B,0x73,0x91,0xC6,0x9D,0x1B,0xAC,0xC8,
-0xCB,0xE8,0xE0,0xA0,0xF4,0x2F,0x90,0x8B,0x4D,0xFB,0xB0,0x36,0x1B,0xF6,0x19,0x7A,
-0x85,0xE0,0x6D,0xF2,0x61,0x13,0x88,0x5C,0x9F,0xE0,0x93,0x0A,0x51,0x97,0x8A,0x5A,
-0xCE,0xAF,0xAB,0xD5,0xF7,0xAA,0x09,0xAA,0x60,0xBD,0xDC,0xD9,0x5F,0xDF,0x72,0xA9,
-0x60,0x13,0x5E,0x00,0x01,0xC9,0x4A,0xFA,0x3F,0xA4,0xEA,0x07,0x03,0x21,0x02,0x8E,
-0x82,0xCA,0x03,0xC2,0x9B,0x8F,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0x9C,0x30,0x81,
-0x99,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,
-0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,
-0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x9B,0xE2,0x07,
-0x57,0x67,0x1C,0x1E,0xC0,0x6A,0x06,0xDE,0x59,0xB4,0x9A,0x2D,0xDF,0xDC,0x19,0x86,
-0x2E,0x30,0x36,0x06,0x03,0x55,0x1D,0x1F,0x04,0x2F,0x30,0x2D,0x30,0x2B,0xA0,0x29,
-0xA0,0x27,0x86,0x25,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x67,
-0x6C,0x6F,0x62,0x61,0x6C,0x73,0x69,0x67,0x6E,0x2E,0x6E,0x65,0x74,0x2F,0x72,0x6F,
-0x6F,0x74,0x2D,0x72,0x32,0x2E,0x63,0x72,0x6C,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,
-0x04,0x18,0x30,0x16,0x80,0x14,0x9B,0xE2,0x07,0x57,0x67,0x1C,0x1E,0xC0,0x6A,0x06,
-0xDE,0x59,0xB4,0x9A,0x2D,0xDF,0xDC,0x19,0x86,0x2E,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x99,0x81,
-0x53,0x87,0x1C,0x68,0x97,0x86,0x91,0xEC,0xE0,0x4A,0xB8,0x44,0x0B,0xAB,0x81,0xAC,
-0x27,0x4F,0xD6,0xC1,0xB8,0x1C,0x43,0x78,0xB3,0x0C,0x9A,0xFC,0xEA,0x2C,0x3C,0x6E,
-0x61,0x1B,0x4D,0x4B,0x29,0xF5,0x9F,0x05,0x1D,0x26,0xC1,0xB8,0xE9,0x83,0x00,0x62,
-0x45,0xB6,0xA9,0x08,0x93,0xB9,0xA9,0x33,0x4B,0x18,0x9A,0xC2,0xF8,0x87,0x88,0x4E,
-0xDB,0xDD,0x71,0x34,0x1A,0xC1,0x54,0xDA,0x46,0x3F,0xE0,0xD3,0x2A,0xAB,0x6D,0x54,
-0x22,0xF5,0x3A,0x62,0xCD,0x20,0x6F,0xBA,0x29,0x89,0xD7,0xDD,0x91,0xEE,0xD3,0x5C,
-0xA2,0x3E,0xA1,0x5B,0x41,0xF5,0xDF,0xE5,0x64,0x43,0x2D,0xE9,0xD5,0x39,0xAB,0xD2,
-0xA2,0xDF,0xB7,0x8B,0xD0,0xC0,0x80,0x19,0x1C,0x45,0xC0,0x2D,0x8C,0xE8,0xF8,0x2D,
-0xA4,0x74,0x56,0x49,0xC5,0x05,0xB5,0x4F,0x15,0xDE,0x6E,0x44,0x78,0x39,0x87,0xA8,
-0x7E,0xBB,0xF3,0x79,0x18,0x91,0xBB,0xF4,0x6F,0x9D,0xC1,0xF0,0x8C,0x35,0x8C,0x5D,
-0x01,0xFB,0xC3,0x6D,0xB9,0xEF,0x44,0x6D,0x79,0x46,0x31,0x7E,0x0A,0xFE,0xA9,0x82,
-0xC1,0xFF,0xEF,0xAB,0x6E,0x20,0xC4,0x50,0xC9,0x5F,0x9D,0x4D,0x9B,0x17,0x8C,0x0C,
-0xE5,0x01,0xC9,0xA0,0x41,0x6A,0x73,0x53,0xFA,0xA5,0x50,0xB4,0x6E,0x25,0x0F,0xFB,
-0x4C,0x18,0xF4,0xFD,0x52,0xD9,0x8E,0x69,0xB1,0xE8,0x11,0x0F,0xDE,0x88,0xD8,0xFB,
-0x1D,0x49,0xF7,0xAA,0xDE,0x95,0xCF,0x20,0x78,0xC2,0x60,0x12,0xDB,0x25,0x40,0x8C,
-0x6A,0xFC,0x7E,0x42,0x38,0x40,0x64,0x12,0xF7,0x9E,0x81,0xE1,0x93,0x2E,
-};
-
-
-/* subject:/OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign */
-/* issuer :/OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign */
-
-
-const unsigned char GlobalSign_Root_CA___R3_certificate[867]={
-0x30,0x82,0x03,0x5F,0x30,0x82,0x02,0x47,0xA0,0x03,0x02,0x01,0x02,0x02,0x0B,0x04,
-0x00,0x00,0x00,0x00,0x01,0x21,0x58,0x53,0x08,0xA2,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,0x4C,0x31,0x20,0x30,0x1E,0x06,
-0x03,0x55,0x04,0x0B,0x13,0x17,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,
-0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x20,0x2D,0x20,0x52,0x33,0x31,0x13,0x30,
-0x11,0x06,0x03,0x55,0x04,0x0A,0x13,0x0A,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,
-0x67,0x6E,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x03,0x13,0x0A,0x47,0x6C,0x6F,
-0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,0x30,0x1E,0x17,0x0D,0x30,0x39,0x30,0x33,0x31,
-0x38,0x31,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x39,0x30,0x33,0x31,0x38,
-0x31,0x30,0x30,0x30,0x30,0x30,0x5A,0x30,0x4C,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x17,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,0x20,0x52,
-0x6F,0x6F,0x74,0x20,0x43,0x41,0x20,0x2D,0x20,0x52,0x33,0x31,0x13,0x30,0x11,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0A,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x53,0x69,0x67,0x6E,
-0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x03,0x13,0x0A,0x47,0x6C,0x6F,0x62,0x61,
-0x6C,0x53,0x69,0x67,0x6E,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,
-0x0A,0x02,0x82,0x01,0x01,0x00,0xCC,0x25,0x76,0x90,0x79,0x06,0x78,0x22,0x16,0xF5,
-0xC0,0x83,0xB6,0x84,0xCA,0x28,0x9E,0xFD,0x05,0x76,0x11,0xC5,0xAD,0x88,0x72,0xFC,
-0x46,0x02,0x43,0xC7,0xB2,0x8A,0x9D,0x04,0x5F,0x24,0xCB,0x2E,0x4B,0xE1,0x60,0x82,
-0x46,0xE1,0x52,0xAB,0x0C,0x81,0x47,0x70,0x6C,0xDD,0x64,0xD1,0xEB,0xF5,0x2C,0xA3,
-0x0F,0x82,0x3D,0x0C,0x2B,0xAE,0x97,0xD7,0xB6,0x14,0x86,0x10,0x79,0xBB,0x3B,0x13,
-0x80,0x77,0x8C,0x08,0xE1,0x49,0xD2,0x6A,0x62,0x2F,0x1F,0x5E,0xFA,0x96,0x68,0xDF,
-0x89,0x27,0x95,0x38,0x9F,0x06,0xD7,0x3E,0xC9,0xCB,0x26,0x59,0x0D,0x73,0xDE,0xB0,
-0xC8,0xE9,0x26,0x0E,0x83,0x15,0xC6,0xEF,0x5B,0x8B,0xD2,0x04,0x60,0xCA,0x49,0xA6,
-0x28,0xF6,0x69,0x3B,0xF6,0xCB,0xC8,0x28,0x91,0xE5,0x9D,0x8A,0x61,0x57,0x37,0xAC,
-0x74,0x14,0xDC,0x74,0xE0,0x3A,0xEE,0x72,0x2F,0x2E,0x9C,0xFB,0xD0,0xBB,0xBF,0xF5,
-0x3D,0x00,0xE1,0x06,0x33,0xE8,0x82,0x2B,0xAE,0x53,0xA6,0x3A,0x16,0x73,0x8C,0xDD,
-0x41,0x0E,0x20,0x3A,0xC0,0xB4,0xA7,0xA1,0xE9,0xB2,0x4F,0x90,0x2E,0x32,0x60,0xE9,
-0x57,0xCB,0xB9,0x04,0x92,0x68,0x68,0xE5,0x38,0x26,0x60,0x75,0xB2,0x9F,0x77,0xFF,
-0x91,0x14,0xEF,0xAE,0x20,0x49,0xFC,0xAD,0x40,0x15,0x48,0xD1,0x02,0x31,0x61,0x19,
-0x5E,0xB8,0x97,0xEF,0xAD,0x77,0xB7,0x64,0x9A,0x7A,0xBF,0x5F,0xC1,0x13,0xEF,0x9B,
-0x62,0xFB,0x0D,0x6C,0xE0,0x54,0x69,0x16,0xA9,0x03,0xDA,0x6E,0xE9,0x83,0x93,0x71,
-0x76,0xC6,0x69,0x85,0x82,0x17,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,
-0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,
-0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,
-0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x8F,0xF0,0x4B,0x7F,0xA8,
-0x2E,0x45,0x24,0xAE,0x4D,0x50,0xFA,0x63,0x9A,0x8B,0xDE,0xE2,0xDD,0x1B,0xBC,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,
-0x01,0x01,0x00,0x4B,0x40,0xDB,0xC0,0x50,0xAA,0xFE,0xC8,0x0C,0xEF,0xF7,0x96,0x54,
-0x45,0x49,0xBB,0x96,0x00,0x09,0x41,0xAC,0xB3,0x13,0x86,0x86,0x28,0x07,0x33,0xCA,
-0x6B,0xE6,0x74,0xB9,0xBA,0x00,0x2D,0xAE,0xA4,0x0A,0xD3,0xF5,0xF1,0xF1,0x0F,0x8A,
-0xBF,0x73,0x67,0x4A,0x83,0xC7,0x44,0x7B,0x78,0xE0,0xAF,0x6E,0x6C,0x6F,0x03,0x29,
-0x8E,0x33,0x39,0x45,0xC3,0x8E,0xE4,0xB9,0x57,0x6C,0xAA,0xFC,0x12,0x96,0xEC,0x53,
-0xC6,0x2D,0xE4,0x24,0x6C,0xB9,0x94,0x63,0xFB,0xDC,0x53,0x68,0x67,0x56,0x3E,0x83,
-0xB8,0xCF,0x35,0x21,0xC3,0xC9,0x68,0xFE,0xCE,0xDA,0xC2,0x53,0xAA,0xCC,0x90,0x8A,
-0xE9,0xF0,0x5D,0x46,0x8C,0x95,0xDD,0x7A,0x58,0x28,0x1A,0x2F,0x1D,0xDE,0xCD,0x00,
-0x37,0x41,0x8F,0xED,0x44,0x6D,0xD7,0x53,0x28,0x97,0x7E,0xF3,0x67,0x04,0x1E,0x15,
-0xD7,0x8A,0x96,0xB4,0xD3,0xDE,0x4C,0x27,0xA4,0x4C,0x1B,0x73,0x73,0x76,0xF4,0x17,
-0x99,0xC2,0x1F,0x7A,0x0E,0xE3,0x2D,0x08,0xAD,0x0A,0x1C,0x2C,0xFF,0x3C,0xAB,0x55,
-0x0E,0x0F,0x91,0x7E,0x36,0xEB,0xC3,0x57,0x49,0xBE,0xE1,0x2E,0x2D,0x7C,0x60,0x8B,
-0xC3,0x41,0x51,0x13,0x23,0x9D,0xCE,0xF7,0x32,0x6B,0x94,0x01,0xA8,0x99,0xE7,0x2C,
-0x33,0x1F,0x3A,0x3B,0x25,0xD2,0x86,0x40,0xCE,0x3B,0x2C,0x86,0x78,0xC9,0x61,0x2F,
-0x14,0xBA,0xEE,0xDB,0x55,0x6F,0xDF,0x84,0xEE,0x05,0x09,0x4D,0xBD,0x28,0xD8,0x72,
-0xCE,0xD3,0x62,0x50,0x65,0x1E,0xEB,0x92,0x97,0x83,0x31,0xD9,0xB3,0xB5,0xCA,0x47,
-0x58,0x3F,0x5F,
-};
-
-
-/* subject:/C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority */
-/* issuer :/C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority */
-
-
-const unsigned char Go_Daddy_Class_2_CA_certificate[1028]={
-0x30,0x82,0x04,0x00,0x30,0x82,0x02,0xE8,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x00,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x63,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x21,
-0x30,0x1F,0x06,0x03,0x55,0x04,0x0A,0x13,0x18,0x54,0x68,0x65,0x20,0x47,0x6F,0x20,
-0x44,0x61,0x64,0x64,0x79,0x20,0x47,0x72,0x6F,0x75,0x70,0x2C,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x31,0x30,0x2F,0x06,0x03,0x55,0x04,0x0B,0x13,0x28,0x47,0x6F,0x20,0x44,
-0x61,0x64,0x64,0x79,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x43,0x65,0x72,
-0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,
-0x72,0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x34,0x30,0x36,0x32,0x39,0x31,0x37,
-0x30,0x36,0x32,0x30,0x5A,0x17,0x0D,0x33,0x34,0x30,0x36,0x32,0x39,0x31,0x37,0x30,
-0x36,0x32,0x30,0x5A,0x30,0x63,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x55,0x53,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x0A,0x13,0x18,0x54,0x68,
-0x65,0x20,0x47,0x6F,0x20,0x44,0x61,0x64,0x64,0x79,0x20,0x47,0x72,0x6F,0x75,0x70,
-0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x31,0x30,0x2F,0x06,0x03,0x55,0x04,0x0B,0x13,
-0x28,0x47,0x6F,0x20,0x44,0x61,0x64,0x64,0x79,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,
-0x32,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,
-0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x82,0x01,0x20,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0D,
-0x00,0x30,0x82,0x01,0x08,0x02,0x82,0x01,0x01,0x00,0xDE,0x9D,0xD7,0xEA,0x57,0x18,
-0x49,0xA1,0x5B,0xEB,0xD7,0x5F,0x48,0x86,0xEA,0xBE,0xDD,0xFF,0xE4,0xEF,0x67,0x1C,
-0xF4,0x65,0x68,0xB3,0x57,0x71,0xA0,0x5E,0x77,0xBB,0xED,0x9B,0x49,0xE9,0x70,0x80,
-0x3D,0x56,0x18,0x63,0x08,0x6F,0xDA,0xF2,0xCC,0xD0,0x3F,0x7F,0x02,0x54,0x22,0x54,
-0x10,0xD8,0xB2,0x81,0xD4,0xC0,0x75,0x3D,0x4B,0x7F,0xC7,0x77,0xC3,0x3E,0x78,0xAB,
-0x1A,0x03,0xB5,0x20,0x6B,0x2F,0x6A,0x2B,0xB1,0xC5,0x88,0x7E,0xC4,0xBB,0x1E,0xB0,
-0xC1,0xD8,0x45,0x27,0x6F,0xAA,0x37,0x58,0xF7,0x87,0x26,0xD7,0xD8,0x2D,0xF6,0xA9,
-0x17,0xB7,0x1F,0x72,0x36,0x4E,0xA6,0x17,0x3F,0x65,0x98,0x92,0xDB,0x2A,0x6E,0x5D,
-0xA2,0xFE,0x88,0xE0,0x0B,0xDE,0x7F,0xE5,0x8D,0x15,0xE1,0xEB,0xCB,0x3A,0xD5,0xE2,
-0x12,0xA2,0x13,0x2D,0xD8,0x8E,0xAF,0x5F,0x12,0x3D,0xA0,0x08,0x05,0x08,0xB6,0x5C,
-0xA5,0x65,0x38,0x04,0x45,0x99,0x1E,0xA3,0x60,0x60,0x74,0xC5,0x41,0xA5,0x72,0x62,
-0x1B,0x62,0xC5,0x1F,0x6F,0x5F,0x1A,0x42,0xBE,0x02,0x51,0x65,0xA8,0xAE,0x23,0x18,
-0x6A,0xFC,0x78,0x03,0xA9,0x4D,0x7F,0x80,0xC3,0xFA,0xAB,0x5A,0xFC,0xA1,0x40,0xA4,
-0xCA,0x19,0x16,0xFE,0xB2,0xC8,0xEF,0x5E,0x73,0x0D,0xEE,0x77,0xBD,0x9A,0xF6,0x79,
-0x98,0xBC,0xB1,0x07,0x67,0xA2,0x15,0x0D,0xDD,0xA0,0x58,0xC6,0x44,0x7B,0x0A,0x3E,
-0x62,0x28,0x5F,0xBA,0x41,0x07,0x53,0x58,0xCF,0x11,0x7E,0x38,0x74,0xC5,0xF8,0xFF,
-0xB5,0x69,0x90,0x8F,0x84,0x74,0xEA,0x97,0x1B,0xAF,0x02,0x01,0x03,0xA3,0x81,0xC0,
-0x30,0x81,0xBD,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xD2,0xC4,
-0xB0,0xD2,0x91,0xD4,0x4C,0x11,0x71,0xB3,0x61,0xCB,0x3D,0xA1,0xFE,0xDD,0xA8,0x6A,
-0xD4,0xE3,0x30,0x81,0x8D,0x06,0x03,0x55,0x1D,0x23,0x04,0x81,0x85,0x30,0x81,0x82,
-0x80,0x14,0xD2,0xC4,0xB0,0xD2,0x91,0xD4,0x4C,0x11,0x71,0xB3,0x61,0xCB,0x3D,0xA1,
-0xFE,0xDD,0xA8,0x6A,0xD4,0xE3,0xA1,0x67,0xA4,0x65,0x30,0x63,0x31,0x0B,0x30,0x09,
-0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,
-0x04,0x0A,0x13,0x18,0x54,0x68,0x65,0x20,0x47,0x6F,0x20,0x44,0x61,0x64,0x64,0x79,
-0x20,0x47,0x72,0x6F,0x75,0x70,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x31,0x30,0x2F,
-0x06,0x03,0x55,0x04,0x0B,0x13,0x28,0x47,0x6F,0x20,0x44,0x61,0x64,0x64,0x79,0x20,
-0x43,0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,
-0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x82,
-0x01,0x00,0x30,0x0C,0x06,0x03,0x55,0x1D,0x13,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,
-0x82,0x01,0x01,0x00,0x32,0x4B,0xF3,0xB2,0xCA,0x3E,0x91,0xFC,0x12,0xC6,0xA1,0x07,
-0x8C,0x8E,0x77,0xA0,0x33,0x06,0x14,0x5C,0x90,0x1E,0x18,0xF7,0x08,0xA6,0x3D,0x0A,
-0x19,0xF9,0x87,0x80,0x11,0x6E,0x69,0xE4,0x96,0x17,0x30,0xFF,0x34,0x91,0x63,0x72,
-0x38,0xEE,0xCC,0x1C,0x01,0xA3,0x1D,0x94,0x28,0xA4,0x31,0xF6,0x7A,0xC4,0x54,0xD7,
-0xF6,0xE5,0x31,0x58,0x03,0xA2,0xCC,0xCE,0x62,0xDB,0x94,0x45,0x73,0xB5,0xBF,0x45,
-0xC9,0x24,0xB5,0xD5,0x82,0x02,0xAD,0x23,0x79,0x69,0x8D,0xB8,0xB6,0x4D,0xCE,0xCF,
-0x4C,0xCA,0x33,0x23,0xE8,0x1C,0x88,0xAA,0x9D,0x8B,0x41,0x6E,0x16,0xC9,0x20,0xE5,
-0x89,0x9E,0xCD,0x3B,0xDA,0x70,0xF7,0x7E,0x99,0x26,0x20,0x14,0x54,0x25,0xAB,0x6E,
-0x73,0x85,0xE6,0x9B,0x21,0x9D,0x0A,0x6C,0x82,0x0E,0xA8,0xF8,0xC2,0x0C,0xFA,0x10,
-0x1E,0x6C,0x96,0xEF,0x87,0x0D,0xC4,0x0F,0x61,0x8B,0xAD,0xEE,0x83,0x2B,0x95,0xF8,
-0x8E,0x92,0x84,0x72,0x39,0xEB,0x20,0xEA,0x83,0xED,0x83,0xCD,0x97,0x6E,0x08,0xBC,
-0xEB,0x4E,0x26,0xB6,0x73,0x2B,0xE4,0xD3,0xF6,0x4C,0xFE,0x26,0x71,0xE2,0x61,0x11,
-0x74,0x4A,0xFF,0x57,0x1A,0x87,0x0F,0x75,0x48,0x2E,0xCF,0x51,0x69,0x17,0xA0,0x02,
-0x12,0x61,0x95,0xD5,0xD1,0x40,0xB2,0x10,0x4C,0xEE,0xC4,0xAC,0x10,0x43,0xA6,0xA5,
-0x9E,0x0A,0xD5,0x95,0x62,0x9A,0x0D,0xCF,0x88,0x82,0xC5,0x32,0x0C,0xE4,0x2B,0x9F,
-0x45,0xE6,0x0D,0x9F,0x28,0x9C,0xB1,0xB9,0x2A,0x5A,0x57,0xAD,0x37,0x0F,0xAF,0x1D,
-0x7F,0xDB,0xBD,0x9F,
-};
-
-
-/* subject:/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./CN=Go Daddy Root Certificate Authority - G2 */
-/* issuer :/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./CN=Go Daddy Root Certificate Authority - G2 */
-
-
-const unsigned char Go_Daddy_Root_Certificate_Authority___G2_certificate[969]={
-0x30,0x82,0x03,0xC5,0x30,0x82,0x02,0xAD,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x00,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,
-0x81,0x83,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,
-0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x08,0x13,0x07,0x41,0x72,0x69,0x7A,0x6F,0x6E,
-0x61,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x07,0x13,0x0A,0x53,0x63,0x6F,0x74,
-0x74,0x73,0x64,0x61,0x6C,0x65,0x31,0x1A,0x30,0x18,0x06,0x03,0x55,0x04,0x0A,0x13,
-0x11,0x47,0x6F,0x44,0x61,0x64,0x64,0x79,0x2E,0x63,0x6F,0x6D,0x2C,0x20,0x49,0x6E,
-0x63,0x2E,0x31,0x31,0x30,0x2F,0x06,0x03,0x55,0x04,0x03,0x13,0x28,0x47,0x6F,0x20,
-0x44,0x61,0x64,0x64,0x79,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,
-0x20,0x2D,0x20,0x47,0x32,0x30,0x1E,0x17,0x0D,0x30,0x39,0x30,0x39,0x30,0x31,0x30,
-0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x37,0x31,0x32,0x33,0x31,0x32,0x33,
-0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0x83,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x06,0x13,0x02,0x55,0x53,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x08,0x13,0x07,
-0x41,0x72,0x69,0x7A,0x6F,0x6E,0x61,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x07,
-0x13,0x0A,0x53,0x63,0x6F,0x74,0x74,0x73,0x64,0x61,0x6C,0x65,0x31,0x1A,0x30,0x18,
-0x06,0x03,0x55,0x04,0x0A,0x13,0x11,0x47,0x6F,0x44,0x61,0x64,0x64,0x79,0x2E,0x63,
-0x6F,0x6D,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x31,0x30,0x2F,0x06,0x03,0x55,0x04,
-0x03,0x13,0x28,0x47,0x6F,0x20,0x44,0x61,0x64,0x64,0x79,0x20,0x52,0x6F,0x6F,0x74,
-0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x2D,0x20,0x47,0x32,0x30,0x82,0x01,0x22,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,
-0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xBF,0x71,0x62,0x08,
-0xF1,0xFA,0x59,0x34,0xF7,0x1B,0xC9,0x18,0xA3,0xF7,0x80,0x49,0x58,0xE9,0x22,0x83,
-0x13,0xA6,0xC5,0x20,0x43,0x01,0x3B,0x84,0xF1,0xE6,0x85,0x49,0x9F,0x27,0xEA,0xF6,
-0x84,0x1B,0x4E,0xA0,0xB4,0xDB,0x70,0x98,0xC7,0x32,0x01,0xB1,0x05,0x3E,0x07,0x4E,
-0xEE,0xF4,0xFA,0x4F,0x2F,0x59,0x30,0x22,0xE7,0xAB,0x19,0x56,0x6B,0xE2,0x80,0x07,
-0xFC,0xF3,0x16,0x75,0x80,0x39,0x51,0x7B,0xE5,0xF9,0x35,0xB6,0x74,0x4E,0xA9,0x8D,
-0x82,0x13,0xE4,0xB6,0x3F,0xA9,0x03,0x83,0xFA,0xA2,0xBE,0x8A,0x15,0x6A,0x7F,0xDE,
-0x0B,0xC3,0xB6,0x19,0x14,0x05,0xCA,0xEA,0xC3,0xA8,0x04,0x94,0x3B,0x46,0x7C,0x32,
-0x0D,0xF3,0x00,0x66,0x22,0xC8,0x8D,0x69,0x6D,0x36,0x8C,0x11,0x18,0xB7,0xD3,0xB2,
-0x1C,0x60,0xB4,0x38,0xFA,0x02,0x8C,0xCE,0xD3,0xDD,0x46,0x07,0xDE,0x0A,0x3E,0xEB,
-0x5D,0x7C,0xC8,0x7C,0xFB,0xB0,0x2B,0x53,0xA4,0x92,0x62,0x69,0x51,0x25,0x05,0x61,
-0x1A,0x44,0x81,0x8C,0x2C,0xA9,0x43,0x96,0x23,0xDF,0xAC,0x3A,0x81,0x9A,0x0E,0x29,
-0xC5,0x1C,0xA9,0xE9,0x5D,0x1E,0xB6,0x9E,0x9E,0x30,0x0A,0x39,0xCE,0xF1,0x88,0x80,
-0xFB,0x4B,0x5D,0xCC,0x32,0xEC,0x85,0x62,0x43,0x25,0x34,0x02,0x56,0x27,0x01,0x91,
-0xB4,0x3B,0x70,0x2A,0x3F,0x6E,0xB1,0xE8,0x9C,0x88,0x01,0x7D,0x9F,0xD4,0xF9,0xDB,
-0x53,0x6D,0x60,0x9D,0xBF,0x2C,0xE7,0x58,0xAB,0xB8,0x5F,0x46,0xFC,0xCE,0xC4,0x1B,
-0x03,0x3C,0x09,0xEB,0x49,0x31,0x5C,0x69,0x46,0xB3,0xE0,0x47,0x02,0x03,0x01,0x00,
-0x01,0xA3,0x42,0x30,0x40,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,
-0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,
-0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,
-0x14,0x3A,0x9A,0x85,0x07,0x10,0x67,0x28,0xB6,0xEF,0xF6,0xBD,0x05,0x41,0x6E,0x20,
-0xC1,0x94,0xDA,0x0F,0xDE,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,
-0x01,0x0B,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x99,0xDB,0x5D,0x79,0xD5,0xF9,0x97,
-0x59,0x67,0x03,0x61,0xF1,0x7E,0x3B,0x06,0x31,0x75,0x2D,0xA1,0x20,0x8E,0x4F,0x65,
-0x87,0xB4,0xF7,0xA6,0x9C,0xBC,0xD8,0xE9,0x2F,0xD0,0xDB,0x5A,0xEE,0xCF,0x74,0x8C,
-0x73,0xB4,0x38,0x42,0xDA,0x05,0x7B,0xF8,0x02,0x75,0xB8,0xFD,0xA5,0xB1,0xD7,0xAE,
-0xF6,0xD7,0xDE,0x13,0xCB,0x53,0x10,0x7E,0x8A,0x46,0xD1,0x97,0xFA,0xB7,0x2E,0x2B,
-0x11,0xAB,0x90,0xB0,0x27,0x80,0xF9,0xE8,0x9F,0x5A,0xE9,0x37,0x9F,0xAB,0xE4,0xDF,
-0x6C,0xB3,0x85,0x17,0x9D,0x3D,0xD9,0x24,0x4F,0x79,0x91,0x35,0xD6,0x5F,0x04,0xEB,
-0x80,0x83,0xAB,0x9A,0x02,0x2D,0xB5,0x10,0xF4,0xD8,0x90,0xC7,0x04,0x73,0x40,0xED,
-0x72,0x25,0xA0,0xA9,0x9F,0xEC,0x9E,0xAB,0x68,0x12,0x99,0x57,0xC6,0x8F,0x12,0x3A,
-0x09,0xA4,0xBD,0x44,0xFD,0x06,0x15,0x37,0xC1,0x9B,0xE4,0x32,0xA3,0xED,0x38,0xE8,
-0xD8,0x64,0xF3,0x2C,0x7E,0x14,0xFC,0x02,0xEA,0x9F,0xCD,0xFF,0x07,0x68,0x17,0xDB,
-0x22,0x90,0x38,0x2D,0x7A,0x8D,0xD1,0x54,0xF1,0x69,0xE3,0x5F,0x33,0xCA,0x7A,0x3D,
-0x7B,0x0A,0xE3,0xCA,0x7F,0x5F,0x39,0xE5,0xE2,0x75,0xBA,0xC5,0x76,0x18,0x33,0xCE,
-0x2C,0xF0,0x2F,0x4C,0xAD,0xF7,0xB1,0xE7,0xCE,0x4F,0xA8,0xC4,0x9B,0x4A,0x54,0x06,
-0xC5,0x7F,0x7D,0xD5,0x08,0x0F,0xE2,0x1C,0xFE,0x7E,0x17,0xB8,0xAC,0x5E,0xF6,0xD4,
-0x16,0xB2,0x43,0x09,0x0C,0x4D,0xF6,0xA7,0x6B,0xB4,0x99,0x84,0x65,0xCA,0x7A,0x88,
-0xE2,0xE2,0x44,0xBE,0x5C,0xF7,0xEA,0x1C,0xF5,
-};
-
-
-/* subject:/C=US/O=GTE Corporation/OU=GTE CyberTrust Solutions, Inc./CN=GTE CyberTrust Global Root */
-/* issuer :/C=US/O=GTE Corporation/OU=GTE CyberTrust Solutions, Inc./CN=GTE CyberTrust Global Root */
-
-
-const unsigned char GTE_CyberTrust_Global_Root_certificate[606]={
-0x30,0x82,0x02,0x5A,0x30,0x82,0x01,0xC3,0x02,0x02,0x01,0xA5,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,0x75,0x31,0x0B,0x30,
-0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x18,0x30,0x16,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x0F,0x47,0x54,0x45,0x20,0x43,0x6F,0x72,0x70,0x6F,0x72,0x61,
-0x74,0x69,0x6F,0x6E,0x31,0x27,0x30,0x25,0x06,0x03,0x55,0x04,0x0B,0x13,0x1E,0x47,
-0x54,0x45,0x20,0x43,0x79,0x62,0x65,0x72,0x54,0x72,0x75,0x73,0x74,0x20,0x53,0x6F,
-0x6C,0x75,0x74,0x69,0x6F,0x6E,0x73,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x23,0x30,
-0x21,0x06,0x03,0x55,0x04,0x03,0x13,0x1A,0x47,0x54,0x45,0x20,0x43,0x79,0x62,0x65,
-0x72,0x54,0x72,0x75,0x73,0x74,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x52,0x6F,
-0x6F,0x74,0x30,0x1E,0x17,0x0D,0x39,0x38,0x30,0x38,0x31,0x33,0x30,0x30,0x32,0x39,
-0x30,0x30,0x5A,0x17,0x0D,0x31,0x38,0x30,0x38,0x31,0x33,0x32,0x33,0x35,0x39,0x30,
-0x30,0x5A,0x30,0x75,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,
-0x53,0x31,0x18,0x30,0x16,0x06,0x03,0x55,0x04,0x0A,0x13,0x0F,0x47,0x54,0x45,0x20,
-0x43,0x6F,0x72,0x70,0x6F,0x72,0x61,0x74,0x69,0x6F,0x6E,0x31,0x27,0x30,0x25,0x06,
-0x03,0x55,0x04,0x0B,0x13,0x1E,0x47,0x54,0x45,0x20,0x43,0x79,0x62,0x65,0x72,0x54,
-0x72,0x75,0x73,0x74,0x20,0x53,0x6F,0x6C,0x75,0x74,0x69,0x6F,0x6E,0x73,0x2C,0x20,
-0x49,0x6E,0x63,0x2E,0x31,0x23,0x30,0x21,0x06,0x03,0x55,0x04,0x03,0x13,0x1A,0x47,
-0x54,0x45,0x20,0x43,0x79,0x62,0x65,0x72,0x54,0x72,0x75,0x73,0x74,0x20,0x47,0x6C,
-0x6F,0x62,0x61,0x6C,0x20,0x52,0x6F,0x6F,0x74,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,
-0x81,0x89,0x02,0x81,0x81,0x00,0x95,0x0F,0xA0,0xB6,0xF0,0x50,0x9C,0xE8,0x7A,0xC7,
-0x88,0xCD,0xDD,0x17,0x0E,0x2E,0xB0,0x94,0xD0,0x1B,0x3D,0x0E,0xF6,0x94,0xC0,0x8A,
-0x94,0xC7,0x06,0xC8,0x90,0x97,0xC8,0xB8,0x64,0x1A,0x7A,0x7E,0x6C,0x3C,0x53,0xE1,
-0x37,0x28,0x73,0x60,0x7F,0xB2,0x97,0x53,0x07,0x9F,0x53,0xF9,0x6D,0x58,0x94,0xD2,
-0xAF,0x8D,0x6D,0x88,0x67,0x80,0xE6,0xED,0xB2,0x95,0xCF,0x72,0x31,0xCA,0xA5,0x1C,
-0x72,0xBA,0x5C,0x02,0xE7,0x64,0x42,0xE7,0xF9,0xA9,0x2C,0xD6,0x3A,0x0D,0xAC,0x8D,
-0x42,0xAA,0x24,0x01,0x39,0xE6,0x9C,0x3F,0x01,0x85,0x57,0x0D,0x58,0x87,0x45,0xF8,
-0xD3,0x85,0xAA,0x93,0x69,0x26,0x85,0x70,0x48,0x80,0x3F,0x12,0x15,0xC7,0x79,0xB4,
-0x1F,0x05,0x2F,0x3B,0x62,0x99,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,
-0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x6D,0xEB,
-0x1B,0x09,0xE9,0x5E,0xD9,0x51,0xDB,0x67,0x22,0x61,0xA4,0x2A,0x3C,0x48,0x77,0xE3,
-0xA0,0x7C,0xA6,0xDE,0x73,0xA2,0x14,0x03,0x85,0x3D,0xFB,0xAB,0x0E,0x30,0xC5,0x83,
-0x16,0x33,0x81,0x13,0x08,0x9E,0x7B,0x34,0x4E,0xDF,0x40,0xC8,0x74,0xD7,0xB9,0x7D,
-0xDC,0xF4,0x76,0x55,0x7D,0x9B,0x63,0x54,0x18,0xE9,0xF0,0xEA,0xF3,0x5C,0xB1,0xD9,
-0x8B,0x42,0x1E,0xB9,0xC0,0x95,0x4E,0xBA,0xFA,0xD5,0xE2,0x7C,0xF5,0x68,0x61,0xBF,
-0x8E,0xEC,0x05,0x97,0x5F,0x5B,0xB0,0xD7,0xA3,0x85,0x34,0xC4,0x24,0xA7,0x0D,0x0F,
-0x95,0x93,0xEF,0xCB,0x94,0xD8,0x9E,0x1F,0x9D,0x5C,0x85,0x6D,0xC7,0xAA,0xAE,0x4F,
-0x1F,0x22,0xB5,0xCD,0x95,0xAD,0xBA,0xA7,0xCC,0xF9,0xAB,0x0B,0x7A,0x7F,
-};
-
-
-/* subject:/C=US/O=Network Solutions L.L.C./CN=Network Solutions Certificate Authority */
-/* issuer :/C=US/O=Network Solutions L.L.C./CN=Network Solutions Certificate Authority */
-
-
-const unsigned char Network_Solutions_Certificate_Authority_certificate[1002]={
-0x30,0x82,0x03,0xE6,0x30,0x82,0x02,0xCE,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x57,
-0xCB,0x33,0x6F,0xC2,0x5C,0x16,0xE6,0x47,0x16,0x17,0xE3,0x90,0x31,0x68,0xE0,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x62,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x21,0x30,
-0x1F,0x06,0x03,0x55,0x04,0x0A,0x13,0x18,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x20,
-0x53,0x6F,0x6C,0x75,0x74,0x69,0x6F,0x6E,0x73,0x20,0x4C,0x2E,0x4C,0x2E,0x43,0x2E,
-0x31,0x30,0x30,0x2E,0x06,0x03,0x55,0x04,0x03,0x13,0x27,0x4E,0x65,0x74,0x77,0x6F,
-0x72,0x6B,0x20,0x53,0x6F,0x6C,0x75,0x74,0x69,0x6F,0x6E,0x73,0x20,0x43,0x65,0x72,
-0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x36,0x31,0x32,0x30,0x31,0x30,0x30,0x30,0x30,
-0x30,0x30,0x5A,0x17,0x0D,0x32,0x39,0x31,0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,
-0x39,0x5A,0x30,0x62,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,
-0x53,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x0A,0x13,0x18,0x4E,0x65,0x74,0x77,
-0x6F,0x72,0x6B,0x20,0x53,0x6F,0x6C,0x75,0x74,0x69,0x6F,0x6E,0x73,0x20,0x4C,0x2E,
-0x4C,0x2E,0x43,0x2E,0x31,0x30,0x30,0x2E,0x06,0x03,0x55,0x04,0x03,0x13,0x27,0x4E,
-0x65,0x74,0x77,0x6F,0x72,0x6B,0x20,0x53,0x6F,0x6C,0x75,0x74,0x69,0x6F,0x6E,0x73,
-0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,
-0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xE4,0xBC,0x7E,0x92,0x30,0x6D,0xC6,0xD8,0x8E,
-0x2B,0x0B,0xBC,0x46,0xCE,0xE0,0x27,0x96,0xDE,0xDE,0xF9,0xFA,0x12,0xD3,0x3C,0x33,
-0x73,0xB3,0x04,0x2F,0xBC,0x71,0x8C,0xE5,0x9F,0xB6,0x22,0x60,0x3E,0x5F,0x5D,0xCE,
-0x09,0xFF,0x82,0x0C,0x1B,0x9A,0x51,0x50,0x1A,0x26,0x89,0xDD,0xD5,0x61,0x5D,0x19,
-0xDC,0x12,0x0F,0x2D,0x0A,0xA2,0x43,0x5D,0x17,0xD0,0x34,0x92,0x20,0xEA,0x73,0xCF,
-0x38,0x2C,0x06,0x26,0x09,0x7A,0x72,0xF7,0xFA,0x50,0x32,0xF8,0xC2,0x93,0xD3,0x69,
-0xA2,0x23,0xCE,0x41,0xB1,0xCC,0xE4,0xD5,0x1F,0x36,0xD1,0x8A,0x3A,0xF8,0x8C,0x63,
-0xE2,0x14,0x59,0x69,0xED,0x0D,0xD3,0x7F,0x6B,0xE8,0xB8,0x03,0xE5,0x4F,0x6A,0xE5,
-0x98,0x63,0x69,0x48,0x05,0xBE,0x2E,0xFF,0x33,0xB6,0xE9,0x97,0x59,0x69,0xF8,0x67,
-0x19,0xAE,0x93,0x61,0x96,0x44,0x15,0xD3,0x72,0xB0,0x3F,0xBC,0x6A,0x7D,0xEC,0x48,
-0x7F,0x8D,0xC3,0xAB,0xAA,0x71,0x2B,0x53,0x69,0x41,0x53,0x34,0xB5,0xB0,0xB9,0xC5,
-0x06,0x0A,0xC4,0xB0,0x45,0xF5,0x41,0x5D,0x6E,0x89,0x45,0x7B,0x3D,0x3B,0x26,0x8C,
-0x74,0xC2,0xE5,0xD2,0xD1,0x7D,0xB2,0x11,0xD4,0xFB,0x58,0x32,0x22,0x9A,0x80,0xC9,
-0xDC,0xFD,0x0C,0xE9,0x7F,0x5E,0x03,0x97,0xCE,0x3B,0x00,0x14,0x87,0x27,0x70,0x38,
-0xA9,0x8E,0x6E,0xB3,0x27,0x76,0x98,0x51,0xE0,0x05,0xE3,0x21,0xAB,0x1A,0xD5,0x85,
-0x22,0x3C,0x29,0xB5,0x9A,0x16,0xC5,0x80,0xA8,0xF4,0xBB,0x6B,0x30,0x8F,0x2F,0x46,
-0x02,0xA2,0xB1,0x0C,0x22,0xE0,0xD3,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0x97,0x30,
-0x81,0x94,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x21,0x30,0xC9,
-0xFB,0x00,0xD7,0x4E,0x98,0xDA,0x87,0xAA,0x2A,0xD0,0xA7,0x2E,0xB1,0x40,0x31,0xA7,
-0x4C,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,
-0x06,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,
-0x01,0xFF,0x30,0x52,0x06,0x03,0x55,0x1D,0x1F,0x04,0x4B,0x30,0x49,0x30,0x47,0xA0,
-0x45,0xA0,0x43,0x86,0x41,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,
-0x6E,0x65,0x74,0x73,0x6F,0x6C,0x73,0x73,0x6C,0x2E,0x63,0x6F,0x6D,0x2F,0x4E,0x65,
-0x74,0x77,0x6F,0x72,0x6B,0x53,0x6F,0x6C,0x75,0x74,0x69,0x6F,0x6E,0x73,0x43,0x65,
-0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x2E,0x63,0x72,0x6C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0xBB,0xAE,0x4B,0xE7,0xB7,0x57,
-0xEB,0x7F,0xAA,0x2D,0xB7,0x73,0x47,0x85,0x6A,0xC1,0xE4,0xA5,0x1D,0xE4,0xE7,0x3C,
-0xE9,0xF4,0x59,0x65,0x77,0xB5,0x7A,0x5B,0x5A,0x8D,0x25,0x36,0xE0,0x7A,0x97,0x2E,
-0x38,0xC0,0x57,0x60,0x83,0x98,0x06,0x83,0x9F,0xB9,0x76,0x7A,0x6E,0x50,0xE0,0xBA,
-0x88,0x2C,0xFC,0x45,0xCC,0x18,0xB0,0x99,0x95,0x51,0x0E,0xEC,0x1D,0xB8,0x88,0xFF,
-0x87,0x50,0x1C,0x82,0xC2,0xE3,0xE0,0x32,0x80,0xBF,0xA0,0x0B,0x47,0xC8,0xC3,0x31,
-0xEF,0x99,0x67,0x32,0x80,0x4F,0x17,0x21,0x79,0x0C,0x69,0x5C,0xDE,0x5E,0x34,0xAE,
-0x02,0xB5,0x26,0xEA,0x50,0xDF,0x7F,0x18,0x65,0x2C,0xC9,0xF2,0x63,0xE1,0xA9,0x07,
-0xFE,0x7C,0x71,0x1F,0x6B,0x33,0x24,0x6A,0x1E,0x05,0xF7,0x05,0x68,0xC0,0x6A,0x12,
-0xCB,0x2E,0x5E,0x61,0xCB,0xAE,0x28,0xD3,0x7E,0xC2,0xB4,0x66,0x91,0x26,0x5F,0x3C,
-0x2E,0x24,0x5F,0xCB,0x58,0x0F,0xEB,0x28,0xEC,0xAF,0x11,0x96,0xF3,0xDC,0x7B,0x6F,
-0xC0,0xA7,0x88,0xF2,0x53,0x77,0xB3,0x60,0x5E,0xAE,0xAE,0x28,0xDA,0x35,0x2C,0x6F,
-0x34,0x45,0xD3,0x26,0xE1,0xDE,0xEC,0x5B,0x4F,0x27,0x6B,0x16,0x7C,0xBD,0x44,0x04,
-0x18,0x82,0xB3,0x89,0x79,0x17,0x10,0x71,0x3D,0x7A,0xA2,0x16,0x4E,0xF5,0x01,0xCD,
-0xA4,0x6C,0x65,0x68,0xA1,0x49,0x76,0x5C,0x43,0xC9,0xD8,0xBC,0x36,0x67,0x6C,0xA5,
-0x94,0xB5,0xD4,0xCC,0xB9,0xBD,0x6A,0x35,0x56,0x21,0xDE,0xD8,0xC3,0xEB,0xFB,0xCB,
-0xA4,0x60,0x4C,0xB0,0x55,0xA0,0xA0,0x7B,0x57,0xB2,
-};
-
-
-/* subject:/L=ValiCert Validation Network/O=ValiCert, Inc./OU=ValiCert Class 3 Policy Validation Authority/CN=http://www.valicert.com//emailAddress=info@valicert.com */
-/* issuer :/L=ValiCert Validation Network/O=ValiCert, Inc./OU=ValiCert Class 3 Policy Validation Authority/CN=http://www.valicert.com//emailAddress=info@valicert.com */
-
-
-const unsigned char RSA_Root_Certificate_1_certificate[747]={
-0x30,0x82,0x02,0xE7,0x30,0x82,0x02,0x50,0x02,0x01,0x01,0x30,0x0D,0x06,0x09,0x2A,
-0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,0xBB,0x31,0x24,0x30,
-0x22,0x06,0x03,0x55,0x04,0x07,0x13,0x1B,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,
-0x20,0x56,0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x4E,0x65,0x74,0x77,
-0x6F,0x72,0x6B,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x61,
-0x6C,0x69,0x43,0x65,0x72,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x35,0x30,0x33,
-0x06,0x03,0x55,0x04,0x0B,0x13,0x2C,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,
-0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x6F,0x6C,0x69,0x63,0x79,0x20,0x56,
-0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x68,0x74,
-0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x61,0x6C,0x69,0x63,0x65,0x72,
-0x74,0x2E,0x63,0x6F,0x6D,0x2F,0x31,0x20,0x30,0x1E,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x09,0x01,0x16,0x11,0x69,0x6E,0x66,0x6F,0x40,0x76,0x61,0x6C,0x69,
-0x63,0x65,0x72,0x74,0x2E,0x63,0x6F,0x6D,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x36,
-0x32,0x36,0x30,0x30,0x32,0x32,0x33,0x33,0x5A,0x17,0x0D,0x31,0x39,0x30,0x36,0x32,
-0x36,0x30,0x30,0x32,0x32,0x33,0x33,0x5A,0x30,0x81,0xBB,0x31,0x24,0x30,0x22,0x06,
-0x03,0x55,0x04,0x07,0x13,0x1B,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,0x56,
-0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,
-0x6B,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x61,0x6C,0x69,
-0x43,0x65,0x72,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x35,0x30,0x33,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x2C,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,0x43,0x6C,
-0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x6F,0x6C,0x69,0x63,0x79,0x20,0x56,0x61,0x6C,
-0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,
-0x79,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x68,0x74,0x74,0x70,
-0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x61,0x6C,0x69,0x63,0x65,0x72,0x74,0x2E,
-0x63,0x6F,0x6D,0x2F,0x31,0x20,0x30,0x1E,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x09,0x01,0x16,0x11,0x69,0x6E,0x66,0x6F,0x40,0x76,0x61,0x6C,0x69,0x63,0x65,
-0x72,0x74,0x2E,0x63,0x6F,0x6D,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,0x02,
-0x81,0x81,0x00,0xE3,0x98,0x51,0x96,0x1C,0xE8,0xD5,0xB1,0x06,0x81,0x6A,0x57,0xC3,
-0x72,0x75,0x93,0xAB,0xCF,0x9E,0xA6,0xFC,0xF3,0x16,0x52,0xD6,0x2D,0x4D,0x9F,0x35,
-0x44,0xA8,0x2E,0x04,0x4D,0x07,0x49,0x8A,0x38,0x29,0xF5,0x77,0x37,0xE7,0xB7,0xAB,
-0x5D,0xDF,0x36,0x71,0x14,0x99,0x8F,0xDC,0xC2,0x92,0xF1,0xE7,0x60,0x92,0x97,0xEC,
-0xD8,0x48,0xDC,0xBF,0xC1,0x02,0x20,0xC6,0x24,0xA4,0x28,0x4C,0x30,0x5A,0x76,0x6D,
-0xB1,0x5C,0xF3,0xDD,0xDE,0x9E,0x10,0x71,0xA1,0x88,0xC7,0x5B,0x9B,0x41,0x6D,0xCA,
-0xB0,0xB8,0x8E,0x15,0xEE,0xAD,0x33,0x2B,0xCF,0x47,0x04,0x5C,0x75,0x71,0x0A,0x98,
-0x24,0x98,0x29,0xA7,0x49,0x59,0xA5,0xDD,0xF8,0xB7,0x43,0x62,0x61,0xF3,0xD3,0xE2,
-0xD0,0x55,0x3F,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x81,0x81,0x00,0x56,0xBB,0x02,0x58,0x84,
-0x67,0x08,0x2C,0xDF,0x1F,0xDB,0x7B,0x49,0x33,0xF5,0xD3,0x67,0x9D,0xF4,0xB4,0x0A,
-0x10,0xB3,0xC9,0xC5,0x2C,0xE2,0x92,0x6A,0x71,0x78,0x27,0xF2,0x70,0x83,0x42,0xD3,
-0x3E,0xCF,0xA9,0x54,0xF4,0xF1,0xD8,0x92,0x16,0x8C,0xD1,0x04,0xCB,0x4B,0xAB,0xC9,
-0x9F,0x45,0xAE,0x3C,0x8A,0xA9,0xB0,0x71,0x33,0x5D,0xC8,0xC5,0x57,0xDF,0xAF,0xA8,
-0x35,0xB3,0x7F,0x89,0x87,0xE9,0xE8,0x25,0x92,0xB8,0x7F,0x85,0x7A,0xAE,0xD6,0xBC,
-0x1E,0x37,0x58,0x2A,0x67,0xC9,0x91,0xCF,0x2A,0x81,0x3E,0xED,0xC6,0x39,0xDF,0xC0,
-0x3E,0x19,0x9C,0x19,0xCC,0x13,0x4D,0x82,0x41,0xB5,0x8C,0xDE,0xE0,0x3D,0x60,0x08,
-0x20,0x0F,0x45,0x7E,0x6B,0xA2,0x7F,0xA3,0x8C,0x15,0xEE,
-};
-
-
-/* subject:/C=US/O=Starfield Technologies, Inc./OU=Starfield Class 2 Certification Authority */
-/* issuer :/C=US/O=Starfield Technologies, Inc./OU=Starfield Class 2 Certification Authority */
-
-
-const unsigned char Starfield_Class_2_CA_certificate[1043]={
-0x30,0x82,0x04,0x0F,0x30,0x82,0x02,0xF7,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x00,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,
-0x68,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x25,
-0x30,0x23,0x06,0x03,0x55,0x04,0x0A,0x13,0x1C,0x53,0x74,0x61,0x72,0x66,0x69,0x65,
-0x6C,0x64,0x20,0x54,0x65,0x63,0x68,0x6E,0x6F,0x6C,0x6F,0x67,0x69,0x65,0x73,0x2C,
-0x20,0x49,0x6E,0x63,0x2E,0x31,0x32,0x30,0x30,0x06,0x03,0x55,0x04,0x0B,0x13,0x29,
-0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,
-0x32,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,
-0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x34,0x30,
-0x36,0x32,0x39,0x31,0x37,0x33,0x39,0x31,0x36,0x5A,0x17,0x0D,0x33,0x34,0x30,0x36,
-0x32,0x39,0x31,0x37,0x33,0x39,0x31,0x36,0x5A,0x30,0x68,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x1C,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x54,0x65,0x63,
-0x68,0x6E,0x6F,0x6C,0x6F,0x67,0x69,0x65,0x73,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,
-0x32,0x30,0x30,0x06,0x03,0x55,0x04,0x0B,0x13,0x29,0x53,0x74,0x61,0x72,0x66,0x69,
-0x65,0x6C,0x64,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x30,0x82,0x01,0x20,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0D,0x00,0x30,0x82,0x01,0x08,0x02,
-0x82,0x01,0x01,0x00,0xB7,0x32,0xC8,0xFE,0xE9,0x71,0xA6,0x04,0x85,0xAD,0x0C,0x11,
-0x64,0xDF,0xCE,0x4D,0xEF,0xC8,0x03,0x18,0x87,0x3F,0xA1,0xAB,0xFB,0x3C,0xA6,0x9F,
-0xF0,0xC3,0xA1,0xDA,0xD4,0xD8,0x6E,0x2B,0x53,0x90,0xFB,0x24,0xA4,0x3E,0x84,0xF0,
-0x9E,0xE8,0x5F,0xEC,0xE5,0x27,0x44,0xF5,0x28,0xA6,0x3F,0x7B,0xDE,0xE0,0x2A,0xF0,
-0xC8,0xAF,0x53,0x2F,0x9E,0xCA,0x05,0x01,0x93,0x1E,0x8F,0x66,0x1C,0x39,0xA7,0x4D,
-0xFA,0x5A,0xB6,0x73,0x04,0x25,0x66,0xEB,0x77,0x7F,0xE7,0x59,0xC6,0x4A,0x99,0x25,
-0x14,0x54,0xEB,0x26,0xC7,0xF3,0x7F,0x19,0xD5,0x30,0x70,0x8F,0xAF,0xB0,0x46,0x2A,
-0xFF,0xAD,0xEB,0x29,0xED,0xD7,0x9F,0xAA,0x04,0x87,0xA3,0xD4,0xF9,0x89,0xA5,0x34,
-0x5F,0xDB,0x43,0x91,0x82,0x36,0xD9,0x66,0x3C,0xB1,0xB8,0xB9,0x82,0xFD,0x9C,0x3A,
-0x3E,0x10,0xC8,0x3B,0xEF,0x06,0x65,0x66,0x7A,0x9B,0x19,0x18,0x3D,0xFF,0x71,0x51,
-0x3C,0x30,0x2E,0x5F,0xBE,0x3D,0x77,0x73,0xB2,0x5D,0x06,0x6C,0xC3,0x23,0x56,0x9A,
-0x2B,0x85,0x26,0x92,0x1C,0xA7,0x02,0xB3,0xE4,0x3F,0x0D,0xAF,0x08,0x79,0x82,0xB8,
-0x36,0x3D,0xEA,0x9C,0xD3,0x35,0xB3,0xBC,0x69,0xCA,0xF5,0xCC,0x9D,0xE8,0xFD,0x64,
-0x8D,0x17,0x80,0x33,0x6E,0x5E,0x4A,0x5D,0x99,0xC9,0x1E,0x87,0xB4,0x9D,0x1A,0xC0,
-0xD5,0x6E,0x13,0x35,0x23,0x5E,0xDF,0x9B,0x5F,0x3D,0xEF,0xD6,0xF7,0x76,0xC2,0xEA,
-0x3E,0xBB,0x78,0x0D,0x1C,0x42,0x67,0x6B,0x04,0xD8,0xF8,0xD6,0xDA,0x6F,0x8B,0xF2,
-0x44,0xA0,0x01,0xAB,0x02,0x01,0x03,0xA3,0x81,0xC5,0x30,0x81,0xC2,0x30,0x1D,0x06,
-0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xBF,0x5F,0xB7,0xD1,0xCE,0xDD,0x1F,0x86,
-0xF4,0x5B,0x55,0xAC,0xDC,0xD7,0x10,0xC2,0x0E,0xA9,0x88,0xE7,0x30,0x81,0x92,0x06,
-0x03,0x55,0x1D,0x23,0x04,0x81,0x8A,0x30,0x81,0x87,0x80,0x14,0xBF,0x5F,0xB7,0xD1,
-0xCE,0xDD,0x1F,0x86,0xF4,0x5B,0x55,0xAC,0xDC,0xD7,0x10,0xC2,0x0E,0xA9,0x88,0xE7,
-0xA1,0x6C,0xA4,0x6A,0x30,0x68,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x55,0x53,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x0A,0x13,0x1C,0x53,0x74,
-0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x54,0x65,0x63,0x68,0x6E,0x6F,0x6C,0x6F,
-0x67,0x69,0x65,0x73,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x32,0x30,0x30,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x29,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x43,
-0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,
-0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x82,0x01,
-0x00,0x30,0x0C,0x06,0x03,0x55,0x1D,0x13,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,
-0x01,0x01,0x00,0x05,0x9D,0x3F,0x88,0x9D,0xD1,0xC9,0x1A,0x55,0xA1,0xAC,0x69,0xF3,
-0xF3,0x59,0xDA,0x9B,0x01,0x87,0x1A,0x4F,0x57,0xA9,0xA1,0x79,0x09,0x2A,0xDB,0xF7,
-0x2F,0xB2,0x1E,0xCC,0xC7,0x5E,0x6A,0xD8,0x83,0x87,0xA1,0x97,0xEF,0x49,0x35,0x3E,
-0x77,0x06,0x41,0x58,0x62,0xBF,0x8E,0x58,0xB8,0x0A,0x67,0x3F,0xEC,0xB3,0xDD,0x21,
-0x66,0x1F,0xC9,0x54,0xFA,0x72,0xCC,0x3D,0x4C,0x40,0xD8,0x81,0xAF,0x77,0x9E,0x83,
-0x7A,0xBB,0xA2,0xC7,0xF5,0x34,0x17,0x8E,0xD9,0x11,0x40,0xF4,0xFC,0x2C,0x2A,0x4D,
-0x15,0x7F,0xA7,0x62,0x5D,0x2E,0x25,0xD3,0x00,0x0B,0x20,0x1A,0x1D,0x68,0xF9,0x17,
-0xB8,0xF4,0xBD,0x8B,0xED,0x28,0x59,0xDD,0x4D,0x16,0x8B,0x17,0x83,0xC8,0xB2,0x65,
-0xC7,0x2D,0x7A,0xA5,0xAA,0xBC,0x53,0x86,0x6D,0xDD,0x57,0xA4,0xCA,0xF8,0x20,0x41,
-0x0B,0x68,0xF0,0xF4,0xFB,0x74,0xBE,0x56,0x5D,0x7A,0x79,0xF5,0xF9,0x1D,0x85,0xE3,
-0x2D,0x95,0xBE,0xF5,0x71,0x90,0x43,0xCC,0x8D,0x1F,0x9A,0x00,0x0A,0x87,0x29,0xE9,
-0x55,0x22,0x58,0x00,0x23,0xEA,0xE3,0x12,0x43,0x29,0x5B,0x47,0x08,0xDD,0x8C,0x41,
-0x6A,0x65,0x06,0xA8,0xE5,0x21,0xAA,0x41,0xB4,0x95,0x21,0x95,0xB9,0x7D,0xD1,0x34,
-0xAB,0x13,0xD6,0xAD,0xBC,0xDC,0xE2,0x3D,0x39,0xCD,0xBD,0x3E,0x75,0x70,0xA1,0x18,
-0x59,0x03,0xC9,0x22,0xB4,0x8F,0x9C,0xD5,0x5E,0x2A,0xD7,0xA5,0xB6,0xD4,0x0A,0x6D,
-0xF8,0xB7,0x40,0x11,0x46,0x9A,0x1F,0x79,0x0E,0x62,0xBF,0x0F,0x97,0xEC,0xE0,0x2F,
-0x1F,0x17,0x94,
-};
-
-
-/* subject:/C=US/ST=Arizona/L=Scottsdale/O=Starfield Technologies, Inc./CN=Starfield Root Certificate Authority - G2 */
-/* issuer :/C=US/ST=Arizona/L=Scottsdale/O=Starfield Technologies, Inc./CN=Starfield Root Certificate Authority - G2 */
-
-
-const unsigned char Starfield_Root_Certificate_Authority___G2_certificate[993]={
-0x30,0x82,0x03,0xDD,0x30,0x82,0x02,0xC5,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x00,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,
-0x81,0x8F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,
-0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x08,0x13,0x07,0x41,0x72,0x69,0x7A,0x6F,0x6E,
-0x61,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x07,0x13,0x0A,0x53,0x63,0x6F,0x74,
-0x74,0x73,0x64,0x61,0x6C,0x65,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x0A,0x13,
-0x1C,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x54,0x65,0x63,0x68,0x6E,
-0x6F,0x6C,0x6F,0x67,0x69,0x65,0x73,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x32,0x30,
-0x30,0x06,0x03,0x55,0x04,0x03,0x13,0x29,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,
-0x64,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,
-0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x2D,0x20,0x47,
-0x32,0x30,0x1E,0x17,0x0D,0x30,0x39,0x30,0x39,0x30,0x31,0x30,0x30,0x30,0x30,0x30,
-0x30,0x5A,0x17,0x0D,0x33,0x37,0x31,0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,
-0x5A,0x30,0x81,0x8F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,
-0x53,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x08,0x13,0x07,0x41,0x72,0x69,0x7A,
-0x6F,0x6E,0x61,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x07,0x13,0x0A,0x53,0x63,
-0x6F,0x74,0x74,0x73,0x64,0x61,0x6C,0x65,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x1C,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x54,0x65,0x63,
-0x68,0x6E,0x6F,0x6C,0x6F,0x67,0x69,0x65,0x73,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,
-0x32,0x30,0x30,0x06,0x03,0x55,0x04,0x03,0x13,0x29,0x53,0x74,0x61,0x72,0x66,0x69,
-0x65,0x6C,0x64,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,
-0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x2D,
-0x20,0x47,0x32,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,
-0x82,0x01,0x01,0x00,0xBD,0xED,0xC1,0x03,0xFC,0xF6,0x8F,0xFC,0x02,0xB1,0x6F,0x5B,
-0x9F,0x48,0xD9,0x9D,0x79,0xE2,0xA2,0xB7,0x03,0x61,0x56,0x18,0xC3,0x47,0xB6,0xD7,
-0xCA,0x3D,0x35,0x2E,0x89,0x43,0xF7,0xA1,0x69,0x9B,0xDE,0x8A,0x1A,0xFD,0x13,0x20,
-0x9C,0xB4,0x49,0x77,0x32,0x29,0x56,0xFD,0xB9,0xEC,0x8C,0xDD,0x22,0xFA,0x72,0xDC,
-0x27,0x61,0x97,0xEE,0xF6,0x5A,0x84,0xEC,0x6E,0x19,0xB9,0x89,0x2C,0xDC,0x84,0x5B,
-0xD5,0x74,0xFB,0x6B,0x5F,0xC5,0x89,0xA5,0x10,0x52,0x89,0x46,0x55,0xF4,0xB8,0x75,
-0x1C,0xE6,0x7F,0xE4,0x54,0xAE,0x4B,0xF8,0x55,0x72,0x57,0x02,0x19,0xF8,0x17,0x71,
-0x59,0xEB,0x1E,0x28,0x07,0x74,0xC5,0x9D,0x48,0xBE,0x6C,0xB4,0xF4,0xA4,0xB0,0xF3,
-0x64,0x37,0x79,0x92,0xC0,0xEC,0x46,0x5E,0x7F,0xE1,0x6D,0x53,0x4C,0x62,0xAF,0xCD,
-0x1F,0x0B,0x63,0xBB,0x3A,0x9D,0xFB,0xFC,0x79,0x00,0x98,0x61,0x74,0xCF,0x26,0x82,
-0x40,0x63,0xF3,0xB2,0x72,0x6A,0x19,0x0D,0x99,0xCA,0xD4,0x0E,0x75,0xCC,0x37,0xFB,
-0x8B,0x89,0xC1,0x59,0xF1,0x62,0x7F,0x5F,0xB3,0x5F,0x65,0x30,0xF8,0xA7,0xB7,0x4D,
-0x76,0x5A,0x1E,0x76,0x5E,0x34,0xC0,0xE8,0x96,0x56,0x99,0x8A,0xB3,0xF0,0x7F,0xA4,
-0xCD,0xBD,0xDC,0x32,0x31,0x7C,0x91,0xCF,0xE0,0x5F,0x11,0xF8,0x6B,0xAA,0x49,0x5C,
-0xD1,0x99,0x94,0xD1,0xA2,0xE3,0x63,0x5B,0x09,0x76,0xB5,0x56,0x62,0xE1,0x4B,0x74,
-0x1D,0x96,0xD4,0x26,0xD4,0x08,0x04,0x59,0xD0,0x98,0x0E,0x0E,0xE6,0xDE,0xFC,0xC3,
-0xEC,0x1F,0x90,0xF1,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,0x0F,0x06,
-0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,
-0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,
-0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x7C,0x0C,0x32,0x1F,0xA7,0xD9,0x30,
-0x7F,0xC4,0x7D,0x68,0xA3,0x62,0xA8,0xA1,0xCE,0xAB,0x07,0x5B,0x27,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,0x01,0x01,
-0x00,0x11,0x59,0xFA,0x25,0x4F,0x03,0x6F,0x94,0x99,0x3B,0x9A,0x1F,0x82,0x85,0x39,
-0xD4,0x76,0x05,0x94,0x5E,0xE1,0x28,0x93,0x6D,0x62,0x5D,0x09,0xC2,0xA0,0xA8,0xD4,
-0xB0,0x75,0x38,0xF1,0x34,0x6A,0x9D,0xE4,0x9F,0x8A,0x86,0x26,0x51,0xE6,0x2C,0xD1,
-0xC6,0x2D,0x6E,0x95,0x20,0x4A,0x92,0x01,0xEC,0xB8,0x8A,0x67,0x7B,0x31,0xE2,0x67,
-0x2E,0x8C,0x95,0x03,0x26,0x2E,0x43,0x9D,0x4A,0x31,0xF6,0x0E,0xB5,0x0C,0xBB,0xB7,
-0xE2,0x37,0x7F,0x22,0xBA,0x00,0xA3,0x0E,0x7B,0x52,0xFB,0x6B,0xBB,0x3B,0xC4,0xD3,
-0x79,0x51,0x4E,0xCD,0x90,0xF4,0x67,0x07,0x19,0xC8,0x3C,0x46,0x7A,0x0D,0x01,0x7D,
-0xC5,0x58,0xE7,0x6D,0xE6,0x85,0x30,0x17,0x9A,0x24,0xC4,0x10,0xE0,0x04,0xF7,0xE0,
-0xF2,0x7F,0xD4,0xAA,0x0A,0xFF,0x42,0x1D,0x37,0xED,0x94,0xE5,0x64,0x59,0x12,0x20,
-0x77,0x38,0xD3,0x32,0x3E,0x38,0x81,0x75,0x96,0x73,0xFA,0x68,0x8F,0xB1,0xCB,0xCE,
-0x1F,0xC5,0xEC,0xFA,0x9C,0x7E,0xCF,0x7E,0xB1,0xF1,0x07,0x2D,0xB6,0xFC,0xBF,0xCA,
-0xA4,0xBF,0xD0,0x97,0x05,0x4A,0xBC,0xEA,0x18,0x28,0x02,0x90,0xBD,0x54,0x78,0x09,
-0x21,0x71,0xD3,0xD1,0x7D,0x1D,0xD9,0x16,0xB0,0xA9,0x61,0x3D,0xD0,0x0A,0x00,0x22,
-0xFC,0xC7,0x7B,0xCB,0x09,0x64,0x45,0x0B,0x3B,0x40,0x81,0xF7,0x7D,0x7C,0x32,0xF5,
-0x98,0xCA,0x58,0x8E,0x7D,0x2A,0xEE,0x90,0x59,0x73,0x64,0xF9,0x36,0x74,0x5E,0x25,
-0xA1,0xF5,0x66,0x05,0x2E,0x7F,0x39,0x15,0xA9,0x2A,0xFB,0x50,0x8B,0x8E,0x85,0x69,
-0xF4,
-};
-
-
-/* subject:/C=US/ST=Arizona/L=Scottsdale/O=Starfield Technologies, Inc./CN=Starfield Services Root Certificate Authority - G2 */
-/* issuer :/C=US/ST=Arizona/L=Scottsdale/O=Starfield Technologies, Inc./CN=Starfield Services Root Certificate Authority - G2 */
-
-
-const unsigned char Starfield_Services_Root_Certificate_Authority___G2_certificate[1011]={
-0x30,0x82,0x03,0xEF,0x30,0x82,0x02,0xD7,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x00,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,
-0x81,0x98,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,
-0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x08,0x13,0x07,0x41,0x72,0x69,0x7A,0x6F,0x6E,
-0x61,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x07,0x13,0x0A,0x53,0x63,0x6F,0x74,
-0x74,0x73,0x64,0x61,0x6C,0x65,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x0A,0x13,
-0x1C,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x54,0x65,0x63,0x68,0x6E,
-0x6F,0x6C,0x6F,0x67,0x69,0x65,0x73,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x3B,0x30,
-0x39,0x06,0x03,0x55,0x04,0x03,0x13,0x32,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,
-0x64,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x20,0x52,0x6F,0x6F,0x74,0x20,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,
-0x6F,0x72,0x69,0x74,0x79,0x20,0x2D,0x20,0x47,0x32,0x30,0x1E,0x17,0x0D,0x30,0x39,
-0x30,0x39,0x30,0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x37,0x31,
-0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0x98,0x31,0x0B,0x30,
-0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x10,0x30,0x0E,0x06,0x03,
-0x55,0x04,0x08,0x13,0x07,0x41,0x72,0x69,0x7A,0x6F,0x6E,0x61,0x31,0x13,0x30,0x11,
-0x06,0x03,0x55,0x04,0x07,0x13,0x0A,0x53,0x63,0x6F,0x74,0x74,0x73,0x64,0x61,0x6C,
-0x65,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x0A,0x13,0x1C,0x53,0x74,0x61,0x72,
-0x66,0x69,0x65,0x6C,0x64,0x20,0x54,0x65,0x63,0x68,0x6E,0x6F,0x6C,0x6F,0x67,0x69,
-0x65,0x73,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x3B,0x30,0x39,0x06,0x03,0x55,0x04,
-0x03,0x13,0x32,0x53,0x74,0x61,0x72,0x66,0x69,0x65,0x6C,0x64,0x20,0x53,0x65,0x72,
-0x76,0x69,0x63,0x65,0x73,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,
-0x20,0x2D,0x20,0x47,0x32,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,
-0x0A,0x02,0x82,0x01,0x01,0x00,0xD5,0x0C,0x3A,0xC4,0x2A,0xF9,0x4E,0xE2,0xF5,0xBE,
-0x19,0x97,0x5F,0x8E,0x88,0x53,0xB1,0x1F,0x3F,0xCB,0xCF,0x9F,0x20,0x13,0x6D,0x29,
-0x3A,0xC8,0x0F,0x7D,0x3C,0xF7,0x6B,0x76,0x38,0x63,0xD9,0x36,0x60,0xA8,0x9B,0x5E,
-0x5C,0x00,0x80,0xB2,0x2F,0x59,0x7F,0xF6,0x87,0xF9,0x25,0x43,0x86,0xE7,0x69,0x1B,
-0x52,0x9A,0x90,0xE1,0x71,0xE3,0xD8,0x2D,0x0D,0x4E,0x6F,0xF6,0xC8,0x49,0xD9,0xB6,
-0xF3,0x1A,0x56,0xAE,0x2B,0xB6,0x74,0x14,0xEB,0xCF,0xFB,0x26,0xE3,0x1A,0xBA,0x1D,
-0x96,0x2E,0x6A,0x3B,0x58,0x94,0x89,0x47,0x56,0xFF,0x25,0xA0,0x93,0x70,0x53,0x83,
-0xDA,0x84,0x74,0x14,0xC3,0x67,0x9E,0x04,0x68,0x3A,0xDF,0x8E,0x40,0x5A,0x1D,0x4A,
-0x4E,0xCF,0x43,0x91,0x3B,0xE7,0x56,0xD6,0x00,0x70,0xCB,0x52,0xEE,0x7B,0x7D,0xAE,
-0x3A,0xE7,0xBC,0x31,0xF9,0x45,0xF6,0xC2,0x60,0xCF,0x13,0x59,0x02,0x2B,0x80,0xCC,
-0x34,0x47,0xDF,0xB9,0xDE,0x90,0x65,0x6D,0x02,0xCF,0x2C,0x91,0xA6,0xA6,0xE7,0xDE,
-0x85,0x18,0x49,0x7C,0x66,0x4E,0xA3,0x3A,0x6D,0xA9,0xB5,0xEE,0x34,0x2E,0xBA,0x0D,
-0x03,0xB8,0x33,0xDF,0x47,0xEB,0xB1,0x6B,0x8D,0x25,0xD9,0x9B,0xCE,0x81,0xD1,0x45,
-0x46,0x32,0x96,0x70,0x87,0xDE,0x02,0x0E,0x49,0x43,0x85,0xB6,0x6C,0x73,0xBB,0x64,
-0xEA,0x61,0x41,0xAC,0xC9,0xD4,0x54,0xDF,0x87,0x2F,0xC7,0x22,0xB2,0x26,0xCC,0x9F,
-0x59,0x54,0x68,0x9F,0xFC,0xBE,0x2A,0x2F,0xC4,0x55,0x1C,0x75,0x40,0x60,0x17,0x85,
-0x02,0x55,0x39,0x8B,0x7F,0x05,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,
-0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,
-0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,
-0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x9C,0x5F,0x00,0xDF,0xAA,
-0x01,0xD7,0x30,0x2B,0x38,0x88,0xA2,0xB8,0x6D,0x4A,0x9C,0xF2,0x11,0x91,0x83,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,
-0x01,0x01,0x00,0x4B,0x36,0xA6,0x84,0x77,0x69,0xDD,0x3B,0x19,0x9F,0x67,0x23,0x08,
-0x6F,0x0E,0x61,0xC9,0xFD,0x84,0xDC,0x5F,0xD8,0x36,0x81,0xCD,0xD8,0x1B,0x41,0x2D,
-0x9F,0x60,0xDD,0xC7,0x1A,0x68,0xD9,0xD1,0x6E,0x86,0xE1,0x88,0x23,0xCF,0x13,0xDE,
-0x43,0xCF,0xE2,0x34,0xB3,0x04,0x9D,0x1F,0x29,0xD5,0xBF,0xF8,0x5E,0xC8,0xD5,0xC1,
-0xBD,0xEE,0x92,0x6F,0x32,0x74,0xF2,0x91,0x82,0x2F,0xBD,0x82,0x42,0x7A,0xAD,0x2A,
-0xB7,0x20,0x7D,0x4D,0xBC,0x7A,0x55,0x12,0xC2,0x15,0xEA,0xBD,0xF7,0x6A,0x95,0x2E,
-0x6C,0x74,0x9F,0xCF,0x1C,0xB4,0xF2,0xC5,0x01,0xA3,0x85,0xD0,0x72,0x3E,0xAD,0x73,
-0xAB,0x0B,0x9B,0x75,0x0C,0x6D,0x45,0xB7,0x8E,0x94,0xAC,0x96,0x37,0xB5,0xA0,0xD0,
-0x8F,0x15,0x47,0x0E,0xE3,0xE8,0x83,0xDD,0x8F,0xFD,0xEF,0x41,0x01,0x77,0xCC,0x27,
-0xA9,0x62,0x85,0x33,0xF2,0x37,0x08,0xEF,0x71,0xCF,0x77,0x06,0xDE,0xC8,0x19,0x1D,
-0x88,0x40,0xCF,0x7D,0x46,0x1D,0xFF,0x1E,0xC7,0xE1,0xCE,0xFF,0x23,0xDB,0xC6,0xFA,
-0x8D,0x55,0x4E,0xA9,0x02,0xE7,0x47,0x11,0x46,0x3E,0xF4,0xFD,0xBD,0x7B,0x29,0x26,
-0xBB,0xA9,0x61,0x62,0x37,0x28,0xB6,0x2D,0x2A,0xF6,0x10,0x86,0x64,0xC9,0x70,0xA7,
-0xD2,0xAD,0xB7,0x29,0x70,0x79,0xEA,0x3C,0xDA,0x63,0x25,0x9F,0xFD,0x68,0xB7,0x30,
-0xEC,0x70,0xFB,0x75,0x8A,0xB7,0x6D,0x60,0x67,0xB2,0x1E,0xC8,0xB9,0xE9,0xD8,0xA8,
-0x6F,0x02,0x8B,0x67,0x0D,0x4D,0x26,0x57,0x71,0xDA,0x20,0xFC,0xC1,0x4A,0x50,0x8D,
-0xB1,0x28,0xBA,
-};
-
-
-/* subject:/C=IL/O=StartCom Ltd./OU=Secure Digital Certificate Signing/CN=StartCom Certification Authority */
-/* issuer :/C=IL/O=StartCom Ltd./OU=Secure Digital Certificate Signing/CN=StartCom Certification Authority */
-
-
-const unsigned char StartCom_Certification_Authority_certificate[1931]={
-0x30,0x82,0x07,0x87,0x30,0x82,0x05,0x6F,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x2D,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,
-0x7D,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x49,0x4C,0x31,0x16,
-0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x53,0x74,0x61,0x72,0x74,0x43,0x6F,
-0x6D,0x20,0x4C,0x74,0x64,0x2E,0x31,0x2B,0x30,0x29,0x06,0x03,0x55,0x04,0x0B,0x13,
-0x22,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x44,0x69,0x67,0x69,0x74,0x61,0x6C,0x20,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x53,0x69,0x67,0x6E,
-0x69,0x6E,0x67,0x31,0x29,0x30,0x27,0x06,0x03,0x55,0x04,0x03,0x13,0x20,0x53,0x74,
-0x61,0x72,0x74,0x43,0x6F,0x6D,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,
-0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,
-0x17,0x0D,0x30,0x36,0x30,0x39,0x31,0x37,0x31,0x39,0x34,0x36,0x33,0x37,0x5A,0x17,
-0x0D,0x33,0x36,0x30,0x39,0x31,0x37,0x31,0x39,0x34,0x36,0x33,0x36,0x5A,0x30,0x7D,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x49,0x4C,0x31,0x16,0x30,
-0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x53,0x74,0x61,0x72,0x74,0x43,0x6F,0x6D,
-0x20,0x4C,0x74,0x64,0x2E,0x31,0x2B,0x30,0x29,0x06,0x03,0x55,0x04,0x0B,0x13,0x22,
-0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x44,0x69,0x67,0x69,0x74,0x61,0x6C,0x20,0x43,
-0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x53,0x69,0x67,0x6E,0x69,
-0x6E,0x67,0x31,0x29,0x30,0x27,0x06,0x03,0x55,0x04,0x03,0x13,0x20,0x53,0x74,0x61,
-0x72,0x74,0x43,0x6F,0x6D,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,
-0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x82,0x02,
-0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,
-0x03,0x82,0x02,0x0F,0x00,0x30,0x82,0x02,0x0A,0x02,0x82,0x02,0x01,0x00,0xC1,0x88,
-0xDB,0x09,0xBC,0x6C,0x46,0x7C,0x78,0x9F,0x95,0x7B,0xB5,0x33,0x90,0xF2,0x72,0x62,
-0xD6,0xC1,0x36,0x20,0x22,0x24,0x5E,0xCE,0xE9,0x77,0xF2,0x43,0x0A,0xA2,0x06,0x64,
-0xA4,0xCC,0x8E,0x36,0xF8,0x38,0xE6,0x23,0xF0,0x6E,0x6D,0xB1,0x3C,0xDD,0x72,0xA3,
-0x85,0x1C,0xA1,0xD3,0x3D,0xB4,0x33,0x2B,0xD3,0x2F,0xAF,0xFE,0xEA,0xB0,0x41,0x59,
-0x67,0xB6,0xC4,0x06,0x7D,0x0A,0x9E,0x74,0x85,0xD6,0x79,0x4C,0x80,0x37,0x7A,0xDF,
-0x39,0x05,0x52,0x59,0xF7,0xF4,0x1B,0x46,0x43,0xA4,0xD2,0x85,0x85,0xD2,0xC3,0x71,
-0xF3,0x75,0x62,0x34,0xBA,0x2C,0x8A,0x7F,0x1E,0x8F,0xEE,0xED,0x34,0xD0,0x11,0xC7,
-0x96,0xCD,0x52,0x3D,0xBA,0x33,0xD6,0xDD,0x4D,0xDE,0x0B,0x3B,0x4A,0x4B,0x9F,0xC2,
-0x26,0x2F,0xFA,0xB5,0x16,0x1C,0x72,0x35,0x77,0xCA,0x3C,0x5D,0xE6,0xCA,0xE1,0x26,
-0x8B,0x1A,0x36,0x76,0x5C,0x01,0xDB,0x74,0x14,0x25,0xFE,0xED,0xB5,0xA0,0x88,0x0F,
-0xDD,0x78,0xCA,0x2D,0x1F,0x07,0x97,0x30,0x01,0x2D,0x72,0x79,0xFA,0x46,0xD6,0x13,
-0x2A,0xA8,0xB9,0xA6,0xAB,0x83,0x49,0x1D,0xE5,0xF2,0xEF,0xDD,0xE4,0x01,0x8E,0x18,
-0x0A,0x8F,0x63,0x53,0x16,0x85,0x62,0xA9,0x0E,0x19,0x3A,0xCC,0xB5,0x66,0xA6,0xC2,
-0x6B,0x74,0x07,0xE4,0x2B,0xE1,0x76,0x3E,0xB4,0x6D,0xD8,0xF6,0x44,0xE1,0x73,0x62,
-0x1F,0x3B,0xC4,0xBE,0xA0,0x53,0x56,0x25,0x6C,0x51,0x09,0xF7,0xAA,0xAB,0xCA,0xBF,
-0x76,0xFD,0x6D,0x9B,0xF3,0x9D,0xDB,0xBF,0x3D,0x66,0xBC,0x0C,0x56,0xAA,0xAF,0x98,
-0x48,0x95,0x3A,0x4B,0xDF,0xA7,0x58,0x50,0xD9,0x38,0x75,0xA9,0x5B,0xEA,0x43,0x0C,
-0x02,0xFF,0x99,0xEB,0xE8,0x6C,0x4D,0x70,0x5B,0x29,0x65,0x9C,0xDD,0xAA,0x5D,0xCC,
-0xAF,0x01,0x31,0xEC,0x0C,0xEB,0xD2,0x8D,0xE8,0xEA,0x9C,0x7B,0xE6,0x6E,0xF7,0x27,
-0x66,0x0C,0x1A,0x48,0xD7,0x6E,0x42,0xE3,0x3F,0xDE,0x21,0x3E,0x7B,0xE1,0x0D,0x70,
-0xFB,0x63,0xAA,0xA8,0x6C,0x1A,0x54,0xB4,0x5C,0x25,0x7A,0xC9,0xA2,0xC9,0x8B,0x16,
-0xA6,0xBB,0x2C,0x7E,0x17,0x5E,0x05,0x4D,0x58,0x6E,0x12,0x1D,0x01,0xEE,0x12,0x10,
-0x0D,0xC6,0x32,0x7F,0x18,0xFF,0xFC,0xF4,0xFA,0xCD,0x6E,0x91,0xE8,0x36,0x49,0xBE,
-0x1A,0x48,0x69,0x8B,0xC2,0x96,0x4D,0x1A,0x12,0xB2,0x69,0x17,0xC1,0x0A,0x90,0xD6,
-0xFA,0x79,0x22,0x48,0xBF,0xBA,0x7B,0x69,0xF8,0x70,0xC7,0xFA,0x7A,0x37,0xD8,0xD8,
-0x0D,0xD2,0x76,0x4F,0x57,0xFF,0x90,0xB7,0xE3,0x91,0xD2,0xDD,0xEF,0xC2,0x60,0xB7,
-0x67,0x3A,0xDD,0xFE,0xAA,0x9C,0xF0,0xD4,0x8B,0x7F,0x72,0x22,0xCE,0xC6,0x9F,0x97,
-0xB6,0xF8,0xAF,0x8A,0xA0,0x10,0xA8,0xD9,0xFB,0x18,0xC6,0xB6,0xB5,0x5C,0x52,0x3C,
-0x89,0xB6,0x19,0x2A,0x73,0x01,0x0A,0x0F,0x03,0xB3,0x12,0x60,0xF2,0x7A,0x2F,0x81,
-0xDB,0xA3,0x6E,0xFF,0x26,0x30,0x97,0xF5,0x8B,0xDD,0x89,0x57,0xB6,0xAD,0x3D,0xB3,
-0xAF,0x2B,0xC5,0xB7,0x76,0x02,0xF0,0xA5,0xD6,0x2B,0x9A,0x86,0x14,0x2A,0x72,0xF6,
-0xE3,0x33,0x8C,0x5D,0x09,0x4B,0x13,0xDF,0xBB,0x8C,0x74,0x13,0x52,0x4B,0x02,0x03,
-0x01,0x00,0x01,0xA3,0x82,0x02,0x10,0x30,0x82,0x02,0x0C,0x30,0x0F,0x06,0x03,0x55,
-0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,
-0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,
-0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x4E,0x0B,0xEF,0x1A,0xA4,0x40,0x5B,0xA5,0x17,
-0x69,0x87,0x30,0xCA,0x34,0x68,0x43,0xD0,0x41,0xAE,0xF2,0x30,0x1F,0x06,0x03,0x55,
-0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x4E,0x0B,0xEF,0x1A,0xA4,0x40,0x5B,0xA5,
-0x17,0x69,0x87,0x30,0xCA,0x34,0x68,0x43,0xD0,0x41,0xAE,0xF2,0x30,0x82,0x01,0x5A,
-0x06,0x03,0x55,0x1D,0x20,0x04,0x82,0x01,0x51,0x30,0x82,0x01,0x4D,0x30,0x82,0x01,
-0x49,0x06,0x0B,0x2B,0x06,0x01,0x04,0x01,0x81,0xB5,0x37,0x01,0x01,0x01,0x30,0x82,
-0x01,0x38,0x30,0x2E,0x06,0x08,0x2B,0x06,0x01,0x05,0x05,0x07,0x02,0x01,0x16,0x22,
-0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x73,0x74,0x61,0x72,0x74,
-0x73,0x73,0x6C,0x2E,0x63,0x6F,0x6D,0x2F,0x70,0x6F,0x6C,0x69,0x63,0x79,0x2E,0x70,
-0x64,0x66,0x30,0x34,0x06,0x08,0x2B,0x06,0x01,0x05,0x05,0x07,0x02,0x01,0x16,0x28,
-0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x73,0x74,0x61,0x72,0x74,
-0x73,0x73,0x6C,0x2E,0x63,0x6F,0x6D,0x2F,0x69,0x6E,0x74,0x65,0x72,0x6D,0x65,0x64,
-0x69,0x61,0x74,0x65,0x2E,0x70,0x64,0x66,0x30,0x81,0xCF,0x06,0x08,0x2B,0x06,0x01,
-0x05,0x05,0x07,0x02,0x02,0x30,0x81,0xC2,0x30,0x27,0x16,0x20,0x53,0x74,0x61,0x72,
-0x74,0x20,0x43,0x6F,0x6D,0x6D,0x65,0x72,0x63,0x69,0x61,0x6C,0x20,0x28,0x53,0x74,
-0x61,0x72,0x74,0x43,0x6F,0x6D,0x29,0x20,0x4C,0x74,0x64,0x2E,0x30,0x03,0x02,0x01,
-0x01,0x1A,0x81,0x96,0x4C,0x69,0x6D,0x69,0x74,0x65,0x64,0x20,0x4C,0x69,0x61,0x62,
-0x69,0x6C,0x69,0x74,0x79,0x2C,0x20,0x72,0x65,0x61,0x64,0x20,0x74,0x68,0x65,0x20,
-0x73,0x65,0x63,0x74,0x69,0x6F,0x6E,0x20,0x2A,0x4C,0x65,0x67,0x61,0x6C,0x20,0x4C,
-0x69,0x6D,0x69,0x74,0x61,0x74,0x69,0x6F,0x6E,0x73,0x2A,0x20,0x6F,0x66,0x20,0x74,
-0x68,0x65,0x20,0x53,0x74,0x61,0x72,0x74,0x43,0x6F,0x6D,0x20,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x20,0x50,0x6F,0x6C,0x69,0x63,0x79,0x20,0x61,0x76,0x61,0x69,0x6C,
-0x61,0x62,0x6C,0x65,0x20,0x61,0x74,0x20,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,
-0x77,0x77,0x2E,0x73,0x74,0x61,0x72,0x74,0x73,0x73,0x6C,0x2E,0x63,0x6F,0x6D,0x2F,
-0x70,0x6F,0x6C,0x69,0x63,0x79,0x2E,0x70,0x64,0x66,0x30,0x11,0x06,0x09,0x60,0x86,
-0x48,0x01,0x86,0xF8,0x42,0x01,0x01,0x04,0x04,0x03,0x02,0x00,0x07,0x30,0x38,0x06,
-0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x42,0x01,0x0D,0x04,0x2B,0x16,0x29,0x53,0x74,
-0x61,0x72,0x74,0x43,0x6F,0x6D,0x20,0x46,0x72,0x65,0x65,0x20,0x53,0x53,0x4C,0x20,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,
-0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,0x02,0x01,0x00,0x8E,0x8F,0xE7,0xDC,0x94,
-0x79,0x7C,0xF1,0x85,0x7F,0x9F,0x49,0x6F,0x6B,0xCA,0x5D,0xFB,0x8C,0xFE,0x04,0xC5,
-0xC1,0x62,0xD1,0x7D,0x42,0x8A,0xBC,0x53,0xB7,0x94,0x03,0x66,0x30,0x3F,0xB1,0xE7,
-0x0A,0xA7,0x50,0x20,0x55,0x25,0x7F,0x76,0x7A,0x14,0x0D,0xEB,0x04,0x0E,0x40,0xE6,
-0x3E,0xD8,0x88,0xAB,0x07,0x27,0x83,0xA9,0x75,0xA6,0x37,0x73,0xC7,0xFD,0x4B,0xD2,
-0x4D,0xAD,0x17,0x40,0xC8,0x46,0xBE,0x3B,0x7F,0x51,0xFC,0xC3,0xB6,0x05,0x31,0xDC,
-0xCD,0x85,0x22,0x4E,0x71,0xB7,0xF2,0x71,0x5E,0xB0,0x1A,0xC6,0xBA,0x93,0x8B,0x78,
-0x92,0x4A,0x85,0xF8,0x78,0x0F,0x83,0xFE,0x2F,0xAD,0x2C,0xF7,0xE4,0xA4,0xBB,0x2D,
-0xD0,0xE7,0x0D,0x3A,0xB8,0x3E,0xCE,0xF6,0x78,0xF6,0xAE,0x47,0x24,0xCA,0xA3,0x35,
-0x36,0xCE,0xC7,0xC6,0x87,0x98,0xDA,0xEC,0xFB,0xE9,0xB2,0xCE,0x27,0x9B,0x88,0xC3,
-0x04,0xA1,0xF6,0x0B,0x59,0x68,0xAF,0xC9,0xDB,0x10,0x0F,0x4D,0xF6,0x64,0x63,0x5C,
-0xA5,0x12,0x6F,0x92,0xB2,0x93,0x94,0xC7,0x88,0x17,0x0E,0x93,0xB6,0x7E,0x62,0x8B,
-0x90,0x7F,0xAB,0x4E,0x9F,0xFC,0xE3,0x75,0x14,0x4F,0x2A,0x32,0xDF,0x5B,0x0D,0xE0,
-0xF5,0x7B,0x93,0x0D,0xAB,0xA1,0xCF,0x87,0xE1,0xA5,0x04,0x45,0xE8,0x3C,0x12,0xA5,
-0x09,0xC5,0xB0,0xD1,0xB7,0x53,0xF3,0x60,0x14,0xBA,0x85,0x69,0x6A,0x21,0x7C,0x1F,
-0x75,0x61,0x17,0x20,0x17,0x7B,0x6C,0x3B,0x41,0x29,0x5C,0xE1,0xAC,0x5A,0xD1,0xCD,
-0x8C,0x9B,0xEB,0x60,0x1D,0x19,0xEC,0xF7,0xE5,0xB0,0xDA,0xF9,0x79,0x18,0xA5,0x45,
-0x3F,0x49,0x43,0x57,0xD2,0xDD,0x24,0xD5,0x2C,0xA3,0xFD,0x91,0x8D,0x27,0xB5,0xE5,
-0xEB,0x14,0x06,0x9A,0x4C,0x7B,0x21,0xBB,0x3A,0xAD,0x30,0x06,0x18,0xC0,0xD8,0xC1,
-0x6B,0x2C,0x7F,0x59,0x5C,0x5D,0x91,0xB1,0x70,0x22,0x57,0xEB,0x8A,0x6B,0x48,0x4A,
-0xD5,0x0F,0x29,0xEC,0xC6,0x40,0xC0,0x2F,0x88,0x4C,0x68,0x01,0x17,0x77,0xF4,0x24,
-0x19,0x4F,0xBD,0xFA,0xE1,0xB2,0x20,0x21,0x4B,0xDD,0x1A,0xD8,0x29,0x7D,0xAA,0xB8,
-0xDE,0x54,0xEC,0x21,0x55,0x80,0x6C,0x1E,0xF5,0x30,0xC8,0xA3,0x10,0xE5,0xB2,0xE6,
-0x2A,0x14,0x31,0xC3,0x85,0x2D,0x8C,0x98,0xB1,0x86,0x5A,0x4F,0x89,0x59,0x2D,0xB9,
-0xC7,0xF7,0x1C,0xC8,0x8A,0x7F,0xC0,0x9D,0x05,0x4A,0xE6,0x42,0x4F,0x62,0xA3,0x6D,
-0x29,0xA4,0x1F,0x85,0xAB,0xDB,0xE5,0x81,0xC8,0xAD,0x2A,0x3D,0x4C,0x5D,0x5B,0x84,
-0x26,0x71,0xC4,0x85,0x5E,0x71,0x24,0xCA,0xA5,0x1B,0x6C,0xD8,0x61,0xD3,0x1A,0xE0,
-0x54,0xDB,0xCE,0xBA,0xA9,0x32,0xB5,0x22,0xF6,0x73,0x41,0x09,0x5D,0xB8,0x17,0x5D,
-0x0E,0x0F,0x99,0x90,0xD6,0x47,0xDA,0x6F,0x0A,0x3A,0x62,0x28,0x14,0x67,0x82,0xD9,
-0xF1,0xD0,0x80,0x59,0x9B,0xCB,0x31,0xD8,0x9B,0x0F,0x8C,0x77,0x4E,0xB5,0x68,0x8A,
-0xF2,0x6C,0xF6,0x24,0x0E,0x2D,0x6C,0x70,0xC5,0x73,0xD1,0xDE,0x14,0xD0,0x71,0x8F,
-0xB6,0xD3,0x7B,0x02,0xF6,0xE3,0xB8,0xD4,0x09,0x6E,0x6B,0x9E,0x75,0x84,0x39,0xE6,
-0x7F,0x25,0xA5,0xF2,0x48,0x00,0xC0,0xA4,0x01,0xDA,0x3F,
-};
-
-
-/* subject:/C=IL/O=StartCom Ltd./CN=StartCom Certification Authority G2 */
-/* issuer :/C=IL/O=StartCom Ltd./CN=StartCom Certification Authority G2 */
-
-
-const unsigned char StartCom_Certification_Authority_G2_certificate[1383]={
-0x30,0x82,0x05,0x63,0x30,0x82,0x03,0x4B,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x3B,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,
-0x53,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x49,0x4C,0x31,0x16,
-0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x53,0x74,0x61,0x72,0x74,0x43,0x6F,
-0x6D,0x20,0x4C,0x74,0x64,0x2E,0x31,0x2C,0x30,0x2A,0x06,0x03,0x55,0x04,0x03,0x13,
-0x23,0x53,0x74,0x61,0x72,0x74,0x43,0x6F,0x6D,0x20,0x43,0x65,0x72,0x74,0x69,0x66,
-0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,
-0x79,0x20,0x47,0x32,0x30,0x1E,0x17,0x0D,0x31,0x30,0x30,0x31,0x30,0x31,0x30,0x31,
-0x30,0x30,0x30,0x31,0x5A,0x17,0x0D,0x33,0x39,0x31,0x32,0x33,0x31,0x32,0x33,0x35,
-0x39,0x30,0x31,0x5A,0x30,0x53,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x49,0x4C,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0A,0x13,0x0D,0x53,0x74,
-0x61,0x72,0x74,0x43,0x6F,0x6D,0x20,0x4C,0x74,0x64,0x2E,0x31,0x2C,0x30,0x2A,0x06,
-0x03,0x55,0x04,0x03,0x13,0x23,0x53,0x74,0x61,0x72,0x74,0x43,0x6F,0x6D,0x20,0x43,
-0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x47,0x32,0x30,0x82,0x02,0x22,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x02,0x0F,
-0x00,0x30,0x82,0x02,0x0A,0x02,0x82,0x02,0x01,0x00,0xB6,0x89,0x36,0x5B,0x07,0xB7,
-0x20,0x36,0xBD,0x82,0xBB,0xE1,0x16,0x20,0x03,0x95,0x7A,0xAF,0x0E,0xA3,0x55,0xC9,
-0x25,0x99,0x4A,0xC5,0xD0,0x56,0x41,0x87,0x90,0x4D,0x21,0x60,0xA4,0x14,0x87,0x3B,
-0xCD,0xFD,0xB2,0x3E,0xB4,0x67,0x03,0x6A,0xED,0xE1,0x0F,0x4B,0xC0,0x91,0x85,0x70,
-0x45,0xE0,0x42,0x9E,0xDE,0x29,0x23,0xD4,0x01,0x0D,0xA0,0x10,0x79,0xB8,0xDB,0x03,
-0xBD,0xF3,0xA9,0x2F,0xD1,0xC6,0xE0,0x0F,0xCB,0x9E,0x8A,0x14,0x0A,0xB8,0xBD,0xF6,
-0x56,0x62,0xF1,0xC5,0x72,0xB6,0x32,0x25,0xD9,0xB2,0xF3,0xBD,0x65,0xC5,0x0D,0x2C,
-0x6E,0xD5,0x92,0x6F,0x18,0x8B,0x00,0x41,0x14,0x82,0x6F,0x40,0x20,0x26,0x7A,0x28,
-0x0F,0xF5,0x1E,0x7F,0x27,0xF7,0x94,0xB1,0x37,0x3D,0xB7,0xC7,0x91,0xF7,0xE2,0x01,
-0xEC,0xFD,0x94,0x89,0xE1,0xCC,0x6E,0xD3,0x36,0xD6,0x0A,0x19,0x79,0xAE,0xD7,0x34,
-0x82,0x65,0xFF,0x7C,0x42,0xBB,0xB6,0xDD,0x0B,0xA6,0x34,0xAF,0x4B,0x60,0xFE,0x7F,
-0x43,0x49,0x06,0x8B,0x8C,0x43,0xB8,0x56,0xF2,0xD9,0x7F,0x21,0x43,0x17,0xEA,0xA7,
-0x48,0x95,0x01,0x75,0x75,0xEA,0x2B,0xA5,0x43,0x95,0xEA,0x15,0x84,0x9D,0x08,0x8D,
-0x26,0x6E,0x55,0x9B,0xAB,0xDC,0xD2,0x39,0xD2,0x31,0x1D,0x60,0xE2,0xAC,0xCC,0x56,
-0x45,0x24,0xF5,0x1C,0x54,0xAB,0xEE,0x86,0xDD,0x96,0x32,0x85,0xF8,0x4C,0x4F,0xE8,
-0x95,0x76,0xB6,0x05,0xDD,0x36,0x23,0x67,0xBC,0xFF,0x15,0xE2,0xCA,0x3B,0xE6,0xA6,
-0xEC,0x3B,0xEC,0x26,0x11,0x34,0x48,0x8D,0xF6,0x80,0x2B,0x1A,0x23,0x02,0xEB,0x8A,
-0x1C,0x3A,0x76,0x2A,0x7B,0x56,0x16,0x1C,0x72,0x2A,0xB3,0xAA,0xE3,0x60,0xA5,0x00,
-0x9F,0x04,0x9B,0xE2,0x6F,0x1E,0x14,0x58,0x5B,0xA5,0x6C,0x8B,0x58,0x3C,0xC3,0xBA,
-0x4E,0x3A,0x5C,0xF7,0xE1,0x96,0x2B,0x3E,0xEF,0x07,0xBC,0xA4,0xE5,0x5D,0xCC,0x4D,
-0x9F,0x0D,0xE1,0xDC,0xAA,0xBB,0xE1,0x6E,0x1A,0xEC,0x8F,0xE1,0xB6,0x4C,0x4D,0x79,
-0x72,0x5D,0x17,0x35,0x0B,0x1D,0xD7,0xC1,0x47,0xDA,0x96,0x24,0xE0,0xD0,0x72,0xA8,
-0x5A,0x5F,0x66,0x2D,0x10,0xDC,0x2F,0x2A,0x13,0xAE,0x26,0xFE,0x0A,0x1C,0x19,0xCC,
-0xD0,0x3E,0x0B,0x9C,0xC8,0x09,0x2E,0xF9,0x5B,0x96,0x7A,0x47,0x9C,0xE9,0x7A,0xF3,
-0x05,0x50,0x74,0x95,0x73,0x9E,0x30,0x09,0xF3,0x97,0x82,0x5E,0xE6,0x8F,0x39,0x08,
-0x1E,0x59,0xE5,0x35,0x14,0x42,0x13,0xFF,0x00,0x9C,0xF7,0xBE,0xAA,0x50,0xCF,0xE2,
-0x51,0x48,0xD7,0xB8,0x6F,0xAF,0xF8,0x4E,0x7E,0x33,0x98,0x92,0x14,0x62,0x3A,0x75,
-0x63,0xCF,0x7B,0xFA,0xDE,0x82,0x3B,0xA9,0xBB,0x39,0xE2,0xC4,0xBD,0x2C,0x00,0x0E,
-0xC8,0x17,0xAC,0x13,0xEF,0x4D,0x25,0x8E,0xD8,0xB3,0x90,0x2F,0xA9,0xDA,0x29,0x7D,
-0x1D,0xAF,0x74,0x3A,0xB2,0x27,0xC0,0xC1,0x1E,0x3E,0x75,0xA3,0x16,0xA9,0xAF,0x7A,
-0x22,0x5D,0x9F,0x13,0x1A,0xCF,0xA7,0xA0,0xEB,0xE3,0x86,0x0A,0xD3,0xFD,0xE6,0x96,
-0x95,0xD7,0x23,0xC8,0x37,0xDD,0xC4,0x7C,0xAA,0x36,0xAC,0x98,0x1A,0x12,0xB1,0xE0,
-0x4E,0xE8,0xB1,0x3B,0xF5,0xD6,0x6F,0xF1,0x30,0xD7,0x02,0x03,0x01,0x00,0x01,0xA3,
-0x42,0x30,0x40,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,
-0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x4B,
-0xC5,0xB4,0x40,0x6B,0xAD,0x1C,0xB3,0xA5,0x1C,0x65,0x6E,0x46,0x36,0x89,0x87,0x05,
-0x0C,0x0E,0xB6,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,
-0x05,0x00,0x03,0x82,0x02,0x01,0x00,0x73,0x57,0x3F,0x2C,0xD5,0x95,0x32,0x7E,0x37,
-0xDB,0x96,0x92,0xEB,0x19,0x5E,0x7E,0x53,0xE7,0x41,0xEC,0x11,0xB6,0x47,0xEF,0xB5,
-0xDE,0xED,0x74,0x5C,0xC5,0xF1,0x8E,0x49,0xE0,0xFC,0x6E,0x99,0x13,0xCD,0x9F,0x8A,
-0xDA,0xCD,0x3A,0x0A,0xD8,0x3A,0x5A,0x09,0x3F,0x5F,0x34,0xD0,0x2F,0x03,0xD2,0x66,
-0x1D,0x1A,0xBD,0x9C,0x90,0x37,0xC8,0x0C,0x8E,0x07,0x5A,0x94,0x45,0x46,0x2A,0xE6,
-0xBE,0x7A,0xDA,0xA1,0xA9,0xA4,0x69,0x12,0x92,0xB0,0x7D,0x36,0xD4,0x44,0x87,0xD7,
-0x51,0xF1,0x29,0x63,0xD6,0x75,0xCD,0x16,0xE4,0x27,0x89,0x1D,0xF8,0xC2,0x32,0x48,
-0xFD,0xDB,0x99,0xD0,0x8F,0x5F,0x54,0x74,0xCC,0xAC,0x67,0x34,0x11,0x62,0xD9,0x0C,
-0x0A,0x37,0x87,0xD1,0xA3,0x17,0x48,0x8E,0xD2,0x17,0x1D,0xF6,0xD7,0xFD,0xDB,0x65,
-0xEB,0xFD,0xA8,0xD4,0xF5,0xD6,0x4F,0xA4,0x5B,0x75,0xE8,0xC5,0xD2,0x60,0xB2,0xDB,
-0x09,0x7E,0x25,0x8B,0x7B,0xBA,0x52,0x92,0x9E,0x3E,0xE8,0xC5,0x77,0xA1,0x3C,0xE0,
-0x4A,0x73,0x6B,0x61,0xCF,0x86,0xDC,0x43,0xFF,0xFF,0x21,0xFE,0x23,0x5D,0x24,0x4A,
-0xF5,0xD3,0x6D,0x0F,0x62,0x04,0x05,0x57,0x82,0xDA,0x6E,0xA4,0x33,0x25,0x79,0x4B,
-0x2E,0x54,0x19,0x8B,0xCC,0x2C,0x3D,0x30,0xE9,0xD1,0x06,0xFF,0xE8,0x32,0x46,0xBE,
-0xB5,0x33,0x76,0x77,0xA8,0x01,0x5D,0x96,0xC1,0xC1,0xD5,0xBE,0xAE,0x25,0xC0,0xC9,
-0x1E,0x0A,0x09,0x20,0x88,0xA1,0x0E,0xC9,0xF3,0x6F,0x4D,0x82,0x54,0x00,0x20,0xA7,
-0xD2,0x8F,0xE4,0x39,0x54,0x17,0x2E,0x8D,0x1E,0xB8,0x1B,0xBB,0x1B,0xBD,0x9A,0x4E,
-0x3B,0x10,0x34,0xDC,0x9C,0x88,0x53,0xEF,0xA2,0x31,0x5B,0x58,0x4F,0x91,0x62,0xC8,
-0xC2,0x9A,0x9A,0xCD,0x15,0x5D,0x38,0xA9,0xD6,0xBE,0xF8,0x13,0xB5,0x9F,0x12,0x69,
-0xF2,0x50,0x62,0xAC,0xFB,0x17,0x37,0xF4,0xEE,0xB8,0x75,0x67,0x60,0x10,0xFB,0x83,
-0x50,0xF9,0x44,0xB5,0x75,0x9C,0x40,0x17,0xB2,0xFE,0xFD,0x79,0x5D,0x6E,0x58,0x58,
-0x5F,0x30,0xFC,0x00,0xAE,0xAF,0x33,0xC1,0x0E,0x4E,0x6C,0xBA,0xA7,0xA6,0xA1,0x7F,
-0x32,0xDB,0x38,0xE0,0xB1,0x72,0x17,0x0A,0x2B,0x91,0xEC,0x6A,0x63,0x26,0xED,0x89,
-0xD4,0x78,0xCC,0x74,0x1E,0x05,0xF8,0x6B,0xFE,0x8C,0x6A,0x76,0x39,0x29,0xAE,0x65,
-0x23,0x12,0x95,0x08,0x22,0x1C,0x97,0xCE,0x5B,0x06,0xEE,0x0C,0xE2,0xBB,0xBC,0x1F,
-0x44,0x93,0xF6,0xD8,0x38,0x45,0x05,0x21,0xED,0xE4,0xAD,0xAB,0x12,0xB6,0x03,0xA4,
-0x42,0x2E,0x2D,0xC4,0x09,0x3A,0x03,0x67,0x69,0x84,0x9A,0xE1,0x59,0x90,0x8A,0x28,
-0x85,0xD5,0x5D,0x74,0xB1,0xD1,0x0E,0x20,0x58,0x9B,0x13,0xA5,0xB0,0x63,0xA6,0xED,
-0x7B,0x47,0xFD,0x45,0x55,0x30,0xA4,0xEE,0x9A,0xD4,0xE6,0xE2,0x87,0xEF,0x98,0xC9,
-0x32,0x82,0x11,0x29,0x22,0xBC,0x00,0x0A,0x31,0x5E,0x2D,0x0F,0xC0,0x8E,0xE9,0x6B,
-0xB2,0x8F,0x2E,0x06,0xD8,0xD1,0x91,0xC7,0xC6,0x12,0xF4,0x4C,0xFD,0x30,0x17,0xC3,
-0xC1,0xDA,0x38,0x5B,0xE3,0xA9,0xEA,0xE6,0xA1,0xBA,0x79,0xEF,0x73,0xD8,0xB6,0x53,
-0x57,0x2D,0xF6,0xD0,0xE1,0xD7,0x48,
-};
-
-
-/* subject:/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Class 2 CA/CN=TC TrustCenter Class 2 CA II */
-/* issuer :/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Class 2 CA/CN=TC TrustCenter Class 2 CA II */
-
-
-const unsigned char TC_TrustCenter_Class_2_CA_II_certificate[1198]={
-0x30,0x82,0x04,0xAA,0x30,0x82,0x03,0x92,0xA0,0x03,0x02,0x01,0x02,0x02,0x0E,0x2E,
-0x6A,0x00,0x01,0x00,0x02,0x1F,0xD7,0x52,0x21,0x2C,0x11,0x5C,0x3B,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x76,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x13,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,
-0x6E,0x74,0x65,0x72,0x20,0x47,0x6D,0x62,0x48,0x31,0x22,0x30,0x20,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x19,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,
-0x65,0x72,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x43,0x41,0x31,0x25,0x30,
-0x23,0x06,0x03,0x55,0x04,0x03,0x13,0x1C,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,
-0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x43,
-0x41,0x20,0x49,0x49,0x30,0x1E,0x17,0x0D,0x30,0x36,0x30,0x31,0x31,0x32,0x31,0x34,
-0x33,0x38,0x34,0x33,0x5A,0x17,0x0D,0x32,0x35,0x31,0x32,0x33,0x31,0x32,0x32,0x35,
-0x39,0x35,0x39,0x5A,0x30,0x76,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x54,0x43,
-0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x47,0x6D,0x62,
-0x48,0x31,0x22,0x30,0x20,0x06,0x03,0x55,0x04,0x0B,0x13,0x19,0x54,0x43,0x20,0x54,
-0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x43,0x6C,0x61,0x73,0x73,
-0x20,0x32,0x20,0x43,0x41,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x03,0x13,0x1C,
-0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x43,
-0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x43,0x41,0x20,0x49,0x49,0x30,0x82,0x01,0x22,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,
-0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xAB,0x80,0x87,
-0x9B,0x8E,0xF0,0xC3,0x7C,0x87,0xD7,0xE8,0x24,0x82,0x11,0xB3,0x3C,0xDD,0x43,0x62,
-0xEE,0xF8,0xC3,0x45,0xDA,0xE8,0xE1,0xA0,0x5F,0xD1,0x2A,0xB2,0xEA,0x93,0x68,0xDF,
-0xB4,0xC8,0xD6,0x43,0xE9,0xC4,0x75,0x59,0x7F,0xFC,0xE1,0x1D,0xF8,0x31,0x70,0x23,
-0x1B,0x88,0x9E,0x27,0xB9,0x7B,0xFD,0x3A,0xD2,0xC9,0xA9,0xE9,0x14,0x2F,0x90,0xBE,
-0x03,0x52,0xC1,0x49,0xCD,0xF6,0xFD,0xE4,0x08,0x66,0x0B,0x57,0x8A,0xA2,0x42,0xA0,
-0xB8,0xD5,0x7F,0x69,0x5C,0x90,0x32,0xB2,0x97,0x0D,0xCA,0x4A,0xDC,0x46,0x3E,0x02,
-0x55,0x89,0x53,0xE3,0x1A,0x5A,0xCB,0x36,0xC6,0x07,0x56,0xF7,0x8C,0xCF,0x11,0xF4,
-0x4C,0xBB,0x30,0x70,0x04,0x95,0xA5,0xF6,0x39,0x8C,0xFD,0x73,0x81,0x08,0x7D,0x89,
-0x5E,0x32,0x1E,0x22,0xA9,0x22,0x45,0x4B,0xB0,0x66,0x2E,0x30,0xCC,0x9F,0x65,0xFD,
-0xFC,0xCB,0x81,0xA9,0xF1,0xE0,0x3B,0xAF,0xA3,0x86,0xD1,0x89,0xEA,0xC4,0x45,0x79,
-0x50,0x5D,0xAE,0xE9,0x21,0x74,0x92,0x4D,0x8B,0x59,0x82,0x8F,0x94,0xE3,0xE9,0x4A,
-0xF1,0xE7,0x49,0xB0,0x14,0xE3,0xF5,0x62,0xCB,0xD5,0x72,0xBD,0x1F,0xB9,0xD2,0x9F,
-0xA0,0xCD,0xA8,0xFA,0x01,0xC8,0xD9,0x0D,0xDF,0xDA,0xFC,0x47,0x9D,0xB3,0xC8,0x54,
-0xDF,0x49,0x4A,0xF1,0x21,0xA9,0xFE,0x18,0x4E,0xEE,0x48,0xD4,0x19,0xBB,0xEF,0x7D,
-0xE4,0xE2,0x9D,0xCB,0x5B,0xB6,0x6E,0xFF,0xE3,0xCD,0x5A,0xE7,0x74,0x82,0x05,0xBA,
-0x80,0x25,0x38,0xCB,0xE4,0x69,0x9E,0xAF,0x41,0xAA,0x1A,0x84,0xF5,0x02,0x03,0x01,
-0x00,0x01,0xA3,0x82,0x01,0x34,0x30,0x82,0x01,0x30,0x30,0x0F,0x06,0x03,0x55,0x1D,
-0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,
-0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,
-0x1D,0x0E,0x04,0x16,0x04,0x14,0xE3,0xAB,0x54,0x4C,0x80,0xA1,0xDB,0x56,0x43,0xB7,
-0x91,0x4A,0xCB,0xF3,0x82,0x7A,0x13,0x5C,0x08,0xAB,0x30,0x81,0xED,0x06,0x03,0x55,
-0x1D,0x1F,0x04,0x81,0xE5,0x30,0x81,0xE2,0x30,0x81,0xDF,0xA0,0x81,0xDC,0xA0,0x81,
-0xD9,0x86,0x35,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x74,0x72,
-0x75,0x73,0x74,0x63,0x65,0x6E,0x74,0x65,0x72,0x2E,0x64,0x65,0x2F,0x63,0x72,0x6C,
-0x2F,0x76,0x32,0x2F,0x74,0x63,0x5F,0x63,0x6C,0x61,0x73,0x73,0x5F,0x32,0x5F,0x63,
-0x61,0x5F,0x49,0x49,0x2E,0x63,0x72,0x6C,0x86,0x81,0x9F,0x6C,0x64,0x61,0x70,0x3A,
-0x2F,0x2F,0x77,0x77,0x77,0x2E,0x74,0x72,0x75,0x73,0x74,0x63,0x65,0x6E,0x74,0x65,
-0x72,0x2E,0x64,0x65,0x2F,0x43,0x4E,0x3D,0x54,0x43,0x25,0x32,0x30,0x54,0x72,0x75,
-0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x25,0x32,0x30,0x43,0x6C,0x61,0x73,0x73,
-0x25,0x32,0x30,0x32,0x25,0x32,0x30,0x43,0x41,0x25,0x32,0x30,0x49,0x49,0x2C,0x4F,
-0x3D,0x54,0x43,0x25,0x32,0x30,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,
-0x72,0x25,0x32,0x30,0x47,0x6D,0x62,0x48,0x2C,0x4F,0x55,0x3D,0x72,0x6F,0x6F,0x74,
-0x63,0x65,0x72,0x74,0x73,0x2C,0x44,0x43,0x3D,0x74,0x72,0x75,0x73,0x74,0x63,0x65,
-0x6E,0x74,0x65,0x72,0x2C,0x44,0x43,0x3D,0x64,0x65,0x3F,0x63,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x65,0x52,0x65,0x76,0x6F,0x63,0x61,0x74,0x69,0x6F,0x6E,
-0x4C,0x69,0x73,0x74,0x3F,0x62,0x61,0x73,0x65,0x3F,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x8C,0xD7,
-0xDF,0x7E,0xEE,0x1B,0x80,0x10,0xB3,0x83,0xF5,0xDB,0x11,0xEA,0x6B,0x4B,0xA8,0x92,
-0x18,0xD9,0xF7,0x07,0x39,0xF5,0x2C,0xBE,0x06,0x75,0x7A,0x68,0x53,0x15,0x1C,0xEA,
-0x4A,0xED,0x5E,0xFC,0x23,0xB2,0x13,0xA0,0xD3,0x09,0xFF,0xF6,0xF6,0x2E,0x6B,0x41,
-0x71,0x79,0xCD,0xE2,0x6D,0xFD,0xAE,0x59,0x6B,0x85,0x1D,0xB8,0x4E,0x22,0x9A,0xED,
-0x66,0x39,0x6E,0x4B,0x94,0xE6,0x55,0xFC,0x0B,0x1B,0x8B,0x77,0xC1,0x53,0x13,0x66,
-0x89,0xD9,0x28,0xD6,0x8B,0xF3,0x45,0x4A,0x63,0xB7,0xFD,0x7B,0x0B,0x61,0x5D,0xB8,
-0x6D,0xBE,0xC3,0xDC,0x5B,0x79,0xD2,0xED,0x86,0xE5,0xA2,0x4D,0xBE,0x5E,0x74,0x7C,
-0x6A,0xED,0x16,0x38,0x1F,0x7F,0x58,0x81,0x5A,0x1A,0xEB,0x32,0x88,0x2D,0xB2,0xF3,
-0x39,0x77,0x80,0xAF,0x5E,0xB6,0x61,0x75,0x29,0xDB,0x23,0x4D,0x88,0xCA,0x50,0x28,
-0xCB,0x85,0xD2,0xD3,0x10,0xA2,0x59,0x6E,0xD3,0x93,0x54,0x00,0x7A,0xA2,0x46,0x95,
-0x86,0x05,0x9C,0xA9,0x19,0x98,0xE5,0x31,0x72,0x0C,0x00,0xE2,0x67,0xD9,0x40,0xE0,
-0x24,0x33,0x7B,0x6F,0x2C,0xB9,0x5C,0xAB,0x65,0x9D,0x2C,0xAC,0x76,0xEA,0x35,0x99,
-0xF5,0x97,0xB9,0x0F,0x24,0xEC,0xC7,0x76,0x21,0x28,0x65,0xAE,0x57,0xE8,0x07,0x88,
-0x75,0x4A,0x56,0xA0,0xD2,0x05,0x3A,0xA4,0xE6,0x8D,0x92,0x88,0x2C,0xF3,0xF2,0xE1,
-0xC1,0xC6,0x61,0xDB,0x41,0xC5,0xC7,0x9B,0xF7,0x0E,0x1A,0x51,0x45,0xC2,0x61,0x6B,
-0xDC,0x64,0x27,0x17,0x8C,0x5A,0xB7,0xDA,0x74,0x28,0xCD,0x97,0xE4,0xBD,
-};
-
-
-/* subject:/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Class 3 CA/CN=TC TrustCenter Class 3 CA II */
-/* issuer :/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Class 3 CA/CN=TC TrustCenter Class 3 CA II */
-
-
-const unsigned char TC_TrustCenter_Class_3_CA_II_certificate[1198]={
-0x30,0x82,0x04,0xAA,0x30,0x82,0x03,0x92,0xA0,0x03,0x02,0x01,0x02,0x02,0x0E,0x4A,
-0x47,0x00,0x01,0x00,0x02,0xE5,0xA0,0x5D,0xD6,0x3F,0x00,0x51,0xBF,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x76,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x13,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,
-0x6E,0x74,0x65,0x72,0x20,0x47,0x6D,0x62,0x48,0x31,0x22,0x30,0x20,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x19,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,
-0x65,0x72,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x43,0x41,0x31,0x25,0x30,
-0x23,0x06,0x03,0x55,0x04,0x03,0x13,0x1C,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,
-0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x43,
-0x41,0x20,0x49,0x49,0x30,0x1E,0x17,0x0D,0x30,0x36,0x30,0x31,0x31,0x32,0x31,0x34,
-0x34,0x31,0x35,0x37,0x5A,0x17,0x0D,0x32,0x35,0x31,0x32,0x33,0x31,0x32,0x32,0x35,
-0x39,0x35,0x39,0x5A,0x30,0x76,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,0x13,0x54,0x43,
-0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x47,0x6D,0x62,
-0x48,0x31,0x22,0x30,0x20,0x06,0x03,0x55,0x04,0x0B,0x13,0x19,0x54,0x43,0x20,0x54,
-0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x43,0x6C,0x61,0x73,0x73,
-0x20,0x33,0x20,0x43,0x41,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x03,0x13,0x1C,
-0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x43,
-0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x43,0x41,0x20,0x49,0x49,0x30,0x82,0x01,0x22,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,
-0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xB4,0xE0,0xBB,
-0x51,0xBB,0x39,0x5C,0x8B,0x04,0xC5,0x4C,0x79,0x1C,0x23,0x86,0x31,0x10,0x63,0x43,
-0x55,0x27,0x3F,0xC6,0x45,0xC7,0xA4,0x3D,0xEC,0x09,0x0D,0x1A,0x1E,0x20,0xC2,0x56,
-0x1E,0xDE,0x1B,0x37,0x07,0x30,0x22,0x2F,0x6F,0xF1,0x06,0xF1,0xAB,0xAD,0xD6,0xC8,
-0xAB,0x61,0xA3,0x2F,0x43,0xC4,0xB0,0xB2,0x2D,0xFC,0xC3,0x96,0x69,0x7B,0x7E,0x8A,
-0xE4,0xCC,0xC0,0x39,0x12,0x90,0x42,0x60,0xC9,0xCC,0x35,0x68,0xEE,0xDA,0x5F,0x90,
-0x56,0x5F,0xCD,0x1C,0x4D,0x5B,0x58,0x49,0xEB,0x0E,0x01,0x4F,0x64,0xFA,0x2C,0x3C,
-0x89,0x58,0xD8,0x2F,0x2E,0xE2,0xB0,0x68,0xE9,0x22,0x3B,0x75,0x89,0xD6,0x44,0x1A,
-0x65,0xF2,0x1B,0x97,0x26,0x1D,0x28,0x6D,0xAC,0xE8,0xBD,0x59,0x1D,0x2B,0x24,0xF6,
-0xD6,0x84,0x03,0x66,0x88,0x24,0x00,0x78,0x60,0xF1,0xF8,0xAB,0xFE,0x02,0xB2,0x6B,
-0xFB,0x22,0xFB,0x35,0xE6,0x16,0xD1,0xAD,0xF6,0x2E,0x12,0xE4,0xFA,0x35,0x6A,0xE5,
-0x19,0xB9,0x5D,0xDB,0x3B,0x1E,0x1A,0xFB,0xD3,0xFF,0x15,0x14,0x08,0xD8,0x09,0x6A,
-0xBA,0x45,0x9D,0x14,0x79,0x60,0x7D,0xAF,0x40,0x8A,0x07,0x73,0xB3,0x93,0x96,0xD3,
-0x74,0x34,0x8D,0x3A,0x37,0x29,0xDE,0x5C,0xEC,0xF5,0xEE,0x2E,0x31,0xC2,0x20,0xDC,
-0xBE,0xF1,0x4F,0x7F,0x23,0x52,0xD9,0x5B,0xE2,0x64,0xD9,0x9C,0xAA,0x07,0x08,0xB5,
-0x45,0xBD,0xD1,0xD0,0x31,0xC1,0xAB,0x54,0x9F,0xA9,0xD2,0xC3,0x62,0x60,0x03,0xF1,
-0xBB,0x39,0x4A,0x92,0x4A,0x3D,0x0A,0xB9,0x9D,0xC5,0xA0,0xFE,0x37,0x02,0x03,0x01,
-0x00,0x01,0xA3,0x82,0x01,0x34,0x30,0x82,0x01,0x30,0x30,0x0F,0x06,0x03,0x55,0x1D,
-0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,
-0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,
-0x1D,0x0E,0x04,0x16,0x04,0x14,0xD4,0xA2,0xFC,0x9F,0xB3,0xC3,0xD8,0x03,0xD3,0x57,
-0x5C,0x07,0xA4,0xD0,0x24,0xA7,0xC0,0xF2,0x00,0xD4,0x30,0x81,0xED,0x06,0x03,0x55,
-0x1D,0x1F,0x04,0x81,0xE5,0x30,0x81,0xE2,0x30,0x81,0xDF,0xA0,0x81,0xDC,0xA0,0x81,
-0xD9,0x86,0x35,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x74,0x72,
-0x75,0x73,0x74,0x63,0x65,0x6E,0x74,0x65,0x72,0x2E,0x64,0x65,0x2F,0x63,0x72,0x6C,
-0x2F,0x76,0x32,0x2F,0x74,0x63,0x5F,0x63,0x6C,0x61,0x73,0x73,0x5F,0x33,0x5F,0x63,
-0x61,0x5F,0x49,0x49,0x2E,0x63,0x72,0x6C,0x86,0x81,0x9F,0x6C,0x64,0x61,0x70,0x3A,
-0x2F,0x2F,0x77,0x77,0x77,0x2E,0x74,0x72,0x75,0x73,0x74,0x63,0x65,0x6E,0x74,0x65,
-0x72,0x2E,0x64,0x65,0x2F,0x43,0x4E,0x3D,0x54,0x43,0x25,0x32,0x30,0x54,0x72,0x75,
-0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x25,0x32,0x30,0x43,0x6C,0x61,0x73,0x73,
-0x25,0x32,0x30,0x33,0x25,0x32,0x30,0x43,0x41,0x25,0x32,0x30,0x49,0x49,0x2C,0x4F,
-0x3D,0x54,0x43,0x25,0x32,0x30,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,
-0x72,0x25,0x32,0x30,0x47,0x6D,0x62,0x48,0x2C,0x4F,0x55,0x3D,0x72,0x6F,0x6F,0x74,
-0x63,0x65,0x72,0x74,0x73,0x2C,0x44,0x43,0x3D,0x74,0x72,0x75,0x73,0x74,0x63,0x65,
-0x6E,0x74,0x65,0x72,0x2C,0x44,0x43,0x3D,0x64,0x65,0x3F,0x63,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x65,0x52,0x65,0x76,0x6F,0x63,0x61,0x74,0x69,0x6F,0x6E,
-0x4C,0x69,0x73,0x74,0x3F,0x62,0x61,0x73,0x65,0x3F,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x36,0x60,
-0xE4,0x70,0xF7,0x06,0x20,0x43,0xD9,0x23,0x1A,0x42,0xF2,0xF8,0xA3,0xB2,0xB9,0x4D,
-0x8A,0xB4,0xF3,0xC2,0x9A,0x55,0x31,0x7C,0xC4,0x3B,0x67,0x9A,0xB4,0xDF,0x4D,0x0E,
-0x8A,0x93,0x4A,0x17,0x8B,0x1B,0x8D,0xCA,0x89,0xE1,0xCF,0x3A,0x1E,0xAC,0x1D,0xF1,
-0x9C,0x32,0xB4,0x8E,0x59,0x76,0xA2,0x41,0x85,0x25,0x37,0xA0,0x13,0xD0,0xF5,0x7C,
-0x4E,0xD5,0xEA,0x96,0xE2,0x6E,0x72,0xC1,0xBB,0x2A,0xFE,0x6C,0x6E,0xF8,0x91,0x98,
-0x46,0xFC,0xC9,0x1B,0x57,0x5B,0xEA,0xC8,0x1A,0x3B,0x3F,0xB0,0x51,0x98,0x3C,0x07,
-0xDA,0x2C,0x59,0x01,0xDA,0x8B,0x44,0xE8,0xE1,0x74,0xFD,0xA7,0x68,0xDD,0x54,0xBA,
-0x83,0x46,0xEC,0xC8,0x46,0xB5,0xF8,0xAF,0x97,0xC0,0x3B,0x09,0x1C,0x8F,0xCE,0x72,
-0x96,0x3D,0x33,0x56,0x70,0xBC,0x96,0xCB,0xD8,0xD5,0x7D,0x20,0x9A,0x83,0x9F,0x1A,
-0xDC,0x39,0xF1,0xC5,0x72,0xA3,0x11,0x03,0xFD,0x3B,0x42,0x52,0x29,0xDB,0xE8,0x01,
-0xF7,0x9B,0x5E,0x8C,0xD6,0x8D,0x86,0x4E,0x19,0xFA,0xBC,0x1C,0xBE,0xC5,0x21,0xA5,
-0x87,0x9E,0x78,0x2E,0x36,0xDB,0x09,0x71,0xA3,0x72,0x34,0xF8,0x6C,0xE3,0x06,0x09,
-0xF2,0x5E,0x56,0xA5,0xD3,0xDD,0x98,0xFA,0xD4,0xE6,0x06,0xF4,0xF0,0xB6,0x20,0x63,
-0x4B,0xEA,0x29,0xBD,0xAA,0x82,0x66,0x1E,0xFB,0x81,0xAA,0xA7,0x37,0xAD,0x13,0x18,
-0xE6,0x92,0xC3,0x81,0xC1,0x33,0xBB,0x88,0x1E,0xA1,0xE7,0xE2,0xB4,0xBD,0x31,0x6C,
-0x0E,0x51,0x3D,0x6F,0xFB,0x96,0x56,0x80,0xE2,0x36,0x17,0xD1,0xDC,0xE4,
-};
-
-
-/* subject:/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Universal CA/CN=TC TrustCenter Universal CA I */
-/* issuer :/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Universal CA/CN=TC TrustCenter Universal CA I */
-
-
-const unsigned char TC_TrustCenter_Universal_CA_I_certificate[993]={
-0x30,0x82,0x03,0xDD,0x30,0x82,0x02,0xC5,0xA0,0x03,0x02,0x01,0x02,0x02,0x0E,0x1D,
-0xA2,0x00,0x01,0x00,0x02,0xEC,0xB7,0x60,0x80,0x78,0x8D,0xB6,0x06,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x79,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x13,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,
-0x6E,0x74,0x65,0x72,0x20,0x47,0x6D,0x62,0x48,0x31,0x24,0x30,0x22,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x1B,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,
-0x65,0x72,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,0x43,0x41,0x31,
-0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x03,0x13,0x1D,0x54,0x43,0x20,0x54,0x72,0x75,
-0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,
-0x61,0x6C,0x20,0x43,0x41,0x20,0x49,0x30,0x1E,0x17,0x0D,0x30,0x36,0x30,0x33,0x32,
-0x32,0x31,0x35,0x35,0x34,0x32,0x38,0x5A,0x17,0x0D,0x32,0x35,0x31,0x32,0x33,0x31,
-0x32,0x32,0x35,0x39,0x35,0x39,0x5A,0x30,0x79,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,
-0x04,0x06,0x13,0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,0x03,0x55,0x04,0x0A,0x13,
-0x13,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,
-0x47,0x6D,0x62,0x48,0x31,0x24,0x30,0x22,0x06,0x03,0x55,0x04,0x0B,0x13,0x1B,0x54,
-0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x55,0x6E,
-0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,0x43,0x41,0x31,0x26,0x30,0x24,0x06,0x03,
-0x55,0x04,0x03,0x13,0x1D,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,
-0x74,0x65,0x72,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,0x43,0x41,
-0x20,0x49,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,
-0x01,0x01,0x00,0xA4,0x77,0x23,0x96,0x44,0xAF,0x90,0xF4,0x31,0xA7,0x10,0xF4,0x26,
-0x87,0x9C,0xF3,0x38,0xD9,0x0F,0x5E,0xDE,0xCF,0x41,0xE8,0x31,0xAD,0xC6,0x74,0x91,
-0x24,0x96,0x78,0x1E,0x09,0xA0,0x9B,0x9A,0x95,0x4A,0x4A,0xF5,0x62,0x7C,0x02,0xA8,
-0xCA,0xAC,0xFB,0x5A,0x04,0x76,0x39,0xDE,0x5F,0xF1,0xF9,0xB3,0xBF,0xF3,0x03,0x58,
-0x55,0xD2,0xAA,0xB7,0xE3,0x04,0x22,0xD1,0xF8,0x94,0xDA,0x22,0x08,0x00,0x8D,0xD3,
-0x7C,0x26,0x5D,0xCC,0x77,0x79,0xE7,0x2C,0x78,0x39,0xA8,0x26,0x73,0x0E,0xA2,0x5D,
-0x25,0x69,0x85,0x4F,0x55,0x0E,0x9A,0xEF,0xC6,0xB9,0x44,0xE1,0x57,0x3D,0xDF,0x1F,
-0x54,0x22,0xE5,0x6F,0x65,0xAA,0x33,0x84,0x3A,0xF3,0xCE,0x7A,0xBE,0x55,0x97,0xAE,
-0x8D,0x12,0x0F,0x14,0x33,0xE2,0x50,0x70,0xC3,0x49,0x87,0x13,0xBC,0x51,0xDE,0xD7,
-0x98,0x12,0x5A,0xEF,0x3A,0x83,0x33,0x92,0x06,0x75,0x8B,0x92,0x7C,0x12,0x68,0x7B,
-0x70,0x6A,0x0F,0xB5,0x9B,0xB6,0x77,0x5B,0x48,0x59,0x9D,0xE4,0xEF,0x5A,0xAD,0xF3,
-0xC1,0x9E,0xD4,0xD7,0x45,0x4E,0xCA,0x56,0x34,0x21,0xBC,0x3E,0x17,0x5B,0x6F,0x77,
-0x0C,0x48,0x01,0x43,0x29,0xB0,0xDD,0x3F,0x96,0x6E,0xE6,0x95,0xAA,0x0C,0xC0,0x20,
-0xB6,0xFD,0x3E,0x36,0x27,0x9C,0xE3,0x5C,0xCF,0x4E,0x81,0xDC,0x19,0xBB,0x91,0x90,
-0x7D,0xEC,0xE6,0x97,0x04,0x1E,0x93,0xCC,0x22,0x49,0xD7,0x97,0x86,0xB6,0x13,0x0A,
-0x3C,0x43,0x23,0x77,0x7E,0xF0,0xDC,0xE6,0xCD,0x24,0x1F,0x3B,0x83,0x9B,0x34,0x3A,
-0x83,0x34,0xE3,0x02,0x03,0x01,0x00,0x01,0xA3,0x63,0x30,0x61,0x30,0x1F,0x06,0x03,
-0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x92,0xA4,0x75,0x2C,0xA4,0x9E,0xBE,
-0x81,0x44,0xEB,0x79,0xFC,0x8A,0xC5,0x95,0xA5,0xEB,0x10,0x75,0x73,0x30,0x0F,0x06,
-0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,
-0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x86,0x30,0x1D,
-0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x92,0xA4,0x75,0x2C,0xA4,0x9E,0xBE,
-0x81,0x44,0xEB,0x79,0xFC,0x8A,0xC5,0x95,0xA5,0xEB,0x10,0x75,0x73,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,
-0x00,0x28,0xD2,0xE0,0x86,0xD5,0xE6,0xF8,0x7B,0xF0,0x97,0xDC,0x22,0x6B,0x3B,0x95,
-0x14,0x56,0x0F,0x11,0x30,0xA5,0x9A,0x4F,0x3A,0xB0,0x3A,0xE0,0x06,0xCB,0x65,0xF5,
-0xED,0xC6,0x97,0x27,0xFE,0x25,0xF2,0x57,0xE6,0x5E,0x95,0x8C,0x3E,0x64,0x60,0x15,
-0x5A,0x7F,0x2F,0x0D,0x01,0xC5,0xB1,0x60,0xFD,0x45,0x35,0xCF,0xF0,0xB2,0xBF,0x06,
-0xD9,0xEF,0x5A,0xBE,0xB3,0x62,0x21,0xB4,0xD7,0xAB,0x35,0x7C,0x53,0x3E,0xA6,0x27,
-0xF1,0xA1,0x2D,0xDA,0x1A,0x23,0x9D,0xCC,0xDD,0xEC,0x3C,0x2D,0x9E,0x27,0x34,0x5D,
-0x0F,0xC2,0x36,0x79,0xBC,0xC9,0x4A,0x62,0x2D,0xED,0x6B,0xD9,0x7D,0x41,0x43,0x7C,
-0xB6,0xAA,0xCA,0xED,0x61,0xB1,0x37,0x82,0x15,0x09,0x1A,0x8A,0x16,0x30,0xD8,0xEC,
-0xC9,0xD6,0x47,0x72,0x78,0x4B,0x10,0x46,0x14,0x8E,0x5F,0x0E,0xAF,0xEC,0xC7,0x2F,
-0xAB,0x10,0xD7,0xB6,0xF1,0x6E,0xEC,0x86,0xB2,0xC2,0xE8,0x0D,0x92,0x73,0xDC,0xA2,
-0xF4,0x0F,0x3A,0xBF,0x61,0x23,0x10,0x89,0x9C,0x48,0x40,0x6E,0x70,0x00,0xB3,0xD3,
-0xBA,0x37,0x44,0x58,0x11,0x7A,0x02,0x6A,0x88,0xF0,0x37,0x34,0xF0,0x19,0xE9,0xAC,
-0xD4,0x65,0x73,0xF6,0x69,0x8C,0x64,0x94,0x3A,0x79,0x85,0x29,0xB0,0x16,0x2B,0x0C,
-0x82,0x3F,0x06,0x9C,0xC7,0xFD,0x10,0x2B,0x9E,0x0F,0x2C,0xB6,0x9E,0xE3,0x15,0xBF,
-0xD9,0x36,0x1C,0xBA,0x25,0x1A,0x52,0x3D,0x1A,0xEC,0x22,0x0C,0x1C,0xE0,0xA4,0xA2,
-0x3D,0xF0,0xE8,0x39,0xCF,0x81,0xC0,0x7B,0xED,0x5D,0x1F,0x6F,0xC5,0xD0,0x0B,0xD7,
-0x98,
-};
-
-
-/* subject:/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Universal CA/CN=TC TrustCenter Universal CA III */
-/* issuer :/C=DE/O=TC TrustCenter GmbH/OU=TC TrustCenter Universal CA/CN=TC TrustCenter Universal CA III */
-
-
-const unsigned char TC_TrustCenter_Universal_CA_III_certificate[997]={
-0x30,0x82,0x03,0xE1,0x30,0x82,0x02,0xC9,0xA0,0x03,0x02,0x01,0x02,0x02,0x0E,0x63,
-0x25,0x00,0x01,0x00,0x02,0x14,0x8D,0x33,0x15,0x02,0xE4,0x6C,0xF4,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x7B,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x13,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,
-0x6E,0x74,0x65,0x72,0x20,0x47,0x6D,0x62,0x48,0x31,0x24,0x30,0x22,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x1B,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,
-0x65,0x72,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,0x43,0x41,0x31,
-0x28,0x30,0x26,0x06,0x03,0x55,0x04,0x03,0x13,0x1F,0x54,0x43,0x20,0x54,0x72,0x75,
-0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,
-0x61,0x6C,0x20,0x43,0x41,0x20,0x49,0x49,0x49,0x30,0x1E,0x17,0x0D,0x30,0x39,0x30,
-0x39,0x30,0x39,0x30,0x38,0x31,0x35,0x32,0x37,0x5A,0x17,0x0D,0x32,0x39,0x31,0x32,
-0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x7B,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x44,0x45,0x31,0x1C,0x30,0x1A,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x13,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,
-0x72,0x20,0x47,0x6D,0x62,0x48,0x31,0x24,0x30,0x22,0x06,0x03,0x55,0x04,0x0B,0x13,
-0x1B,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,0x65,0x6E,0x74,0x65,0x72,0x20,
-0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,0x43,0x41,0x31,0x28,0x30,0x26,
-0x06,0x03,0x55,0x04,0x03,0x13,0x1F,0x54,0x43,0x20,0x54,0x72,0x75,0x73,0x74,0x43,
-0x65,0x6E,0x74,0x65,0x72,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,0x6C,0x20,
-0x43,0x41,0x20,0x49,0x49,0x49,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,
-0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xC2,0xDA,0x9C,0x62,0xB0,0xB9,0x71,0x12,0xB0,
-0x0B,0xC8,0x1A,0x57,0xB2,0xAE,0x83,0x14,0x99,0xB3,0x34,0x4B,0x9B,0x90,0xA2,0xC5,
-0xE7,0xE7,0x2F,0x02,0xA0,0x4D,0x2D,0xA4,0xFA,0x85,0xDA,0x9B,0x25,0x85,0x2D,0x40,
-0x28,0x20,0x6D,0xEA,0xE0,0xBD,0xB1,0x48,0x83,0x22,0x29,0x44,0x9F,0x4E,0x83,0xEE,
-0x35,0x51,0x13,0x73,0x74,0xD5,0xBC,0xF2,0x30,0x66,0x94,0x53,0xC0,0x40,0x36,0x2F,
-0x0C,0x84,0x65,0xCE,0x0F,0x6E,0xC2,0x58,0x93,0xE8,0x2C,0x0B,0x3A,0xE9,0xC1,0x8E,
-0xFB,0xF2,0x6B,0xCA,0x3C,0xE2,0x9C,0x4E,0x8E,0xE4,0xF9,0x7D,0xD3,0x27,0x9F,0x1B,
-0xD5,0x67,0x78,0x87,0x2D,0x7F,0x0B,0x47,0xB3,0xC7,0xE8,0xC9,0x48,0x7C,0xAF,0x2F,
-0xCC,0x0A,0xD9,0x41,0xEF,0x9F,0xFE,0x9A,0xE1,0xB2,0xAE,0xF9,0x53,0xB5,0xE5,0xE9,
-0x46,0x9F,0x60,0xE3,0xDF,0x8D,0xD3,0x7F,0xFB,0x96,0x7E,0xB3,0xB5,0x72,0xF8,0x4B,
-0xAD,0x08,0x79,0xCD,0x69,0x89,0x40,0x27,0xF5,0x2A,0xC1,0xAD,0x43,0xEC,0xA4,0x53,
-0xC8,0x61,0xB6,0xF7,0xD2,0x79,0x2A,0x67,0x18,0x76,0x48,0x6D,0x5B,0x25,0x01,0xD1,
-0x26,0xC5,0xB7,0x57,0x69,0x23,0x15,0x5B,0x61,0x8A,0xAD,0xF0,0x1B,0x2D,0xD9,0xAF,
-0x5C,0xF1,0x26,0x90,0x69,0xA9,0xD5,0x0C,0x40,0xF5,0x33,0x80,0x43,0x8F,0x9C,0xA3,
-0x76,0x2A,0x45,0xB4,0xAF,0xBF,0x7F,0x3E,0x87,0x3F,0x76,0xC5,0xCD,0x2A,0xDE,0x20,
-0xC5,0x16,0x58,0xCB,0xF9,0x1B,0xF5,0x0F,0xCB,0x0D,0x11,0x52,0x64,0xB8,0xD2,0x76,
-0x62,0x77,0x83,0xF1,0x58,0x9F,0xFF,0x02,0x03,0x01,0x00,0x01,0xA3,0x63,0x30,0x61,
-0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x56,0xE7,0xE1,
-0x5B,0x25,0x43,0x80,0xE0,0xF6,0x8C,0xE1,0x71,0xBC,0x8E,0xE5,0x80,0x2F,0xC4,0x48,
-0xE2,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,
-0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,
-0x01,0x06,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x56,0xE7,0xE1,
-0x5B,0x25,0x43,0x80,0xE0,0xF6,0x8C,0xE1,0x71,0xBC,0x8E,0xE5,0x80,0x2F,0xC4,0x48,
-0xE2,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,
-0x03,0x82,0x01,0x01,0x00,0x83,0xC7,0xAF,0xEA,0x7F,0x4D,0x0A,0x3C,0x39,0xB1,0x68,
-0xBE,0x7B,0x6D,0x89,0x2E,0xE9,0xB3,0x09,0xE7,0x18,0x57,0x8D,0x85,0x9A,0x17,0xF3,
-0x76,0x42,0x50,0x13,0x0F,0xC7,0x90,0x6F,0x33,0xAD,0xC5,0x49,0x60,0x2B,0x6C,0x49,
-0x58,0x19,0xD4,0xE2,0xBE,0xB7,0xBF,0xAB,0x49,0xBC,0x94,0xC8,0xAB,0xBE,0x28,0x6C,
-0x16,0x68,0xE0,0xC8,0x97,0x46,0x20,0xA0,0x68,0x67,0x60,0x88,0x39,0x20,0x51,0xD8,
-0x68,0x01,0x11,0xCE,0xA7,0xF6,0x11,0x07,0xF6,0xEC,0xEC,0xAC,0x1A,0x1F,0xB2,0x66,
-0x6E,0x56,0x67,0x60,0x7A,0x74,0x5E,0xC0,0x6D,0x97,0x36,0xAE,0xB5,0x0D,0x5D,0x66,
-0x73,0xC0,0x25,0x32,0x45,0xD8,0x4A,0x06,0x07,0x8F,0xC4,0xB7,0x07,0xB1,0x4D,0x06,
-0x0D,0xE1,0xA5,0xEB,0xF4,0x75,0xCA,0xBA,0x9C,0xD0,0xBD,0xB3,0xD3,0x32,0x24,0x4C,
-0xEE,0x7E,0xE2,0x76,0x04,0x4B,0x49,0x53,0xD8,0xF2,0xE9,0x54,0x33,0xFC,0xE5,0x71,
-0x1F,0x3D,0x14,0x5C,0x96,0x4B,0xF1,0x3A,0xF2,0x00,0xBB,0x6C,0xB4,0xFA,0x96,0x55,
-0x08,0x88,0x09,0xC1,0xCC,0x91,0x19,0x29,0xB0,0x20,0x2D,0xFF,0xCB,0x38,0xA4,0x40,
-0xE1,0x17,0xBE,0x79,0x61,0x80,0xFF,0x07,0x03,0x86,0x4C,0x4E,0x7B,0x06,0x9F,0x11,
-0x86,0x8D,0x89,0xEE,0x27,0xC4,0xDB,0xE2,0xBC,0x19,0x8E,0x0B,0xC3,0xC3,0x13,0xC7,
-0x2D,0x03,0x63,0x3B,0xD3,0xE8,0xE4,0xA2,0x2A,0xC2,0x82,0x08,0x94,0x16,0x54,0xF0,
-0xEF,0x1F,0x27,0x90,0x25,0xB8,0x0D,0x0E,0x28,0x1B,0x47,0x77,0x47,0xBD,0x1C,0xA8,
-0x25,0xF1,0x94,0xB4,0x66,
-};
-
-
-/* subject:/C=ZA/ST=Western Cape/L=Cape Town/O=Thawte Consulting cc/OU=Certification Services Division/CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com */
-/* issuer :/C=ZA/ST=Western Cape/L=Cape Town/O=Thawte Consulting cc/OU=Certification Services Division/CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com */
-
-
-const unsigned char Thawte_Premium_Server_CA_certificate[811]={
-0x30,0x82,0x03,0x27,0x30,0x82,0x02,0x90,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,
-0x81,0xCE,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x5A,0x41,0x31,
-0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x08,0x13,0x0C,0x57,0x65,0x73,0x74,0x65,0x72,
-0x6E,0x20,0x43,0x61,0x70,0x65,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04,0x07,0x13,
-0x09,0x43,0x61,0x70,0x65,0x20,0x54,0x6F,0x77,0x6E,0x31,0x1D,0x30,0x1B,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x14,0x54,0x68,0x61,0x77,0x74,0x65,0x20,0x43,0x6F,0x6E,0x73,
-0x75,0x6C,0x74,0x69,0x6E,0x67,0x20,0x63,0x63,0x31,0x28,0x30,0x26,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x1F,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,
-0x6E,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x20,0x44,0x69,0x76,0x69,0x73,
-0x69,0x6F,0x6E,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x54,0x68,
-0x61,0x77,0x74,0x65,0x20,0x50,0x72,0x65,0x6D,0x69,0x75,0x6D,0x20,0x53,0x65,0x72,
-0x76,0x65,0x72,0x20,0x43,0x41,0x31,0x28,0x30,0x26,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x09,0x01,0x16,0x19,0x70,0x72,0x65,0x6D,0x69,0x75,0x6D,0x2D,0x73,
-0x65,0x72,0x76,0x65,0x72,0x40,0x74,0x68,0x61,0x77,0x74,0x65,0x2E,0x63,0x6F,0x6D,
-0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x38,0x30,0x31,0x30,0x30,0x30,0x30,0x30,0x30,
-0x5A,0x17,0x0D,0x32,0x30,0x31,0x32,0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,
-0x30,0x81,0xCE,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x5A,0x41,
-0x31,0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x08,0x13,0x0C,0x57,0x65,0x73,0x74,0x65,
-0x72,0x6E,0x20,0x43,0x61,0x70,0x65,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04,0x07,
-0x13,0x09,0x43,0x61,0x70,0x65,0x20,0x54,0x6F,0x77,0x6E,0x31,0x1D,0x30,0x1B,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x14,0x54,0x68,0x61,0x77,0x74,0x65,0x20,0x43,0x6F,0x6E,
-0x73,0x75,0x6C,0x74,0x69,0x6E,0x67,0x20,0x63,0x63,0x31,0x28,0x30,0x26,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x1F,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,
-0x6F,0x6E,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x20,0x44,0x69,0x76,0x69,
-0x73,0x69,0x6F,0x6E,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x54,
-0x68,0x61,0x77,0x74,0x65,0x20,0x50,0x72,0x65,0x6D,0x69,0x75,0x6D,0x20,0x53,0x65,
-0x72,0x76,0x65,0x72,0x20,0x43,0x41,0x31,0x28,0x30,0x26,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x09,0x01,0x16,0x19,0x70,0x72,0x65,0x6D,0x69,0x75,0x6D,0x2D,
-0x73,0x65,0x72,0x76,0x65,0x72,0x40,0x74,0x68,0x61,0x77,0x74,0x65,0x2E,0x63,0x6F,
-0x6D,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,0x02,0x81,0x81,0x00,0xD2,0x36,
-0x36,0x6A,0x8B,0xD7,0xC2,0x5B,0x9E,0xDA,0x81,0x41,0x62,0x8F,0x38,0xEE,0x49,0x04,
-0x55,0xD6,0xD0,0xEF,0x1C,0x1B,0x95,0x16,0x47,0xEF,0x18,0x48,0x35,0x3A,0x52,0xF4,
-0x2B,0x6A,0x06,0x8F,0x3B,0x2F,0xEA,0x56,0xE3,0xAF,0x86,0x8D,0x9E,0x17,0xF7,0x9E,
-0xB4,0x65,0x75,0x02,0x4D,0xEF,0xCB,0x09,0xA2,0x21,0x51,0xD8,0x9B,0xD0,0x67,0xD0,
-0xBA,0x0D,0x92,0x06,0x14,0x73,0xD4,0x93,0xCB,0x97,0x2A,0x00,0x9C,0x5C,0x4E,0x0C,
-0xBC,0xFA,0x15,0x52,0xFC,0xF2,0x44,0x6E,0xDA,0x11,0x4A,0x6E,0x08,0x9F,0x2F,0x2D,
-0xE3,0xF9,0xAA,0x3A,0x86,0x73,0xB6,0x46,0x53,0x58,0xC8,0x89,0x05,0xBD,0x83,0x11,
-0xB8,0x73,0x3F,0xAA,0x07,0x8D,0xF4,0x42,0x4D,0xE7,0x40,0x9D,0x1C,0x37,0x02,0x03,
-0x01,0x00,0x01,0xA3,0x13,0x30,0x11,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,
-0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x26,0x48,0x2C,0x16,0xC2,
-0x58,0xFA,0xE8,0x16,0x74,0x0C,0xAA,0xAA,0x5F,0x54,0x3F,0xF2,0xD7,0xC9,0x78,0x60,
-0x5E,0x5E,0x6E,0x37,0x63,0x22,0x77,0x36,0x7E,0xB2,0x17,0xC4,0x34,0xB9,0xF5,0x08,
-0x85,0xFC,0xC9,0x01,0x38,0xFF,0x4D,0xBE,0xF2,0x16,0x42,0x43,0xE7,0xBB,0x5A,0x46,
-0xFB,0xC1,0xC6,0x11,0x1F,0xF1,0x4A,0xB0,0x28,0x46,0xC9,0xC3,0xC4,0x42,0x7D,0xBC,
-0xFA,0xAB,0x59,0x6E,0xD5,0xB7,0x51,0x88,0x11,0xE3,0xA4,0x85,0x19,0x6B,0x82,0x4C,
-0xA4,0x0C,0x12,0xAD,0xE9,0xA4,0xAE,0x3F,0xF1,0xC3,0x49,0x65,0x9A,0x8C,0xC5,0xC8,
-0x3E,0x25,0xB7,0x94,0x99,0xBB,0x92,0x32,0x71,0x07,0xF0,0x86,0x5E,0xED,0x50,0x27,
-0xA6,0x0D,0xA6,0x23,0xF9,0xBB,0xCB,0xA6,0x07,0x14,0x42,
-};
-
-
-/* subject:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2006 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA */
-/* issuer :/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2006 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA */
-
-
-const unsigned char thawte_Primary_Root_CA_certificate[1060]={
-0x30,0x82,0x04,0x20,0x30,0x82,0x03,0x08,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x34,
-0x4E,0xD5,0x57,0x20,0xD5,0xED,0xEC,0x49,0xF4,0x2F,0xCE,0x37,0xDB,0x2B,0x6D,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,
-0xA9,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,
-0x30,0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,
-0x20,0x49,0x6E,0x63,0x2E,0x31,0x28,0x30,0x26,0x06,0x03,0x55,0x04,0x0B,0x13,0x1F,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x53,0x65,
-0x72,0x76,0x69,0x63,0x65,0x73,0x20,0x44,0x69,0x76,0x69,0x73,0x69,0x6F,0x6E,0x31,
-0x38,0x30,0x36,0x06,0x03,0x55,0x04,0x0B,0x13,0x2F,0x28,0x63,0x29,0x20,0x32,0x30,
-0x30,0x36,0x20,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,
-0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,
-0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,
-0x04,0x03,0x13,0x16,0x74,0x68,0x61,0x77,0x74,0x65,0x20,0x50,0x72,0x69,0x6D,0x61,
-0x72,0x79,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x1E,0x17,0x0D,0x30,0x36,
-0x31,0x31,0x31,0x37,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x36,0x30,
-0x37,0x31,0x36,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0xA9,0x31,0x0B,0x30,
-0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,0x30,0x13,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x0C,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x28,0x30,0x26,0x06,0x03,0x55,0x04,0x0B,0x13,0x1F,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x53,0x65,0x72,0x76,0x69,0x63,
-0x65,0x73,0x20,0x44,0x69,0x76,0x69,0x73,0x69,0x6F,0x6E,0x31,0x38,0x30,0x36,0x06,
-0x03,0x55,0x04,0x0B,0x13,0x2F,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x36,0x20,0x74,
-0x68,0x61,0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,
-0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,
-0x20,0x6F,0x6E,0x6C,0x79,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,
-0x74,0x68,0x61,0x77,0x74,0x65,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x52,
-0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,
-0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xAC,0xA0,0xF0,0xFB,0x80,0x59,0xD4,0x9C,0xC7,
-0xA4,0xCF,0x9D,0xA1,0x59,0x73,0x09,0x10,0x45,0x0C,0x0D,0x2C,0x6E,0x68,0xF1,0x6C,
-0x5B,0x48,0x68,0x49,0x59,0x37,0xFC,0x0B,0x33,0x19,0xC2,0x77,0x7F,0xCC,0x10,0x2D,
-0x95,0x34,0x1C,0xE6,0xEB,0x4D,0x09,0xA7,0x1C,0xD2,0xB8,0xC9,0x97,0x36,0x02,0xB7,
-0x89,0xD4,0x24,0x5F,0x06,0xC0,0xCC,0x44,0x94,0x94,0x8D,0x02,0x62,0x6F,0xEB,0x5A,
-0xDD,0x11,0x8D,0x28,0x9A,0x5C,0x84,0x90,0x10,0x7A,0x0D,0xBD,0x74,0x66,0x2F,0x6A,
-0x38,0xA0,0xE2,0xD5,0x54,0x44,0xEB,0x1D,0x07,0x9F,0x07,0xBA,0x6F,0xEE,0xE9,0xFD,
-0x4E,0x0B,0x29,0xF5,0x3E,0x84,0xA0,0x01,0xF1,0x9C,0xAB,0xF8,0x1C,0x7E,0x89,0xA4,
-0xE8,0xA1,0xD8,0x71,0x65,0x0D,0xA3,0x51,0x7B,0xEE,0xBC,0xD2,0x22,0x60,0x0D,0xB9,
-0x5B,0x9D,0xDF,0xBA,0xFC,0x51,0x5B,0x0B,0xAF,0x98,0xB2,0xE9,0x2E,0xE9,0x04,0xE8,
-0x62,0x87,0xDE,0x2B,0xC8,0xD7,0x4E,0xC1,0x4C,0x64,0x1E,0xDD,0xCF,0x87,0x58,0xBA,
-0x4A,0x4F,0xCA,0x68,0x07,0x1D,0x1C,0x9D,0x4A,0xC6,0xD5,0x2F,0x91,0xCC,0x7C,0x71,
-0x72,0x1C,0xC5,0xC0,0x67,0xEB,0x32,0xFD,0xC9,0x92,0x5C,0x94,0xDA,0x85,0xC0,0x9B,
-0xBF,0x53,0x7D,0x2B,0x09,0xF4,0x8C,0x9D,0x91,0x1F,0x97,0x6A,0x52,0xCB,0xDE,0x09,
-0x36,0xA4,0x77,0xD8,0x7B,0x87,0x50,0x44,0xD5,0x3E,0x6E,0x29,0x69,0xFB,0x39,0x49,
-0x26,0x1E,0x09,0xA5,0x80,0x7B,0x40,0x2D,0xEB,0xE8,0x27,0x85,0xC9,0xFE,0x61,0xFD,
-0x7E,0xE6,0x7C,0x97,0x1D,0xD5,0x9D,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,
-0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,
-0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,
-0x06,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x7B,0x5B,0x45,0xCF,
-0xAF,0xCE,0xCB,0x7A,0xFD,0x31,0x92,0x1A,0x6A,0xB6,0xF3,0x46,0xEB,0x57,0x48,0x50,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,
-0x82,0x01,0x01,0x00,0x79,0x11,0xC0,0x4B,0xB3,0x91,0xB6,0xFC,0xF0,0xE9,0x67,0xD4,
-0x0D,0x6E,0x45,0xBE,0x55,0xE8,0x93,0xD2,0xCE,0x03,0x3F,0xED,0xDA,0x25,0xB0,0x1D,
-0x57,0xCB,0x1E,0x3A,0x76,0xA0,0x4C,0xEC,0x50,0x76,0xE8,0x64,0x72,0x0C,0xA4,0xA9,
-0xF1,0xB8,0x8B,0xD6,0xD6,0x87,0x84,0xBB,0x32,0xE5,0x41,0x11,0xC0,0x77,0xD9,0xB3,
-0x60,0x9D,0xEB,0x1B,0xD5,0xD1,0x6E,0x44,0x44,0xA9,0xA6,0x01,0xEC,0x55,0x62,0x1D,
-0x77,0xB8,0x5C,0x8E,0x48,0x49,0x7C,0x9C,0x3B,0x57,0x11,0xAC,0xAD,0x73,0x37,0x8E,
-0x2F,0x78,0x5C,0x90,0x68,0x47,0xD9,0x60,0x60,0xE6,0xFC,0x07,0x3D,0x22,0x20,0x17,
-0xC4,0xF7,0x16,0xE9,0xC4,0xD8,0x72,0xF9,0xC8,0x73,0x7C,0xDF,0x16,0x2F,0x15,0xA9,
-0x3E,0xFD,0x6A,0x27,0xB6,0xA1,0xEB,0x5A,0xBA,0x98,0x1F,0xD5,0xE3,0x4D,0x64,0x0A,
-0x9D,0x13,0xC8,0x61,0xBA,0xF5,0x39,0x1C,0x87,0xBA,0xB8,0xBD,0x7B,0x22,0x7F,0xF6,
-0xFE,0xAC,0x40,0x79,0xE5,0xAC,0x10,0x6F,0x3D,0x8F,0x1B,0x79,0x76,0x8B,0xC4,0x37,
-0xB3,0x21,0x18,0x84,0xE5,0x36,0x00,0xEB,0x63,0x20,0x99,0xB9,0xE9,0xFE,0x33,0x04,
-0xBB,0x41,0xC8,0xC1,0x02,0xF9,0x44,0x63,0x20,0x9E,0x81,0xCE,0x42,0xD3,0xD6,0x3F,
-0x2C,0x76,0xD3,0x63,0x9C,0x59,0xDD,0x8F,0xA6,0xE1,0x0E,0xA0,0x2E,0x41,0xF7,0x2E,
-0x95,0x47,0xCF,0xBC,0xFD,0x33,0xF3,0xF6,0x0B,0x61,0x7E,0x7E,0x91,0x2B,0x81,0x47,
-0xC2,0x27,0x30,0xEE,0xA7,0x10,0x5D,0x37,0x8F,0x5C,0x39,0x2B,0xE4,0x04,0xF0,0x7B,
-0x8D,0x56,0x8C,0x68,
-};
-
-
-/* subject:/C=US/O=thawte, Inc./OU=(c) 2007 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA - G2 */
-/* issuer :/C=US/O=thawte, Inc./OU=(c) 2007 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA - G2 */
-
-
-const unsigned char thawte_Primary_Root_CA___G2_certificate[652]={
-0x30,0x82,0x02,0x88,0x30,0x82,0x02,0x0D,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x35,
-0xFC,0x26,0x5C,0xD9,0x84,0x4F,0xC9,0x3D,0x26,0x3D,0x57,0x9B,0xAE,0xD7,0x56,0x30,
-0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x03,0x30,0x81,0x84,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,0x30,0x13,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0C,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,
-0x63,0x2E,0x31,0x38,0x30,0x36,0x06,0x03,0x55,0x04,0x0B,0x13,0x2F,0x28,0x63,0x29,
-0x20,0x32,0x30,0x30,0x37,0x20,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,
-0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x24,0x30,0x22,
-0x06,0x03,0x55,0x04,0x03,0x13,0x1B,0x74,0x68,0x61,0x77,0x74,0x65,0x20,0x50,0x72,
-0x69,0x6D,0x61,0x72,0x79,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x20,0x2D,0x20,
-0x47,0x32,0x30,0x1E,0x17,0x0D,0x30,0x37,0x31,0x31,0x30,0x35,0x30,0x30,0x30,0x30,
-0x30,0x30,0x5A,0x17,0x0D,0x33,0x38,0x30,0x31,0x31,0x38,0x32,0x33,0x35,0x39,0x35,
-0x39,0x5A,0x30,0x81,0x84,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,
-0x55,0x53,0x31,0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x74,0x68,0x61,
-0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x38,0x30,0x36,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x2F,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x37,0x20,0x74,0x68,0x61,
-0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,
-0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,
-0x6E,0x6C,0x79,0x31,0x24,0x30,0x22,0x06,0x03,0x55,0x04,0x03,0x13,0x1B,0x74,0x68,
-0x61,0x77,0x74,0x65,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x52,0x6F,0x6F,
-0x74,0x20,0x43,0x41,0x20,0x2D,0x20,0x47,0x32,0x30,0x76,0x30,0x10,0x06,0x07,0x2A,
-0x86,0x48,0xCE,0x3D,0x02,0x01,0x06,0x05,0x2B,0x81,0x04,0x00,0x22,0x03,0x62,0x00,
-0x04,0xA2,0xD5,0x9C,0x82,0x7B,0x95,0x9D,0xF1,0x52,0x78,0x87,0xFE,0x8A,0x16,0xBF,
-0x05,0xE6,0xDF,0xA3,0x02,0x4F,0x0D,0x07,0xC6,0x00,0x51,0xBA,0x0C,0x02,0x52,0x2D,
-0x22,0xA4,0x42,0x39,0xC4,0xFE,0x8F,0xEA,0xC9,0xC1,0xBE,0xD4,0x4D,0xFF,0x9F,0x7A,
-0x9E,0xE2,0xB1,0x7C,0x9A,0xAD,0xA7,0x86,0x09,0x73,0x87,0xD1,0xE7,0x9A,0xE3,0x7A,
-0xA5,0xAA,0x6E,0xFB,0xBA,0xB3,0x70,0xC0,0x67,0x88,0xA2,0x35,0xD4,0xA3,0x9A,0xB1,
-0xFD,0xAD,0xC2,0xEF,0x31,0xFA,0xA8,0xB9,0xF3,0xFB,0x08,0xC6,0x91,0xD1,0xFB,0x29,
-0x95,0xA3,0x42,0x30,0x40,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,
-0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,
-0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,
-0x14,0x9A,0xD8,0x00,0x30,0x00,0xE7,0x6B,0x7F,0x85,0x18,0xEE,0x8B,0xB6,0xCE,0x8A,
-0x0C,0xF8,0x11,0xE1,0xBB,0x30,0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,
-0x03,0x03,0x69,0x00,0x30,0x66,0x02,0x31,0x00,0xDD,0xF8,0xE0,0x57,0x47,0x5B,0xA7,
-0xE6,0x0A,0xC3,0xBD,0xF5,0x80,0x8A,0x97,0x35,0x0D,0x1B,0x89,0x3C,0x54,0x86,0x77,
-0x28,0xCA,0xA1,0xF4,0x79,0xDE,0xB5,0xE6,0x38,0xB0,0xF0,0x65,0x70,0x8C,0x7F,0x02,
-0x54,0xC2,0xBF,0xFF,0xD8,0xA1,0x3E,0xD9,0xCF,0x02,0x31,0x00,0xC4,0x8D,0x94,0xFC,
-0xDC,0x53,0xD2,0xDC,0x9D,0x78,0x16,0x1F,0x15,0x33,0x23,0x53,0x52,0xE3,0x5A,0x31,
-0x5D,0x9D,0xCA,0xAE,0xBD,0x13,0x29,0x44,0x0D,0x27,0x5B,0xA8,0xE7,0x68,0x9C,0x12,
-0xF7,0x58,0x3F,0x2E,0x72,0x02,0x57,0xA3,0x8F,0xA1,0x14,0x2E,
-};
-
-
-/* subject:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2008 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA - G3 */
-/* issuer :/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 2008 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA - G3 */
-
-
-const unsigned char thawte_Primary_Root_CA___G3_certificate[1070]={
-0x30,0x82,0x04,0x2A,0x30,0x82,0x03,0x12,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x60,
-0x01,0x97,0xB7,0x46,0xA7,0xEA,0xB4,0xB4,0x9A,0xD6,0x4B,0x2F,0xF7,0x90,0xFB,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,0x81,
-0xAE,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x15,
-0x30,0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,
-0x20,0x49,0x6E,0x63,0x2E,0x31,0x28,0x30,0x26,0x06,0x03,0x55,0x04,0x0B,0x13,0x1F,
-0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x53,0x65,
-0x72,0x76,0x69,0x63,0x65,0x73,0x20,0x44,0x69,0x76,0x69,0x73,0x69,0x6F,0x6E,0x31,
-0x38,0x30,0x36,0x06,0x03,0x55,0x04,0x0B,0x13,0x2F,0x28,0x63,0x29,0x20,0x32,0x30,
-0x30,0x38,0x20,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,
-0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,
-0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x24,0x30,0x22,0x06,0x03,0x55,
-0x04,0x03,0x13,0x1B,0x74,0x68,0x61,0x77,0x74,0x65,0x20,0x50,0x72,0x69,0x6D,0x61,
-0x72,0x79,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x20,0x2D,0x20,0x47,0x33,0x30,
-0x1E,0x17,0x0D,0x30,0x38,0x30,0x34,0x30,0x32,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,
-0x17,0x0D,0x33,0x37,0x31,0x32,0x30,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,
-0x81,0xAE,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,
-0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x0A,0x13,0x0C,0x74,0x68,0x61,0x77,0x74,0x65,
-0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x28,0x30,0x26,0x06,0x03,0x55,0x04,0x0B,0x13,
-0x1F,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x53,
-0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x20,0x44,0x69,0x76,0x69,0x73,0x69,0x6F,0x6E,
-0x31,0x38,0x30,0x36,0x06,0x03,0x55,0x04,0x0B,0x13,0x2F,0x28,0x63,0x29,0x20,0x32,
-0x30,0x30,0x38,0x20,0x74,0x68,0x61,0x77,0x74,0x65,0x2C,0x20,0x49,0x6E,0x63,0x2E,
-0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,
-0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x24,0x30,0x22,0x06,0x03,
-0x55,0x04,0x03,0x13,0x1B,0x74,0x68,0x61,0x77,0x74,0x65,0x20,0x50,0x72,0x69,0x6D,
-0x61,0x72,0x79,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x20,0x2D,0x20,0x47,0x33,
-0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,
-0x00,0xB2,0xBF,0x27,0x2C,0xFB,0xDB,0xD8,0x5B,0xDD,0x78,0x7B,0x1B,0x9E,0x77,0x66,
-0x81,0xCB,0x3E,0xBC,0x7C,0xAE,0xF3,0xA6,0x27,0x9A,0x34,0xA3,0x68,0x31,0x71,0x38,
-0x33,0x62,0xE4,0xF3,0x71,0x66,0x79,0xB1,0xA9,0x65,0xA3,0xA5,0x8B,0xD5,0x8F,0x60,
-0x2D,0x3F,0x42,0xCC,0xAA,0x6B,0x32,0xC0,0x23,0xCB,0x2C,0x41,0xDD,0xE4,0xDF,0xFC,
-0x61,0x9C,0xE2,0x73,0xB2,0x22,0x95,0x11,0x43,0x18,0x5F,0xC4,0xB6,0x1F,0x57,0x6C,
-0x0A,0x05,0x58,0x22,0xC8,0x36,0x4C,0x3A,0x7C,0xA5,0xD1,0xCF,0x86,0xAF,0x88,0xA7,
-0x44,0x02,0x13,0x74,0x71,0x73,0x0A,0x42,0x59,0x02,0xF8,0x1B,0x14,0x6B,0x42,0xDF,
-0x6F,0x5F,0xBA,0x6B,0x82,0xA2,0x9D,0x5B,0xE7,0x4A,0xBD,0x1E,0x01,0x72,0xDB,0x4B,
-0x74,0xE8,0x3B,0x7F,0x7F,0x7D,0x1F,0x04,0xB4,0x26,0x9B,0xE0,0xB4,0x5A,0xAC,0x47,
-0x3D,0x55,0xB8,0xD7,0xB0,0x26,0x52,0x28,0x01,0x31,0x40,0x66,0xD8,0xD9,0x24,0xBD,
-0xF6,0x2A,0xD8,0xEC,0x21,0x49,0x5C,0x9B,0xF6,0x7A,0xE9,0x7F,0x55,0x35,0x7E,0x96,
-0x6B,0x8D,0x93,0x93,0x27,0xCB,0x92,0xBB,0xEA,0xAC,0x40,0xC0,0x9F,0xC2,0xF8,0x80,
-0xCF,0x5D,0xF4,0x5A,0xDC,0xCE,0x74,0x86,0xA6,0x3E,0x6C,0x0B,0x53,0xCA,0xBD,0x92,
-0xCE,0x19,0x06,0x72,0xE6,0x0C,0x5C,0x38,0x69,0xC7,0x04,0xD6,0xBC,0x6C,0xCE,0x5B,
-0xF6,0xF7,0x68,0x9C,0xDC,0x25,0x15,0x48,0x88,0xA1,0xE9,0xA9,0xF8,0x98,0x9C,0xE0,
-0xF3,0xD5,0x31,0x28,0x61,0x11,0x6C,0x67,0x96,0x8D,0x39,0x99,0xCB,0xC2,0x45,0x24,
-0x39,0x02,0x03,0x01,0x00,0x01,0xA3,0x42,0x30,0x40,0x30,0x0F,0x06,0x03,0x55,0x1D,
-0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,
-0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,
-0x1D,0x0E,0x04,0x16,0x04,0x14,0xAD,0x6C,0xAA,0x94,0x60,0x9C,0xED,0xE4,0xFF,0xFA,
-0x3E,0x0A,0x74,0x2B,0x63,0x03,0xF7,0xB6,0x59,0xBF,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x1A,0x40,
-0xD8,0x95,0x65,0xAC,0x09,0x92,0x89,0xC6,0x39,0xF4,0x10,0xE5,0xA9,0x0E,0x66,0x53,
-0x5D,0x78,0xDE,0xFA,0x24,0x91,0xBB,0xE7,0x44,0x51,0xDF,0xC6,0x16,0x34,0x0A,0xEF,
-0x6A,0x44,0x51,0xEA,0x2B,0x07,0x8A,0x03,0x7A,0xC3,0xEB,0x3F,0x0A,0x2C,0x52,0x16,
-0xA0,0x2B,0x43,0xB9,0x25,0x90,0x3F,0x70,0xA9,0x33,0x25,0x6D,0x45,0x1A,0x28,0x3B,
-0x27,0xCF,0xAA,0xC3,0x29,0x42,0x1B,0xDF,0x3B,0x4C,0xC0,0x33,0x34,0x5B,0x41,0x88,
-0xBF,0x6B,0x2B,0x65,0xAF,0x28,0xEF,0xB2,0xF5,0xC3,0xAA,0x66,0xCE,0x7B,0x56,0xEE,
-0xB7,0xC8,0xCB,0x67,0xC1,0xC9,0x9C,0x1A,0x18,0xB8,0xC4,0xC3,0x49,0x03,0xF1,0x60,
-0x0E,0x50,0xCD,0x46,0xC5,0xF3,0x77,0x79,0xF7,0xB6,0x15,0xE0,0x38,0xDB,0xC7,0x2F,
-0x28,0xA0,0x0C,0x3F,0x77,0x26,0x74,0xD9,0x25,0x12,0xDA,0x31,0xDA,0x1A,0x1E,0xDC,
-0x29,0x41,0x91,0x22,0x3C,0x69,0xA7,0xBB,0x02,0xF2,0xB6,0x5C,0x27,0x03,0x89,0xF4,
-0x06,0xEA,0x9B,0xE4,0x72,0x82,0xE3,0xA1,0x09,0xC1,0xE9,0x00,0x19,0xD3,0x3E,0xD4,
-0x70,0x6B,0xBA,0x71,0xA6,0xAA,0x58,0xAE,0xF4,0xBB,0xE9,0x6C,0xB6,0xEF,0x87,0xCC,
-0x9B,0xBB,0xFF,0x39,0xE6,0x56,0x61,0xD3,0x0A,0xA7,0xC4,0x5C,0x4C,0x60,0x7B,0x05,
-0x77,0x26,0x7A,0xBF,0xD8,0x07,0x52,0x2C,0x62,0xF7,0x70,0x63,0xD9,0x39,0xBC,0x6F,
-0x1C,0xC2,0x79,0xDC,0x76,0x29,0xAF,0xCE,0xC5,0x2C,0x64,0x04,0x5E,0x88,0x36,0x6E,
-0x31,0xD4,0x40,0x1A,0x62,0x34,0x36,0x3F,0x35,0x01,0xAE,0xAC,0x63,0xA0,
-};
-
-
-/* subject:/C=ZA/ST=Western Cape/L=Cape Town/O=Thawte Consulting cc/OU=Certification Services Division/CN=Thawte Server CA/emailAddress=server-certs@thawte.com */
-/* issuer :/C=ZA/ST=Western Cape/L=Cape Town/O=Thawte Consulting cc/OU=Certification Services Division/CN=Thawte Server CA/emailAddress=server-certs@thawte.com */
-
-
-const unsigned char Thawte_Server_CA_certificate[791]={
-0x30,0x82,0x03,0x13,0x30,0x82,0x02,0x7C,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,
-0x81,0xC4,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x5A,0x41,0x31,
-0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x08,0x13,0x0C,0x57,0x65,0x73,0x74,0x65,0x72,
-0x6E,0x20,0x43,0x61,0x70,0x65,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04,0x07,0x13,
-0x09,0x43,0x61,0x70,0x65,0x20,0x54,0x6F,0x77,0x6E,0x31,0x1D,0x30,0x1B,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x14,0x54,0x68,0x61,0x77,0x74,0x65,0x20,0x43,0x6F,0x6E,0x73,
-0x75,0x6C,0x74,0x69,0x6E,0x67,0x20,0x63,0x63,0x31,0x28,0x30,0x26,0x06,0x03,0x55,
-0x04,0x0B,0x13,0x1F,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,
-0x6E,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x20,0x44,0x69,0x76,0x69,0x73,
-0x69,0x6F,0x6E,0x31,0x19,0x30,0x17,0x06,0x03,0x55,0x04,0x03,0x13,0x10,0x54,0x68,
-0x61,0x77,0x74,0x65,0x20,0x53,0x65,0x72,0x76,0x65,0x72,0x20,0x43,0x41,0x31,0x26,
-0x30,0x24,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x09,0x01,0x16,0x17,0x73,
-0x65,0x72,0x76,0x65,0x72,0x2D,0x63,0x65,0x72,0x74,0x73,0x40,0x74,0x68,0x61,0x77,
-0x74,0x65,0x2E,0x63,0x6F,0x6D,0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x38,0x30,0x31,
-0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x30,0x31,0x32,0x33,0x31,0x32,
-0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0xC4,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,
-0x04,0x06,0x13,0x02,0x5A,0x41,0x31,0x15,0x30,0x13,0x06,0x03,0x55,0x04,0x08,0x13,
-0x0C,0x57,0x65,0x73,0x74,0x65,0x72,0x6E,0x20,0x43,0x61,0x70,0x65,0x31,0x12,0x30,
-0x10,0x06,0x03,0x55,0x04,0x07,0x13,0x09,0x43,0x61,0x70,0x65,0x20,0x54,0x6F,0x77,
-0x6E,0x31,0x1D,0x30,0x1B,0x06,0x03,0x55,0x04,0x0A,0x13,0x14,0x54,0x68,0x61,0x77,
-0x74,0x65,0x20,0x43,0x6F,0x6E,0x73,0x75,0x6C,0x74,0x69,0x6E,0x67,0x20,0x63,0x63,
-0x31,0x28,0x30,0x26,0x06,0x03,0x55,0x04,0x0B,0x13,0x1F,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,
-0x73,0x20,0x44,0x69,0x76,0x69,0x73,0x69,0x6F,0x6E,0x31,0x19,0x30,0x17,0x06,0x03,
-0x55,0x04,0x03,0x13,0x10,0x54,0x68,0x61,0x77,0x74,0x65,0x20,0x53,0x65,0x72,0x76,
-0x65,0x72,0x20,0x43,0x41,0x31,0x26,0x30,0x24,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,
-0x0D,0x01,0x09,0x01,0x16,0x17,0x73,0x65,0x72,0x76,0x65,0x72,0x2D,0x63,0x65,0x72,
-0x74,0x73,0x40,0x74,0x68,0x61,0x77,0x74,0x65,0x2E,0x63,0x6F,0x6D,0x30,0x81,0x9F,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,
-0x81,0x8D,0x00,0x30,0x81,0x89,0x02,0x81,0x81,0x00,0xD3,0xA4,0x50,0x6E,0xC8,0xFF,
-0x56,0x6B,0xE6,0xCF,0x5D,0xB6,0xEA,0x0C,0x68,0x75,0x47,0xA2,0xAA,0xC2,0xDA,0x84,
-0x25,0xFC,0xA8,0xF4,0x47,0x51,0xDA,0x85,0xB5,0x20,0x74,0x94,0x86,0x1E,0x0F,0x75,
-0xC9,0xE9,0x08,0x61,0xF5,0x06,0x6D,0x30,0x6E,0x15,0x19,0x02,0xE9,0x52,0xC0,0x62,
-0xDB,0x4D,0x99,0x9E,0xE2,0x6A,0x0C,0x44,0x38,0xCD,0xFE,0xBE,0xE3,0x64,0x09,0x70,
-0xC5,0xFE,0xB1,0x6B,0x29,0xB6,0x2F,0x49,0xC8,0x3B,0xD4,0x27,0x04,0x25,0x10,0x97,
-0x2F,0xE7,0x90,0x6D,0xC0,0x28,0x42,0x99,0xD7,0x4C,0x43,0xDE,0xC3,0xF5,0x21,0x6D,
-0x54,0x9F,0x5D,0xC3,0x58,0xE1,0xC0,0xE4,0xD9,0x5B,0xB0,0xB8,0xDC,0xB4,0x7B,0xDF,
-0x36,0x3A,0xC2,0xB5,0x66,0x22,0x12,0xD6,0x87,0x0D,0x02,0x03,0x01,0x00,0x01,0xA3,
-0x13,0x30,0x11,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x07,0xFA,0x4C,0x69,0x5C,0xFB,0x95,0xCC,0x46,
-0xEE,0x85,0x83,0x4D,0x21,0x30,0x8E,0xCA,0xD9,0xA8,0x6F,0x49,0x1A,0xE6,0xDA,0x51,
-0xE3,0x60,0x70,0x6C,0x84,0x61,0x11,0xA1,0x1A,0xC8,0x48,0x3E,0x59,0x43,0x7D,0x4F,
-0x95,0x3D,0xA1,0x8B,0xB7,0x0B,0x62,0x98,0x7A,0x75,0x8A,0xDD,0x88,0x4E,0x4E,0x9E,
-0x40,0xDB,0xA8,0xCC,0x32,0x74,0xB9,0x6F,0x0D,0xC6,0xE3,0xB3,0x44,0x0B,0xD9,0x8A,
-0x6F,0x9A,0x29,0x9B,0x99,0x18,0x28,0x3B,0xD1,0xE3,0x40,0x28,0x9A,0x5A,0x3C,0xD5,
-0xB5,0xE7,0x20,0x1B,0x8B,0xCA,0xA4,0xAB,0x8D,0xE9,0x51,0xD9,0xE2,0x4C,0x2C,0x59,
-0xA9,0xDA,0xB9,0xB2,0x75,0x1B,0xF6,0x42,0xF2,0xEF,0xC7,0xF2,0x18,0xF9,0x89,0xBC,
-0xA3,0xFF,0x8A,0x23,0x2E,0x70,0x47,
-};
-
-
-/* subject:/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN - DATACorp SGC */
-/* issuer :/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN - DATACorp SGC */
-
-
-const unsigned char UTN_DATACorp_SGC_Root_CA_certificate[1122]={
-0x30,0x82,0x04,0x5E,0x30,0x82,0x03,0x46,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x44,
-0xBE,0x0C,0x8B,0x50,0x00,0x21,0xB4,0x11,0xD3,0x2A,0x68,0x06,0xA9,0xAD,0x69,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,
-0x93,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x08,0x13,0x02,0x55,0x54,0x31,0x17,0x30,0x15,0x06,
-0x03,0x55,0x04,0x07,0x13,0x0E,0x53,0x61,0x6C,0x74,0x20,0x4C,0x61,0x6B,0x65,0x20,
-0x43,0x69,0x74,0x79,0x31,0x1E,0x30,0x1C,0x06,0x03,0x55,0x04,0x0A,0x13,0x15,0x54,
-0x68,0x65,0x20,0x55,0x53,0x45,0x52,0x54,0x52,0x55,0x53,0x54,0x20,0x4E,0x65,0x74,
-0x77,0x6F,0x72,0x6B,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x0B,0x13,0x18,0x68,
-0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x75,0x73,0x65,0x72,0x74,0x72,
-0x75,0x73,0x74,0x2E,0x63,0x6F,0x6D,0x31,0x1B,0x30,0x19,0x06,0x03,0x55,0x04,0x03,
-0x13,0x12,0x55,0x54,0x4E,0x20,0x2D,0x20,0x44,0x41,0x54,0x41,0x43,0x6F,0x72,0x70,
-0x20,0x53,0x47,0x43,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x36,0x32,0x34,0x31,0x38,
-0x35,0x37,0x32,0x31,0x5A,0x17,0x0D,0x31,0x39,0x30,0x36,0x32,0x34,0x31,0x39,0x30,
-0x36,0x33,0x30,0x5A,0x30,0x81,0x93,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,
-0x13,0x02,0x55,0x53,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x08,0x13,0x02,0x55,
-0x54,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x07,0x13,0x0E,0x53,0x61,0x6C,0x74,
-0x20,0x4C,0x61,0x6B,0x65,0x20,0x43,0x69,0x74,0x79,0x31,0x1E,0x30,0x1C,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x15,0x54,0x68,0x65,0x20,0x55,0x53,0x45,0x52,0x54,0x52,0x55,
-0x53,0x54,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x21,0x30,0x1F,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x18,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,
-0x75,0x73,0x65,0x72,0x74,0x72,0x75,0x73,0x74,0x2E,0x63,0x6F,0x6D,0x31,0x1B,0x30,
-0x19,0x06,0x03,0x55,0x04,0x03,0x13,0x12,0x55,0x54,0x4E,0x20,0x2D,0x20,0x44,0x41,
-0x54,0x41,0x43,0x6F,0x72,0x70,0x20,0x53,0x47,0x43,0x30,0x82,0x01,0x22,0x30,0x0D,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,
-0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xDF,0xEE,0x58,0x10,0xA2,
-0x2B,0x6E,0x55,0xC4,0x8E,0xBF,0x2E,0x46,0x09,0xE7,0xE0,0x08,0x0F,0x2E,0x2B,0x7A,
-0x13,0x94,0x1B,0xBD,0xF6,0xB6,0x80,0x8E,0x65,0x05,0x93,0x00,0x1E,0xBC,0xAF,0xE2,
-0x0F,0x8E,0x19,0x0D,0x12,0x47,0xEC,0xAC,0xAD,0xA3,0xFA,0x2E,0x70,0xF8,0xDE,0x6E,
-0xFB,0x56,0x42,0x15,0x9E,0x2E,0x5C,0xEF,0x23,0xDE,0x21,0xB9,0x05,0x76,0x27,0x19,
-0x0F,0x4F,0xD6,0xC3,0x9C,0xB4,0xBE,0x94,0x19,0x63,0xF2,0xA6,0x11,0x0A,0xEB,0x53,
-0x48,0x9C,0xBE,0xF2,0x29,0x3B,0x16,0xE8,0x1A,0xA0,0x4C,0xA6,0xC9,0xF4,0x18,0x59,
-0x68,0xC0,0x70,0xF2,0x53,0x00,0xC0,0x5E,0x50,0x82,0xA5,0x56,0x6F,0x36,0xF9,0x4A,
-0xE0,0x44,0x86,0xA0,0x4D,0x4E,0xD6,0x47,0x6E,0x49,0x4A,0xCB,0x67,0xD7,0xA6,0xC4,
-0x05,0xB9,0x8E,0x1E,0xF4,0xFC,0xFF,0xCD,0xE7,0x36,0xE0,0x9C,0x05,0x6C,0xB2,0x33,
-0x22,0x15,0xD0,0xB4,0xE0,0xCC,0x17,0xC0,0xB2,0xC0,0xF4,0xFE,0x32,0x3F,0x29,0x2A,
-0x95,0x7B,0xD8,0xF2,0xA7,0x4E,0x0F,0x54,0x7C,0xA1,0x0D,0x80,0xB3,0x09,0x03,0xC1,
-0xFF,0x5C,0xDD,0x5E,0x9A,0x3E,0xBC,0xAE,0xBC,0x47,0x8A,0x6A,0xAE,0x71,0xCA,0x1F,
-0xB1,0x2A,0xB8,0x5F,0x42,0x05,0x0B,0xEC,0x46,0x30,0xD1,0x72,0x0B,0xCA,0xE9,0x56,
-0x6D,0xF5,0xEF,0xDF,0x78,0xBE,0x61,0xBA,0xB2,0xA5,0xAE,0x04,0x4C,0xBC,0xA8,0xAC,
-0x69,0x15,0x97,0xBD,0xEF,0xEB,0xB4,0x8C,0xBF,0x35,0xF8,0xD4,0xC3,0xD1,0x28,0x0E,
-0x5C,0x3A,0x9F,0x70,0x18,0x33,0x20,0x77,0xC4,0xA2,0xAF,0x02,0x03,0x01,0x00,0x01,
-0xA3,0x81,0xAB,0x30,0x81,0xA8,0x30,0x0B,0x06,0x03,0x55,0x1D,0x0F,0x04,0x04,0x03,
-0x02,0x01,0xC6,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x53,
-0x32,0xD1,0xB3,0xCF,0x7F,0xFA,0xE0,0xF1,0xA0,0x5D,0x85,0x4E,0x92,0xD2,0x9E,0x45,
-0x1D,0xB4,0x4F,0x30,0x3D,0x06,0x03,0x55,0x1D,0x1F,0x04,0x36,0x30,0x34,0x30,0x32,
-0xA0,0x30,0xA0,0x2E,0x86,0x2C,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,
-0x2E,0x75,0x73,0x65,0x72,0x74,0x72,0x75,0x73,0x74,0x2E,0x63,0x6F,0x6D,0x2F,0x55,
-0x54,0x4E,0x2D,0x44,0x41,0x54,0x41,0x43,0x6F,0x72,0x70,0x53,0x47,0x43,0x2E,0x63,
-0x72,0x6C,0x30,0x2A,0x06,0x03,0x55,0x1D,0x25,0x04,0x23,0x30,0x21,0x06,0x08,0x2B,
-0x06,0x01,0x05,0x05,0x07,0x03,0x01,0x06,0x0A,0x2B,0x06,0x01,0x04,0x01,0x82,0x37,
-0x0A,0x03,0x03,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x42,0x04,0x01,0x30,0x0D,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,
-0x01,0x00,0x27,0x35,0x97,0x00,0x8A,0x8B,0x28,0xBD,0xC6,0x33,0x30,0x1E,0x29,0xFC,
-0xE2,0xF7,0xD5,0x98,0xD4,0x40,0xBB,0x60,0xCA,0xBF,0xAB,0x17,0x2C,0x09,0x36,0x7F,
-0x50,0xFA,0x41,0xDC,0xAE,0x96,0x3A,0x0A,0x23,0x3E,0x89,0x59,0xC9,0xA3,0x07,0xED,
-0x1B,0x37,0xAD,0xFC,0x7C,0xBE,0x51,0x49,0x5A,0xDE,0x3A,0x0A,0x54,0x08,0x16,0x45,
-0xC2,0x99,0xB1,0x87,0xCD,0x8C,0x68,0xE0,0x69,0x03,0xE9,0xC4,0x4E,0x98,0xB2,0x3B,
-0x8C,0x16,0xB3,0x0E,0xA0,0x0C,0x98,0x50,0x9B,0x93,0xA9,0x70,0x09,0xC8,0x2C,0xA3,
-0x8F,0xDF,0x02,0xE4,0xE0,0x71,0x3A,0xF1,0xB4,0x23,0x72,0xA0,0xAA,0x01,0xDF,0xDF,
-0x98,0x3E,0x14,0x50,0xA0,0x31,0x26,0xBD,0x28,0xE9,0x5A,0x30,0x26,0x75,0xF9,0x7B,
-0x60,0x1C,0x8D,0xF3,0xCD,0x50,0x26,0x6D,0x04,0x27,0x9A,0xDF,0xD5,0x0D,0x45,0x47,
-0x29,0x6B,0x2C,0xE6,0x76,0xD9,0xA9,0x29,0x7D,0x32,0xDD,0xC9,0x36,0x3C,0xBD,0xAE,
-0x35,0xF1,0x11,0x9E,0x1D,0xBB,0x90,0x3F,0x12,0x47,0x4E,0x8E,0xD7,0x7E,0x0F,0x62,
-0x73,0x1D,0x52,0x26,0x38,0x1C,0x18,0x49,0xFD,0x30,0x74,0x9A,0xC4,0xE5,0x22,0x2F,
-0xD8,0xC0,0x8D,0xED,0x91,0x7A,0x4C,0x00,0x8F,0x72,0x7F,0x5D,0xDA,0xDD,0x1B,0x8B,
-0x45,0x6B,0xE7,0xDD,0x69,0x97,0xA8,0xC5,0x56,0x4C,0x0F,0x0C,0xF6,0x9F,0x7A,0x91,
-0x37,0xF6,0x97,0x82,0xE0,0xDD,0x71,0x69,0xFF,0x76,0x3F,0x60,0x4D,0x3C,0xCF,0xF7,
-0x99,0xF9,0xC6,0x57,0xF4,0xC9,0x55,0x39,0x78,0xBA,0x2C,0x79,0xC9,0xA6,0x88,0x2B,
-0xF4,0x08,
-};
-
-
-/* subject:/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN-USERFirst-Hardware */
-/* issuer :/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN-USERFirst-Hardware */
-
-
-const unsigned char UTN_USERFirst_Hardware_Root_CA_certificate[1144]={
-0x30,0x82,0x04,0x74,0x30,0x82,0x03,0x5C,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x44,
-0xBE,0x0C,0x8B,0x50,0x00,0x24,0xB4,0x11,0xD3,0x36,0x2A,0xFE,0x65,0x0A,0xFD,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,
-0x97,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x08,0x13,0x02,0x55,0x54,0x31,0x17,0x30,0x15,0x06,
-0x03,0x55,0x04,0x07,0x13,0x0E,0x53,0x61,0x6C,0x74,0x20,0x4C,0x61,0x6B,0x65,0x20,
-0x43,0x69,0x74,0x79,0x31,0x1E,0x30,0x1C,0x06,0x03,0x55,0x04,0x0A,0x13,0x15,0x54,
-0x68,0x65,0x20,0x55,0x53,0x45,0x52,0x54,0x52,0x55,0x53,0x54,0x20,0x4E,0x65,0x74,
-0x77,0x6F,0x72,0x6B,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x0B,0x13,0x18,0x68,
-0x74,0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x75,0x73,0x65,0x72,0x74,0x72,
-0x75,0x73,0x74,0x2E,0x63,0x6F,0x6D,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,
-0x13,0x16,0x55,0x54,0x4E,0x2D,0x55,0x53,0x45,0x52,0x46,0x69,0x72,0x73,0x74,0x2D,
-0x48,0x61,0x72,0x64,0x77,0x61,0x72,0x65,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x37,
-0x30,0x39,0x31,0x38,0x31,0x30,0x34,0x32,0x5A,0x17,0x0D,0x31,0x39,0x30,0x37,0x30,
-0x39,0x31,0x38,0x31,0x39,0x32,0x32,0x5A,0x30,0x81,0x97,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,
-0x08,0x13,0x02,0x55,0x54,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x07,0x13,0x0E,
-0x53,0x61,0x6C,0x74,0x20,0x4C,0x61,0x6B,0x65,0x20,0x43,0x69,0x74,0x79,0x31,0x1E,
-0x30,0x1C,0x06,0x03,0x55,0x04,0x0A,0x13,0x15,0x54,0x68,0x65,0x20,0x55,0x53,0x45,
-0x52,0x54,0x52,0x55,0x53,0x54,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x21,
-0x30,0x1F,0x06,0x03,0x55,0x04,0x0B,0x13,0x18,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,
-0x77,0x77,0x77,0x2E,0x75,0x73,0x65,0x72,0x74,0x72,0x75,0x73,0x74,0x2E,0x63,0x6F,
-0x6D,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,0x55,0x54,0x4E,0x2D,
-0x55,0x53,0x45,0x52,0x46,0x69,0x72,0x73,0x74,0x2D,0x48,0x61,0x72,0x64,0x77,0x61,
-0x72,0x65,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,
-0x01,0x01,0x00,0xB1,0xF7,0xC3,0x38,0x3F,0xB4,0xA8,0x7F,0xCF,0x39,0x82,0x51,0x67,
-0xD0,0x6D,0x9F,0xD2,0xFF,0x58,0xF3,0xE7,0x9F,0x2B,0xEC,0x0D,0x89,0x54,0x99,0xB9,
-0x38,0x99,0x16,0xF7,0xE0,0x21,0x79,0x48,0xC2,0xBB,0x61,0x74,0x12,0x96,0x1D,0x3C,
-0x6A,0x72,0xD5,0x3C,0x10,0x67,0x3A,0x39,0xED,0x2B,0x13,0xCD,0x66,0xEB,0x95,0x09,
-0x33,0xA4,0x6C,0x97,0xB1,0xE8,0xC6,0xEC,0xC1,0x75,0x79,0x9C,0x46,0x5E,0x8D,0xAB,
-0xD0,0x6A,0xFD,0xB9,0x2A,0x55,0x17,0x10,0x54,0xB3,0x19,0xF0,0x9A,0xF6,0xF1,0xB1,
-0x5D,0xB6,0xA7,0x6D,0xFB,0xE0,0x71,0x17,0x6B,0xA2,0x88,0xFB,0x00,0xDF,0xFE,0x1A,
-0x31,0x77,0x0C,0x9A,0x01,0x7A,0xB1,0x32,0xE3,0x2B,0x01,0x07,0x38,0x6E,0xC3,0xA5,
-0x5E,0x23,0xBC,0x45,0x9B,0x7B,0x50,0xC1,0xC9,0x30,0x8F,0xDB,0xE5,0x2B,0x7A,0xD3,
-0x5B,0xFB,0x33,0x40,0x1E,0xA0,0xD5,0x98,0x17,0xBC,0x8B,0x87,0xC3,0x89,0xD3,0x5D,
-0xA0,0x8E,0xB2,0xAA,0xAA,0xF6,0x8E,0x69,0x88,0x06,0xC5,0xFA,0x89,0x21,0xF3,0x08,
-0x9D,0x69,0x2E,0x09,0x33,0x9B,0x29,0x0D,0x46,0x0F,0x8C,0xCC,0x49,0x34,0xB0,0x69,
-0x51,0xBD,0xF9,0x06,0xCD,0x68,0xAD,0x66,0x4C,0xBC,0x3E,0xAC,0x61,0xBD,0x0A,0x88,
-0x0E,0xC8,0xDF,0x3D,0xEE,0x7C,0x04,0x4C,0x9D,0x0A,0x5E,0x6B,0x91,0xD6,0xEE,0xC7,
-0xED,0x28,0x8D,0xAB,0x4D,0x87,0x89,0x73,0xD0,0x6E,0xA4,0xD0,0x1E,0x16,0x8B,0x14,
-0xE1,0x76,0x44,0x03,0x7F,0x63,0xAC,0xE4,0xCD,0x49,0x9C,0xC5,0x92,0xF4,0xAB,0x32,
-0xA1,0x48,0x5B,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,0xB9,0x30,0x81,0xB6,0x30,0x0B,
-0x06,0x03,0x55,0x1D,0x0F,0x04,0x04,0x03,0x02,0x01,0xC6,0x30,0x0F,0x06,0x03,0x55,
-0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,
-0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xA1,0x72,0x5F,0x26,0x1B,0x28,0x98,0x43,0x95,
-0x5D,0x07,0x37,0xD5,0x85,0x96,0x9D,0x4B,0xD2,0xC3,0x45,0x30,0x44,0x06,0x03,0x55,
-0x1D,0x1F,0x04,0x3D,0x30,0x3B,0x30,0x39,0xA0,0x37,0xA0,0x35,0x86,0x33,0x68,0x74,
-0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x75,0x73,0x65,0x72,0x74,0x72,0x75,
-0x73,0x74,0x2E,0x63,0x6F,0x6D,0x2F,0x55,0x54,0x4E,0x2D,0x55,0x53,0x45,0x52,0x46,
-0x69,0x72,0x73,0x74,0x2D,0x48,0x61,0x72,0x64,0x77,0x61,0x72,0x65,0x2E,0x63,0x72,
-0x6C,0x30,0x31,0x06,0x03,0x55,0x1D,0x25,0x04,0x2A,0x30,0x28,0x06,0x08,0x2B,0x06,
-0x01,0x05,0x05,0x07,0x03,0x01,0x06,0x08,0x2B,0x06,0x01,0x05,0x05,0x07,0x03,0x05,
-0x06,0x08,0x2B,0x06,0x01,0x05,0x05,0x07,0x03,0x06,0x06,0x08,0x2B,0x06,0x01,0x05,
-0x05,0x07,0x03,0x07,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x47,0x19,0x0F,0xDE,0x74,0xC6,0x99,0x97,
-0xAF,0xFC,0xAD,0x28,0x5E,0x75,0x8E,0xEB,0x2D,0x67,0xEE,0x4E,0x7B,0x2B,0xD7,0x0C,
-0xFF,0xF6,0xDE,0xCB,0x55,0xA2,0x0A,0xE1,0x4C,0x54,0x65,0x93,0x60,0x6B,0x9F,0x12,
-0x9C,0xAD,0x5E,0x83,0x2C,0xEB,0x5A,0xAE,0xC0,0xE4,0x2D,0xF4,0x00,0x63,0x1D,0xB8,
-0xC0,0x6C,0xF2,0xCF,0x49,0xBB,0x4D,0x93,0x6F,0x06,0xA6,0x0A,0x22,0xB2,0x49,0x62,
-0x08,0x4E,0xFF,0xC8,0xC8,0x14,0xB2,0x88,0x16,0x5D,0xE7,0x01,0xE4,0x12,0x95,0xE5,
-0x45,0x34,0xB3,0x8B,0x69,0xBD,0xCF,0xB4,0x85,0x8F,0x75,0x51,0x9E,0x7D,0x3A,0x38,
-0x3A,0x14,0x48,0x12,0xC6,0xFB,0xA7,0x3B,0x1A,0x8D,0x0D,0x82,0x40,0x07,0xE8,0x04,
-0x08,0x90,0xA1,0x89,0xCB,0x19,0x50,0xDF,0xCA,0x1C,0x01,0xBC,0x1D,0x04,0x19,0x7B,
-0x10,0x76,0x97,0x3B,0xEE,0x90,0x90,0xCA,0xC4,0x0E,0x1F,0x16,0x6E,0x75,0xEF,0x33,
-0xF8,0xD3,0x6F,0x5B,0x1E,0x96,0xE3,0xE0,0x74,0x77,0x74,0x7B,0x8A,0xA2,0x6E,0x2D,
-0xDD,0x76,0xD6,0x39,0x30,0x82,0xF0,0xAB,0x9C,0x52,0xF2,0x2A,0xC7,0xAF,0x49,0x5E,
-0x7E,0xC7,0x68,0xE5,0x82,0x81,0xC8,0x6A,0x27,0xF9,0x27,0x88,0x2A,0xD5,0x58,0x50,
-0x95,0x1F,0xF0,0x3B,0x1C,0x57,0xBB,0x7D,0x14,0x39,0x62,0x2B,0x9A,0xC9,0x94,0x92,
-0x2A,0xA3,0x22,0x0C,0xFF,0x89,0x26,0x7D,0x5F,0x23,0x2B,0x47,0xD7,0x15,0x1D,0xA9,
-0x6A,0x9E,0x51,0x0D,0x2A,0x51,0x9E,0x81,0xF9,0xD4,0x3B,0x5E,0x70,0x12,0x7F,0x10,
-0x32,0x9C,0x1E,0xBB,0x9D,0xF8,0x66,0xA8,
-};
-
-
-/* subject:/L=ValiCert Validation Network/O=ValiCert, Inc./OU=ValiCert Class 1 Policy Validation Authority/CN=http://www.valicert.com//emailAddress=info@valicert.com */
-/* issuer :/L=ValiCert Validation Network/O=ValiCert, Inc./OU=ValiCert Class 1 Policy Validation Authority/CN=http://www.valicert.com//emailAddress=info@valicert.com */
-
-
-const unsigned char ValiCert_Class_1_VA_certificate[747]={
-0x30,0x82,0x02,0xE7,0x30,0x82,0x02,0x50,0x02,0x01,0x01,0x30,0x0D,0x06,0x09,0x2A,
-0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,0xBB,0x31,0x24,0x30,
-0x22,0x06,0x03,0x55,0x04,0x07,0x13,0x1B,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,
-0x20,0x56,0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x4E,0x65,0x74,0x77,
-0x6F,0x72,0x6B,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x61,
-0x6C,0x69,0x43,0x65,0x72,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x35,0x30,0x33,
-0x06,0x03,0x55,0x04,0x0B,0x13,0x2C,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,
-0x43,0x6C,0x61,0x73,0x73,0x20,0x31,0x20,0x50,0x6F,0x6C,0x69,0x63,0x79,0x20,0x56,
-0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x68,0x74,
-0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x61,0x6C,0x69,0x63,0x65,0x72,
-0x74,0x2E,0x63,0x6F,0x6D,0x2F,0x31,0x20,0x30,0x1E,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x09,0x01,0x16,0x11,0x69,0x6E,0x66,0x6F,0x40,0x76,0x61,0x6C,0x69,
-0x63,0x65,0x72,0x74,0x2E,0x63,0x6F,0x6D,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x36,
-0x32,0x35,0x32,0x32,0x32,0x33,0x34,0x38,0x5A,0x17,0x0D,0x31,0x39,0x30,0x36,0x32,
-0x35,0x32,0x32,0x32,0x33,0x34,0x38,0x5A,0x30,0x81,0xBB,0x31,0x24,0x30,0x22,0x06,
-0x03,0x55,0x04,0x07,0x13,0x1B,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,0x56,
-0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,
-0x6B,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x61,0x6C,0x69,
-0x43,0x65,0x72,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x35,0x30,0x33,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x2C,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,0x43,0x6C,
-0x61,0x73,0x73,0x20,0x31,0x20,0x50,0x6F,0x6C,0x69,0x63,0x79,0x20,0x56,0x61,0x6C,
-0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,
-0x79,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x68,0x74,0x74,0x70,
-0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x61,0x6C,0x69,0x63,0x65,0x72,0x74,0x2E,
-0x63,0x6F,0x6D,0x2F,0x31,0x20,0x30,0x1E,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x09,0x01,0x16,0x11,0x69,0x6E,0x66,0x6F,0x40,0x76,0x61,0x6C,0x69,0x63,0x65,
-0x72,0x74,0x2E,0x63,0x6F,0x6D,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,0x02,
-0x81,0x81,0x00,0xD8,0x59,0x82,0x7A,0x89,0xB8,0x96,0xBA,0xA6,0x2F,0x68,0x6F,0x58,
-0x2E,0xA7,0x54,0x1C,0x06,0x6E,0xF4,0xEA,0x8D,0x48,0xBC,0x31,0x94,0x17,0xF0,0xF3,
-0x4E,0xBC,0xB2,0xB8,0x35,0x92,0x76,0xB0,0xD0,0xA5,0xA5,0x01,0xD7,0x00,0x03,0x12,
-0x22,0x19,0x08,0xF8,0xFF,0x11,0x23,0x9B,0xCE,0x07,0xF5,0xBF,0x69,0x1A,0x26,0xFE,
-0x4E,0xE9,0xD1,0x7F,0x9D,0x2C,0x40,0x1D,0x59,0x68,0x6E,0xA6,0xF8,0x58,0xB0,0x9D,
-0x1A,0x8F,0xD3,0x3F,0xF1,0xDC,0x19,0x06,0x81,0xA8,0x0E,0xE0,0x3A,0xDD,0xC8,0x53,
-0x45,0x09,0x06,0xE6,0x0F,0x70,0xC3,0xFA,0x40,0xA6,0x0E,0xE2,0x56,0x05,0x0F,0x18,
-0x4D,0xFC,0x20,0x82,0xD1,0x73,0x55,0x74,0x8D,0x76,0x72,0xA0,0x1D,0x9D,0x1D,0xC0,
-0xDD,0x3F,0x71,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x81,0x81,0x00,0x50,0x68,0x3D,0x49,0xF4,
-0x2C,0x1C,0x06,0x94,0xDF,0x95,0x60,0x7F,0x96,0x7B,0x17,0xFE,0x4F,0x71,0xAD,0x64,
-0xC8,0xDD,0x77,0xD2,0xEF,0x59,0x55,0xE8,0x3F,0xE8,0x8E,0x05,0x2A,0x21,0xF2,0x07,
-0xD2,0xB5,0xA7,0x52,0xFE,0x9C,0xB1,0xB6,0xE2,0x5B,0x77,0x17,0x40,0xEA,0x72,0xD6,
-0x23,0xCB,0x28,0x81,0x32,0xC3,0x00,0x79,0x18,0xEC,0x59,0x17,0x89,0xC9,0xC6,0x6A,
-0x1E,0x71,0xC9,0xFD,0xB7,0x74,0xA5,0x25,0x45,0x69,0xC5,0x48,0xAB,0x19,0xE1,0x45,
-0x8A,0x25,0x6B,0x19,0xEE,0xE5,0xBB,0x12,0xF5,0x7F,0xF7,0xA6,0x8D,0x51,0xC3,0xF0,
-0x9D,0x74,0xB7,0xA9,0x3E,0xA0,0xA5,0xFF,0xB6,0x49,0x03,0x13,0xDA,0x22,0xCC,0xED,
-0x71,0x82,0x2B,0x99,0xCF,0x3A,0xB7,0xF5,0x2D,0x72,0xC8,
-};
-
-
-/* subject:/L=ValiCert Validation Network/O=ValiCert, Inc./OU=ValiCert Class 2 Policy Validation Authority/CN=http://www.valicert.com//emailAddress=info@valicert.com */
-/* issuer :/L=ValiCert Validation Network/O=ValiCert, Inc./OU=ValiCert Class 2 Policy Validation Authority/CN=http://www.valicert.com//emailAddress=info@valicert.com */
-
-
-const unsigned char ValiCert_Class_2_VA_certificate[747]={
-0x30,0x82,0x02,0xE7,0x30,0x82,0x02,0x50,0x02,0x01,0x01,0x30,0x0D,0x06,0x09,0x2A,
-0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,0xBB,0x31,0x24,0x30,
-0x22,0x06,0x03,0x55,0x04,0x07,0x13,0x1B,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,
-0x20,0x56,0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x4E,0x65,0x74,0x77,
-0x6F,0x72,0x6B,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x61,
-0x6C,0x69,0x43,0x65,0x72,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x35,0x30,0x33,
-0x06,0x03,0x55,0x04,0x0B,0x13,0x2C,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,
-0x43,0x6C,0x61,0x73,0x73,0x20,0x32,0x20,0x50,0x6F,0x6C,0x69,0x63,0x79,0x20,0x56,
-0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x68,0x74,
-0x74,0x70,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x61,0x6C,0x69,0x63,0x65,0x72,
-0x74,0x2E,0x63,0x6F,0x6D,0x2F,0x31,0x20,0x30,0x1E,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x09,0x01,0x16,0x11,0x69,0x6E,0x66,0x6F,0x40,0x76,0x61,0x6C,0x69,
-0x63,0x65,0x72,0x74,0x2E,0x63,0x6F,0x6D,0x30,0x1E,0x17,0x0D,0x39,0x39,0x30,0x36,
-0x32,0x36,0x30,0x30,0x31,0x39,0x35,0x34,0x5A,0x17,0x0D,0x31,0x39,0x30,0x36,0x32,
-0x36,0x30,0x30,0x31,0x39,0x35,0x34,0x5A,0x30,0x81,0xBB,0x31,0x24,0x30,0x22,0x06,
-0x03,0x55,0x04,0x07,0x13,0x1B,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,0x56,
-0x61,0x6C,0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,
-0x6B,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x61,0x6C,0x69,
-0x43,0x65,0x72,0x74,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x35,0x30,0x33,0x06,0x03,
-0x55,0x04,0x0B,0x13,0x2C,0x56,0x61,0x6C,0x69,0x43,0x65,0x72,0x74,0x20,0x43,0x6C,
-0x61,0x73,0x73,0x20,0x32,0x20,0x50,0x6F,0x6C,0x69,0x63,0x79,0x20,0x56,0x61,0x6C,
-0x69,0x64,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,
-0x79,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,0x04,0x03,0x13,0x18,0x68,0x74,0x74,0x70,
-0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x61,0x6C,0x69,0x63,0x65,0x72,0x74,0x2E,
-0x63,0x6F,0x6D,0x2F,0x31,0x20,0x30,0x1E,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,
-0x01,0x09,0x01,0x16,0x11,0x69,0x6E,0x66,0x6F,0x40,0x76,0x61,0x6C,0x69,0x63,0x65,
-0x72,0x74,0x2E,0x63,0x6F,0x6D,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,0x02,
-0x81,0x81,0x00,0xCE,0x3A,0x71,0xCA,0xE5,0xAB,0xC8,0x59,0x92,0x55,0xD7,0xAB,0xD8,
-0x74,0x0E,0xF9,0xEE,0xD9,0xF6,0x55,0x47,0x59,0x65,0x47,0x0E,0x05,0x55,0xDC,0xEB,
-0x98,0x36,0x3C,0x5C,0x53,0x5D,0xD3,0x30,0xCF,0x38,0xEC,0xBD,0x41,0x89,0xED,0x25,
-0x42,0x09,0x24,0x6B,0x0A,0x5E,0xB3,0x7C,0xDD,0x52,0x2D,0x4C,0xE6,0xD4,0xD6,0x7D,
-0x5A,0x59,0xA9,0x65,0xD4,0x49,0x13,0x2D,0x24,0x4D,0x1C,0x50,0x6F,0xB5,0xC1,0x85,
-0x54,0x3B,0xFE,0x71,0xE4,0xD3,0x5C,0x42,0xF9,0x80,0xE0,0x91,0x1A,0x0A,0x5B,0x39,
-0x36,0x67,0xF3,0x3F,0x55,0x7C,0x1B,0x3F,0xB4,0x5F,0x64,0x73,0x34,0xE3,0xB4,0x12,
-0xBF,0x87,0x64,0xF8,0xDA,0x12,0xFF,0x37,0x27,0xC1,0xB3,0x43,0xBB,0xEF,0x7B,0x6E,
-0x2E,0x69,0xF7,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x81,0x81,0x00,0x3B,0x7F,0x50,0x6F,0x6F,
-0x50,0x94,0x99,0x49,0x62,0x38,0x38,0x1F,0x4B,0xF8,0xA5,0xC8,0x3E,0xA7,0x82,0x81,
-0xF6,0x2B,0xC7,0xE8,0xC5,0xCE,0xE8,0x3A,0x10,0x82,0xCB,0x18,0x00,0x8E,0x4D,0xBD,
-0xA8,0x58,0x7F,0xA1,0x79,0x00,0xB5,0xBB,0xE9,0x8D,0xAF,0x41,0xD9,0x0F,0x34,0xEE,
-0x21,0x81,0x19,0xA0,0x32,0x49,0x28,0xF4,0xC4,0x8E,0x56,0xD5,0x52,0x33,0xFD,0x50,
-0xD5,0x7E,0x99,0x6C,0x03,0xE4,0xC9,0x4C,0xFC,0xCB,0x6C,0xAB,0x66,0xB3,0x4A,0x21,
-0x8C,0xE5,0xB5,0x0C,0x32,0x3E,0x10,0xB2,0xCC,0x6C,0xA1,0xDC,0x9A,0x98,0x4C,0x02,
-0x5B,0xF3,0xCE,0xB9,0x9E,0xA5,0x72,0x0E,0x4A,0xB7,0x3F,0x3C,0xE6,0x16,0x68,0xF8,
-0xBE,0xED,0x74,0x4C,0xBC,0x5B,0xD5,0x62,0x1F,0x43,0xDD,
-};
-
-
-/* subject:/C=US/O=VeriSign, Inc./OU=Class 3 Public Primary Certification Authority */
-/* issuer :/C=US/O=VeriSign, Inc./OU=Class 3 Public Primary Certification Authority */
-
-
-const unsigned char Verisign_Class_3_Public_Primary_Certification_Authority_certificate[576]={
-0x30,0x82,0x02,0x3C,0x30,0x82,0x01,0xA5,0x02,0x10,0x3C,0x91,0x31,0xCB,0x1F,0xF6,
-0xD0,0x1B,0x0E,0x9A,0xB8,0xD0,0x44,0xBF,0x12,0xBE,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x5F,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x37,0x30,0x35,0x06,0x03,0x55,0x04,0x0B,0x13,0x2E,0x43,0x6C,0x61,0x73,
-0x73,0x20,0x33,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,0x50,0x72,0x69,0x6D,0x61,
-0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,
-0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x39,0x36,
-0x30,0x31,0x32,0x39,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x32,0x38,0x30,
-0x38,0x30,0x32,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x5F,0x31,0x0B,0x30,0x09,
-0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,
-0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,
-0x63,0x2E,0x31,0x37,0x30,0x35,0x06,0x03,0x55,0x04,0x0B,0x13,0x2E,0x43,0x6C,0x61,
-0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,0x50,0x72,0x69,0x6D,
-0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,
-0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x81,0x9F,0x30,0x0D,
-0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,
-0x00,0x30,0x81,0x89,0x02,0x81,0x81,0x00,0xC9,0x5C,0x59,0x9E,0xF2,0x1B,0x8A,0x01,
-0x14,0xB4,0x10,0xDF,0x04,0x40,0xDB,0xE3,0x57,0xAF,0x6A,0x45,0x40,0x8F,0x84,0x0C,
-0x0B,0xD1,0x33,0xD9,0xD9,0x11,0xCF,0xEE,0x02,0x58,0x1F,0x25,0xF7,0x2A,0xA8,0x44,
-0x05,0xAA,0xEC,0x03,0x1F,0x78,0x7F,0x9E,0x93,0xB9,0x9A,0x00,0xAA,0x23,0x7D,0xD6,
-0xAC,0x85,0xA2,0x63,0x45,0xC7,0x72,0x27,0xCC,0xF4,0x4C,0xC6,0x75,0x71,0xD2,0x39,
-0xEF,0x4F,0x42,0xF0,0x75,0xDF,0x0A,0x90,0xC6,0x8E,0x20,0x6F,0x98,0x0F,0xF8,0xAC,
-0x23,0x5F,0x70,0x29,0x36,0xA4,0xC9,0x86,0xE7,0xB1,0x9A,0x20,0xCB,0x53,0xA5,0x85,
-0xE7,0x3D,0xBE,0x7D,0x9A,0xFE,0x24,0x45,0x33,0xDC,0x76,0x15,0xED,0x0F,0xA2,0x71,
-0x64,0x4C,0x65,0x2E,0x81,0x68,0x45,0xA7,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,
-0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x81,0x81,0x00,
-0x10,0x72,0x52,0xA9,0x05,0x14,0x19,0x32,0x08,0x41,0xF0,0xC5,0x6B,0x0A,0xCC,0x7E,
-0x0F,0x21,0x19,0xCD,0xE4,0x67,0xDC,0x5F,0xA9,0x1B,0xE6,0xCA,0xE8,0x73,0x9D,0x22,
-0xD8,0x98,0x6E,0x73,0x03,0x61,0x91,0xC5,0x7C,0xB0,0x45,0x40,0x6E,0x44,0x9D,0x8D,
-0xB0,0xB1,0x96,0x74,0x61,0x2D,0x0D,0xA9,0x45,0xD2,0xA4,0x92,0x2A,0xD6,0x9A,0x75,
-0x97,0x6E,0x3F,0x53,0xFD,0x45,0x99,0x60,0x1D,0xA8,0x2B,0x4C,0xF9,0x5E,0xA7,0x09,
-0xD8,0x75,0x30,0xD7,0xD2,0x65,0x60,0x3D,0x67,0xD6,0x48,0x55,0x75,0x69,0x3F,0x91,
-0xF5,0x48,0x0B,0x47,0x69,0x22,0x69,0x82,0x96,0xBE,0xC9,0xC8,0x38,0x86,0x4A,0x7A,
-0x2C,0x73,0x19,0x48,0x69,0x4E,0x6B,0x7C,0x65,0xBF,0x0F,0xFC,0x70,0xCE,0x88,0x90,
-};
-
-
-/* subject:/C=US/O=VeriSign, Inc./OU=Class 3 Public Primary Certification Authority - G2/OU=(c) 1998 VeriSign, Inc. - For authorized use only/OU=VeriSign Trust Network */
-/* issuer :/C=US/O=VeriSign, Inc./OU=Class 3 Public Primary Certification Authority - G2/OU=(c) 1998 VeriSign, Inc. - For authorized use only/OU=VeriSign Trust Network */
-
-
-const unsigned char Verisign_Class_3_Public_Primary_Certification_Authority___G2_certificate[774]={
-0x30,0x82,0x03,0x02,0x30,0x82,0x02,0x6B,0x02,0x10,0x7D,0xD9,0xFE,0x07,0xCF,0xA8,
-0x1E,0xB7,0x10,0x79,0x67,0xFB,0xA7,0x89,0x34,0xC6,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,0xC1,0x31,0x0B,0x30,0x09,
-0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,
-0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,
-0x63,0x2E,0x31,0x3C,0x30,0x3A,0x06,0x03,0x55,0x04,0x0B,0x13,0x33,0x43,0x6C,0x61,
-0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,0x50,0x72,0x69,0x6D,
-0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,
-0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x2D,0x20,0x47,0x32,
-0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,0x28,0x63,0x29,0x20,0x31,
-0x39,0x39,0x38,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,
-0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x1F,0x30,0x1D,
-0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,
-0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x30,0x1E,0x17,
-0x0D,0x39,0x38,0x30,0x35,0x31,0x38,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,
-0x32,0x38,0x30,0x38,0x30,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0xC1,
-0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,
-0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,
-0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x3C,0x30,0x3A,0x06,0x03,0x55,0x04,0x0B,0x13,
-0x33,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,
-0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,
-0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,
-0x2D,0x20,0x47,0x32,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,0x28,
-0x63,0x29,0x20,0x31,0x39,0x39,0x38,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,
-0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,
-0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,0x65,0x72,0x69,0x53,
-0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,
-0x6B,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,
-0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,0x02,0x81,0x81,0x00,0xCC,0x5E,
-0xD1,0x11,0x5D,0x5C,0x69,0xD0,0xAB,0xD3,0xB9,0x6A,0x4C,0x99,0x1F,0x59,0x98,0x30,
-0x8E,0x16,0x85,0x20,0x46,0x6D,0x47,0x3F,0xD4,0x85,0x20,0x84,0xE1,0x6D,0xB3,0xF8,
-0xA4,0xED,0x0C,0xF1,0x17,0x0F,0x3B,0xF9,0xA7,0xF9,0x25,0xD7,0xC1,0xCF,0x84,0x63,
-0xF2,0x7C,0x63,0xCF,0xA2,0x47,0xF2,0xC6,0x5B,0x33,0x8E,0x64,0x40,0x04,0x68,0xC1,
-0x80,0xB9,0x64,0x1C,0x45,0x77,0xC7,0xD8,0x6E,0xF5,0x95,0x29,0x3C,0x50,0xE8,0x34,
-0xD7,0x78,0x1F,0xA8,0xBA,0x6D,0x43,0x91,0x95,0x8F,0x45,0x57,0x5E,0x7E,0xC5,0xFB,
-0xCA,0xA4,0x04,0xEB,0xEA,0x97,0x37,0x54,0x30,0x6F,0xBB,0x01,0x47,0x32,0x33,0xCD,
-0xDC,0x57,0x9B,0x64,0x69,0x61,0xF8,0x9B,0x1D,0x1C,0x89,0x4F,0x5C,0x67,0x02,0x03,
-0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x03,0x81,0x81,0x00,0x51,0x4D,0xCD,0xBE,0x5C,0xCB,0x98,0x19,0x9C,0x15,
-0xB2,0x01,0x39,0x78,0x2E,0x4D,0x0F,0x67,0x70,0x70,0x99,0xC6,0x10,0x5A,0x94,0xA4,
-0x53,0x4D,0x54,0x6D,0x2B,0xAF,0x0D,0x5D,0x40,0x8B,0x64,0xD3,0xD7,0xEE,0xDE,0x56,
-0x61,0x92,0x5F,0xA6,0xC4,0x1D,0x10,0x61,0x36,0xD3,0x2C,0x27,0x3C,0xE8,0x29,0x09,
-0xB9,0x11,0x64,0x74,0xCC,0xB5,0x73,0x9F,0x1C,0x48,0xA9,0xBC,0x61,0x01,0xEE,0xE2,
-0x17,0xA6,0x0C,0xE3,0x40,0x08,0x3B,0x0E,0xE7,0xEB,0x44,0x73,0x2A,0x9A,0xF1,0x69,
-0x92,0xEF,0x71,0x14,0xC3,0x39,0xAC,0x71,0xA7,0x91,0x09,0x6F,0xE4,0x71,0x06,0xB3,
-0xBA,0x59,0x57,0x26,0x79,0x00,0xF6,0xF8,0x0D,0xA2,0x33,0x30,0x28,0xD4,0xAA,0x58,
-0xA0,0x9D,0x9D,0x69,0x91,0xFD,
-};
-
-
-/* subject:/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 1999 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 3 Public Primary Certification Authority - G3 */
-/* issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 1999 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 3 Public Primary Certification Authority - G3 */
-
-
-const unsigned char Verisign_Class_3_Public_Primary_Certification_Authority___G3_certificate[1054]={
-0x30,0x82,0x04,0x1A,0x30,0x82,0x03,0x02,0x02,0x11,0x00,0x9B,0x7E,0x06,0x49,0xA3,
-0x3E,0x62,0xB9,0xD5,0xEE,0x90,0x48,0x71,0x29,0xEF,0x57,0x30,0x0D,0x06,0x09,0x2A,
-0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,0xCA,0x31,0x0B,0x30,
-0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,
-0x6E,0x63,0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,0x65,
-0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,
-0x77,0x6F,0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,0x28,
-0x63,0x29,0x20,0x31,0x39,0x39,0x39,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,
-0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,
-0x31,0x45,0x30,0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,0x65,0x72,0x69,0x53,
-0x69,0x67,0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,0x6C,
-0x69,0x63,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x20,0x2D,0x20,0x47,0x33,0x30,0x1E,0x17,0x0D,0x39,0x39,0x31,0x30,0x30,
-0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x36,0x30,0x37,0x31,0x36,
-0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0xCA,0x31,0x0B,0x30,0x09,0x06,0x03,
-0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,
-0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,
-0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,0x65,0x72,0x69,0x53,
-0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,
-0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,0x28,0x63,0x29,0x20,
-0x31,0x39,0x39,0x39,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,
-0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x45,0x30,
-0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,
-0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,
-0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,
-0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,
-0x2D,0x20,0x47,0x33,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,
-0x02,0x82,0x01,0x01,0x00,0xCB,0xBA,0x9C,0x52,0xFC,0x78,0x1F,0x1A,0x1E,0x6F,0x1B,
-0x37,0x73,0xBD,0xF8,0xC9,0x6B,0x94,0x12,0x30,0x4F,0xF0,0x36,0x47,0xF5,0xD0,0x91,
-0x0A,0xF5,0x17,0xC8,0xA5,0x61,0xC1,0x16,0x40,0x4D,0xFB,0x8A,0x61,0x90,0xE5,0x76,
-0x20,0xC1,0x11,0x06,0x7D,0xAB,0x2C,0x6E,0xA6,0xF5,0x11,0x41,0x8E,0xFA,0x2D,0xAD,
-0x2A,0x61,0x59,0xA4,0x67,0x26,0x4C,0xD0,0xE8,0xBC,0x52,0x5B,0x70,0x20,0x04,0x58,
-0xD1,0x7A,0xC9,0xA4,0x69,0xBC,0x83,0x17,0x64,0xAD,0x05,0x8B,0xBC,0xD0,0x58,0xCE,
-0x8D,0x8C,0xF5,0xEB,0xF0,0x42,0x49,0x0B,0x9D,0x97,0x27,0x67,0x32,0x6E,0xE1,0xAE,
-0x93,0x15,0x1C,0x70,0xBC,0x20,0x4D,0x2F,0x18,0xDE,0x92,0x88,0xE8,0x6C,0x85,0x57,
-0x11,0x1A,0xE9,0x7E,0xE3,0x26,0x11,0x54,0xA2,0x45,0x96,0x55,0x83,0xCA,0x30,0x89,
-0xE8,0xDC,0xD8,0xA3,0xED,0x2A,0x80,0x3F,0x7F,0x79,0x65,0x57,0x3E,0x15,0x20,0x66,
-0x08,0x2F,0x95,0x93,0xBF,0xAA,0x47,0x2F,0xA8,0x46,0x97,0xF0,0x12,0xE2,0xFE,0xC2,
-0x0A,0x2B,0x51,0xE6,0x76,0xE6,0xB7,0x46,0xB7,0xE2,0x0D,0xA6,0xCC,0xA8,0xC3,0x4C,
-0x59,0x55,0x89,0xE6,0xE8,0x53,0x5C,0x1C,0xEA,0x9D,0xF0,0x62,0x16,0x0B,0xA7,0xC9,
-0x5F,0x0C,0xF0,0xDE,0xC2,0x76,0xCE,0xAF,0xF7,0x6A,0xF2,0xFA,0x41,0xA6,0xA2,0x33,
-0x14,0xC9,0xE5,0x7A,0x63,0xD3,0x9E,0x62,0x37,0xD5,0x85,0x65,0x9E,0x0E,0xE6,0x53,
-0x24,0x74,0x1B,0x5E,0x1D,0x12,0x53,0x5B,0xC7,0x2C,0xE7,0x83,0x49,0x3B,0x15,0xAE,
-0x8A,0x68,0xB9,0x57,0x97,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x11,0x14,
-0x96,0xC1,0xAB,0x92,0x08,0xF7,0x3F,0x2F,0xC9,0xB2,0xFE,0xE4,0x5A,0x9F,0x64,0xDE,
-0xDB,0x21,0x4F,0x86,0x99,0x34,0x76,0x36,0x57,0xDD,0xD0,0x15,0x2F,0xC5,0xAD,0x7F,
-0x15,0x1F,0x37,0x62,0x73,0x3E,0xD4,0xE7,0x5F,0xCE,0x17,0x03,0xDB,0x35,0xFA,0x2B,
-0xDB,0xAE,0x60,0x09,0x5F,0x1E,0x5F,0x8F,0x6E,0xBB,0x0B,0x3D,0xEA,0x5A,0x13,0x1E,
-0x0C,0x60,0x6F,0xB5,0xC0,0xB5,0x23,0x22,0x2E,0x07,0x0B,0xCB,0xA9,0x74,0xCB,0x47,
-0xBB,0x1D,0xC1,0xD7,0xA5,0x6B,0xCC,0x2F,0xD2,0x42,0xFD,0x49,0xDD,0xA7,0x89,0xCF,
-0x53,0xBA,0xDA,0x00,0x5A,0x28,0xBF,0x82,0xDF,0xF8,0xBA,0x13,0x1D,0x50,0x86,0x82,
-0xFD,0x8E,0x30,0x8F,0x29,0x46,0xB0,0x1E,0x3D,0x35,0xDA,0x38,0x62,0x16,0x18,0x4A,
-0xAD,0xE6,0xB6,0x51,0x6C,0xDE,0xAF,0x62,0xEB,0x01,0xD0,0x1E,0x24,0xFE,0x7A,0x8F,
-0x12,0x1A,0x12,0x68,0xB8,0xFB,0x66,0x99,0x14,0x14,0x45,0x5C,0xAE,0xE7,0xAE,0x69,
-0x17,0x81,0x2B,0x5A,0x37,0xC9,0x5E,0x2A,0xF4,0xC6,0xE2,0xA1,0x5C,0x54,0x9B,0xA6,
-0x54,0x00,0xCF,0xF0,0xF1,0xC1,0xC7,0x98,0x30,0x1A,0x3B,0x36,0x16,0xDB,0xA3,0x6E,
-0xEA,0xFD,0xAD,0xB2,0xC2,0xDA,0xEF,0x02,0x47,0x13,0x8A,0xC0,0xF1,0xB3,0x31,0xAD,
-0x4F,0x1C,0xE1,0x4F,0x9C,0xAF,0x0F,0x0C,0x9D,0xF7,0x78,0x0D,0xD8,0xF4,0x35,0x56,
-0x80,0xDA,0xB7,0x6D,0x17,0x8F,0x9D,0x1E,0x81,0x64,0xE1,0xFE,0xC5,0x45,0xBA,0xAD,
-0x6B,0xB9,0x0A,0x7A,0x4E,0x4F,0x4B,0x84,0xEE,0x4B,0xF1,0x7D,0xDD,0x11,
-};
-
-
-/* subject:/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 2007 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 3 Public Primary Certification Authority - G4 */
-/* issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 2007 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 3 Public Primary Certification Authority - G4 */
-
-
-const unsigned char VeriSign_Class_3_Public_Primary_Certification_Authority___G4_certificate[904]={
-0x30,0x82,0x03,0x84,0x30,0x82,0x03,0x0A,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x2F,
-0x80,0xFE,0x23,0x8C,0x0E,0x22,0x0F,0x48,0x67,0x12,0x28,0x91,0x87,0xAC,0xB3,0x30,
-0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x03,0x30,0x81,0xCA,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,
-0x49,0x6E,0x63,0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,
-0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,
-0x74,0x77,0x6F,0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,
-0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x37,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,
-0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,
-0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,
-0x79,0x31,0x45,0x30,0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,0x65,0x72,0x69,
-0x53,0x69,0x67,0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,
-0x6C,0x69,0x63,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x20,0x2D,0x20,0x47,0x34,0x30,0x1E,0x17,0x0D,0x30,0x37,0x31,0x31,
-0x30,0x35,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x38,0x30,0x31,0x31,
-0x38,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0xCA,0x31,0x0B,0x30,0x09,0x06,
-0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,
-0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,
-0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,0x65,0x72,0x69,
-0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,0x77,0x6F,
-0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,0x28,0x63,0x29,
-0x20,0x32,0x30,0x30,0x37,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,
-0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,
-0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x45,
-0x30,0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,0x65,0x72,0x69,0x53,0x69,0x67,
-0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,
-0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,
-0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,
-0x20,0x2D,0x20,0x47,0x34,0x30,0x76,0x30,0x10,0x06,0x07,0x2A,0x86,0x48,0xCE,0x3D,
-0x02,0x01,0x06,0x05,0x2B,0x81,0x04,0x00,0x22,0x03,0x62,0x00,0x04,0xA7,0x56,0x7A,
-0x7C,0x52,0xDA,0x64,0x9B,0x0E,0x2D,0x5C,0xD8,0x5E,0xAC,0x92,0x3D,0xFE,0x01,0xE6,
-0x19,0x4A,0x3D,0x14,0x03,0x4B,0xFA,0x60,0x27,0x20,0xD9,0x83,0x89,0x69,0xFA,0x54,
-0xC6,0x9A,0x18,0x5E,0x55,0x2A,0x64,0xDE,0x06,0xF6,0x8D,0x4A,0x3B,0xAD,0x10,0x3C,
-0x65,0x3D,0x90,0x88,0x04,0x89,0xE0,0x30,0x61,0xB3,0xAE,0x5D,0x01,0xA7,0x7B,0xDE,
-0x7C,0xB2,0xBE,0xCA,0x65,0x61,0x00,0x86,0xAE,0xDA,0x8F,0x7B,0xD0,0x89,0xAD,0x4D,
-0x1D,0x59,0x9A,0x41,0xB1,0xBC,0x47,0x80,0xDC,0x9E,0x62,0xC3,0xF9,0xA3,0x81,0xB2,
-0x30,0x81,0xAF,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,0x30,
-0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,
-0x03,0x02,0x01,0x06,0x30,0x6D,0x06,0x08,0x2B,0x06,0x01,0x05,0x05,0x07,0x01,0x0C,
-0x04,0x61,0x30,0x5F,0xA1,0x5D,0xA0,0x5B,0x30,0x59,0x30,0x57,0x30,0x55,0x16,0x09,
-0x69,0x6D,0x61,0x67,0x65,0x2F,0x67,0x69,0x66,0x30,0x21,0x30,0x1F,0x30,0x07,0x06,
-0x05,0x2B,0x0E,0x03,0x02,0x1A,0x04,0x14,0x8F,0xE5,0xD3,0x1A,0x86,0xAC,0x8D,0x8E,
-0x6B,0xC3,0xCF,0x80,0x6A,0xD4,0x48,0x18,0x2C,0x7B,0x19,0x2E,0x30,0x25,0x16,0x23,
-0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x6C,0x6F,0x67,0x6F,0x2E,0x76,0x65,0x72,0x69,
-0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x2F,0x76,0x73,0x6C,0x6F,0x67,0x6F,0x2E,
-0x67,0x69,0x66,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0xB3,0x16,
-0x91,0xFD,0xEE,0xA6,0x6E,0xE4,0xB5,0x2E,0x49,0x8F,0x87,0x78,0x81,0x80,0xEC,0xE5,
-0xB1,0xB5,0x30,0x0A,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x04,0x03,0x03,0x03,0x68,
-0x00,0x30,0x65,0x02,0x30,0x66,0x21,0x0C,0x18,0x26,0x60,0x5A,0x38,0x7B,0x56,0x42,
-0xE0,0xA7,0xFC,0x36,0x84,0x51,0x91,0x20,0x2C,0x76,0x4D,0x43,0x3D,0xC4,0x1D,0x84,
-0x23,0xD0,0xAC,0xD6,0x7C,0x35,0x06,0xCE,0xCD,0x69,0xBD,0x90,0x0D,0xDB,0x6C,0x48,
-0x42,0x1D,0x0E,0xAA,0x42,0x02,0x31,0x00,0x9C,0x3D,0x48,0x39,0x23,0x39,0x58,0x1A,
-0x15,0x12,0x59,0x6A,0x9E,0xEF,0xD5,0x59,0xB2,0x1D,0x52,0x2C,0x99,0x71,0xCD,0xC7,
-0x29,0xDF,0x1B,0x2A,0x61,0x7B,0x71,0xD1,0xDE,0xF3,0xC0,0xE5,0x0D,0x3A,0x4A,0xAA,
-0x2D,0xA7,0xD8,0x86,0x2A,0xDD,0x2E,0x10,
-};
-
-
-/* subject:/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 2006 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 3 Public Primary Certification Authority - G5 */
-/* issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 2006 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 3 Public Primary Certification Authority - G5 */
-
-
-const unsigned char VeriSign_Class_3_Public_Primary_Certification_Authority___G5_certificate[1239]={
-0x30,0x82,0x04,0xD3,0x30,0x82,0x03,0xBB,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x18,
-0xDA,0xD1,0x9E,0x26,0x7D,0xE8,0xBB,0x4A,0x21,0x58,0xCD,0xCC,0x6B,0x3B,0x4A,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,
-0xCA,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,
-0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,
-0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,
-0x13,0x16,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,
-0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,
-0x0B,0x13,0x31,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x36,0x20,0x56,0x65,0x72,0x69,
-0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,
-0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,
-0x6F,0x6E,0x6C,0x79,0x31,0x45,0x30,0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,
-0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,
-0x50,0x75,0x62,0x6C,0x69,0x63,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,
-0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x74,0x79,0x20,0x2D,0x20,0x47,0x35,0x30,0x1E,0x17,0x0D,0x30,
-0x36,0x31,0x31,0x30,0x38,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x36,
-0x30,0x37,0x31,0x36,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0xCA,0x31,0x0B,
-0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,
-0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,
-0x49,0x6E,0x63,0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,
-0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,
-0x74,0x77,0x6F,0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,
-0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x36,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,
-0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,
-0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,
-0x79,0x31,0x45,0x30,0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,0x65,0x72,0x69,
-0x53,0x69,0x67,0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x33,0x20,0x50,0x75,0x62,
-0x6C,0x69,0x63,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x20,0x2D,0x20,0x47,0x35,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,
-0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xAF,0x24,0x08,0x08,0x29,0x7A,0x35,
-0x9E,0x60,0x0C,0xAA,0xE7,0x4B,0x3B,0x4E,0xDC,0x7C,0xBC,0x3C,0x45,0x1C,0xBB,0x2B,
-0xE0,0xFE,0x29,0x02,0xF9,0x57,0x08,0xA3,0x64,0x85,0x15,0x27,0xF5,0xF1,0xAD,0xC8,
-0x31,0x89,0x5D,0x22,0xE8,0x2A,0xAA,0xA6,0x42,0xB3,0x8F,0xF8,0xB9,0x55,0xB7,0xB1,
-0xB7,0x4B,0xB3,0xFE,0x8F,0x7E,0x07,0x57,0xEC,0xEF,0x43,0xDB,0x66,0x62,0x15,0x61,
-0xCF,0x60,0x0D,0xA4,0xD8,0xDE,0xF8,0xE0,0xC3,0x62,0x08,0x3D,0x54,0x13,0xEB,0x49,
-0xCA,0x59,0x54,0x85,0x26,0xE5,0x2B,0x8F,0x1B,0x9F,0xEB,0xF5,0xA1,0x91,0xC2,0x33,
-0x49,0xD8,0x43,0x63,0x6A,0x52,0x4B,0xD2,0x8F,0xE8,0x70,0x51,0x4D,0xD1,0x89,0x69,
-0x7B,0xC7,0x70,0xF6,0xB3,0xDC,0x12,0x74,0xDB,0x7B,0x5D,0x4B,0x56,0xD3,0x96,0xBF,
-0x15,0x77,0xA1,0xB0,0xF4,0xA2,0x25,0xF2,0xAF,0x1C,0x92,0x67,0x18,0xE5,0xF4,0x06,
-0x04,0xEF,0x90,0xB9,0xE4,0x00,0xE4,0xDD,0x3A,0xB5,0x19,0xFF,0x02,0xBA,0xF4,0x3C,
-0xEE,0xE0,0x8B,0xEB,0x37,0x8B,0xEC,0xF4,0xD7,0xAC,0xF2,0xF6,0xF0,0x3D,0xAF,0xDD,
-0x75,0x91,0x33,0x19,0x1D,0x1C,0x40,0xCB,0x74,0x24,0x19,0x21,0x93,0xD9,0x14,0xFE,
-0xAC,0x2A,0x52,0xC7,0x8F,0xD5,0x04,0x49,0xE4,0x8D,0x63,0x47,0x88,0x3C,0x69,0x83,
-0xCB,0xFE,0x47,0xBD,0x2B,0x7E,0x4F,0xC5,0x95,0xAE,0x0E,0x9D,0xD4,0xD1,0x43,0xC0,
-0x67,0x73,0xE3,0x14,0x08,0x7E,0xE5,0x3F,0x9F,0x73,0xB8,0x33,0x0A,0xCF,0x5D,0x3F,
-0x34,0x87,0x96,0x8A,0xEE,0x53,0xE8,0x25,0x15,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,
-0xB2,0x30,0x81,0xAF,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x05,
-0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,
-0x04,0x03,0x02,0x01,0x06,0x30,0x6D,0x06,0x08,0x2B,0x06,0x01,0x05,0x05,0x07,0x01,
-0x0C,0x04,0x61,0x30,0x5F,0xA1,0x5D,0xA0,0x5B,0x30,0x59,0x30,0x57,0x30,0x55,0x16,
-0x09,0x69,0x6D,0x61,0x67,0x65,0x2F,0x67,0x69,0x66,0x30,0x21,0x30,0x1F,0x30,0x07,
-0x06,0x05,0x2B,0x0E,0x03,0x02,0x1A,0x04,0x14,0x8F,0xE5,0xD3,0x1A,0x86,0xAC,0x8D,
-0x8E,0x6B,0xC3,0xCF,0x80,0x6A,0xD4,0x48,0x18,0x2C,0x7B,0x19,0x2E,0x30,0x25,0x16,
-0x23,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x6C,0x6F,0x67,0x6F,0x2E,0x76,0x65,0x72,
-0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x2F,0x76,0x73,0x6C,0x6F,0x67,0x6F,
-0x2E,0x67,0x69,0x66,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x7F,
-0xD3,0x65,0xA7,0xC2,0xDD,0xEC,0xBB,0xF0,0x30,0x09,0xF3,0x43,0x39,0xFA,0x02,0xAF,
-0x33,0x31,0x33,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,
-0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x93,0x24,0x4A,0x30,0x5F,0x62,0xCF,0xD8,0x1A,
-0x98,0x2F,0x3D,0xEA,0xDC,0x99,0x2D,0xBD,0x77,0xF6,0xA5,0x79,0x22,0x38,0xEC,0xC4,
-0xA7,0xA0,0x78,0x12,0xAD,0x62,0x0E,0x45,0x70,0x64,0xC5,0xE7,0x97,0x66,0x2D,0x98,
-0x09,0x7E,0x5F,0xAF,0xD6,0xCC,0x28,0x65,0xF2,0x01,0xAA,0x08,0x1A,0x47,0xDE,0xF9,
-0xF9,0x7C,0x92,0x5A,0x08,0x69,0x20,0x0D,0xD9,0x3E,0x6D,0x6E,0x3C,0x0D,0x6E,0xD8,
-0xE6,0x06,0x91,0x40,0x18,0xB9,0xF8,0xC1,0xED,0xDF,0xDB,0x41,0xAA,0xE0,0x96,0x20,
-0xC9,0xCD,0x64,0x15,0x38,0x81,0xC9,0x94,0xEE,0xA2,0x84,0x29,0x0B,0x13,0x6F,0x8E,
-0xDB,0x0C,0xDD,0x25,0x02,0xDB,0xA4,0x8B,0x19,0x44,0xD2,0x41,0x7A,0x05,0x69,0x4A,
-0x58,0x4F,0x60,0xCA,0x7E,0x82,0x6A,0x0B,0x02,0xAA,0x25,0x17,0x39,0xB5,0xDB,0x7F,
-0xE7,0x84,0x65,0x2A,0x95,0x8A,0xBD,0x86,0xDE,0x5E,0x81,0x16,0x83,0x2D,0x10,0xCC,
-0xDE,0xFD,0xA8,0x82,0x2A,0x6D,0x28,0x1F,0x0D,0x0B,0xC4,0xE5,0xE7,0x1A,0x26,0x19,
-0xE1,0xF4,0x11,0x6F,0x10,0xB5,0x95,0xFC,0xE7,0x42,0x05,0x32,0xDB,0xCE,0x9D,0x51,
-0x5E,0x28,0xB6,0x9E,0x85,0xD3,0x5B,0xEF,0xA5,0x7D,0x45,0x40,0x72,0x8E,0xB7,0x0E,
-0x6B,0x0E,0x06,0xFB,0x33,0x35,0x48,0x71,0xB8,0x9D,0x27,0x8B,0xC4,0x65,0x5F,0x0D,
-0x86,0x76,0x9C,0x44,0x7A,0xF6,0x95,0x5C,0xF6,0x5D,0x32,0x08,0x33,0xA4,0x54,0xB6,
-0x18,0x3F,0x68,0x5C,0xF2,0x42,0x4A,0x85,0x38,0x54,0x83,0x5F,0xD1,0xE8,0x2C,0xF2,
-0xAC,0x11,0xD6,0xA8,0xED,0x63,0x6A,
-};
-
-
-/* subject:/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 1999 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 4 Public Primary Certification Authority - G3 */
-/* issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 1999 VeriSign, Inc. - For authorized use only/CN=VeriSign Class 4 Public Primary Certification Authority - G3 */
-
-
-const unsigned char Verisign_Class_4_Public_Primary_Certification_Authority___G3_certificate[1054]={
-0x30,0x82,0x04,0x1A,0x30,0x82,0x03,0x02,0x02,0x11,0x00,0xEC,0xA0,0xA7,0x8B,0x6E,
-0x75,0x6A,0x01,0xCF,0xC4,0x7C,0xCC,0x2F,0x94,0x5E,0xD7,0x30,0x0D,0x06,0x09,0x2A,
-0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,0xCA,0x31,0x0B,0x30,
-0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,
-0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,
-0x6E,0x63,0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,0x65,
-0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,
-0x77,0x6F,0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,0x28,
-0x63,0x29,0x20,0x31,0x39,0x39,0x39,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,
-0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,
-0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,
-0x31,0x45,0x30,0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,0x65,0x72,0x69,0x53,
-0x69,0x67,0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x34,0x20,0x50,0x75,0x62,0x6C,
-0x69,0x63,0x20,0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,
-0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,
-0x74,0x79,0x20,0x2D,0x20,0x47,0x33,0x30,0x1E,0x17,0x0D,0x39,0x39,0x31,0x30,0x30,
-0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x33,0x36,0x30,0x37,0x31,0x36,
-0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,0xCA,0x31,0x0B,0x30,0x09,0x06,0x03,
-0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,
-0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,
-0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,0x13,0x16,0x56,0x65,0x72,0x69,0x53,
-0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,
-0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,0x0B,0x13,0x31,0x28,0x63,0x29,0x20,
-0x31,0x39,0x39,0x39,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,
-0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,0x20,0x61,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,0x6F,0x6E,0x6C,0x79,0x31,0x45,0x30,
-0x43,0x06,0x03,0x55,0x04,0x03,0x13,0x3C,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,
-0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x34,0x20,0x50,0x75,0x62,0x6C,0x69,0x63,0x20,
-0x50,0x72,0x69,0x6D,0x61,0x72,0x79,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,
-0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x20,
-0x2D,0x20,0x47,0x33,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,
-0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,
-0x02,0x82,0x01,0x01,0x00,0xAD,0xCB,0xA5,0x11,0x69,0xC6,0x59,0xAB,0xF1,0x8F,0xB5,
-0x19,0x0F,0x56,0xCE,0xCC,0xB5,0x1F,0x20,0xE4,0x9E,0x26,0x25,0x4B,0xE0,0x73,0x65,
-0x89,0x59,0xDE,0xD0,0x83,0xE4,0xF5,0x0F,0xB5,0xBB,0xAD,0xF1,0x7C,0xE8,0x21,0xFC,
-0xE4,0xE8,0x0C,0xEE,0x7C,0x45,0x22,0x19,0x76,0x92,0xB4,0x13,0xB7,0x20,0x5B,0x09,
-0xFA,0x61,0xAE,0xA8,0xF2,0xA5,0x8D,0x85,0xC2,0x2A,0xD6,0xDE,0x66,0x36,0xD2,0x9B,
-0x02,0xF4,0xA8,0x92,0x60,0x7C,0x9C,0x69,0xB4,0x8F,0x24,0x1E,0xD0,0x86,0x52,0xF6,
-0x32,0x9C,0x41,0x58,0x1E,0x22,0xBD,0xCD,0x45,0x62,0x95,0x08,0x6E,0xD0,0x66,0xDD,
-0x53,0xA2,0xCC,0xF0,0x10,0xDC,0x54,0x73,0x8B,0x04,0xA1,0x46,0x33,0x33,0x5C,0x17,
-0x40,0xB9,0x9E,0x4D,0xD3,0xF3,0xBE,0x55,0x83,0xE8,0xB1,0x89,0x8E,0x5A,0x7C,0x9A,
-0x96,0x22,0x90,0x3B,0x88,0x25,0xF2,0xD2,0x53,0x88,0x02,0x0C,0x0B,0x78,0xF2,0xE6,
-0x37,0x17,0x4B,0x30,0x46,0x07,0xE4,0x80,0x6D,0xA6,0xD8,0x96,0x2E,0xE8,0x2C,0xF8,
-0x11,0xB3,0x38,0x0D,0x66,0xA6,0x9B,0xEA,0xC9,0x23,0x5B,0xDB,0x8E,0xE2,0xF3,0x13,
-0x8E,0x1A,0x59,0x2D,0xAA,0x02,0xF0,0xEC,0xA4,0x87,0x66,0xDC,0xC1,0x3F,0xF5,0xD8,
-0xB9,0xF4,0xEC,0x82,0xC6,0xD2,0x3D,0x95,0x1D,0xE5,0xC0,0x4F,0x84,0xC9,0xD9,0xA3,
-0x44,0x28,0x06,0x6A,0xD7,0x45,0xAC,0xF0,0x6B,0x6A,0xEF,0x4E,0x5F,0xF8,0x11,0x82,
-0x1E,0x38,0x63,0x34,0x66,0x50,0xD4,0x3E,0x93,0x73,0xFA,0x30,0xC3,0x66,0xAD,0xFF,
-0x93,0x2D,0x97,0xEF,0x03,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,
-0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x8F,0xFA,
-0x25,0x6B,0x4F,0x5B,0xE4,0xA4,0x4E,0x27,0x55,0xAB,0x22,0x15,0x59,0x3C,0xCA,0xB5,
-0x0A,0xD4,0x4A,0xDB,0xAB,0xDD,0xA1,0x5F,0x53,0xC5,0xA0,0x57,0x39,0xC2,0xCE,0x47,
-0x2B,0xBE,0x3A,0xC8,0x56,0xBF,0xC2,0xD9,0x27,0x10,0x3A,0xB1,0x05,0x3C,0xC0,0x77,
-0x31,0xBB,0x3A,0xD3,0x05,0x7B,0x6D,0x9A,0x1C,0x30,0x8C,0x80,0xCB,0x93,0x93,0x2A,
-0x83,0xAB,0x05,0x51,0x82,0x02,0x00,0x11,0x67,0x6B,0xF3,0x88,0x61,0x47,0x5F,0x03,
-0x93,0xD5,0x5B,0x0D,0xE0,0xF1,0xD4,0xA1,0x32,0x35,0x85,0xB2,0x3A,0xDB,0xB0,0x82,
-0xAB,0xD1,0xCB,0x0A,0xBC,0x4F,0x8C,0x5B,0xC5,0x4B,0x00,0x3B,0x1F,0x2A,0x82,0xA6,
-0x7E,0x36,0x85,0xDC,0x7E,0x3C,0x67,0x00,0xB5,0xE4,0x3B,0x52,0xE0,0xA8,0xEB,0x5D,
-0x15,0xF9,0xC6,0x6D,0xF0,0xAD,0x1D,0x0E,0x85,0xB7,0xA9,0x9A,0x73,0x14,0x5A,0x5B,
-0x8F,0x41,0x28,0xC0,0xD5,0xE8,0x2D,0x4D,0xA4,0x5E,0xCD,0xAA,0xD9,0xED,0xCE,0xDC,
-0xD8,0xD5,0x3C,0x42,0x1D,0x17,0xC1,0x12,0x5D,0x45,0x38,0xC3,0x38,0xF3,0xFC,0x85,
-0x2E,0x83,0x46,0x48,0xB2,0xD7,0x20,0x5F,0x92,0x36,0x8F,0xE7,0x79,0x0F,0x98,0x5E,
-0x99,0xE8,0xF0,0xD0,0xA4,0xBB,0xF5,0x53,0xBD,0x2A,0xCE,0x59,0xB0,0xAF,0x6E,0x7F,
-0x6C,0xBB,0xD2,0x1E,0x00,0xB0,0x21,0xED,0xF8,0x41,0x62,0x82,0xB9,0xD8,0xB2,0xC4,
-0xBB,0x46,0x50,0xF3,0x31,0xC5,0x8F,0x01,0xA8,0x74,0xEB,0xF5,0x78,0x27,0xDA,0xE7,
-0xF7,0x66,0x43,0xF3,0x9E,0x83,0x3E,0x20,0xAA,0xC3,0x35,0x60,0x91,0xCE,
-};
-
-
-/* subject:/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 2008 VeriSign, Inc. - For authorized use only/CN=VeriSign Universal Root Certification Authority */
-/* issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=(c) 2008 VeriSign, Inc. - For authorized use only/CN=VeriSign Universal Root Certification Authority */
-
-
-const unsigned char VeriSign_Universal_Root_Certification_Authority_certificate[1213]={
-0x30,0x82,0x04,0xB9,0x30,0x82,0x03,0xA1,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x40,
-0x1A,0xC4,0x64,0x21,0xB3,0x13,0x21,0x03,0x0E,0xBB,0xE4,0x12,0x1A,0xC5,0x1D,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30,0x81,
-0xBD,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,
-0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,
-0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,
-0x13,0x16,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,
-0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,
-0x0B,0x13,0x31,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x38,0x20,0x56,0x65,0x72,0x69,
-0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,
-0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,
-0x6F,0x6E,0x6C,0x79,0x31,0x38,0x30,0x36,0x06,0x03,0x55,0x04,0x03,0x13,0x2F,0x56,
-0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,
-0x6C,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,
-0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,
-0x17,0x0D,0x30,0x38,0x30,0x34,0x30,0x32,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,
-0x0D,0x33,0x37,0x31,0x32,0x30,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x81,
-0xBD,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x17,
-0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,
-0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x0B,
-0x13,0x16,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x54,0x72,0x75,0x73,0x74,
-0x20,0x4E,0x65,0x74,0x77,0x6F,0x72,0x6B,0x31,0x3A,0x30,0x38,0x06,0x03,0x55,0x04,
-0x0B,0x13,0x31,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x38,0x20,0x56,0x65,0x72,0x69,
-0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x2D,0x20,0x46,0x6F,0x72,
-0x20,0x61,0x75,0x74,0x68,0x6F,0x72,0x69,0x7A,0x65,0x64,0x20,0x75,0x73,0x65,0x20,
-0x6F,0x6E,0x6C,0x79,0x31,0x38,0x30,0x36,0x06,0x03,0x55,0x04,0x03,0x13,0x2F,0x56,
-0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x55,0x6E,0x69,0x76,0x65,0x72,0x73,0x61,
-0x6C,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,
-0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x82,
-0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,
-0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xC7,
-0x61,0x37,0x5E,0xB1,0x01,0x34,0xDB,0x62,0xD7,0x15,0x9B,0xFF,0x58,0x5A,0x8C,0x23,
-0x23,0xD6,0x60,0x8E,0x91,0xD7,0x90,0x98,0x83,0x7A,0xE6,0x58,0x19,0x38,0x8C,0xC5,
-0xF6,0xE5,0x64,0x85,0xB4,0xA2,0x71,0xFB,0xED,0xBD,0xB9,0xDA,0xCD,0x4D,0x00,0xB4,
-0xC8,0x2D,0x73,0xA5,0xC7,0x69,0x71,0x95,0x1F,0x39,0x3C,0xB2,0x44,0x07,0x9C,0xE8,
-0x0E,0xFA,0x4D,0x4A,0xC4,0x21,0xDF,0x29,0x61,0x8F,0x32,0x22,0x61,0x82,0xC5,0x87,
-0x1F,0x6E,0x8C,0x7C,0x5F,0x16,0x20,0x51,0x44,0xD1,0x70,0x4F,0x57,0xEA,0xE3,0x1C,
-0xE3,0xCC,0x79,0xEE,0x58,0xD8,0x0E,0xC2,0xB3,0x45,0x93,0xC0,0x2C,0xE7,0x9A,0x17,
-0x2B,0x7B,0x00,0x37,0x7A,0x41,0x33,0x78,0xE1,0x33,0xE2,0xF3,0x10,0x1A,0x7F,0x87,
-0x2C,0xBE,0xF6,0xF5,0xF7,0x42,0xE2,0xE5,0xBF,0x87,0x62,0x89,0x5F,0x00,0x4B,0xDF,
-0xC5,0xDD,0xE4,0x75,0x44,0x32,0x41,0x3A,0x1E,0x71,0x6E,0x69,0xCB,0x0B,0x75,0x46,
-0x08,0xD1,0xCA,0xD2,0x2B,0x95,0xD0,0xCF,0xFB,0xB9,0x40,0x6B,0x64,0x8C,0x57,0x4D,
-0xFC,0x13,0x11,0x79,0x84,0xED,0x5E,0x54,0xF6,0x34,0x9F,0x08,0x01,0xF3,0x10,0x25,
-0x06,0x17,0x4A,0xDA,0xF1,0x1D,0x7A,0x66,0x6B,0x98,0x60,0x66,0xA4,0xD9,0xEF,0xD2,
-0x2E,0x82,0xF1,0xF0,0xEF,0x09,0xEA,0x44,0xC9,0x15,0x6A,0xE2,0x03,0x6E,0x33,0xD3,
-0xAC,0x9F,0x55,0x00,0xC7,0xF6,0x08,0x6A,0x94,0xB9,0x5F,0xDC,0xE0,0x33,0xF1,0x84,
-0x60,0xF9,0x5B,0x27,0x11,0xB4,0xFC,0x16,0xF2,0xBB,0x56,0x6A,0x80,0x25,0x8D,0x02,
-0x03,0x01,0x00,0x01,0xA3,0x81,0xB2,0x30,0x81,0xAF,0x30,0x0F,0x06,0x03,0x55,0x1D,
-0x13,0x01,0x01,0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,
-0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x6D,0x06,0x08,0x2B,
-0x06,0x01,0x05,0x05,0x07,0x01,0x0C,0x04,0x61,0x30,0x5F,0xA1,0x5D,0xA0,0x5B,0x30,
-0x59,0x30,0x57,0x30,0x55,0x16,0x09,0x69,0x6D,0x61,0x67,0x65,0x2F,0x67,0x69,0x66,
-0x30,0x21,0x30,0x1F,0x30,0x07,0x06,0x05,0x2B,0x0E,0x03,0x02,0x1A,0x04,0x14,0x8F,
-0xE5,0xD3,0x1A,0x86,0xAC,0x8D,0x8E,0x6B,0xC3,0xCF,0x80,0x6A,0xD4,0x48,0x18,0x2C,
-0x7B,0x19,0x2E,0x30,0x25,0x16,0x23,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x6C,0x6F,
-0x67,0x6F,0x2E,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x2F,
-0x76,0x73,0x6C,0x6F,0x67,0x6F,0x2E,0x67,0x69,0x66,0x30,0x1D,0x06,0x03,0x55,0x1D,
-0x0E,0x04,0x16,0x04,0x14,0xB6,0x77,0xFA,0x69,0x48,0x47,0x9F,0x53,0x12,0xD5,0xC2,
-0xEA,0x07,0x32,0x76,0x07,0xD1,0x97,0x07,0x19,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
-0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x4A,0xF8,0xF8,
-0xB0,0x03,0xE6,0x2C,0x67,0x7B,0xE4,0x94,0x77,0x63,0xCC,0x6E,0x4C,0xF9,0x7D,0x0E,
-0x0D,0xDC,0xC8,0xB9,0x35,0xB9,0x70,0x4F,0x63,0xFA,0x24,0xFA,0x6C,0x83,0x8C,0x47,
-0x9D,0x3B,0x63,0xF3,0x9A,0xF9,0x76,0x32,0x95,0x91,0xB1,0x77,0xBC,0xAC,0x9A,0xBE,
-0xB1,0xE4,0x31,0x21,0xC6,0x81,0x95,0x56,0x5A,0x0E,0xB1,0xC2,0xD4,0xB1,0xA6,0x59,
-0xAC,0xF1,0x63,0xCB,0xB8,0x4C,0x1D,0x59,0x90,0x4A,0xEF,0x90,0x16,0x28,0x1F,0x5A,
-0xAE,0x10,0xFB,0x81,0x50,0x38,0x0C,0x6C,0xCC,0xF1,0x3D,0xC3,0xF5,0x63,0xE3,0xB3,
-0xE3,0x21,0xC9,0x24,0x39,0xE9,0xFD,0x15,0x66,0x46,0xF4,0x1B,0x11,0xD0,0x4D,0x73,
-0xA3,0x7D,0x46,0xF9,0x3D,0xED,0xA8,0x5F,0x62,0xD4,0xF1,0x3F,0xF8,0xE0,0x74,0x57,
-0x2B,0x18,0x9D,0x81,0xB4,0xC4,0x28,0xDA,0x94,0x97,0xA5,0x70,0xEB,0xAC,0x1D,0xBE,
-0x07,0x11,0xF0,0xD5,0xDB,0xDD,0xE5,0x8C,0xF0,0xD5,0x32,0xB0,0x83,0xE6,0x57,0xE2,
-0x8F,0xBF,0xBE,0xA1,0xAA,0xBF,0x3D,0x1D,0xB5,0xD4,0x38,0xEA,0xD7,0xB0,0x5C,0x3A,
-0x4F,0x6A,0x3F,0x8F,0xC0,0x66,0x6C,0x63,0xAA,0xE9,0xD9,0xA4,0x16,0xF4,0x81,0xD1,
-0x95,0x14,0x0E,0x7D,0xCD,0x95,0x34,0xD9,0xD2,0x8F,0x70,0x73,0x81,0x7B,0x9C,0x7E,
-0xBD,0x98,0x61,0xD8,0x45,0x87,0x98,0x90,0xC5,0xEB,0x86,0x30,0xC6,0x35,0xBF,0xF0,
-0xFF,0xC3,0x55,0x88,0x83,0x4B,0xEF,0x05,0x92,0x06,0x71,0xF2,0xB8,0x98,0x93,0xB7,
-0xEC,0xCD,0x82,0x61,0xF1,0x38,0xE6,0x4F,0x97,0x98,0x2A,0x5A,0x8D,
-};
-
-
-/* subject:/C=US/OU=www.xrampsecurity.com/O=XRamp Security Services Inc/CN=XRamp Global Certification Authority */
-/* issuer :/C=US/OU=www.xrampsecurity.com/O=XRamp Security Services Inc/CN=XRamp Global Certification Authority */
-
-
-const unsigned char XRamp_Global_CA_Root_certificate[1076]={
-0x30,0x82,0x04,0x30,0x30,0x82,0x03,0x18,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x50,
-0x94,0x6C,0xEC,0x18,0xEA,0xD5,0x9C,0x4D,0xD5,0x97,0xEF,0x75,0x8F,0xA0,0xAD,0x30,
-0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,
-0x82,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x1E,
-0x30,0x1C,0x06,0x03,0x55,0x04,0x0B,0x13,0x15,0x77,0x77,0x77,0x2E,0x78,0x72,0x61,
-0x6D,0x70,0x73,0x65,0x63,0x75,0x72,0x69,0x74,0x79,0x2E,0x63,0x6F,0x6D,0x31,0x24,
-0x30,0x22,0x06,0x03,0x55,0x04,0x0A,0x13,0x1B,0x58,0x52,0x61,0x6D,0x70,0x20,0x53,
-0x65,0x63,0x75,0x72,0x69,0x74,0x79,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,
-0x20,0x49,0x6E,0x63,0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,0x04,0x03,0x13,0x24,0x58,
-0x52,0x61,0x6D,0x70,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,0x20,0x43,0x65,0x72,0x74,
-0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,
-0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x30,0x34,0x31,0x31,0x30,0x31,0x31,0x37,0x31,
-0x34,0x30,0x34,0x5A,0x17,0x0D,0x33,0x35,0x30,0x31,0x30,0x31,0x30,0x35,0x33,0x37,
-0x31,0x39,0x5A,0x30,0x81,0x82,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,
-0x02,0x55,0x53,0x31,0x1E,0x30,0x1C,0x06,0x03,0x55,0x04,0x0B,0x13,0x15,0x77,0x77,
-0x77,0x2E,0x78,0x72,0x61,0x6D,0x70,0x73,0x65,0x63,0x75,0x72,0x69,0x74,0x79,0x2E,
-0x63,0x6F,0x6D,0x31,0x24,0x30,0x22,0x06,0x03,0x55,0x04,0x0A,0x13,0x1B,0x58,0x52,
-0x61,0x6D,0x70,0x20,0x53,0x65,0x63,0x75,0x72,0x69,0x74,0x79,0x20,0x53,0x65,0x72,
-0x76,0x69,0x63,0x65,0x73,0x20,0x49,0x6E,0x63,0x31,0x2D,0x30,0x2B,0x06,0x03,0x55,
-0x04,0x03,0x13,0x24,0x58,0x52,0x61,0x6D,0x70,0x20,0x47,0x6C,0x6F,0x62,0x61,0x6C,
-0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,
-0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,
-0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,
-0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0x98,0x24,0x1E,0xBD,0x15,0xB4,0xBA,
-0xDF,0xC7,0x8C,0xA5,0x27,0xB6,0x38,0x0B,0x69,0xF3,0xB6,0x4E,0xA8,0x2C,0x2E,0x21,
-0x1D,0x5C,0x44,0xDF,0x21,0x5D,0x7E,0x23,0x74,0xFE,0x5E,0x7E,0xB4,0x4A,0xB7,0xA6,
-0xAD,0x1F,0xAE,0xE0,0x06,0x16,0xE2,0x9B,0x5B,0xD9,0x67,0x74,0x6B,0x5D,0x80,0x8F,
-0x29,0x9D,0x86,0x1B,0xD9,0x9C,0x0D,0x98,0x6D,0x76,0x10,0x28,0x58,0xE4,0x65,0xB0,
-0x7F,0x4A,0x98,0x79,0x9F,0xE0,0xC3,0x31,0x7E,0x80,0x2B,0xB5,0x8C,0xC0,0x40,0x3B,
-0x11,0x86,0xD0,0xCB,0xA2,0x86,0x36,0x60,0xA4,0xD5,0x30,0x82,0x6D,0xD9,0x6E,0xD0,
-0x0F,0x12,0x04,0x33,0x97,0x5F,0x4F,0x61,0x5A,0xF0,0xE4,0xF9,0x91,0xAB,0xE7,0x1D,
-0x3B,0xBC,0xE8,0xCF,0xF4,0x6B,0x2D,0x34,0x7C,0xE2,0x48,0x61,0x1C,0x8E,0xF3,0x61,
-0x44,0xCC,0x6F,0xA0,0x4A,0xA9,0x94,0xB0,0x4D,0xDA,0xE7,0xA9,0x34,0x7A,0x72,0x38,
-0xA8,0x41,0xCC,0x3C,0x94,0x11,0x7D,0xEB,0xC8,0xA6,0x8C,0xB7,0x86,0xCB,0xCA,0x33,
-0x3B,0xD9,0x3D,0x37,0x8B,0xFB,0x7A,0x3E,0x86,0x2C,0xE7,0x73,0xD7,0x0A,0x57,0xAC,
-0x64,0x9B,0x19,0xEB,0xF4,0x0F,0x04,0x08,0x8A,0xAC,0x03,0x17,0x19,0x64,0xF4,0x5A,
-0x25,0x22,0x8D,0x34,0x2C,0xB2,0xF6,0x68,0x1D,0x12,0x6D,0xD3,0x8A,0x1E,0x14,0xDA,
-0xC4,0x8F,0xA6,0xE2,0x23,0x85,0xD5,0x7A,0x0D,0xBD,0x6A,0xE0,0xE9,0xEC,0xEC,0x17,
-0xBB,0x42,0x1B,0x67,0xAA,0x25,0xED,0x45,0x83,0x21,0xFC,0xC1,0xC9,0x7C,0xD5,0x62,
-0x3E,0xFA,0xF2,0xC5,0x2D,0xD3,0xFD,0xD4,0x65,0x02,0x03,0x01,0x00,0x01,0xA3,0x81,
-0x9F,0x30,0x81,0x9C,0x30,0x13,0x06,0x09,0x2B,0x06,0x01,0x04,0x01,0x82,0x37,0x14,
-0x02,0x04,0x06,0x1E,0x04,0x00,0x43,0x00,0x41,0x30,0x0B,0x06,0x03,0x55,0x1D,0x0F,
-0x04,0x04,0x03,0x02,0x01,0x86,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,
-0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,
-0x04,0x14,0xC6,0x4F,0xA2,0x3D,0x06,0x63,0x84,0x09,0x9C,0xCE,0x62,0xE4,0x04,0xAC,
-0x8D,0x5C,0xB5,0xE9,0xB6,0x1B,0x30,0x36,0x06,0x03,0x55,0x1D,0x1F,0x04,0x2F,0x30,
-0x2D,0x30,0x2B,0xA0,0x29,0xA0,0x27,0x86,0x25,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,
-0x63,0x72,0x6C,0x2E,0x78,0x72,0x61,0x6D,0x70,0x73,0x65,0x63,0x75,0x72,0x69,0x74,
-0x79,0x2E,0x63,0x6F,0x6D,0x2F,0x58,0x47,0x43,0x41,0x2E,0x63,0x72,0x6C,0x30,0x10,
-0x06,0x09,0x2B,0x06,0x01,0x04,0x01,0x82,0x37,0x15,0x01,0x04,0x03,0x02,0x01,0x01,
-0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,
-0x82,0x01,0x01,0x00,0x91,0x15,0x39,0x03,0x01,0x1B,0x67,0xFB,0x4A,0x1C,0xF9,0x0A,
-0x60,0x5B,0xA1,0xDA,0x4D,0x97,0x62,0xF9,0x24,0x53,0x27,0xD7,0x82,0x64,0x4E,0x90,
-0x2E,0xC3,0x49,0x1B,0x2B,0x9A,0xDC,0xFC,0xA8,0x78,0x67,0x35,0xF1,0x1D,0xF0,0x11,
-0xBD,0xB7,0x48,0xE3,0x10,0xF6,0x0D,0xDF,0x3F,0xD2,0xC9,0xB6,0xAA,0x55,0xA4,0x48,
-0xBA,0x02,0xDB,0xDE,0x59,0x2E,0x15,0x5B,0x3B,0x9D,0x16,0x7D,0x47,0xD7,0x37,0xEA,
-0x5F,0x4D,0x76,0x12,0x36,0xBB,0x1F,0xD7,0xA1,0x81,0x04,0x46,0x20,0xA3,0x2C,0x6D,
-0xA9,0x9E,0x01,0x7E,0x3F,0x29,0xCE,0x00,0x93,0xDF,0xFD,0xC9,0x92,0x73,0x89,0x89,
-0x64,0x9E,0xE7,0x2B,0xE4,0x1C,0x91,0x2C,0xD2,0xB9,0xCE,0x7D,0xCE,0x6F,0x31,0x99,
-0xD3,0xE6,0xBE,0xD2,0x1E,0x90,0xF0,0x09,0x14,0x79,0x5C,0x23,0xAB,0x4D,0xD2,0xDA,
-0x21,0x1F,0x4D,0x99,0x79,0x9D,0xE1,0xCF,0x27,0x9F,0x10,0x9B,0x1C,0x88,0x0D,0xB0,
-0x8A,0x64,0x41,0x31,0xB8,0x0E,0x6C,0x90,0x24,0xA4,0x9B,0x5C,0x71,0x8F,0xBA,0xBB,
-0x7E,0x1C,0x1B,0xDB,0x6A,0x80,0x0F,0x21,0xBC,0xE9,0xDB,0xA6,0xB7,0x40,0xF4,0xB2,
-0x8B,0xA9,0xB1,0xE4,0xEF,0x9A,0x1A,0xD0,0x3D,0x69,0x99,0xEE,0xA8,0x28,0xA3,0xE1,
-0x3C,0xB3,0xF0,0xB2,0x11,0x9C,0xCF,0x7C,0x40,0xE6,0xDD,0xE7,0x43,0x7D,0xA2,0xD8,
-0x3A,0xB5,0xA9,0x8D,0xF2,0x34,0x99,0xC4,0xD4,0x10,0xE1,0x06,0xFD,0x09,0x84,0x10,
-0x3B,0xEE,0xC4,0x4C,0xF4,0xEC,0x27,0x7C,0x42,0xC2,0x74,0x7C,0x82,0x8A,0x09,0xC9,
-0xB4,0x03,0x25,0xBC,
-};
-
-
-const unsigned char* kSSLCertCertificateList[] = {
- AddTrust_External_Root_certificate,
- AddTrust_Low_Value_Services_Root_certificate,
- AddTrust_Public_Services_Root_certificate,
- AddTrust_Qualified_Certificates_Root_certificate,
- AffirmTrust_Commercial_certificate,
- AffirmTrust_Networking_certificate,
- AffirmTrust_Premium_certificate,
- AffirmTrust_Premium_ECC_certificate,
- America_Online_Root_Certification_Authority_1_certificate,
- America_Online_Root_Certification_Authority_2_certificate,
- Baltimore_CyberTrust_Root_certificate,
- Comodo_AAA_Services_root_certificate,
- COMODO_Certification_Authority_certificate,
- COMODO_ECC_Certification_Authority_certificate,
- Comodo_Secure_Services_root_certificate,
- Comodo_Trusted_Services_root_certificate,
- Cybertrust_Global_Root_certificate,
- DigiCert_Assured_ID_Root_CA_certificate,
- DigiCert_Global_Root_CA_certificate,
- DigiCert_High_Assurance_EV_Root_CA_certificate,
- Entrust_net_Premium_2048_Secure_Server_CA_certificate,
- Entrust_net_Secure_Server_CA_certificate,
- Entrust_Root_Certification_Authority_certificate,
- Equifax_Secure_CA_certificate,
- Equifax_Secure_eBusiness_CA_1_certificate,
- Equifax_Secure_eBusiness_CA_2_certificate,
- Equifax_Secure_Global_eBusiness_CA_certificate,
- GeoTrust_Global_CA_certificate,
- GeoTrust_Global_CA_2_certificate,
- GeoTrust_Primary_Certification_Authority_certificate,
- GeoTrust_Primary_Certification_Authority___G2_certificate,
- GeoTrust_Primary_Certification_Authority___G3_certificate,
- GeoTrust_Universal_CA_certificate,
- GeoTrust_Universal_CA_2_certificate,
- GlobalSign_Root_CA_certificate,
- GlobalSign_Root_CA___R2_certificate,
- GlobalSign_Root_CA___R3_certificate,
- Go_Daddy_Class_2_CA_certificate,
- Go_Daddy_Root_Certificate_Authority___G2_certificate,
- GTE_CyberTrust_Global_Root_certificate,
- Network_Solutions_Certificate_Authority_certificate,
- RSA_Root_Certificate_1_certificate,
- Starfield_Class_2_CA_certificate,
- Starfield_Root_Certificate_Authority___G2_certificate,
- Starfield_Services_Root_Certificate_Authority___G2_certificate,
- StartCom_Certification_Authority_certificate,
- StartCom_Certification_Authority_G2_certificate,
- TC_TrustCenter_Class_2_CA_II_certificate,
- TC_TrustCenter_Class_3_CA_II_certificate,
- TC_TrustCenter_Universal_CA_I_certificate,
- TC_TrustCenter_Universal_CA_III_certificate,
- Thawte_Premium_Server_CA_certificate,
- thawte_Primary_Root_CA_certificate,
- thawte_Primary_Root_CA___G2_certificate,
- thawte_Primary_Root_CA___G3_certificate,
- Thawte_Server_CA_certificate,
- UTN_DATACorp_SGC_Root_CA_certificate,
- UTN_USERFirst_Hardware_Root_CA_certificate,
- ValiCert_Class_1_VA_certificate,
- ValiCert_Class_2_VA_certificate,
- Verisign_Class_3_Public_Primary_Certification_Authority_certificate,
- Verisign_Class_3_Public_Primary_Certification_Authority___G2_certificate,
- Verisign_Class_3_Public_Primary_Certification_Authority___G3_certificate,
- VeriSign_Class_3_Public_Primary_Certification_Authority___G4_certificate,
- VeriSign_Class_3_Public_Primary_Certification_Authority___G5_certificate,
- Verisign_Class_4_Public_Primary_Certification_Authority___G3_certificate,
- VeriSign_Universal_Root_Certification_Authority_certificate,
- XRamp_Global_CA_Root_certificate,
-};
-
-const size_t kSSLCertCertificateSizeList[] = {
- 1082,
- 1052,
- 1049,
- 1058,
- 848,
- 848,
- 1354,
- 514,
- 936,
- 1448,
- 891,
- 1078,
- 1057,
- 653,
- 1091,
- 1095,
- 933,
- 955,
- 947,
- 969,
- 1120,
- 1244,
- 1173,
- 804,
- 646,
- 804,
- 660,
- 856,
- 874,
- 896,
- 690,
- 1026,
- 1388,
- 1392,
- 889,
- 958,
- 867,
- 1028,
- 969,
- 606,
- 1002,
- 747,
- 1043,
- 993,
- 1011,
- 1931,
- 1383,
- 1198,
- 1198,
- 993,
- 997,
- 811,
- 1060,
- 652,
- 1070,
- 791,
- 1122,
- 1144,
- 747,
- 747,
- 576,
- 774,
- 1054,
- 904,
- 1239,
- 1054,
- 1213,
- 1076,
-};
-
diff --git a/base/sslsocketfactory.cc b/base/sslsocketfactory.cc
deleted file mode 100644
index f44724e..0000000
--- a/base/sslsocketfactory.cc
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * libjingle
- * Copyright 2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/autodetectproxy.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/httpcommon-inl.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslsocketfactory.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// ProxySocketAdapter
-// TODO: Consider combining AutoDetectProxy and ProxySocketAdapter. I think
-// the socket adapter is the more appropriate idiom for automatic proxy
-// detection. We may or may not want to combine proxydetect.* as well.
-///////////////////////////////////////////////////////////////////////////////
-
-class ProxySocketAdapter : public AsyncSocketAdapter {
- public:
- ProxySocketAdapter(SslSocketFactory* factory, int family, int type)
- : AsyncSocketAdapter(NULL), factory_(factory), family_(family),
- type_(type), detect_(NULL) {
- }
- virtual ~ProxySocketAdapter() {
- Close();
- }
-
- virtual int Connect(const SocketAddress& addr) {
- ASSERT(NULL == detect_);
- ASSERT(NULL == socket_);
- remote_ = addr;
- if (remote_.IsAnyIP() && remote_.hostname().empty()) {
- LOG_F(LS_ERROR) << "Empty address";
- return SOCKET_ERROR;
- }
- Url<char> url("/", remote_.HostAsURIString(), remote_.port());
- detect_ = new AutoDetectProxy(factory_->agent_);
- detect_->set_server_url(url.url());
- detect_->SignalWorkDone.connect(this,
- &ProxySocketAdapter::OnProxyDetectionComplete);
- detect_->Start();
- return SOCKET_ERROR;
- }
- virtual int GetError() const {
- if (socket_) {
- return socket_->GetError();
- }
- return detect_ ? EWOULDBLOCK : EADDRNOTAVAIL;
- }
- virtual int Close() {
- if (socket_) {
- return socket_->Close();
- }
- if (detect_) {
- detect_->Destroy(false);
- detect_ = NULL;
- }
- return 0;
- }
- virtual ConnState GetState() const {
- if (socket_) {
- return socket_->GetState();
- }
- return detect_ ? CS_CONNECTING : CS_CLOSED;
- }
-
-private:
- // AutoDetectProxy Slots
- void OnProxyDetectionComplete(SignalThread* thread) {
- ASSERT(detect_ == thread);
- Attach(factory_->CreateProxySocket(detect_->proxy(), family_, type_));
- detect_->Release();
- detect_ = NULL;
- if (0 == AsyncSocketAdapter::Connect(remote_)) {
- SignalConnectEvent(this);
- } else if (!IsBlockingError(socket_->GetError())) {
- SignalCloseEvent(this, socket_->GetError());
- }
- }
-
- SslSocketFactory* factory_;
- int family_;
- int type_;
- SocketAddress remote_;
- AutoDetectProxy* detect_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// SslSocketFactory
-///////////////////////////////////////////////////////////////////////////////
-
-Socket* SslSocketFactory::CreateSocket(int type) {
- return CreateSocket(AF_INET, type);
-}
-
-Socket* SslSocketFactory::CreateSocket(int family, int type) {
- return factory_->CreateSocket(family, type);
-}
-
-AsyncSocket* SslSocketFactory::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* SslSocketFactory::CreateAsyncSocket(int family, int type) {
- if (autodetect_proxy_) {
- return new ProxySocketAdapter(this, family, type);
- } else {
- return CreateProxySocket(proxy_, family, type);
- }
-}
-
-
-AsyncSocket* SslSocketFactory::CreateProxySocket(const ProxyInfo& proxy,
- int family,
- int type) {
- AsyncSocket* socket = factory_->CreateAsyncSocket(family, type);
- if (!socket)
- return NULL;
-
- // Binary logging happens at the lowest level
- if (!logging_label_.empty() && binary_mode_) {
- socket = new LoggingSocketAdapter(socket, logging_level_,
- logging_label_.c_str(), binary_mode_);
- }
-
- if (proxy.type) {
- AsyncSocket* proxy_socket = 0;
- if (proxy_.type == PROXY_SOCKS5) {
- proxy_socket = new AsyncSocksProxySocket(socket, proxy.address,
- proxy.username, proxy.password);
- } else {
- // Note: we are trying unknown proxies as HTTPS currently
- AsyncHttpsProxySocket* http_proxy =
- new AsyncHttpsProxySocket(socket, agent_, proxy.address,
- proxy.username, proxy.password);
- http_proxy->SetForceConnect(force_connect_ || !hostname_.empty());
- proxy_socket = http_proxy;
- }
- if (!proxy_socket) {
- delete socket;
- return NULL;
- }
- socket = proxy_socket; // for our purposes the proxy is now the socket
- }
-
- if (!hostname_.empty()) {
- if (SSLAdapter* ssl_adapter = SSLAdapter::Create(socket)) {
- ssl_adapter->set_ignore_bad_cert(ignore_bad_cert_);
- ssl_adapter->StartSSL(hostname_.c_str(), true);
- socket = ssl_adapter;
- } else {
- LOG_F(LS_ERROR) << "SSL unavailable";
- }
- }
-
- // Regular logging occurs at the highest level
- if (!logging_label_.empty() && !binary_mode_) {
- socket = new LoggingSocketAdapter(socket, logging_level_,
- logging_label_.c_str(), binary_mode_);
- }
- return socket;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/sslsocketfactory.h b/base/sslsocketfactory.h
deleted file mode 100644
index 32acd15..0000000
--- a/base/sslsocketfactory.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * libjingle
- * Copyright 2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SSLSOCKETFACTORY_H__
-#define TALK_BASE_SSLSOCKETFACTORY_H__
-
-#include "talk/base/proxyinfo.h"
-#include "talk/base/socketserver.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// SslSocketFactory
-///////////////////////////////////////////////////////////////////////////////
-
-class SslSocketFactory : public SocketFactory {
- public:
- SslSocketFactory(SocketFactory* factory, const std::string& user_agent)
- : factory_(factory), agent_(user_agent), autodetect_proxy_(true),
- force_connect_(false), logging_level_(LS_VERBOSE), binary_mode_(false),
- ignore_bad_cert_(false) {
- }
-
- void SetAutoDetectProxy() {
- autodetect_proxy_ = true;
- }
- void SetForceConnect(bool force) {
- force_connect_ = force;
- }
- void SetProxy(const ProxyInfo& proxy) {
- autodetect_proxy_ = false;
- proxy_ = proxy;
- }
- bool autodetect_proxy() const { return autodetect_proxy_; }
- const ProxyInfo& proxy() const { return proxy_; }
-
- void UseSSL(const char* hostname) { hostname_ = hostname; }
- void DisableSSL() { hostname_.clear(); }
- void SetIgnoreBadCert(bool ignore) { ignore_bad_cert_ = ignore; }
- bool ignore_bad_cert() const { return ignore_bad_cert_; }
-
- void SetLogging(LoggingSeverity level, const std::string& label,
- bool binary_mode = false) {
- logging_level_ = level;
- logging_label_ = label;
- binary_mode_ = binary_mode;
- }
-
- // SocketFactory Interface
- virtual Socket* CreateSocket(int type);
- virtual Socket* CreateSocket(int family, int type);
-
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- private:
- friend class ProxySocketAdapter;
- AsyncSocket* CreateProxySocket(const ProxyInfo& proxy, int family, int type);
-
- SocketFactory* factory_;
- std::string agent_;
- bool autodetect_proxy_, force_connect_;
- ProxyInfo proxy_;
- std::string hostname_, logging_label_;
- LoggingSeverity logging_level_;
- bool binary_mode_;
- bool ignore_bad_cert_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SSLSOCKETFACTORY_H__
diff --git a/base/sslstreamadapter.cc b/base/sslstreamadapter.cc
deleted file mode 100644
index dc59ee0..0000000
--- a/base/sslstreamadapter.cc
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/sslconfig.h"
-
-#if SSL_USE_SCHANNEL
-
-// SChannel support for DTLS and peer-to-peer mode are not
-// done.
-#elif SSL_USE_OPENSSL // && !SSL_USE_SCHANNEL
-
-#include "talk/base/opensslstreamadapter.h"
-
-#elif SSL_USE_NSS // && !SSL_USE_SCHANNEL && !SSL_USE_OPENSSL
-
-#include "talk/base/nssstreamadapter.h"
-
-#endif // !SSL_USE_OPENSSL && !SSL_USE_SCHANNEL && !SSL_USE_NSS
-
-///////////////////////////////////////////////////////////////////////////////
-
-namespace talk_base {
-
-SSLStreamAdapter* SSLStreamAdapter::Create(StreamInterface* stream) {
-#if SSL_USE_SCHANNEL
- return NULL;
-#elif SSL_USE_OPENSSL // !SSL_USE_SCHANNEL
- return new OpenSSLStreamAdapter(stream);
-#elif SSL_USE_NSS // !SSL_USE_SCHANNEL && !SSL_USE_OPENSSL
- return new NSSStreamAdapter(stream);
-#else // !SSL_USE_SCHANNEL && !SSL_USE_OPENSSL && !SSL_USE_NSS
- return NULL;
-#endif
-}
-
-// Note: this matches the logic above with SCHANNEL dominating
-#if SSL_USE_SCHANNEL
-bool SSLStreamAdapter::HaveDtls() { return false; }
-bool SSLStreamAdapter::HaveDtlsSrtp() { return false; }
-bool SSLStreamAdapter::HaveExporter() { return false; }
-#elif SSL_USE_OPENSSL
-bool SSLStreamAdapter::HaveDtls() {
- return OpenSSLStreamAdapter::HaveDtls();
-}
-bool SSLStreamAdapter::HaveDtlsSrtp() {
- return OpenSSLStreamAdapter::HaveDtlsSrtp();
-}
-bool SSLStreamAdapter::HaveExporter() {
- return OpenSSLStreamAdapter::HaveExporter();
-}
-#elif SSL_USE_NSS
-bool SSLStreamAdapter::HaveDtls() {
- return NSSStreamAdapter::HaveDtls();
-}
-bool SSLStreamAdapter::HaveDtlsSrtp() {
- return NSSStreamAdapter::HaveDtlsSrtp();
-}
-bool SSLStreamAdapter::HaveExporter() {
- return NSSStreamAdapter::HaveExporter();
-}
-#endif // !SSL_USE_SCHANNEL && !SSL_USE_OPENSSL && !SSL_USE_NSS
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/sslstreamadapter.h b/base/sslstreamadapter.h
deleted file mode 100644
index 1811f95..0000000
--- a/base/sslstreamadapter.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SSLSTREAMADAPTER_H_
-#define TALK_BASE_SSLSTREAMADAPTER_H_
-
-#include <string>
-#include <vector>
-
-#include "talk/base/stream.h"
-#include "talk/base/sslidentity.h"
-
-namespace talk_base {
-
-// SSLStreamAdapter : A StreamInterfaceAdapter that does SSL/TLS.
-// After SSL has been started, the stream will only open on successful
-// SSL verification of certificates, and the communication is
-// encrypted of course.
-//
-// This class was written with SSLAdapter as a starting point. It
-// offers a similar interface, with two differences: there is no
-// support for a restartable SSL connection, and this class has a
-// peer-to-peer mode.
-//
-// The SSL library requires initialization and cleanup. Static method
-// for doing this are in SSLAdapter. They should possibly be moved out
-// to a neutral class.
-
-
-enum SSLRole { SSL_CLIENT, SSL_SERVER };
-enum SSLMode { SSL_MODE_TLS, SSL_MODE_DTLS };
-
-// Errors for Read -- in the high range so no conflict with OpenSSL.
-enum { SSE_MSG_TRUNC = 0xff0001 };
-
-class SSLStreamAdapter : public StreamAdapterInterface {
- public:
- // Instantiate an SSLStreamAdapter wrapping the given stream,
- // (using the selected implementation for the platform).
- // Caller is responsible for freeing the returned object.
- static SSLStreamAdapter* Create(StreamInterface* stream);
-
- explicit SSLStreamAdapter(StreamInterface* stream)
- : StreamAdapterInterface(stream), ignore_bad_cert_(false) { }
-
- void set_ignore_bad_cert(bool ignore) { ignore_bad_cert_ = ignore; }
- bool ignore_bad_cert() const { return ignore_bad_cert_; }
-
- // Specify our SSL identity: key and certificate. Mostly this is
- // only used in the peer-to-peer mode (unless we actually want to
- // provide a client certificate to a server).
- // SSLStream takes ownership of the SSLIdentity object and will
- // free it when appropriate. Should be called no more than once on a
- // given SSLStream instance.
- virtual void SetIdentity(SSLIdentity* identity) = 0;
-
- // Call this to indicate that we are to play the server's role in
- // the peer-to-peer mode.
- // The default argument is for backward compatibility
- // TODO(ekr@rtfm.com): rename this SetRole to reflect its new function
- virtual void SetServerRole(SSLRole role = SSL_SERVER) = 0;
-
- // Do DTLS or TLS
- virtual void SetMode(SSLMode mode) = 0;
-
- // The mode of operation is selected by calling either
- // StartSSLWithServer or StartSSLWithPeer.
- // Use of the stream prior to calling either of these functions will
- // pass data in clear text.
- // Calling one of these functions causes SSL negotiation to begin as
- // soon as possible: right away if the underlying wrapped stream is
- // already opened, or else as soon as it opens.
- //
- // These functions return a negative error code on failure.
- // Returning 0 means success so far, but negotiation is probably not
- // complete and will continue asynchronously. In that case, the
- // exposed stream will open after successful negotiation and
- // verification, or an SE_CLOSE event will be raised if negotiation
- // fails.
-
- // StartSSLWithServer starts SSL negotiation with a server in
- // traditional mode. server_name specifies the expected server name
- // which the server's certificate needs to specify.
- virtual int StartSSLWithServer(const char* server_name) = 0;
-
- // StartSSLWithPeer starts negotiation in the special peer-to-peer
- // mode.
- // Generally, SetIdentity() and possibly SetServerRole() should have
- // been called before this.
- // SetPeerCertificate() or SetPeerCertificateDigest() must also be called.
- // It may be called after StartSSLWithPeer() but must be called before the
- // underlying stream opens.
- virtual int StartSSLWithPeer() = 0;
-
- // Specify the digest of the certificate that our peer is expected to use in
- // peer-to-peer mode. Only this certificate will be accepted during
- // SSL verification. The certificate is assumed to have been
- // obtained through some other secure channel (such as the XMPP
- // channel). Unlike SetPeerCertificate(), this must specify the
- // terminal certificate, not just a CA.
- // SSLStream makes a copy of the digest value.
- virtual bool SetPeerCertificateDigest(const std::string& digest_alg,
- const unsigned char* digest_val,
- size_t digest_len) = 0;
-
- // Retrieves the peer's X.509 certificate, if a connection has been
- // established. It returns the transmitted over SSL, including the entire
- // chain. The returned certificate is owned by the caller.
- virtual bool GetPeerCertificate(SSLCertificate** cert) const = 0;
-
- // Key Exporter interface from RFC 5705
- // Arguments are:
- // label -- the exporter label.
- // part of the RFC defining each exporter
- // usage (IN)
- // context/context_len -- a context to bind to for this connection;
- // optional, can be NULL, 0 (IN)
- // use_context -- whether to use the context value
- // (needed to distinguish no context from
- // zero-length ones).
- // result -- where to put the computed value
- // result_len -- the length of the computed value
- virtual bool ExportKeyingMaterial(const std::string& label,
- const uint8* context,
- size_t context_len,
- bool use_context,
- uint8* result,
- size_t result_len) {
- return false; // Default is unsupported
- }
-
-
- // DTLS-SRTP interface
- virtual bool SetDtlsSrtpCiphers(const std::vector<std::string>& ciphers) {
- return false;
- }
-
- virtual bool GetDtlsSrtpCipher(std::string* cipher) {
- return false;
- }
-
- // Capabilities testing
- static bool HaveDtls();
- static bool HaveDtlsSrtp();
- static bool HaveExporter();
-
- // If true, the server certificate need not match the configured
- // server_name, and in fact missing certificate authority and other
- // verification errors are ignored.
- bool ignore_bad_cert_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SSLSTREAMADAPTER_H_
diff --git a/base/sslstreamadapter_unittest.cc b/base/sslstreamadapter_unittest.cc
deleted file mode 100644
index fe276b3..0000000
--- a/base/sslstreamadapter_unittest.cc
+++ /dev/null
@@ -1,958 +0,0 @@
-/*
- * libjingle
- * Copyright 2011, Google Inc.
- * Portions Copyright 2011, RTFM, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include <algorithm>
-#include <set>
-#include <string>
-
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslconfig.h"
-#include "talk/base/sslidentity.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/stream.h"
-
-static const int kBlockSize = 4096;
-static const char kAES_CM_HMAC_SHA1_80[] = "AES_CM_128_HMAC_SHA1_80";
-static const char kAES_CM_HMAC_SHA1_32[] = "AES_CM_128_HMAC_SHA1_32";
-static const char kExporterLabel[] = "label";
-static const unsigned char kExporterContext[] = "context";
-static int kExporterContextLen = sizeof(kExporterContext);
-
-static const char kRSA_PRIVATE_KEY_PEM[] =
- "-----BEGIN RSA PRIVATE KEY-----\n"
- "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMYRkbhmI7kVA/rM\n"
- "czsZ+6JDhDvnkF+vn6yCAGuRPV03zuRqZtDy4N4to7PZu9PjqrRl7nDMXrG3YG9y\n"
- "rlIAZ72KjcKKFAJxQyAKLCIdawKRyp8RdK3LEySWEZb0AV58IadqPZDTNHHRX8dz\n"
- "5aTSMsbbkZ+C/OzTnbiMqLL/vg6jAgMBAAECgYAvgOs4FJcgvp+TuREx7YtiYVsH\n"
- "mwQPTum2z/8VzWGwR8BBHBvIpVe1MbD/Y4seyI2aco/7UaisatSgJhsU46/9Y4fq\n"
- "2TwXH9QANf4at4d9n/R6rzwpAJOpgwZgKvdQjkfrKTtgLV+/dawvpxUYkRH4JZM1\n"
- "CVGukMfKNrSVH4Ap4QJBAOJmGV1ASPnB4r4nc99at7JuIJmd7fmuVUwUgYi4XgaR\n"
- "WhScBsgYwZ/JoywdyZJgnbcrTDuVcWG56B3vXbhdpMsCQQDf9zeJrjnPZ3Cqm79y\n"
- "kdqANep0uwZciiNiWxsQrCHztywOvbFhdp8iYVFG9EK8DMY41Y5TxUwsHD+67zao\n"
- "ZNqJAkEA1suLUP/GvL8IwuRneQd2tWDqqRQ/Td3qq03hP7e77XtF/buya3Ghclo5\n"
- "54czUR89QyVfJEC6278nzA7n2h1uVQJAcG6mztNL6ja/dKZjYZye2CY44QjSlLo0\n"
- "MTgTSjdfg/28fFn2Jjtqf9Pi/X+50LWI/RcYMC2no606wRk9kyOuIQJBAK6VSAim\n"
- "1pOEjsYQn0X5KEIrz1G3bfCbB848Ime3U2/FWlCHMr6ch8kCZ5d1WUeJD3LbwMNG\n"
- "UCXiYxSsu20QNVw=\n"
- "-----END RSA PRIVATE KEY-----\n";
-
-static const char kCERT_PEM[] =
- "-----BEGIN CERTIFICATE-----\n"
- "MIIBmTCCAQKgAwIBAgIEbzBSAjANBgkqhkiG9w0BAQsFADARMQ8wDQYDVQQDEwZX\n"
- "ZWJSVEMwHhcNMTQwMTAyMTgyNDQ3WhcNMTQwMjAxMTgyNDQ3WjARMQ8wDQYDVQQD\n"
- "EwZXZWJSVEMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMYRkbhmI7kVA/rM\n"
- "czsZ+6JDhDvnkF+vn6yCAGuRPV03zuRqZtDy4N4to7PZu9PjqrRl7nDMXrG3YG9y\n"
- "rlIAZ72KjcKKFAJxQyAKLCIdawKRyp8RdK3LEySWEZb0AV58IadqPZDTNHHRX8dz\n"
- "5aTSMsbbkZ+C/OzTnbiMqLL/vg6jAgMBAAEwDQYJKoZIhvcNAQELBQADgYEAUflI\n"
- "VUe5Krqf5RVa5C3u/UTAOAUJBiDS3VANTCLBxjuMsvqOG0WvaYWP3HYPgrz0jXK2\n"
- "LJE/mGw3MyFHEqi81jh95J+ypl6xKW6Rm8jKLR87gUvCaVYn/Z4/P3AqcQTB7wOv\n"
- "UD0A8qfhfDM+LK6rPAnCsVN0NRDY3jvd6rzix9M=\n"
- "-----END CERTIFICATE-----\n";
-
-#define MAYBE_SKIP_TEST(feature) \
- if (!(talk_base::SSLStreamAdapter::feature())) { \
- LOG(LS_INFO) << "Feature disabled... skipping"; \
- return; \
- }
-
-class SSLStreamAdapterTestBase;
-
-class SSLDummyStream : public talk_base::StreamInterface,
- public sigslot::has_slots<> {
- public:
- explicit SSLDummyStream(SSLStreamAdapterTestBase *test,
- const std::string &side,
- talk_base::FifoBuffer *in,
- talk_base::FifoBuffer *out) :
- test_(test),
- side_(side),
- in_(in),
- out_(out),
- first_packet_(true) {
- in_->SignalEvent.connect(this, &SSLDummyStream::OnEventIn);
- out_->SignalEvent.connect(this, &SSLDummyStream::OnEventOut);
- }
-
- virtual talk_base::StreamState GetState() const { return talk_base::SS_OPEN; }
-
- virtual talk_base::StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- talk_base::StreamResult r;
-
- r = in_->Read(buffer, buffer_len, read, error);
- if (r == talk_base::SR_BLOCK)
- return talk_base::SR_BLOCK;
- if (r == talk_base::SR_EOS)
- return talk_base::SR_EOS;
-
- if (r != talk_base::SR_SUCCESS) {
- ADD_FAILURE();
- return talk_base::SR_ERROR;
- }
-
- return talk_base::SR_SUCCESS;
- }
-
- // Catch readability events on in and pass them up.
- virtual void OnEventIn(talk_base::StreamInterface *stream, int sig,
- int err) {
- int mask = (talk_base::SE_READ | talk_base::SE_CLOSE);
-
- if (sig & mask) {
- LOG(LS_INFO) << "SSLDummyStream::OnEvent side=" << side_ << " sig="
- << sig << " forwarding upward";
- PostEvent(sig & mask, 0);
- }
- }
-
- // Catch writeability events on out and pass them up.
- virtual void OnEventOut(talk_base::StreamInterface *stream, int sig,
- int err) {
- if (sig & talk_base::SE_WRITE) {
- LOG(LS_INFO) << "SSLDummyStream::OnEvent side=" << side_ << " sig="
- << sig << " forwarding upward";
-
- PostEvent(sig & talk_base::SE_WRITE, 0);
- }
- }
-
- // Write to the outgoing FifoBuffer
- talk_base::StreamResult WriteData(const void* data, size_t data_len,
- size_t* written, int* error) {
- return out_->Write(data, data_len, written, error);
- }
-
- // Defined later
- virtual talk_base::StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
-
- virtual void Close() {
- LOG(LS_INFO) << "Closing outbound stream";
- out_->Close();
- }
-
- private:
- SSLStreamAdapterTestBase *test_;
- const std::string side_;
- talk_base::FifoBuffer *in_;
- talk_base::FifoBuffer *out_;
- bool first_packet_;
-};
-
-static const int kFifoBufferSize = 4096;
-
-class SSLStreamAdapterTestBase : public testing::Test,
- public sigslot::has_slots<> {
- public:
- SSLStreamAdapterTestBase(const std::string& client_cert_pem,
- const std::string& client_private_key_pem,
- bool dtls) :
- client_buffer_(kFifoBufferSize), server_buffer_(kFifoBufferSize),
- client_stream_(
- new SSLDummyStream(this, "c2s", &client_buffer_, &server_buffer_)),
- server_stream_(
- new SSLDummyStream(this, "s2c", &server_buffer_, &client_buffer_)),
- client_ssl_(talk_base::SSLStreamAdapter::Create(client_stream_)),
- server_ssl_(talk_base::SSLStreamAdapter::Create(server_stream_)),
- client_identity_(NULL), server_identity_(NULL),
- delay_(0), mtu_(1460), loss_(0), lose_first_packet_(false),
- damage_(false), dtls_(dtls),
- handshake_wait_(5000), identities_set_(false) {
- // Set use of the test RNG to get predictable loss patterns.
- talk_base::SetRandomTestMode(true);
-
- // Set up the slots
- client_ssl_->SignalEvent.connect(this, &SSLStreamAdapterTestBase::OnEvent);
- server_ssl_->SignalEvent.connect(this, &SSLStreamAdapterTestBase::OnEvent);
-
- if (!client_cert_pem.empty() && !client_private_key_pem.empty()) {
- client_identity_ = talk_base::SSLIdentity::FromPEMStrings(
- client_private_key_pem, client_cert_pem);
- } else {
- client_identity_ = talk_base::SSLIdentity::Generate("client");
- }
- server_identity_ = talk_base::SSLIdentity::Generate("server");
-
- client_ssl_->SetIdentity(client_identity_);
- server_ssl_->SetIdentity(server_identity_);
- }
-
- ~SSLStreamAdapterTestBase() {
- // Put it back for the next test.
- talk_base::SetRandomTestMode(false);
- }
-
- static void SetUpTestCase() {
- talk_base::InitializeSSL();
- }
-
- static void TearDownTestCase() {
- talk_base::CleanupSSL();
- }
-
- // Recreate the client/server identities with the specified validity period.
- // |not_before| and |not_after| are offsets from the current time in number
- // of seconds.
- void ResetIdentitiesWithValidity(int not_before, int not_after) {
- client_stream_ =
- new SSLDummyStream(this, "c2s", &client_buffer_, &server_buffer_);
- server_stream_ =
- new SSLDummyStream(this, "s2c", &server_buffer_, &client_buffer_);
-
- client_ssl_.reset(talk_base::SSLStreamAdapter::Create(client_stream_));
- server_ssl_.reset(talk_base::SSLStreamAdapter::Create(server_stream_));
-
- client_ssl_->SignalEvent.connect(this, &SSLStreamAdapterTestBase::OnEvent);
- server_ssl_->SignalEvent.connect(this, &SSLStreamAdapterTestBase::OnEvent);
-
- talk_base::SSLIdentityParams client_params;
- client_params.common_name = "client";
- client_params.not_before = not_before;
- client_params.not_after = not_after;
- client_identity_ = talk_base::SSLIdentity::GenerateForTest(client_params);
-
- talk_base::SSLIdentityParams server_params;
- server_params.common_name = "server";
- server_params.not_before = not_before;
- server_params.not_after = not_after;
- server_identity_ = talk_base::SSLIdentity::GenerateForTest(server_params);
-
- client_ssl_->SetIdentity(client_identity_);
- server_ssl_->SetIdentity(server_identity_);
- }
-
- virtual void OnEvent(talk_base::StreamInterface *stream, int sig, int err) {
- LOG(LS_INFO) << "SSLStreamAdapterTestBase::OnEvent sig=" << sig;
-
- if (sig & talk_base::SE_READ) {
- ReadData(stream);
- }
-
- if ((stream == client_ssl_.get()) && (sig & talk_base::SE_WRITE)) {
- WriteData();
- }
- }
-
- void SetPeerIdentitiesByDigest(bool correct) {
- unsigned char digest[20];
- size_t digest_len;
- bool rv;
-
- LOG(LS_INFO) << "Setting peer identities by digest";
-
- rv = server_identity_->certificate().ComputeDigest(talk_base::DIGEST_SHA_1,
- digest, 20,
- &digest_len);
- ASSERT_TRUE(rv);
- if (!correct) {
- LOG(LS_INFO) << "Setting bogus digest for server cert";
- digest[0]++;
- }
- rv = client_ssl_->SetPeerCertificateDigest(talk_base::DIGEST_SHA_1, digest,
- digest_len);
- ASSERT_TRUE(rv);
-
-
- rv = client_identity_->certificate().ComputeDigest(talk_base::DIGEST_SHA_1,
- digest, 20, &digest_len);
- ASSERT_TRUE(rv);
- if (!correct) {
- LOG(LS_INFO) << "Setting bogus digest for client cert";
- digest[0]++;
- }
- rv = server_ssl_->SetPeerCertificateDigest(talk_base::DIGEST_SHA_1, digest,
- digest_len);
- ASSERT_TRUE(rv);
-
- identities_set_ = true;
- }
-
- void TestHandshake(bool expect_success = true) {
- server_ssl_->SetMode(dtls_ ? talk_base::SSL_MODE_DTLS :
- talk_base::SSL_MODE_TLS);
- client_ssl_->SetMode(dtls_ ? talk_base::SSL_MODE_DTLS :
- talk_base::SSL_MODE_TLS);
-
- if (!dtls_) {
- // Make sure we simulate a reliable network for TLS.
- // This is just a check to make sure that people don't write wrong
- // tests.
- ASSERT((mtu_ == 1460) && (loss_ == 0) && (lose_first_packet_ == 0));
- }
-
- if (!identities_set_)
- SetPeerIdentitiesByDigest(true);
-
- // Start the handshake
- int rv;
-
- server_ssl_->SetServerRole();
- rv = server_ssl_->StartSSLWithPeer();
- ASSERT_EQ(0, rv);
-
- rv = client_ssl_->StartSSLWithPeer();
- ASSERT_EQ(0, rv);
-
- // Now run the handshake
- if (expect_success) {
- EXPECT_TRUE_WAIT((client_ssl_->GetState() == talk_base::SS_OPEN)
- && (server_ssl_->GetState() == talk_base::SS_OPEN),
- handshake_wait_);
- } else {
- EXPECT_TRUE_WAIT(client_ssl_->GetState() == talk_base::SS_CLOSED,
- handshake_wait_);
- }
- }
-
- talk_base::StreamResult DataWritten(SSLDummyStream *from, const void *data,
- size_t data_len, size_t *written,
- int *error) {
- // Randomly drop loss_ percent of packets
- if (talk_base::CreateRandomId() % 100 < static_cast<uint32>(loss_)) {
- LOG(LS_INFO) << "Randomly dropping packet, size=" << data_len;
- *written = data_len;
- return talk_base::SR_SUCCESS;
- }
- if (dtls_ && (data_len > mtu_)) {
- LOG(LS_INFO) << "Dropping packet > mtu, size=" << data_len;
- *written = data_len;
- return talk_base::SR_SUCCESS;
- }
-
- // Optionally damage application data (type 23). Note that we don't damage
- // handshake packets and we damage the last byte to keep the header
- // intact but break the MAC.
- if (damage_ && (*static_cast<const unsigned char *>(data) == 23)) {
- std::vector<char> buf(data_len);
-
- LOG(LS_INFO) << "Damaging packet";
-
- memcpy(&buf[0], data, data_len);
- buf[data_len - 1]++;
-
- return from->WriteData(&buf[0], data_len, written, error);
- }
-
- return from->WriteData(data, data_len, written, error);
- }
-
- void SetDelay(int delay) {
- delay_ = delay;
- }
- int GetDelay() { return delay_; }
-
- void SetLoseFirstPacket(bool lose) {
- lose_first_packet_ = lose;
- }
- bool GetLoseFirstPacket() { return lose_first_packet_; }
-
- void SetLoss(int percent) {
- loss_ = percent;
- }
-
- void SetDamage() {
- damage_ = true;
- }
-
- void SetMtu(size_t mtu) {
- mtu_ = mtu;
- }
-
- void SetHandshakeWait(int wait) {
- handshake_wait_ = wait;
- }
-
- void SetDtlsSrtpCiphers(const std::vector<std::string> &ciphers,
- bool client) {
- if (client)
- client_ssl_->SetDtlsSrtpCiphers(ciphers);
- else
- server_ssl_->SetDtlsSrtpCiphers(ciphers);
- }
-
- bool GetDtlsSrtpCipher(bool client, std::string *retval) {
- if (client)
- return client_ssl_->GetDtlsSrtpCipher(retval);
- else
- return server_ssl_->GetDtlsSrtpCipher(retval);
- }
-
- bool GetPeerCertificate(bool client, talk_base::SSLCertificate** cert) {
- if (client)
- return client_ssl_->GetPeerCertificate(cert);
- else
- return server_ssl_->GetPeerCertificate(cert);
- }
-
- bool ExportKeyingMaterial(const char *label,
- const unsigned char *context,
- size_t context_len,
- bool use_context,
- bool client,
- unsigned char *result,
- size_t result_len) {
- if (client)
- return client_ssl_->ExportKeyingMaterial(label,
- context, context_len,
- use_context,
- result, result_len);
- else
- return server_ssl_->ExportKeyingMaterial(label,
- context, context_len,
- use_context,
- result, result_len);
- }
-
- // To be implemented by subclasses.
- virtual void WriteData() = 0;
- virtual void ReadData(talk_base::StreamInterface *stream) = 0;
- virtual void TestTransfer(int size) = 0;
-
- protected:
- talk_base::FifoBuffer client_buffer_;
- talk_base::FifoBuffer server_buffer_;
- SSLDummyStream *client_stream_; // freed by client_ssl_ destructor
- SSLDummyStream *server_stream_; // freed by server_ssl_ destructor
- talk_base::scoped_ptr<talk_base::SSLStreamAdapter> client_ssl_;
- talk_base::scoped_ptr<talk_base::SSLStreamAdapter> server_ssl_;
- talk_base::SSLIdentity *client_identity_; // freed by client_ssl_ destructor
- talk_base::SSLIdentity *server_identity_; // freed by server_ssl_ destructor
- int delay_;
- size_t mtu_;
- int loss_;
- bool lose_first_packet_;
- bool damage_;
- bool dtls_;
- int handshake_wait_;
- bool identities_set_;
-};
-
-class SSLStreamAdapterTestTLS : public SSLStreamAdapterTestBase {
- public:
- SSLStreamAdapterTestTLS() :
- SSLStreamAdapterTestBase("", "", false) {
- };
-
- // Test data transfer for TLS
- virtual void TestTransfer(int size) {
- LOG(LS_INFO) << "Starting transfer test with " << size << " bytes";
- // Create some dummy data to send.
- size_t received;
-
- send_stream_.ReserveSize(size);
- for (int i = 0; i < size; ++i) {
- char ch = static_cast<char>(i);
- send_stream_.Write(&ch, 1, NULL, NULL);
- }
- send_stream_.Rewind();
-
- // Prepare the receive stream.
- recv_stream_.ReserveSize(size);
-
- // Start sending
- WriteData();
-
- // Wait for the client to close
- EXPECT_TRUE_WAIT(server_ssl_->GetState() == talk_base::SS_CLOSED, 10000);
-
- // Now check the data
- recv_stream_.GetSize(&received);
-
- EXPECT_EQ(static_cast<size_t>(size), received);
- EXPECT_EQ(0, memcmp(send_stream_.GetBuffer(),
- recv_stream_.GetBuffer(), size));
- }
-
- void WriteData() {
- size_t position, tosend, size;
- talk_base::StreamResult rv;
- size_t sent;
- char block[kBlockSize];
-
- send_stream_.GetSize(&size);
- if (!size)
- return;
-
- for (;;) {
- send_stream_.GetPosition(&position);
- if (send_stream_.Read(block, sizeof(block), &tosend, NULL) !=
- talk_base::SR_EOS) {
- rv = client_ssl_->Write(block, tosend, &sent, 0);
-
- if (rv == talk_base::SR_SUCCESS) {
- send_stream_.SetPosition(position + sent);
- LOG(LS_VERBOSE) << "Sent: " << position + sent;
- } else if (rv == talk_base::SR_BLOCK) {
- LOG(LS_VERBOSE) << "Blocked...";
- send_stream_.SetPosition(position);
- break;
- } else {
- ADD_FAILURE();
- break;
- }
- } else {
- // Now close
- LOG(LS_INFO) << "Wrote " << position << " bytes. Closing";
- client_ssl_->Close();
- break;
- }
- }
- };
-
- virtual void ReadData(talk_base::StreamInterface *stream) {
- char buffer[1600];
- size_t bread;
- int err2;
- talk_base::StreamResult r;
-
- for (;;) {
- r = stream->Read(buffer, sizeof(buffer), &bread, &err2);
-
- if (r == talk_base::SR_ERROR || r == talk_base::SR_EOS) {
- // Unfortunately, errors are the way that the stream adapter
- // signals close in OpenSSL
- stream->Close();
- return;
- }
-
- if (r == talk_base::SR_BLOCK)
- break;
-
- ASSERT_EQ(talk_base::SR_SUCCESS, r);
- LOG(LS_INFO) << "Read " << bread;
-
- recv_stream_.Write(buffer, bread, NULL, NULL);
- }
- }
-
- private:
- talk_base::MemoryStream send_stream_;
- talk_base::MemoryStream recv_stream_;
-};
-
-class SSLStreamAdapterTestDTLS : public SSLStreamAdapterTestBase {
- public:
- SSLStreamAdapterTestDTLS() :
- SSLStreamAdapterTestBase("", "", true),
- packet_size_(1000), count_(0), sent_(0) {
- }
-
- SSLStreamAdapterTestDTLS(const std::string& cert_pem,
- const std::string& private_key_pem) :
- SSLStreamAdapterTestBase(cert_pem, private_key_pem, true),
- packet_size_(1000), count_(0), sent_(0) {
- }
-
- virtual void WriteData() {
- unsigned char *packet = new unsigned char[1600];
-
- do {
- memset(packet, sent_ & 0xff, packet_size_);
- *(reinterpret_cast<uint32_t *>(packet)) = sent_;
-
- size_t sent;
- int rv = client_ssl_->Write(packet, packet_size_, &sent, 0);
- if (rv == talk_base::SR_SUCCESS) {
- LOG(LS_VERBOSE) << "Sent: " << sent_;
- sent_++;
- } else if (rv == talk_base::SR_BLOCK) {
- LOG(LS_VERBOSE) << "Blocked...";
- break;
- } else {
- ADD_FAILURE();
- break;
- }
- } while (sent_ < count_);
-
- delete [] packet;
- }
-
- virtual void ReadData(talk_base::StreamInterface *stream) {
- unsigned char buffer[2000];
- size_t bread;
- int err2;
- talk_base::StreamResult r;
-
- for (;;) {
- r = stream->Read(buffer, 2000, &bread, &err2);
-
- if (r == talk_base::SR_ERROR) {
- // Unfortunately, errors are the way that the stream adapter
- // signals close right now
- stream->Close();
- return;
- }
-
- if (r == talk_base::SR_BLOCK)
- break;
-
- ASSERT_EQ(talk_base::SR_SUCCESS, r);
- LOG(LS_INFO) << "Read " << bread;
-
- // Now parse the datagram
- ASSERT_EQ(packet_size_, bread);
- unsigned char* ptr_to_buffer = buffer;
- uint32_t packet_num = *(reinterpret_cast<uint32_t *>(ptr_to_buffer));
-
- for (size_t i = 4; i < packet_size_; i++) {
- ASSERT_EQ((packet_num & 0xff), buffer[i]);
- }
- received_.insert(packet_num);
- }
- }
-
- virtual void TestTransfer(int count) {
- count_ = count;
-
- WriteData();
-
- EXPECT_TRUE_WAIT(sent_ == count_, 10000);
- LOG(LS_INFO) << "sent_ == " << sent_;
-
- if (damage_) {
- WAIT(false, 2000);
- EXPECT_EQ(0U, received_.size());
- } else if (loss_ == 0) {
- EXPECT_EQ_WAIT(static_cast<size_t>(sent_), received_.size(), 1000);
- } else {
- LOG(LS_INFO) << "Sent " << sent_ << " packets; received " <<
- received_.size();
- }
- };
-
- private:
- size_t packet_size_;
- int count_;
- int sent_;
- std::set<int> received_;
-};
-
-
-talk_base::StreamResult SSLDummyStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- *written = data_len;
-
- LOG(LS_INFO) << "Writing to loopback " << data_len;
-
- if (first_packet_) {
- first_packet_ = false;
- if (test_->GetLoseFirstPacket()) {
- LOG(LS_INFO) << "Losing initial packet of length " << data_len;
- return talk_base::SR_SUCCESS;
- }
- }
-
- return test_->DataWritten(this, data, data_len, written, error);
-
- return talk_base::SR_SUCCESS;
-};
-
-class SSLStreamAdapterTestDTLSFromPEMStrings : public SSLStreamAdapterTestDTLS {
- public:
- SSLStreamAdapterTestDTLSFromPEMStrings() :
- SSLStreamAdapterTestDTLS(kCERT_PEM, kRSA_PRIVATE_KEY_PEM) {
- }
-};
-
-// Basic tests: TLS
-
-// Test that we cannot read/write if we have not yet handshaked.
-// This test only applies to NSS because OpenSSL has passthrough
-// semantics for I/O before the handshake is started.
-#if SSL_USE_NSS
-TEST_F(SSLStreamAdapterTestTLS, TestNoReadWriteBeforeConnect) {
- talk_base::StreamResult rv;
- char block[kBlockSize];
- size_t dummy;
-
- rv = client_ssl_->Write(block, sizeof(block), &dummy, NULL);
- ASSERT_EQ(talk_base::SR_BLOCK, rv);
-
- rv = client_ssl_->Read(block, sizeof(block), &dummy, NULL);
- ASSERT_EQ(talk_base::SR_BLOCK, rv);
-}
-#endif
-
-
-// Test that we can make a handshake work
-TEST_F(SSLStreamAdapterTestTLS, TestTLSConnect) {
- TestHandshake();
-};
-
-// Test transfer -- trivial
-TEST_F(SSLStreamAdapterTestTLS, TestTLSTransfer) {
- TestHandshake();
- TestTransfer(100000);
-};
-
-// Test read-write after close.
-TEST_F(SSLStreamAdapterTestTLS, ReadWriteAfterClose) {
- TestHandshake();
- TestTransfer(100000);
- client_ssl_->Close();
-
- talk_base::StreamResult rv;
- char block[kBlockSize];
- size_t dummy;
-
- // It's an error to write after closed.
- rv = client_ssl_->Write(block, sizeof(block), &dummy, NULL);
- ASSERT_EQ(talk_base::SR_ERROR, rv);
-
- // But after closed read gives you EOS.
- rv = client_ssl_->Read(block, sizeof(block), &dummy, NULL);
- ASSERT_EQ(talk_base::SR_EOS, rv);
-};
-
-// Test a handshake with a bogus peer digest
-TEST_F(SSLStreamAdapterTestTLS, TestTLSBogusDigest) {
- SetPeerIdentitiesByDigest(false);
- TestHandshake(false);
-};
-
-// Test moving a bunch of data
-
-// Basic tests: DTLS
-// Test that we can make a handshake work
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSConnect) {
- MAYBE_SKIP_TEST(HaveDtls);
- TestHandshake();
-};
-
-// Test that we can make a handshake work if the first packet in
-// each direction is lost. This gives us predictable loss
-// rather than having to tune random
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSConnectWithLostFirstPacket) {
- MAYBE_SKIP_TEST(HaveDtls);
- SetLoseFirstPacket(true);
- TestHandshake();
-};
-
-// Test a handshake with loss and delay
-TEST_F(SSLStreamAdapterTestDTLS,
- TestDTLSConnectWithLostFirstPacketDelay2s) {
- MAYBE_SKIP_TEST(HaveDtls);
- SetLoseFirstPacket(true);
- SetDelay(2000);
- SetHandshakeWait(20000);
- TestHandshake();
-};
-
-// Test a handshake with small MTU
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSConnectWithSmallMtu) {
- MAYBE_SKIP_TEST(HaveDtls);
- SetMtu(700);
- SetHandshakeWait(20000);
- TestHandshake();
-};
-
-// Test transfer -- trivial
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSTransfer) {
- MAYBE_SKIP_TEST(HaveDtls);
- TestHandshake();
- TestTransfer(100);
-};
-
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSTransferWithLoss) {
- MAYBE_SKIP_TEST(HaveDtls);
- TestHandshake();
- SetLoss(10);
- TestTransfer(100);
-};
-
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSTransferWithDamage) {
- MAYBE_SKIP_TEST(HaveDtls);
- SetDamage(); // Must be called first because first packet
- // write happens at end of handshake.
- TestHandshake();
- TestTransfer(100);
-};
-
-// Test DTLS-SRTP with all high ciphers
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpHigh) {
- MAYBE_SKIP_TEST(HaveDtlsSrtp);
- std::vector<std::string> high;
- high.push_back(kAES_CM_HMAC_SHA1_80);
- SetDtlsSrtpCiphers(high, true);
- SetDtlsSrtpCiphers(high, false);
- TestHandshake();
-
- std::string client_cipher;
- ASSERT_TRUE(GetDtlsSrtpCipher(true, &client_cipher));
- std::string server_cipher;
- ASSERT_TRUE(GetDtlsSrtpCipher(false, &server_cipher));
-
- ASSERT_EQ(client_cipher, server_cipher);
- ASSERT_EQ(client_cipher, kAES_CM_HMAC_SHA1_80);
-};
-
-// Test DTLS-SRTP with all low ciphers
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpLow) {
- MAYBE_SKIP_TEST(HaveDtlsSrtp);
- std::vector<std::string> low;
- low.push_back(kAES_CM_HMAC_SHA1_32);
- SetDtlsSrtpCiphers(low, true);
- SetDtlsSrtpCiphers(low, false);
- TestHandshake();
-
- std::string client_cipher;
- ASSERT_TRUE(GetDtlsSrtpCipher(true, &client_cipher));
- std::string server_cipher;
- ASSERT_TRUE(GetDtlsSrtpCipher(false, &server_cipher));
-
- ASSERT_EQ(client_cipher, server_cipher);
- ASSERT_EQ(client_cipher, kAES_CM_HMAC_SHA1_32);
-};
-
-
-// Test DTLS-SRTP with a mismatch -- should not converge
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpHighLow) {
- MAYBE_SKIP_TEST(HaveDtlsSrtp);
- std::vector<std::string> high;
- high.push_back(kAES_CM_HMAC_SHA1_80);
- std::vector<std::string> low;
- low.push_back(kAES_CM_HMAC_SHA1_32);
- SetDtlsSrtpCiphers(high, true);
- SetDtlsSrtpCiphers(low, false);
- TestHandshake();
-
- std::string client_cipher;
- ASSERT_FALSE(GetDtlsSrtpCipher(true, &client_cipher));
- std::string server_cipher;
- ASSERT_FALSE(GetDtlsSrtpCipher(false, &server_cipher));
-};
-
-// Test DTLS-SRTP with each side being mixed -- should select high
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSSrtpMixed) {
- MAYBE_SKIP_TEST(HaveDtlsSrtp);
- std::vector<std::string> mixed;
- mixed.push_back(kAES_CM_HMAC_SHA1_80);
- mixed.push_back(kAES_CM_HMAC_SHA1_32);
- SetDtlsSrtpCiphers(mixed, true);
- SetDtlsSrtpCiphers(mixed, false);
- TestHandshake();
-
- std::string client_cipher;
- ASSERT_TRUE(GetDtlsSrtpCipher(true, &client_cipher));
- std::string server_cipher;
- ASSERT_TRUE(GetDtlsSrtpCipher(false, &server_cipher));
-
- ASSERT_EQ(client_cipher, server_cipher);
- ASSERT_EQ(client_cipher, kAES_CM_HMAC_SHA1_80);
-};
-
-// Test an exporter
-TEST_F(SSLStreamAdapterTestDTLS, TestDTLSExporter) {
- MAYBE_SKIP_TEST(HaveExporter);
- TestHandshake();
- unsigned char client_out[20];
- unsigned char server_out[20];
-
- bool result;
- result = ExportKeyingMaterial(kExporterLabel,
- kExporterContext, kExporterContextLen,
- true, true,
- client_out, sizeof(client_out));
- ASSERT_TRUE(result);
-
- result = ExportKeyingMaterial(kExporterLabel,
- kExporterContext, kExporterContextLen,
- true, false,
- server_out, sizeof(server_out));
- ASSERT_TRUE(result);
-
- ASSERT_TRUE(!memcmp(client_out, server_out, sizeof(client_out)));
-}
-
-// Test not yet valid certificates are not rejected.
-TEST_F(SSLStreamAdapterTestDTLS, TestCertNotYetValid) {
- MAYBE_SKIP_TEST(HaveDtls);
- long one_day = 60 * 60 * 24;
- // Make the certificates not valid until one day later.
- ResetIdentitiesWithValidity(one_day, one_day);
- TestHandshake();
-}
-
-// Test expired certificates are not rejected.
-TEST_F(SSLStreamAdapterTestDTLS, TestCertExpired) {
- MAYBE_SKIP_TEST(HaveDtls);
- long one_day = 60 * 60 * 24;
- // Make the certificates already expired.
- ResetIdentitiesWithValidity(-one_day, -one_day);
- TestHandshake();
-}
-
-// Test data transfer using certs created from strings.
-TEST_F(SSLStreamAdapterTestDTLSFromPEMStrings, TestTransfer) {
- MAYBE_SKIP_TEST(HaveDtls);
- TestHandshake();
- TestTransfer(100);
-}
-
-// Test getting the remote certificate.
-TEST_F(SSLStreamAdapterTestDTLSFromPEMStrings, TestDTLSGetPeerCertificate) {
- MAYBE_SKIP_TEST(HaveDtls);
-
- // Peer certificates haven't been received yet.
- talk_base::scoped_ptr<talk_base::SSLCertificate> client_peer_cert;
- ASSERT_FALSE(GetPeerCertificate(true, client_peer_cert.accept()));
- ASSERT_FALSE(client_peer_cert != NULL);
-
- talk_base::scoped_ptr<talk_base::SSLCertificate> server_peer_cert;
- ASSERT_FALSE(GetPeerCertificate(false, server_peer_cert.accept()));
- ASSERT_FALSE(server_peer_cert != NULL);
-
- TestHandshake();
-
- // The client should have a peer certificate after the handshake.
- ASSERT_TRUE(GetPeerCertificate(true, client_peer_cert.accept()));
- ASSERT_TRUE(client_peer_cert != NULL);
-
- // It's not kCERT_PEM.
- std::string client_peer_string = client_peer_cert->ToPEMString();
- ASSERT_NE(kCERT_PEM, client_peer_string);
-
- // It must not have a chain, because the test certs are self-signed.
- talk_base::SSLCertChain* client_peer_chain;
- ASSERT_FALSE(client_peer_cert->GetChain(&client_peer_chain));
-
- // The server should have a peer certificate after the handshake.
- ASSERT_TRUE(GetPeerCertificate(false, server_peer_cert.accept()));
- ASSERT_TRUE(server_peer_cert != NULL);
-
- // It's kCERT_PEM
- ASSERT_EQ(kCERT_PEM, server_peer_cert->ToPEMString());
-
- // It must not have a chain, because the test certs are self-signed.
- talk_base::SSLCertChain* server_peer_chain;
- ASSERT_FALSE(server_peer_cert->GetChain(&server_peer_chain));
-}
diff --git a/base/sslstreamadapterhelper.cc b/base/sslstreamadapterhelper.cc
deleted file mode 100644
index 7be2878..0000000
--- a/base/sslstreamadapterhelper.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- * Copyright 2012, RTFM, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include <vector>
-
-#if HAVE_CONFIG_H
-#include "config.h"
-#endif // HAVE_CONFIG_H
-
-#include "talk/base/sslstreamadapterhelper.h"
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-void SSLStreamAdapterHelper::SetIdentity(SSLIdentity* identity) {
- ASSERT(identity_.get() == NULL);
- identity_.reset(identity);
-}
-
-void SSLStreamAdapterHelper::SetServerRole(SSLRole role) {
- role_ = role;
-}
-
-int SSLStreamAdapterHelper::StartSSLWithServer(const char* server_name) {
- ASSERT(server_name != NULL && server_name[0] != '\0');
- ssl_server_name_ = server_name;
- return StartSSL();
-}
-
-int SSLStreamAdapterHelper::StartSSLWithPeer() {
- ASSERT(ssl_server_name_.empty());
- // It is permitted to specify peer_certificate_ only later.
- return StartSSL();
-}
-
-void SSLStreamAdapterHelper::SetMode(SSLMode mode) {
- ASSERT(state_ == SSL_NONE);
- ssl_mode_ = mode;
-}
-
-StreamState SSLStreamAdapterHelper::GetState() const {
- switch (state_) {
- case SSL_WAIT:
- case SSL_CONNECTING:
- return SS_OPENING;
- case SSL_CONNECTED:
- return SS_OPEN;
- default:
- return SS_CLOSED;
- };
- // not reached
-}
-
-bool SSLStreamAdapterHelper::GetPeerCertificate(SSLCertificate** cert) const {
- if (!peer_certificate_)
- return false;
-
- *cert = peer_certificate_->GetReference();
- return true;
-}
-
-bool SSLStreamAdapterHelper::SetPeerCertificateDigest(
- const std::string &digest_alg,
- const unsigned char* digest_val,
- size_t digest_len) {
- ASSERT(peer_certificate_.get() == NULL);
- ASSERT(peer_certificate_digest_algorithm_.empty());
- ASSERT(ssl_server_name_.empty());
- size_t expected_len;
-
- if (!GetDigestLength(digest_alg, &expected_len)) {
- LOG(LS_WARNING) << "Unknown digest algorithm: " << digest_alg;
- return false;
- }
- if (expected_len != digest_len)
- return false;
-
- peer_certificate_digest_value_.SetData(digest_val, digest_len);
- peer_certificate_digest_algorithm_ = digest_alg;
-
- return true;
-}
-
-void SSLStreamAdapterHelper::Error(const char* context, int err, bool signal) {
- LOG(LS_WARNING) << "SSLStreamAdapterHelper::Error("
- << context << ", " << err << "," << signal << ")";
- state_ = SSL_ERROR;
- ssl_error_code_ = err;
- Cleanup();
- if (signal)
- StreamAdapterInterface::OnEvent(stream(), SE_CLOSE, err);
-}
-
-void SSLStreamAdapterHelper::Close() {
- Cleanup();
- ASSERT(state_ == SSL_CLOSED || state_ == SSL_ERROR);
- StreamAdapterInterface::Close();
-}
-
-int SSLStreamAdapterHelper::StartSSL() {
- ASSERT(state_ == SSL_NONE);
-
- if (StreamAdapterInterface::GetState() != SS_OPEN) {
- state_ = SSL_WAIT;
- return 0;
- }
-
- state_ = SSL_CONNECTING;
- int err = BeginSSL();
- if (err) {
- Error("BeginSSL", err, false);
- return err;
- }
-
- return 0;
-}
-
-} // namespace talk_base
-
diff --git a/base/sslstreamadapterhelper.h b/base/sslstreamadapterhelper.h
deleted file mode 100644
index 5023d52..0000000
--- a/base/sslstreamadapterhelper.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SSLSTREAMADAPTERHELPER_H_
-#define TALK_BASE_SSLSTREAMADAPTERHELPER_H_
-
-#include <string>
-#include <vector>
-
-#include "talk/base/buffer.h"
-#include "talk/base/stream.h"
-#include "talk/base/sslidentity.h"
-#include "talk/base/sslstreamadapter.h"
-
-namespace talk_base {
-
-// SSLStreamAdapterHelper : A stream adapter which implements much
-// of the logic that is common between the known implementations
-// (NSS and OpenSSL)
-class SSLStreamAdapterHelper : public SSLStreamAdapter {
- public:
- explicit SSLStreamAdapterHelper(StreamInterface* stream)
- : SSLStreamAdapter(stream),
- state_(SSL_NONE),
- role_(SSL_CLIENT),
- ssl_error_code_(0), // Not meaningful yet
- ssl_mode_(SSL_MODE_TLS) {}
-
-
- // Overrides of SSLStreamAdapter
- virtual void SetIdentity(SSLIdentity* identity);
- virtual void SetServerRole(SSLRole role = SSL_SERVER);
- virtual void SetMode(SSLMode mode);
-
- virtual int StartSSLWithServer(const char* server_name);
- virtual int StartSSLWithPeer();
-
- virtual bool SetPeerCertificateDigest(const std::string& digest_alg,
- const unsigned char* digest_val,
- size_t digest_len);
- virtual bool GetPeerCertificate(SSLCertificate** cert) const;
- virtual StreamState GetState() const;
- virtual void Close();
-
- protected:
- // Internal helper methods
- // The following method returns 0 on success and a negative
- // error code on failure. The error code may be either -1 or
- // from the impl on some other error cases, so it can't really be
- // interpreted unfortunately.
-
- // Perform SSL negotiation steps.
- int ContinueSSL();
-
- // Error handler helper. signal is given as true for errors in
- // asynchronous contexts (when an error code was not returned
- // through some other method), and in that case an SE_CLOSE event is
- // raised on the stream with the specified error.
- // A 0 error means a graceful close, otherwise there is not really enough
- // context to interpret the error code.
- virtual void Error(const char* context, int err, bool signal);
-
- // Must be implemented by descendents
- virtual int BeginSSL() = 0;
- virtual void Cleanup() = 0;
- virtual bool GetDigestLength(const std::string& algorithm,
- size_t* length) = 0;
-
- enum SSLState {
- // Before calling one of the StartSSL methods, data flows
- // in clear text.
- SSL_NONE,
- SSL_WAIT, // waiting for the stream to open to start SSL negotiation
- SSL_CONNECTING, // SSL negotiation in progress
- SSL_CONNECTED, // SSL stream successfully established
- SSL_ERROR, // some SSL error occurred, stream is closed
- SSL_CLOSED // Clean close
- };
-
- // MSG_MAX is the maximum generic stream message number.
- enum { MSG_DTLS_TIMEOUT = MSG_MAX + 1 };
-
- SSLState state_;
- SSLRole role_;
- int ssl_error_code_; // valid when state_ == SSL_ERROR
-
- // Our key and certificate, mostly useful in peer-to-peer mode.
- scoped_ptr<SSLIdentity> identity_;
- // in traditional mode, the server name that the server's certificate
- // must specify. Empty in peer-to-peer mode.
- std::string ssl_server_name_;
- // The peer's certificate. Only used for GetPeerCertificate.
- scoped_ptr<SSLCertificate> peer_certificate_;
-
- // The digest of the certificate that the peer must present.
- Buffer peer_certificate_digest_value_;
- std::string peer_certificate_digest_algorithm_;
-
- // Do DTLS or not
- SSLMode ssl_mode_;
-
- private:
- // Go from state SSL_NONE to either SSL_CONNECTING or SSL_WAIT,
- // depending on whether the underlying stream is already open or
- // not. Returns 0 on success and a negative value on error.
- int StartSSL();
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SSLSTREAMADAPTERHELPER_H_
diff --git a/base/stream.cc b/base/stream.cc
deleted file mode 100644
index 02ae409..0000000
--- a/base/stream.cc
+++ /dev/null
@@ -1,1352 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if defined(POSIX)
-#include <sys/file.h>
-#endif // POSIX
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <string>
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#define fileno _fileno
-#endif
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamInterface
-///////////////////////////////////////////////////////////////////////////////
-StreamInterface::~StreamInterface() {
-}
-
-StreamResult StreamInterface::WriteAll(const void* data, size_t data_len,
- size_t* written, int* error) {
- StreamResult result = SR_SUCCESS;
- size_t total_written = 0, current_written;
- while (total_written < data_len) {
- result = Write(static_cast<const char*>(data) + total_written,
- data_len - total_written, ¤t_written, error);
- if (result != SR_SUCCESS)
- break;
- total_written += current_written;
- }
- if (written)
- *written = total_written;
- return result;
-}
-
-StreamResult StreamInterface::ReadAll(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- StreamResult result = SR_SUCCESS;
- size_t total_read = 0, current_read;
- while (total_read < buffer_len) {
- result = Read(static_cast<char*>(buffer) + total_read,
- buffer_len - total_read, ¤t_read, error);
- if (result != SR_SUCCESS)
- break;
- total_read += current_read;
- }
- if (read)
- *read = total_read;
- return result;
-}
-
-StreamResult StreamInterface::ReadLine(std::string* line) {
- line->clear();
- StreamResult result = SR_SUCCESS;
- while (true) {
- char ch;
- result = Read(&ch, sizeof(ch), NULL, NULL);
- if (result != SR_SUCCESS) {
- break;
- }
- if (ch == '\n') {
- break;
- }
- line->push_back(ch);
- }
- if (!line->empty()) { // give back the line we've collected so far with
- result = SR_SUCCESS; // a success code. Otherwise return the last code
- }
- return result;
-}
-
-void StreamInterface::PostEvent(Thread* t, int events, int err) {
- t->Post(this, MSG_POST_EVENT, new StreamEventData(events, err));
-}
-
-void StreamInterface::PostEvent(int events, int err) {
- PostEvent(Thread::Current(), events, err);
-}
-
-StreamInterface::StreamInterface() {
-}
-
-void StreamInterface::OnMessage(Message* msg) {
- if (MSG_POST_EVENT == msg->message_id) {
- StreamEventData* pe = static_cast<StreamEventData*>(msg->pdata);
- SignalEvent(this, pe->events, pe->error);
- delete msg->pdata;
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamAdapterInterface
-///////////////////////////////////////////////////////////////////////////////
-
-StreamAdapterInterface::StreamAdapterInterface(StreamInterface* stream,
- bool owned)
- : stream_(stream), owned_(owned) {
- if (NULL != stream_)
- stream_->SignalEvent.connect(this, &StreamAdapterInterface::OnEvent);
-}
-
-void StreamAdapterInterface::Attach(StreamInterface* stream, bool owned) {
- if (NULL != stream_)
- stream_->SignalEvent.disconnect(this);
- if (owned_)
- delete stream_;
- stream_ = stream;
- owned_ = owned;
- if (NULL != stream_)
- stream_->SignalEvent.connect(this, &StreamAdapterInterface::OnEvent);
-}
-
-StreamInterface* StreamAdapterInterface::Detach() {
- if (NULL != stream_)
- stream_->SignalEvent.disconnect(this);
- StreamInterface* stream = stream_;
- stream_ = NULL;
- return stream;
-}
-
-StreamAdapterInterface::~StreamAdapterInterface() {
- if (owned_)
- delete stream_;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamTap
-///////////////////////////////////////////////////////////////////////////////
-
-StreamTap::StreamTap(StreamInterface* stream, StreamInterface* tap)
- : StreamAdapterInterface(stream), tap_(), tap_result_(SR_SUCCESS),
- tap_error_(0) {
- AttachTap(tap);
-}
-
-void StreamTap::AttachTap(StreamInterface* tap) {
- tap_.reset(tap);
-}
-
-StreamInterface* StreamTap::DetachTap() {
- return tap_.release();
-}
-
-StreamResult StreamTap::GetTapResult(int* error) {
- if (error) {
- *error = tap_error_;
- }
- return tap_result_;
-}
-
-StreamResult StreamTap::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- size_t backup_read;
- if (!read) {
- read = &backup_read;
- }
- StreamResult res = StreamAdapterInterface::Read(buffer, buffer_len,
- read, error);
- if ((res == SR_SUCCESS) && (tap_result_ == SR_SUCCESS)) {
- tap_result_ = tap_->WriteAll(buffer, *read, NULL, &tap_error_);
- }
- return res;
-}
-
-StreamResult StreamTap::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- size_t backup_written;
- if (!written) {
- written = &backup_written;
- }
- StreamResult res = StreamAdapterInterface::Write(data, data_len,
- written, error);
- if ((res == SR_SUCCESS) && (tap_result_ == SR_SUCCESS)) {
- tap_result_ = tap_->WriteAll(data, *written, NULL, &tap_error_);
- }
- return res;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamSegment
-///////////////////////////////////////////////////////////////////////////////
-
-StreamSegment::StreamSegment(StreamInterface* stream)
- : StreamAdapterInterface(stream), start_(SIZE_UNKNOWN), pos_(0),
- length_(SIZE_UNKNOWN) {
- // It's ok for this to fail, in which case start_ is left as SIZE_UNKNOWN.
- stream->GetPosition(&start_);
-}
-
-StreamSegment::StreamSegment(StreamInterface* stream, size_t length)
- : StreamAdapterInterface(stream), start_(SIZE_UNKNOWN), pos_(0),
- length_(length) {
- // It's ok for this to fail, in which case start_ is left as SIZE_UNKNOWN.
- stream->GetPosition(&start_);
-}
-
-StreamResult StreamSegment::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- if (SIZE_UNKNOWN != length_) {
- if (pos_ >= length_)
- return SR_EOS;
- buffer_len = _min(buffer_len, length_ - pos_);
- }
- size_t backup_read;
- if (!read) {
- read = &backup_read;
- }
- StreamResult result = StreamAdapterInterface::Read(buffer, buffer_len,
- read, error);
- if (SR_SUCCESS == result) {
- pos_ += *read;
- }
- return result;
-}
-
-bool StreamSegment::SetPosition(size_t position) {
- if (SIZE_UNKNOWN == start_)
- return false; // Not seekable
- if ((SIZE_UNKNOWN != length_) && (position > length_))
- return false; // Seek past end of segment
- if (!StreamAdapterInterface::SetPosition(start_ + position))
- return false;
- pos_ = position;
- return true;
-}
-
-bool StreamSegment::GetPosition(size_t* position) const {
- if (SIZE_UNKNOWN == start_)
- return false; // Not seekable
- if (!StreamAdapterInterface::GetPosition(position))
- return false;
- if (position) {
- ASSERT(*position >= start_);
- *position -= start_;
- }
- return true;
-}
-
-bool StreamSegment::GetSize(size_t* size) const {
- if (!StreamAdapterInterface::GetSize(size))
- return false;
- if (size) {
- if (SIZE_UNKNOWN != start_) {
- ASSERT(*size >= start_);
- *size -= start_;
- }
- if (SIZE_UNKNOWN != length_) {
- *size = _min(*size, length_);
- }
- }
- return true;
-}
-
-bool StreamSegment::GetAvailable(size_t* size) const {
- if (!StreamAdapterInterface::GetAvailable(size))
- return false;
- if (size && (SIZE_UNKNOWN != length_))
- *size = _min(*size, length_ - pos_);
- return true;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// NullStream
-///////////////////////////////////////////////////////////////////////////////
-
-NullStream::NullStream() {
-}
-
-NullStream::~NullStream() {
-}
-
-StreamState NullStream::GetState() const {
- return SS_OPEN;
-}
-
-StreamResult NullStream::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- if (error) *error = -1;
- return SR_ERROR;
-}
-
-StreamResult NullStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (written) *written = data_len;
- return SR_SUCCESS;
-}
-
-void NullStream::Close() {
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// FileStream
-///////////////////////////////////////////////////////////////////////////////
-
-FileStream::FileStream() : file_(NULL) {
-}
-
-FileStream::~FileStream() {
- FileStream::Close();
-}
-
-bool FileStream::Open(const std::string& filename, const char* mode,
- int* error) {
- Close();
-#ifdef WIN32
- std::wstring wfilename;
- if (Utf8ToWindowsFilename(filename, &wfilename)) {
- file_ = _wfopen(wfilename.c_str(), ToUtf16(mode).c_str());
- } else {
- if (error) {
- *error = -1;
- return false;
- }
- }
-#else
- file_ = fopen(filename.c_str(), mode);
-#endif
- if (!file_ && error) {
- *error = errno;
- }
- return (file_ != NULL);
-}
-
-bool FileStream::OpenShare(const std::string& filename, const char* mode,
- int shflag, int* error) {
- Close();
-#ifdef WIN32
- std::wstring wfilename;
- if (Utf8ToWindowsFilename(filename, &wfilename)) {
- file_ = _wfsopen(wfilename.c_str(), ToUtf16(mode).c_str(), shflag);
- if (!file_ && error) {
- *error = errno;
- return false;
- }
- return file_ != NULL;
- } else {
- if (error) {
- *error = -1;
- }
- return false;
- }
-#else
- return Open(filename, mode, error);
-#endif
-}
-
-bool FileStream::DisableBuffering() {
- if (!file_)
- return false;
- return (setvbuf(file_, NULL, _IONBF, 0) == 0);
-}
-
-StreamState FileStream::GetState() const {
- return (file_ == NULL) ? SS_CLOSED : SS_OPEN;
-}
-
-StreamResult FileStream::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- if (!file_)
- return SR_EOS;
- size_t result = fread(buffer, 1, buffer_len, file_);
- if ((result == 0) && (buffer_len > 0)) {
- if (feof(file_))
- return SR_EOS;
- if (error)
- *error = errno;
- return SR_ERROR;
- }
- if (read)
- *read = result;
- return SR_SUCCESS;
-}
-
-StreamResult FileStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (!file_)
- return SR_EOS;
- size_t result = fwrite(data, 1, data_len, file_);
- if ((result == 0) && (data_len > 0)) {
- if (error)
- *error = errno;
- return SR_ERROR;
- }
- if (written)
- *written = result;
- return SR_SUCCESS;
-}
-
-void FileStream::Close() {
- if (file_) {
- DoClose();
- file_ = NULL;
- }
-}
-
-bool FileStream::SetPosition(size_t position) {
- if (!file_)
- return false;
- return (fseek(file_, static_cast<int>(position), SEEK_SET) == 0);
-}
-
-bool FileStream::GetPosition(size_t* position) const {
- ASSERT(NULL != position);
- if (!file_)
- return false;
- long result = ftell(file_);
- if (result < 0)
- return false;
- if (position)
- *position = result;
- return true;
-}
-
-bool FileStream::GetSize(size_t* size) const {
- ASSERT(NULL != size);
- if (!file_)
- return false;
- struct stat file_stats;
- if (fstat(fileno(file_), &file_stats) != 0)
- return false;
- if (size)
- *size = file_stats.st_size;
- return true;
-}
-
-bool FileStream::GetAvailable(size_t* size) const {
- ASSERT(NULL != size);
- if (!GetSize(size))
- return false;
- long result = ftell(file_);
- if (result < 0)
- return false;
- if (size)
- *size -= result;
- return true;
-}
-
-bool FileStream::ReserveSize(size_t size) {
- // TODO: extend the file to the proper length
- return true;
-}
-
-bool FileStream::GetSize(const std::string& filename, size_t* size) {
- struct stat file_stats;
- if (stat(filename.c_str(), &file_stats) != 0)
- return false;
- *size = file_stats.st_size;
- return true;
-}
-
-bool FileStream::Flush() {
- if (file_) {
- return (0 == fflush(file_));
- }
- // try to flush empty file?
- ASSERT(false);
- return false;
-}
-
-#if defined(POSIX) && !defined(__native_client__)
-
-bool FileStream::TryLock() {
- if (file_ == NULL) {
- // Stream not open.
- ASSERT(false);
- return false;
- }
-
- return flock(fileno(file_), LOCK_EX|LOCK_NB) == 0;
-}
-
-bool FileStream::Unlock() {
- if (file_ == NULL) {
- // Stream not open.
- ASSERT(false);
- return false;
- }
-
- return flock(fileno(file_), LOCK_UN) == 0;
-}
-
-#endif
-
-void FileStream::DoClose() {
- fclose(file_);
-}
-
-CircularFileStream::CircularFileStream(size_t max_size)
- : max_write_size_(max_size),
- position_(0),
- marked_position_(max_size / 2),
- last_write_position_(0),
- read_segment_(READ_LATEST),
- read_segment_available_(0) {
-}
-
-bool CircularFileStream::Open(
- const std::string& filename, const char* mode, int* error) {
- if (!FileStream::Open(filename.c_str(), mode, error))
- return false;
-
- if (strchr(mode, "r") != NULL) { // Opened in read mode.
- // Check if the buffer has been overwritten and determine how to read the
- // log in time sequence.
- size_t file_size;
- GetSize(&file_size);
- if (file_size == position_) {
- // The buffer has not been overwritten yet. Read 0 .. file_size
- read_segment_ = READ_LATEST;
- read_segment_available_ = file_size;
- } else {
- // The buffer has been over written. There are three segments: The first
- // one is 0 .. marked_position_, which is the marked earliest log. The
- // second one is position_ .. file_size, which is the middle log. The
- // last one is marked_position_ .. position_, which is the latest log.
- read_segment_ = READ_MARKED;
- read_segment_available_ = marked_position_;
- last_write_position_ = position_;
- }
-
- // Read from the beginning.
- position_ = 0;
- SetPosition(position_);
- }
-
- return true;
-}
-
-StreamResult CircularFileStream::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- if (read_segment_available_ == 0) {
- size_t file_size;
- switch (read_segment_) {
- case READ_MARKED: // Finished READ_MARKED and start READ_MIDDLE.
- read_segment_ = READ_MIDDLE;
- position_ = last_write_position_;
- SetPosition(position_);
- GetSize(&file_size);
- read_segment_available_ = file_size - position_;
- break;
-
- case READ_MIDDLE: // Finished READ_MIDDLE and start READ_LATEST.
- read_segment_ = READ_LATEST;
- position_ = marked_position_;
- SetPosition(position_);
- read_segment_available_ = last_write_position_ - position_;
- break;
-
- default: // Finished READ_LATEST and return EOS.
- return talk_base::SR_EOS;
- }
- }
-
- size_t local_read;
- if (!read) read = &local_read;
-
- size_t to_read = talk_base::_min(buffer_len, read_segment_available_);
- talk_base::StreamResult result
- = talk_base::FileStream::Read(buffer, to_read, read, error);
- if (result == talk_base::SR_SUCCESS) {
- read_segment_available_ -= *read;
- position_ += *read;
- }
- return result;
-}
-
-StreamResult CircularFileStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (position_ >= max_write_size_) {
- ASSERT(position_ == max_write_size_);
- position_ = marked_position_;
- SetPosition(position_);
- }
-
- size_t local_written;
- if (!written) written = &local_written;
-
- size_t to_eof = max_write_size_ - position_;
- size_t to_write = talk_base::_min(data_len, to_eof);
- talk_base::StreamResult result
- = talk_base::FileStream::Write(data, to_write, written, error);
- if (result == talk_base::SR_SUCCESS) {
- position_ += *written;
- }
- return result;
-}
-
-AsyncWriteStream::~AsyncWriteStream() {
- write_thread_->Clear(this, 0, NULL);
- ClearBufferAndWrite();
-
- CritScope cs(&crit_stream_);
- stream_.reset();
-}
-
-// This is needed by some stream writers, such as RtpDumpWriter.
-bool AsyncWriteStream::GetPosition(size_t* position) const {
- CritScope cs(&crit_stream_);
- return stream_->GetPosition(position);
-}
-
-// This is needed by some stream writers, such as the plugin log writers.
-StreamResult AsyncWriteStream::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- CritScope cs(&crit_stream_);
- return stream_->Read(buffer, buffer_len, read, error);
-}
-
-void AsyncWriteStream::Close() {
- if (state_ == SS_CLOSED) {
- return;
- }
-
- write_thread_->Clear(this, 0, NULL);
- ClearBufferAndWrite();
-
- CritScope cs(&crit_stream_);
- stream_->Close();
- state_ = SS_CLOSED;
-}
-
-StreamResult AsyncWriteStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (state_ == SS_CLOSED) {
- return SR_ERROR;
- }
-
- size_t previous_buffer_length = 0;
- {
- CritScope cs(&crit_buffer_);
- previous_buffer_length = buffer_.length();
- buffer_.AppendData(data, data_len);
- }
-
- if (previous_buffer_length == 0) {
- // If there's stuff already in the buffer, then we already called
- // Post and the write_thread_ hasn't pulled it out yet, so we
- // don't need to re-Post.
- write_thread_->Post(this, 0, NULL);
- }
- // Return immediately, assuming that it works.
- if (written) {
- *written = data_len;
- }
- return SR_SUCCESS;
-}
-
-void AsyncWriteStream::OnMessage(talk_base::Message* pmsg) {
- ClearBufferAndWrite();
-}
-
-bool AsyncWriteStream::Flush() {
- if (state_ == SS_CLOSED) {
- return false;
- }
-
- ClearBufferAndWrite();
-
- CritScope cs(&crit_stream_);
- return stream_->Flush();
-}
-
-void AsyncWriteStream::ClearBufferAndWrite() {
- Buffer to_write;
- {
- CritScope cs_buffer(&crit_buffer_);
- buffer_.TransferTo(&to_write);
- }
-
- if (to_write.length() > 0) {
- CritScope cs(&crit_stream_);
- stream_->WriteAll(to_write.data(), to_write.length(), NULL, NULL);
- }
-}
-
-#if defined(POSIX) && !defined(__native_client__)
-
-// Have to identically rewrite the FileStream destructor or else it would call
-// the base class's Close() instead of the sub-class's.
-POpenStream::~POpenStream() {
- POpenStream::Close();
-}
-
-bool POpenStream::Open(const std::string& subcommand,
- const char* mode,
- int* error) {
- Close();
- file_ = popen(subcommand.c_str(), mode);
- if (file_ == NULL) {
- if (error)
- *error = errno;
- return false;
- }
- return true;
-}
-
-bool POpenStream::OpenShare(const std::string& subcommand, const char* mode,
- int shflag, int* error) {
- return Open(subcommand, mode, error);
-}
-
-void POpenStream::DoClose() {
- wait_status_ = pclose(file_);
-}
-
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// MemoryStream
-///////////////////////////////////////////////////////////////////////////////
-
-MemoryStreamBase::MemoryStreamBase()
- : buffer_(NULL), buffer_length_(0), data_length_(0),
- seek_position_(0) {
-}
-
-StreamState MemoryStreamBase::GetState() const {
- return SS_OPEN;
-}
-
-StreamResult MemoryStreamBase::Read(void* buffer, size_t bytes,
- size_t* bytes_read, int* error) {
- if (seek_position_ >= data_length_) {
- return SR_EOS;
- }
- size_t available = data_length_ - seek_position_;
- if (bytes > available) {
- // Read partial buffer
- bytes = available;
- }
- memcpy(buffer, &buffer_[seek_position_], bytes);
- seek_position_ += bytes;
- if (bytes_read) {
- *bytes_read = bytes;
- }
- return SR_SUCCESS;
-}
-
-StreamResult MemoryStreamBase::Write(const void* buffer, size_t bytes,
- size_t* bytes_written, int* error) {
- size_t available = buffer_length_ - seek_position_;
- if (0 == available) {
- // Increase buffer size to the larger of:
- // a) new position rounded up to next 256 bytes
- // b) double the previous length
- size_t new_buffer_length = _max(((seek_position_ + bytes) | 0xFF) + 1,
- buffer_length_ * 2);
- StreamResult result = DoReserve(new_buffer_length, error);
- if (SR_SUCCESS != result) {
- return result;
- }
- ASSERT(buffer_length_ >= new_buffer_length);
- available = buffer_length_ - seek_position_;
- }
-
- if (bytes > available) {
- bytes = available;
- }
- memcpy(&buffer_[seek_position_], buffer, bytes);
- seek_position_ += bytes;
- if (data_length_ < seek_position_) {
- data_length_ = seek_position_;
- }
- if (bytes_written) {
- *bytes_written = bytes;
- }
- return SR_SUCCESS;
-}
-
-void MemoryStreamBase::Close() {
- // nothing to do
-}
-
-bool MemoryStreamBase::SetPosition(size_t position) {
- if (position > data_length_)
- return false;
- seek_position_ = position;
- return true;
-}
-
-bool MemoryStreamBase::GetPosition(size_t* position) const {
- if (position)
- *position = seek_position_;
- return true;
-}
-
-bool MemoryStreamBase::GetSize(size_t* size) const {
- if (size)
- *size = data_length_;
- return true;
-}
-
-bool MemoryStreamBase::GetAvailable(size_t* size) const {
- if (size)
- *size = data_length_ - seek_position_;
- return true;
-}
-
-bool MemoryStreamBase::ReserveSize(size_t size) {
- return (SR_SUCCESS == DoReserve(size, NULL));
-}
-
-StreamResult MemoryStreamBase::DoReserve(size_t size, int* error) {
- return (buffer_length_ >= size) ? SR_SUCCESS : SR_EOS;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-MemoryStream::MemoryStream()
- : buffer_alloc_(NULL) {
-}
-
-MemoryStream::MemoryStream(const char* data)
- : buffer_alloc_(NULL) {
- SetData(data, strlen(data));
-}
-
-MemoryStream::MemoryStream(const void* data, size_t length)
- : buffer_alloc_(NULL) {
- SetData(data, length);
-}
-
-MemoryStream::~MemoryStream() {
- delete [] buffer_alloc_;
-}
-
-void MemoryStream::SetData(const void* data, size_t length) {
- data_length_ = buffer_length_ = length;
- delete [] buffer_alloc_;
- buffer_alloc_ = new char[buffer_length_ + kAlignment];
- buffer_ = reinterpret_cast<char*>(ALIGNP(buffer_alloc_, kAlignment));
- memcpy(buffer_, data, data_length_);
- seek_position_ = 0;
-}
-
-StreamResult MemoryStream::DoReserve(size_t size, int* error) {
- if (buffer_length_ >= size)
- return SR_SUCCESS;
-
- if (char* new_buffer_alloc = new char[size + kAlignment]) {
- char* new_buffer = reinterpret_cast<char*>(
- ALIGNP(new_buffer_alloc, kAlignment));
- memcpy(new_buffer, buffer_, data_length_);
- delete [] buffer_alloc_;
- buffer_alloc_ = new_buffer_alloc;
- buffer_ = new_buffer;
- buffer_length_ = size;
- return SR_SUCCESS;
- }
-
- if (error) {
- *error = ENOMEM;
- }
- return SR_ERROR;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-ExternalMemoryStream::ExternalMemoryStream() {
-}
-
-ExternalMemoryStream::ExternalMemoryStream(void* data, size_t length) {
- SetData(data, length);
-}
-
-ExternalMemoryStream::~ExternalMemoryStream() {
-}
-
-void ExternalMemoryStream::SetData(void* data, size_t length) {
- data_length_ = buffer_length_ = length;
- buffer_ = static_cast<char*>(data);
- seek_position_ = 0;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// FifoBuffer
-///////////////////////////////////////////////////////////////////////////////
-
-FifoBuffer::FifoBuffer(size_t size)
- : state_(SS_OPEN), buffer_(new char[size]), buffer_length_(size),
- data_length_(0), read_position_(0), owner_(Thread::Current()) {
- // all events are done on the owner_ thread
-}
-
-FifoBuffer::FifoBuffer(size_t size, Thread* owner)
- : state_(SS_OPEN), buffer_(new char[size]), buffer_length_(size),
- data_length_(0), read_position_(0), owner_(owner) {
- // all events are done on the owner_ thread
-}
-
-FifoBuffer::~FifoBuffer() {
-}
-
-bool FifoBuffer::GetBuffered(size_t* size) const {
- CritScope cs(&crit_);
- *size = data_length_;
- return true;
-}
-
-bool FifoBuffer::SetCapacity(size_t size) {
- CritScope cs(&crit_);
- if (data_length_ > size) {
- return false;
- }
-
- if (size != buffer_length_) {
- char* buffer = new char[size];
- const size_t copy = data_length_;
- const size_t tail_copy = _min(copy, buffer_length_ - read_position_);
- memcpy(buffer, &buffer_[read_position_], tail_copy);
- memcpy(buffer + tail_copy, &buffer_[0], copy - tail_copy);
- buffer_.reset(buffer);
- read_position_ = 0;
- buffer_length_ = size;
- }
- return true;
-}
-
-StreamResult FifoBuffer::ReadOffset(void* buffer, size_t bytes,
- size_t offset, size_t* bytes_read) {
- CritScope cs(&crit_);
- return ReadOffsetLocked(buffer, bytes, offset, bytes_read);
-}
-
-StreamResult FifoBuffer::WriteOffset(const void* buffer, size_t bytes,
- size_t offset, size_t* bytes_written) {
- CritScope cs(&crit_);
- return WriteOffsetLocked(buffer, bytes, offset, bytes_written);
-}
-
-StreamState FifoBuffer::GetState() const {
- return state_;
-}
-
-StreamResult FifoBuffer::Read(void* buffer, size_t bytes,
- size_t* bytes_read, int* error) {
- CritScope cs(&crit_);
- const bool was_writable = data_length_ < buffer_length_;
- size_t copy = 0;
- StreamResult result = ReadOffsetLocked(buffer, bytes, 0, ©);
-
- if (result == SR_SUCCESS) {
- // If read was successful then adjust the read position and number of
- // bytes buffered.
- read_position_ = (read_position_ + copy) % buffer_length_;
- data_length_ -= copy;
- if (bytes_read) {
- *bytes_read = copy;
- }
-
- // if we were full before, and now we're not, post an event
- if (!was_writable && copy > 0) {
- PostEvent(owner_, SE_WRITE, 0);
- }
- }
- return result;
-}
-
-StreamResult FifoBuffer::Write(const void* buffer, size_t bytes,
- size_t* bytes_written, int* error) {
- CritScope cs(&crit_);
-
- const bool was_readable = (data_length_ > 0);
- size_t copy = 0;
- StreamResult result = WriteOffsetLocked(buffer, bytes, 0, ©);
-
- if (result == SR_SUCCESS) {
- // If write was successful then adjust the number of readable bytes.
- data_length_ += copy;
- if (bytes_written) {
- *bytes_written = copy;
- }
-
- // if we didn't have any data to read before, and now we do, post an event
- if (!was_readable && copy > 0) {
- PostEvent(owner_, SE_READ, 0);
- }
- }
- return result;
-}
-
-void FifoBuffer::Close() {
- CritScope cs(&crit_);
- state_ = SS_CLOSED;
-}
-
-const void* FifoBuffer::GetReadData(size_t* size) {
- CritScope cs(&crit_);
- *size = (read_position_ + data_length_ <= buffer_length_) ?
- data_length_ : buffer_length_ - read_position_;
- return &buffer_[read_position_];
-}
-
-void FifoBuffer::ConsumeReadData(size_t size) {
- CritScope cs(&crit_);
- ASSERT(size <= data_length_);
- const bool was_writable = data_length_ < buffer_length_;
- read_position_ = (read_position_ + size) % buffer_length_;
- data_length_ -= size;
- if (!was_writable && size > 0) {
- PostEvent(owner_, SE_WRITE, 0);
- }
-}
-
-void* FifoBuffer::GetWriteBuffer(size_t* size) {
- CritScope cs(&crit_);
- if (state_ == SS_CLOSED) {
- return NULL;
- }
-
- // if empty, reset the write position to the beginning, so we can get
- // the biggest possible block
- if (data_length_ == 0) {
- read_position_ = 0;
- }
-
- const size_t write_position = (read_position_ + data_length_)
- % buffer_length_;
- *size = (write_position > read_position_ || data_length_ == 0) ?
- buffer_length_ - write_position : read_position_ - write_position;
- return &buffer_[write_position];
-}
-
-void FifoBuffer::ConsumeWriteBuffer(size_t size) {
- CritScope cs(&crit_);
- ASSERT(size <= buffer_length_ - data_length_);
- const bool was_readable = (data_length_ > 0);
- data_length_ += size;
- if (!was_readable && size > 0) {
- PostEvent(owner_, SE_READ, 0);
- }
-}
-
-bool FifoBuffer::GetWriteRemaining(size_t* size) const {
- CritScope cs(&crit_);
- *size = buffer_length_ - data_length_;
- return true;
-}
-
-StreamResult FifoBuffer::ReadOffsetLocked(void* buffer,
- size_t bytes,
- size_t offset,
- size_t* bytes_read) {
- if (offset >= data_length_) {
- return (state_ != SS_CLOSED) ? SR_BLOCK : SR_EOS;
- }
-
- const size_t available = data_length_ - offset;
- const size_t read_position = (read_position_ + offset) % buffer_length_;
- const size_t copy = _min(bytes, available);
- const size_t tail_copy = _min(copy, buffer_length_ - read_position);
- char* const p = static_cast<char*>(buffer);
- memcpy(p, &buffer_[read_position], tail_copy);
- memcpy(p + tail_copy, &buffer_[0], copy - tail_copy);
-
- if (bytes_read) {
- *bytes_read = copy;
- }
- return SR_SUCCESS;
-}
-
-StreamResult FifoBuffer::WriteOffsetLocked(const void* buffer,
- size_t bytes,
- size_t offset,
- size_t* bytes_written) {
- if (state_ == SS_CLOSED) {
- return SR_EOS;
- }
-
- if (data_length_ + offset >= buffer_length_) {
- return SR_BLOCK;
- }
-
- const size_t available = buffer_length_ - data_length_ - offset;
- const size_t write_position = (read_position_ + data_length_ + offset)
- % buffer_length_;
- const size_t copy = _min(bytes, available);
- const size_t tail_copy = _min(copy, buffer_length_ - write_position);
- const char* const p = static_cast<const char*>(buffer);
- memcpy(&buffer_[write_position], p, tail_copy);
- memcpy(&buffer_[0], p + tail_copy, copy - tail_copy);
-
- if (bytes_written) {
- *bytes_written = copy;
- }
- return SR_SUCCESS;
-}
-
-
-
-///////////////////////////////////////////////////////////////////////////////
-// LoggingAdapter
-///////////////////////////////////////////////////////////////////////////////
-
-LoggingAdapter::LoggingAdapter(StreamInterface* stream, LoggingSeverity level,
- const std::string& label, bool hex_mode)
- : StreamAdapterInterface(stream), level_(level), hex_mode_(hex_mode) {
- set_label(label);
-}
-
-void LoggingAdapter::set_label(const std::string& label) {
- label_.assign("[");
- label_.append(label);
- label_.append("]");
-}
-
-StreamResult LoggingAdapter::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- size_t local_read; if (!read) read = &local_read;
- StreamResult result = StreamAdapterInterface::Read(buffer, buffer_len, read,
- error);
- if (result == SR_SUCCESS) {
- LogMultiline(level_, label_.c_str(), true, buffer, *read, hex_mode_, &lms_);
- }
- return result;
-}
-
-StreamResult LoggingAdapter::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- size_t local_written;
- if (!written) written = &local_written;
- StreamResult result = StreamAdapterInterface::Write(data, data_len, written,
- error);
- if (result == SR_SUCCESS) {
- LogMultiline(level_, label_.c_str(), false, data, *written, hex_mode_,
- &lms_);
- }
- return result;
-}
-
-void LoggingAdapter::Close() {
- LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
- LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
- LOG_V(level_) << label_ << " Closed locally";
- StreamAdapterInterface::Close();
-}
-
-void LoggingAdapter::OnEvent(StreamInterface* stream, int events, int err) {
- if (events & SE_OPEN) {
- LOG_V(level_) << label_ << " Open";
- } else if (events & SE_CLOSE) {
- LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
- LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
- LOG_V(level_) << label_ << " Closed with error: " << err;
- }
- StreamAdapterInterface::OnEvent(stream, events, err);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// StringStream - Reads/Writes to an external std::string
-///////////////////////////////////////////////////////////////////////////////
-
-StringStream::StringStream(std::string& str)
- : str_(str), read_pos_(0), read_only_(false) {
-}
-
-StringStream::StringStream(const std::string& str)
- : str_(const_cast<std::string&>(str)), read_pos_(0), read_only_(true) {
-}
-
-StreamState StringStream::GetState() const {
- return SS_OPEN;
-}
-
-StreamResult StringStream::Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- size_t available = _min(buffer_len, str_.size() - read_pos_);
- if (!available)
- return SR_EOS;
- memcpy(buffer, str_.data() + read_pos_, available);
- read_pos_ += available;
- if (read)
- *read = available;
- return SR_SUCCESS;
-}
-
-StreamResult StringStream::Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (read_only_) {
- if (error) {
- *error = -1;
- }
- return SR_ERROR;
- }
- str_.append(static_cast<const char*>(data),
- static_cast<const char*>(data) + data_len);
- if (written)
- *written = data_len;
- return SR_SUCCESS;
-}
-
-void StringStream::Close() {
-}
-
-bool StringStream::SetPosition(size_t position) {
- if (position > str_.size())
- return false;
- read_pos_ = position;
- return true;
-}
-
-bool StringStream::GetPosition(size_t* position) const {
- if (position)
- *position = read_pos_;
- return true;
-}
-
-bool StringStream::GetSize(size_t* size) const {
- if (size)
- *size = str_.size();
- return true;
-}
-
-bool StringStream::GetAvailable(size_t* size) const {
- if (size)
- *size = str_.size() - read_pos_;
- return true;
-}
-
-bool StringStream::ReserveSize(size_t size) {
- if (read_only_)
- return false;
- str_.reserve(size);
- return true;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamReference
-///////////////////////////////////////////////////////////////////////////////
-
-StreamReference::StreamReference(StreamInterface* stream)
- : StreamAdapterInterface(stream, false) {
- // owner set to false so the destructor does not free the stream.
- stream_ref_count_ = new StreamRefCount(stream);
-}
-
-StreamInterface* StreamReference::NewReference() {
- stream_ref_count_->AddReference();
- return new StreamReference(stream_ref_count_, stream());
-}
-
-StreamReference::~StreamReference() {
- stream_ref_count_->Release();
-}
-
-StreamReference::StreamReference(StreamRefCount* stream_ref_count,
- StreamInterface* stream)
- : StreamAdapterInterface(stream, false),
- stream_ref_count_(stream_ref_count) {
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-StreamResult Flow(StreamInterface* source,
- char* buffer, size_t buffer_len,
- StreamInterface* sink,
- size_t* data_len /* = NULL */) {
- ASSERT(buffer_len > 0);
-
- StreamResult result;
- size_t count, read_pos, write_pos;
- if (data_len) {
- read_pos = *data_len;
- } else {
- read_pos = 0;
- }
-
- bool end_of_stream = false;
- do {
- // Read until buffer is full, end of stream, or error
- while (!end_of_stream && (read_pos < buffer_len)) {
- result = source->Read(buffer + read_pos, buffer_len - read_pos,
- &count, NULL);
- if (result == SR_EOS) {
- end_of_stream = true;
- } else if (result != SR_SUCCESS) {
- if (data_len) {
- *data_len = read_pos;
- }
- return result;
- } else {
- read_pos += count;
- }
- }
-
- // Write until buffer is empty, or error (including end of stream)
- write_pos = 0;
- while (write_pos < read_pos) {
- result = sink->Write(buffer + write_pos, read_pos - write_pos,
- &count, NULL);
- if (result != SR_SUCCESS) {
- if (data_len) {
- *data_len = read_pos - write_pos;
- if (write_pos > 0) {
- memmove(buffer, buffer + write_pos, *data_len);
- }
- }
- return result;
- }
- write_pos += count;
- }
-
- read_pos = 0;
- } while (!end_of_stream);
-
- if (data_len) {
- *data_len = 0;
- }
- return SR_SUCCESS;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/stream.h b/base/stream.h
deleted file mode 100644
index fceb4a8..0000000
--- a/base/stream.h
+++ /dev/null
@@ -1,837 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_STREAM_H_
-#define TALK_BASE_STREAM_H_
-
-#include <stdio.h>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/buffer.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamInterface is a generic asynchronous stream interface, supporting read,
-// write, and close operations, and asynchronous signalling of state changes.
-// The interface is designed with file, memory, and socket implementations in
-// mind. Some implementations offer extended operations, such as seeking.
-///////////////////////////////////////////////////////////////////////////////
-
-// The following enumerations are declared outside of the StreamInterface
-// class for brevity in use.
-
-// The SS_OPENING state indicates that the stream will signal open or closed
-// in the future.
-enum StreamState { SS_CLOSED, SS_OPENING, SS_OPEN };
-
-// Stream read/write methods return this value to indicate various success
-// and failure conditions described below.
-enum StreamResult { SR_ERROR, SR_SUCCESS, SR_BLOCK, SR_EOS };
-
-// StreamEvents are used to asynchronously signal state transitionss. The flags
-// may be combined.
-// SE_OPEN: The stream has transitioned to the SS_OPEN state
-// SE_CLOSE: The stream has transitioned to the SS_CLOSED state
-// SE_READ: Data is available, so Read is likely to not return SR_BLOCK
-// SE_WRITE: Data can be written, so Write is likely to not return SR_BLOCK
-enum StreamEvent { SE_OPEN = 1, SE_READ = 2, SE_WRITE = 4, SE_CLOSE = 8 };
-
-class Thread;
-
-struct StreamEventData : public MessageData {
- int events, error;
- StreamEventData(int ev, int er) : events(ev), error(er) { }
-};
-
-class StreamInterface : public MessageHandler {
- public:
- enum {
- MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT
- };
-
- virtual ~StreamInterface();
-
- virtual StreamState GetState() const = 0;
-
- // Read attempts to fill buffer of size buffer_len. Write attempts to send
- // data_len bytes stored in data. The variables read and write are set only
- // on SR_SUCCESS (see below). Likewise, error is only set on SR_ERROR.
- // Read and Write return a value indicating:
- // SR_ERROR: an error occurred, which is returned in a non-null error
- // argument. Interpretation of the error requires knowledge of the
- // stream's concrete type, which limits its usefulness.
- // SR_SUCCESS: some number of bytes were successfully written, which is
- // returned in a non-null read/write argument.
- // SR_BLOCK: the stream is in non-blocking mode, and the operation would
- // block, or the stream is in SS_OPENING state.
- // SR_EOS: the end-of-stream has been reached, or the stream is in the
- // SS_CLOSED state.
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) = 0;
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error) = 0;
- // Attempt to transition to the SS_CLOSED state. SE_CLOSE will not be
- // signalled as a result of this call.
- virtual void Close() = 0;
-
- // Streams may signal one or more StreamEvents to indicate state changes.
- // The first argument identifies the stream on which the state change occured.
- // The second argument is a bit-wise combination of StreamEvents.
- // If SE_CLOSE is signalled, then the third argument is the associated error
- // code. Otherwise, the value is undefined.
- // Note: Not all streams will support asynchronous event signalling. However,
- // SS_OPENING and SR_BLOCK returned from stream member functions imply that
- // certain events will be raised in the future.
- sigslot::signal3<StreamInterface*, int, int> SignalEvent;
-
- // Like calling SignalEvent, but posts a message to the specified thread,
- // which will call SignalEvent. This helps unroll the stack and prevent
- // re-entrancy.
- void PostEvent(Thread* t, int events, int err);
- // Like the aforementioned method, but posts to the current thread.
- void PostEvent(int events, int err);
-
- //
- // OPTIONAL OPERATIONS
- //
- // Not all implementations will support the following operations. In general,
- // a stream will only support an operation if it reasonably efficient to do
- // so. For example, while a socket could buffer incoming data to support
- // seeking, it will not do so. Instead, a buffering stream adapter should
- // be used.
- //
- // Even though several of these operations are related, you should
- // always use whichever operation is most relevant. For example, you may
- // be tempted to use GetSize() and GetPosition() to deduce the result of
- // GetAvailable(). However, a stream which is read-once may support the
- // latter operation but not the former.
- //
-
- // The following four methods are used to avoid copying data multiple times.
-
- // GetReadData returns a pointer to a buffer which is owned by the stream.
- // The buffer contains data_len bytes. NULL is returned if no data is
- // available, or if the method fails. If the caller processes the data, it
- // must call ConsumeReadData with the number of processed bytes. GetReadData
- // does not require a matching call to ConsumeReadData if the data is not
- // processed. Read and ConsumeReadData invalidate the buffer returned by
- // GetReadData.
- virtual const void* GetReadData(size_t* data_len) { return NULL; }
- virtual void ConsumeReadData(size_t used) {}
-
- // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
- // The buffer has a capacity of buf_len bytes. NULL is returned if there is
- // no buffer available, or if the method fails. The call may write data to
- // the buffer, and then call ConsumeWriteBuffer with the number of bytes
- // written. GetWriteBuffer does not require a matching call to
- // ConsumeWriteData if no data is written. Write, ForceWrite, and
- // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
- // TODO: Allow the caller to specify a minimum buffer size. If the specified
- // amount of buffer is not yet available, return NULL and Signal SE_WRITE
- // when it is available. If the requested amount is too large, return an
- // error.
- virtual void* GetWriteBuffer(size_t* buf_len) { return NULL; }
- virtual void ConsumeWriteBuffer(size_t used) {}
-
- // Write data_len bytes found in data, circumventing any throttling which
- // would could cause SR_BLOCK to be returned. Returns true if all the data
- // was written. Otherwise, the method is unsupported, or an unrecoverable
- // error occurred, and the error value is set. This method should be used
- // sparingly to write critical data which should not be throttled. A stream
- // which cannot circumvent its blocking constraints should not implement this
- // method.
- // NOTE: This interface is being considered experimentally at the moment. It
- // would be used by JUDP and BandwidthStream as a way to circumvent certain
- // soft limits in writing.
- //virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
- // if (error) *error = -1;
- // return false;
- //}
-
- // Seek to a byte offset from the beginning of the stream. Returns false if
- // the stream does not support seeking, or cannot seek to the specified
- // position.
- virtual bool SetPosition(size_t position) { return false; }
-
- // Get the byte offset of the current position from the start of the stream.
- // Returns false if the position is not known.
- virtual bool GetPosition(size_t* position) const { return false; }
-
- // Get the byte length of the entire stream. Returns false if the length
- // is not known.
- virtual bool GetSize(size_t* size) const { return false; }
-
- // Return the number of Read()-able bytes remaining before end-of-stream.
- // Returns false if not known.
- virtual bool GetAvailable(size_t* size) const { return false; }
-
- // Return the number of Write()-able bytes remaining before end-of-stream.
- // Returns false if not known.
- virtual bool GetWriteRemaining(size_t* size) const { return false; }
-
- // Return true if flush is successful.
- virtual bool Flush() { return false; }
-
- // Communicates the amount of data which will be written to the stream. The
- // stream may choose to preallocate memory to accomodate this data. The
- // stream may return false to indicate that there is not enough room (ie,
- // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
- // function should not affect the existing state of data in the stream.
- virtual bool ReserveSize(size_t size) { return true; }
-
- //
- // CONVENIENCE METHODS
- //
- // These methods are implemented in terms of other methods, for convenience.
- //
-
- // Seek to the start of the stream.
- inline bool Rewind() { return SetPosition(0); }
-
- // WriteAll is a helper function which repeatedly calls Write until all the
- // data is written, or something other than SR_SUCCESS is returned. Note that
- // unlike Write, the argument 'written' is always set, and may be non-zero
- // on results other than SR_SUCCESS. The remaining arguments have the
- // same semantics as Write.
- StreamResult WriteAll(const void* data, size_t data_len,
- size_t* written, int* error);
-
- // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
- // until a non-SR_SUCCESS result is returned. 'read' is always set.
- StreamResult ReadAll(void* buffer, size_t buffer_len,
- size_t* read, int* error);
-
- // ReadLine is a helper function which repeatedly calls Read until it hits
- // the end-of-line character, or something other than SR_SUCCESS.
- // TODO: this is too inefficient to keep here. Break this out into a buffered
- // readline object or adapter
- StreamResult ReadLine(std::string* line);
-
- protected:
- StreamInterface();
-
- // MessageHandler Interface
- virtual void OnMessage(Message* msg);
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(StreamInterface);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamAdapterInterface is a convenient base-class for adapting a stream.
-// By default, all operations are pass-through. Override the methods that you
-// require adaptation. Streams should really be upgraded to reference-counted.
-// In the meantime, use the owned flag to indicate whether the adapter should
-// own the adapted stream.
-///////////////////////////////////////////////////////////////////////////////
-
-class StreamAdapterInterface : public StreamInterface,
- public sigslot::has_slots<> {
- public:
- explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
-
- // Core Stream Interface
- virtual StreamState GetState() const {
- return stream_->GetState();
- }
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- return stream_->Read(buffer, buffer_len, read, error);
- }
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- return stream_->Write(data, data_len, written, error);
- }
- virtual void Close() {
- stream_->Close();
- }
-
- // Optional Stream Interface
- /* Note: Many stream adapters were implemented prior to this Read/Write
- interface. Therefore, a simple pass through of data in those cases may
- be broken. At a later time, we should do a once-over pass of all
- adapters, and make them compliant with these interfaces, after which this
- code can be uncommented.
- virtual const void* GetReadData(size_t* data_len) {
- return stream_->GetReadData(data_len);
- }
- virtual void ConsumeReadData(size_t used) {
- stream_->ConsumeReadData(used);
- }
-
- virtual void* GetWriteBuffer(size_t* buf_len) {
- return stream_->GetWriteBuffer(buf_len);
- }
- virtual void ConsumeWriteBuffer(size_t used) {
- stream_->ConsumeWriteBuffer(used);
- }
- */
-
- /* Note: This interface is currently undergoing evaluation.
- virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
- return stream_->ForceWrite(data, data_len, error);
- }
- */
-
- virtual bool SetPosition(size_t position) {
- return stream_->SetPosition(position);
- }
- virtual bool GetPosition(size_t* position) const {
- return stream_->GetPosition(position);
- }
- virtual bool GetSize(size_t* size) const {
- return stream_->GetSize(size);
- }
- virtual bool GetAvailable(size_t* size) const {
- return stream_->GetAvailable(size);
- }
- virtual bool GetWriteRemaining(size_t* size) const {
- return stream_->GetWriteRemaining(size);
- }
- virtual bool ReserveSize(size_t size) {
- return stream_->ReserveSize(size);
- }
- virtual bool Flush() {
- return stream_->Flush();
- }
-
- void Attach(StreamInterface* stream, bool owned = true);
- StreamInterface* Detach();
-
- protected:
- virtual ~StreamAdapterInterface();
-
- // Note that the adapter presents itself as the origin of the stream events,
- // since users of the adapter may not recognize the adapted object.
- virtual void OnEvent(StreamInterface* stream, int events, int err) {
- SignalEvent(this, events, err);
- }
- StreamInterface* stream() { return stream_; }
-
- private:
- StreamInterface* stream_;
- bool owned_;
- DISALLOW_EVIL_CONSTRUCTORS(StreamAdapterInterface);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamTap is a non-modifying, pass-through adapter, which copies all data
-// in either direction to the tap. Note that errors or blocking on writing to
-// the tap will prevent further tap writes from occurring.
-///////////////////////////////////////////////////////////////////////////////
-
-class StreamTap : public StreamAdapterInterface {
- public:
- explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
-
- void AttachTap(StreamInterface* tap);
- StreamInterface* DetachTap();
- StreamResult GetTapResult(int* error);
-
- // StreamAdapterInterface Interface
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
-
- private:
- scoped_ptr<StreamInterface> tap_;
- StreamResult tap_result_;
- int tap_error_;
- DISALLOW_EVIL_CONSTRUCTORS(StreamTap);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamSegment adapts a read stream, to expose a subset of the adapted
-// stream's data. This is useful for cases where a stream contains multiple
-// documents concatenated together. StreamSegment can expose a subset of
-// the data as an independent stream, including support for rewinding and
-// seeking.
-///////////////////////////////////////////////////////////////////////////////
-
-class StreamSegment : public StreamAdapterInterface {
- public:
- // The current position of the adapted stream becomes the beginning of the
- // segment. If a length is specified, it bounds the length of the segment.
- explicit StreamSegment(StreamInterface* stream);
- explicit StreamSegment(StreamInterface* stream, size_t length);
-
- // StreamAdapterInterface Interface
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual bool SetPosition(size_t position);
- virtual bool GetPosition(size_t* position) const;
- virtual bool GetSize(size_t* size) const;
- virtual bool GetAvailable(size_t* size) const;
-
- private:
- size_t start_, pos_, length_;
- DISALLOW_EVIL_CONSTRUCTORS(StreamSegment);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// NullStream gives errors on read, and silently discards all written data.
-///////////////////////////////////////////////////////////////////////////////
-
-class NullStream : public StreamInterface {
- public:
- NullStream();
- virtual ~NullStream();
-
- // StreamInterface Interface
- virtual StreamState GetState() const;
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- virtual void Close();
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// FileStream is a simple implementation of a StreamInterface, which does not
-// support asynchronous notification.
-///////////////////////////////////////////////////////////////////////////////
-
-class FileStream : public StreamInterface {
- public:
- FileStream();
- virtual ~FileStream();
-
- // The semantics of filename and mode are the same as stdio's fopen
- virtual bool Open(const std::string& filename, const char* mode, int* error);
- virtual bool OpenShare(const std::string& filename, const char* mode,
- int shflag, int* error);
-
- // By default, reads and writes are buffered for efficiency. Disabling
- // buffering causes writes to block until the bytes on disk are updated.
- virtual bool DisableBuffering();
-
- virtual StreamState GetState() const;
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- virtual void Close();
- virtual bool SetPosition(size_t position);
- virtual bool GetPosition(size_t* position) const;
- virtual bool GetSize(size_t* size) const;
- virtual bool GetAvailable(size_t* size) const;
- virtual bool ReserveSize(size_t size);
-
- virtual bool Flush();
-
-#if defined(POSIX) && !defined(__native_client__)
- // Tries to aquire an exclusive lock on the file.
- // Use OpenShare(...) on win32 to get similar functionality.
- bool TryLock();
- bool Unlock();
-#endif
-
- // Note: Deprecated in favor of Filesystem::GetFileSize().
- static bool GetSize(const std::string& filename, size_t* size);
-
- protected:
- virtual void DoClose();
-
- FILE* file_;
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(FileStream);
-};
-
-// A stream that caps the output at a certain size, dropping content from the
-// middle of the logical stream and maintaining equal parts of the start/end of
-// the logical stream.
-class CircularFileStream : public FileStream {
- public:
- explicit CircularFileStream(size_t max_size);
-
- virtual bool Open(const std::string& filename, const char* mode, int* error);
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
-
- private:
- enum ReadSegment {
- READ_MARKED, // Read 0 .. marked_position_
- READ_MIDDLE, // Read position_ .. file_size
- READ_LATEST, // Read marked_position_ .. position_ if the buffer was
- // overwritten or 0 .. position_ otherwise.
- };
-
- size_t max_write_size_;
- size_t position_;
- size_t marked_position_;
- size_t last_write_position_;
- ReadSegment read_segment_;
- size_t read_segment_available_;
-};
-
-// A stream which pushes writes onto a separate thread and
-// returns from the write call immediately.
-class AsyncWriteStream : public StreamInterface {
- public:
- // Takes ownership of the stream, but not the thread.
- AsyncWriteStream(StreamInterface* stream, talk_base::Thread* write_thread)
- : stream_(stream),
- write_thread_(write_thread),
- state_(stream ? stream->GetState() : SS_CLOSED) {
- }
-
- virtual ~AsyncWriteStream();
-
- // StreamInterface Interface
- virtual StreamState GetState() const { return state_; }
- // This is needed by some stream writers, such as RtpDumpWriter.
- virtual bool GetPosition(size_t* position) const;
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- virtual void Close();
- virtual bool Flush();
-
- protected:
- // From MessageHandler
- virtual void OnMessage(talk_base::Message* pmsg);
- virtual void ClearBufferAndWrite();
-
- private:
- talk_base::scoped_ptr<StreamInterface> stream_;
- Thread* write_thread_;
- StreamState state_;
- Buffer buffer_;
- mutable CriticalSection crit_stream_;
- CriticalSection crit_buffer_;
-
- DISALLOW_EVIL_CONSTRUCTORS(AsyncWriteStream);
-};
-
-
-#if defined(POSIX) && !defined(__native_client__)
-// A FileStream that is actually not a file, but the output or input of a
-// sub-command. See "man 3 popen" for documentation of the underlying OS popen()
-// function.
-class POpenStream : public FileStream {
- public:
- POpenStream() : wait_status_(-1) {}
- virtual ~POpenStream();
-
- virtual bool Open(const std::string& subcommand, const char* mode,
- int* error);
- // Same as Open(). shflag is ignored.
- virtual bool OpenShare(const std::string& subcommand, const char* mode,
- int shflag, int* error);
-
- // Returns the wait status from the last Close() of an Open()'ed stream, or
- // -1 if no Open()+Close() has been done on this object. Meaning of the number
- // is documented in "man 2 wait".
- int GetWaitStatus() const { return wait_status_; }
-
- protected:
- virtual void DoClose();
-
- private:
- int wait_status_;
-};
-#endif // POSIX
-
-///////////////////////////////////////////////////////////////////////////////
-// MemoryStream is a simple implementation of a StreamInterface over in-memory
-// data. Data is read and written at the current seek position. Reads return
-// end-of-stream when they reach the end of data. Writes actually extend the
-// end of data mark.
-///////////////////////////////////////////////////////////////////////////////
-
-class MemoryStreamBase : public StreamInterface {
- public:
- virtual StreamState GetState() const;
- virtual StreamResult Read(void* buffer, size_t bytes, size_t* bytes_read,
- int* error);
- virtual StreamResult Write(const void* buffer, size_t bytes,
- size_t* bytes_written, int* error);
- virtual void Close();
- virtual bool SetPosition(size_t position);
- virtual bool GetPosition(size_t* position) const;
- virtual bool GetSize(size_t* size) const;
- virtual bool GetAvailable(size_t* size) const;
- virtual bool ReserveSize(size_t size);
-
- char* GetBuffer() { return buffer_; }
- const char* GetBuffer() const { return buffer_; }
-
- protected:
- MemoryStreamBase();
-
- virtual StreamResult DoReserve(size_t size, int* error);
-
- // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
- char* buffer_;
- size_t buffer_length_;
- size_t data_length_;
- size_t seek_position_;
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(MemoryStreamBase);
-};
-
-// MemoryStream dynamically resizes to accomodate written data.
-
-class MemoryStream : public MemoryStreamBase {
- public:
- MemoryStream();
- explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
- MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
- virtual ~MemoryStream();
-
- void SetData(const void* data, size_t length);
-
- protected:
- virtual StreamResult DoReserve(size_t size, int* error);
- // Memory Streams are aligned for efficiency.
- static const int kAlignment = 16;
- char* buffer_alloc_;
-};
-
-// ExternalMemoryStream adapts an external memory buffer, so writes which would
-// extend past the end of the buffer will return end-of-stream.
-
-class ExternalMemoryStream : public MemoryStreamBase {
- public:
- ExternalMemoryStream();
- ExternalMemoryStream(void* data, size_t length);
- virtual ~ExternalMemoryStream();
-
- void SetData(void* data, size_t length);
-};
-
-// FifoBuffer allows for efficient, thread-safe buffering of data between
-// writer and reader. As the data can wrap around the end of the buffer,
-// MemoryStreamBase can't help us here.
-
-class FifoBuffer : public StreamInterface {
- public:
- // Creates a FIFO buffer with the specified capacity.
- explicit FifoBuffer(size_t length);
- // Creates a FIFO buffer with the specified capacity and owner
- FifoBuffer(size_t length, Thread* owner);
- virtual ~FifoBuffer();
- // Gets the amount of data currently readable from the buffer.
- bool GetBuffered(size_t* data_len) const;
- // Resizes the buffer to the specified capacity. Fails if data_length_ > size
- bool SetCapacity(size_t length);
-
- // Read into |buffer| with an offset from the current read position, offset
- // is specified in number of bytes.
- // This method doesn't adjust read position nor the number of available
- // bytes, user has to call ConsumeReadData() to do this.
- StreamResult ReadOffset(void* buffer, size_t bytes, size_t offset,
- size_t* bytes_read);
-
- // Write |buffer| with an offset from the current write position, offset is
- // specified in number of bytes.
- // This method doesn't adjust the number of buffered bytes, user has to call
- // ConsumeWriteBuffer() to do this.
- StreamResult WriteOffset(const void* buffer, size_t bytes, size_t offset,
- size_t* bytes_written);
-
- // StreamInterface methods
- virtual StreamState GetState() const;
- virtual StreamResult Read(void* buffer, size_t bytes,
- size_t* bytes_read, int* error);
- virtual StreamResult Write(const void* buffer, size_t bytes,
- size_t* bytes_written, int* error);
- virtual void Close();
- virtual const void* GetReadData(size_t* data_len);
- virtual void ConsumeReadData(size_t used);
- virtual void* GetWriteBuffer(size_t* buf_len);
- virtual void ConsumeWriteBuffer(size_t used);
- virtual bool GetWriteRemaining(size_t* size) const;
-
- private:
- // Helper method that implements ReadOffset. Caller must acquire a lock
- // when calling this method.
- StreamResult ReadOffsetLocked(void* buffer, size_t bytes, size_t offset,
- size_t* bytes_read);
-
- // Helper method that implements WriteOffset. Caller must acquire a lock
- // when calling this method.
- StreamResult WriteOffsetLocked(const void* buffer, size_t bytes,
- size_t offset, size_t* bytes_written);
-
- StreamState state_; // keeps the opened/closed state of the stream
- scoped_ptr<char[]> buffer_; // the allocated buffer
- size_t buffer_length_; // size of the allocated buffer
- size_t data_length_; // amount of readable data in the buffer
- size_t read_position_; // offset to the readable data
- Thread* owner_; // stream callbacks are dispatched on this thread
- mutable CriticalSection crit_; // object lock
- DISALLOW_EVIL_CONSTRUCTORS(FifoBuffer);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-class LoggingAdapter : public StreamAdapterInterface {
- public:
- LoggingAdapter(StreamInterface* stream, LoggingSeverity level,
- const std::string& label, bool hex_mode = false);
-
- void set_label(const std::string& label);
-
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- virtual void Close();
-
- protected:
- virtual void OnEvent(StreamInterface* stream, int events, int err);
-
- private:
- LoggingSeverity level_;
- std::string label_;
- bool hex_mode_;
- LogMultilineState lms_;
-
- DISALLOW_EVIL_CONSTRUCTORS(LoggingAdapter);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StringStream - Reads/Writes to an external std::string
-///////////////////////////////////////////////////////////////////////////////
-
-class StringStream : public StreamInterface {
- public:
- explicit StringStream(std::string& str);
- explicit StringStream(const std::string& str);
-
- virtual StreamState GetState() const;
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error);
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error);
- virtual void Close();
- virtual bool SetPosition(size_t position);
- virtual bool GetPosition(size_t* position) const;
- virtual bool GetSize(size_t* size) const;
- virtual bool GetAvailable(size_t* size) const;
- virtual bool ReserveSize(size_t size);
-
- private:
- std::string& str_;
- size_t read_pos_;
- bool read_only_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamReference - A reference counting stream adapter
-///////////////////////////////////////////////////////////////////////////////
-
-// Keep in mind that the streams and adapters defined in this file are
-// not thread-safe, so this has limited uses.
-
-// A StreamRefCount holds the reference count and a pointer to the
-// wrapped stream. It deletes the wrapped stream when there are no
-// more references. We can then have multiple StreamReference
-// instances pointing to one StreamRefCount, all wrapping the same
-// stream.
-
-class StreamReference : public StreamAdapterInterface {
- class StreamRefCount;
- public:
- // Constructor for the first reference to a stream
- // Note: get more references through NewReference(). Use this
- // constructor only once on a given stream.
- explicit StreamReference(StreamInterface* stream);
- StreamInterface* GetStream() { return stream(); }
- StreamInterface* NewReference();
- virtual ~StreamReference();
-
- private:
- class StreamRefCount {
- public:
- explicit StreamRefCount(StreamInterface* stream)
- : stream_(stream), ref_count_(1) {
- }
- void AddReference() {
- CritScope lock(&cs_);
- ++ref_count_;
- }
- void Release() {
- int ref_count;
- { // Atomic ops would have been a better fit here.
- CritScope lock(&cs_);
- ref_count = --ref_count_;
- }
- if (ref_count == 0) {
- delete stream_;
- delete this;
- }
- }
- private:
- StreamInterface* stream_;
- int ref_count_;
- CriticalSection cs_;
- DISALLOW_EVIL_CONSTRUCTORS(StreamRefCount);
- };
-
- // Constructor for adding references
- explicit StreamReference(StreamRefCount* stream_ref_count,
- StreamInterface* stream);
-
- StreamRefCount* stream_ref_count_;
- DISALLOW_EVIL_CONSTRUCTORS(StreamReference);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Flow attempts to move bytes from source to sink via buffer of size
-// buffer_len. The function returns SR_SUCCESS when source reaches
-// end-of-stream (returns SR_EOS), and all the data has been written successful
-// to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
-// returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
-// with the unexpected StreamResult value.
-// data_len is the length of the valid data in buffer. in case of error
-// this is the data that read from source but can't move to destination.
-// as a pass in parameter, it indicates data in buffer that should move to sink
-StreamResult Flow(StreamInterface* source,
- char* buffer, size_t buffer_len,
- StreamInterface* sink, size_t* data_len = NULL);
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_STREAM_H_
diff --git a/base/stream_unittest.cc b/base/stream_unittest.cc
deleted file mode 100644
index 856c943..0000000
--- a/base/stream_unittest.cc
+++ /dev/null
@@ -1,509 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/stream.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// TestStream
-///////////////////////////////////////////////////////////////////////////////
-
-class TestStream : public StreamInterface {
- public:
- TestStream() : pos_(0) { }
-
- virtual StreamState GetState() const { return SS_OPEN; }
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- unsigned char* uc_buffer = static_cast<unsigned char*>(buffer);
- for (size_t i = 0; i < buffer_len; ++i) {
- uc_buffer[i] = static_cast<unsigned char>(pos_++);
- }
- if (read)
- *read = buffer_len;
- return SR_SUCCESS;
- }
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (error)
- *error = -1;
- return SR_ERROR;
- }
- virtual void Close() { }
- virtual bool SetPosition(size_t position) {
- pos_ = position;
- return true;
- }
- virtual bool GetPosition(size_t* position) const {
- if (position) *position = pos_;
- return true;
- }
- virtual bool GetSize(size_t* size) const {
- return false;
- }
- virtual bool GetAvailable(size_t* size) const {
- return false;
- }
-
- private:
- size_t pos_;
-};
-
-bool VerifyTestBuffer(unsigned char* buffer, size_t len,
- unsigned char value) {
- bool passed = true;
- for (size_t i = 0; i < len; ++i) {
- if (buffer[i] != value++) {
- passed = false;
- break;
- }
- }
- // Ensure that we don't pass again without re-writing
- memset(buffer, 0, len);
- return passed;
-}
-
-void SeekTest(StreamInterface* stream, const unsigned char value) {
- size_t bytes;
- unsigned char buffer[13] = { 0 };
- const size_t kBufSize = sizeof(buffer);
-
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_SUCCESS);
- EXPECT_EQ(bytes, kBufSize);
- EXPECT_TRUE(VerifyTestBuffer(buffer, kBufSize, value));
- EXPECT_TRUE(stream->GetPosition(&bytes));
- EXPECT_EQ(13U, bytes);
-
- EXPECT_TRUE(stream->SetPosition(7));
-
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_SUCCESS);
- EXPECT_EQ(bytes, kBufSize);
- EXPECT_TRUE(VerifyTestBuffer(buffer, kBufSize, value + 7));
- EXPECT_TRUE(stream->GetPosition(&bytes));
- EXPECT_EQ(20U, bytes);
-}
-
-TEST(StreamSegment, TranslatesPosition) {
- TestStream* test = new TestStream;
- // Verify behavior of original stream
- SeekTest(test, 0);
- StreamSegment* segment = new StreamSegment(test);
- // Verify behavior of adapted stream (all values offset by 20)
- SeekTest(segment, 20);
- delete segment;
-}
-
-TEST(StreamSegment, SupportsArtificialTermination) {
- TestStream* test = new TestStream;
-
- size_t bytes;
- unsigned char buffer[5000] = { 0 };
- const size_t kBufSize = sizeof(buffer);
-
- {
- StreamInterface* stream = test;
-
- // Read a lot of bytes
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_SUCCESS);
- EXPECT_EQ(bytes, kBufSize);
- EXPECT_TRUE(VerifyTestBuffer(buffer, kBufSize, 0));
-
- // Test seeking far ahead
- EXPECT_TRUE(stream->SetPosition(12345));
-
- // Read a bunch more bytes
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_SUCCESS);
- EXPECT_EQ(bytes, kBufSize);
- EXPECT_TRUE(VerifyTestBuffer(buffer, kBufSize, 12345 % 256));
- }
-
- // Create a segment of test stream in range [100,600)
- EXPECT_TRUE(test->SetPosition(100));
- StreamSegment* segment = new StreamSegment(test, 500);
-
- {
- StreamInterface* stream = segment;
-
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_SUCCESS);
- EXPECT_EQ(500U, bytes);
- EXPECT_TRUE(VerifyTestBuffer(buffer, 500, 100));
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_EOS);
-
- // Test seeking past "end" of stream
- EXPECT_FALSE(stream->SetPosition(12345));
- EXPECT_FALSE(stream->SetPosition(501));
-
- // Test seeking to end (edge case)
- EXPECT_TRUE(stream->SetPosition(500));
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_EOS);
-
- // Test seeking to start
- EXPECT_TRUE(stream->SetPosition(0));
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_SUCCESS);
- EXPECT_EQ(500U, bytes);
- EXPECT_TRUE(VerifyTestBuffer(buffer, 500, 100));
- EXPECT_EQ(stream->Read(buffer, kBufSize, &bytes, NULL), SR_EOS);
- }
-
- delete segment;
-}
-
-TEST(FifoBufferTest, TestAll) {
- const size_t kSize = 16;
- const char in[kSize * 2 + 1] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
- char out[kSize * 2];
- void* p;
- const void* q;
- size_t bytes;
- FifoBuffer buf(kSize);
- StreamInterface* stream = &buf;
-
- // Test assumptions about base state
- EXPECT_EQ(SS_OPEN, stream->GetState());
- EXPECT_EQ(SR_BLOCK, stream->Read(out, kSize, &bytes, NULL));
- EXPECT_TRUE(NULL != stream->GetReadData(&bytes));
- EXPECT_EQ((size_t)0, bytes);
- stream->ConsumeReadData(0);
- EXPECT_TRUE(NULL != stream->GetWriteBuffer(&bytes));
- EXPECT_EQ(kSize, bytes);
- stream->ConsumeWriteBuffer(0);
-
- // Try a full write
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
-
- // Try a write that should block
- EXPECT_EQ(SR_BLOCK, stream->Write(in, kSize, &bytes, NULL));
-
- // Try a full read
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize));
-
- // Try a read that should block
- EXPECT_EQ(SR_BLOCK, stream->Read(out, kSize, &bytes, NULL));
-
- // Try a too-big write
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize * 2, &bytes, NULL));
- EXPECT_EQ(bytes, kSize);
-
- // Try a too-big read
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize * 2, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize));
-
- // Try some small writes and reads
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize / 2));
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize / 2));
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize / 2));
-
- // Try wraparound reads and writes in the following pattern
- // WWWWWWWWWWWW.... 0123456789AB....
- // RRRRRRRRXXXX.... ........89AB....
- // WWWW....XXXXWWWW 4567....89AB0123
- // XXXX....RRRRXXXX 4567........0123
- // XXXXWWWWWWWWXXXX 4567012345670123
- // RRRRXXXXXXXXRRRR ....01234567....
- // ....RRRRRRRR.... ................
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize * 3 / 4, &bytes, NULL));
- EXPECT_EQ(kSize * 3 / 4, bytes);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize / 2));
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 4, &bytes, NULL));
- EXPECT_EQ(kSize / 4 , bytes);
- EXPECT_EQ(0, memcmp(in + kSize / 2, out, kSize / 4));
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2 , bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize / 2));
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- EXPECT_EQ(kSize / 2 , bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize / 2));
-
- // Use GetWriteBuffer to reset the read_position for the next tests
- stream->GetWriteBuffer(&bytes);
- stream->ConsumeWriteBuffer(0);
-
- // Try using GetReadData to do a full read
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize, &bytes, NULL));
- q = stream->GetReadData(&bytes);
- EXPECT_TRUE(NULL != q);
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(0, memcmp(q, in, kSize));
- stream->ConsumeReadData(kSize);
- EXPECT_EQ(SR_BLOCK, stream->Read(out, kSize, &bytes, NULL));
-
- // Try using GetReadData to do some small reads
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize, &bytes, NULL));
- q = stream->GetReadData(&bytes);
- EXPECT_TRUE(NULL != q);
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(0, memcmp(q, in, kSize / 2));
- stream->ConsumeReadData(kSize / 2);
- q = stream->GetReadData(&bytes);
- EXPECT_TRUE(NULL != q);
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(0, memcmp(q, in + kSize / 2, kSize / 2));
- stream->ConsumeReadData(kSize / 2);
- EXPECT_EQ(SR_BLOCK, stream->Read(out, kSize, &bytes, NULL));
-
- // Try using GetReadData in a wraparound case
- // WWWWWWWWWWWWWWWW 0123456789ABCDEF
- // RRRRRRRRRRRRXXXX ............CDEF
- // WWWWWWWW....XXXX 01234567....CDEF
- // ............RRRR 01234567........
- // RRRRRRRR........ ................
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize, &bytes, NULL));
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize * 3 / 4, &bytes, NULL));
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize / 2, &bytes, NULL));
- q = stream->GetReadData(&bytes);
- EXPECT_TRUE(NULL != q);
- EXPECT_EQ(kSize / 4, bytes);
- EXPECT_EQ(0, memcmp(q, in + kSize * 3 / 4, kSize / 4));
- stream->ConsumeReadData(kSize / 4);
- q = stream->GetReadData(&bytes);
- EXPECT_TRUE(NULL != q);
- EXPECT_EQ(kSize / 2, bytes);
- EXPECT_EQ(0, memcmp(q, in, kSize / 2));
- stream->ConsumeReadData(kSize / 2);
-
- // Use GetWriteBuffer to reset the read_position for the next tests
- stream->GetWriteBuffer(&bytes);
- stream->ConsumeWriteBuffer(0);
-
- // Try using GetWriteBuffer to do a full write
- p = stream->GetWriteBuffer(&bytes);
- EXPECT_TRUE(NULL != p);
- EXPECT_EQ(kSize, bytes);
- memcpy(p, in, kSize);
- stream->ConsumeWriteBuffer(kSize);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize));
-
- // Try using GetWriteBuffer to do some small writes
- p = stream->GetWriteBuffer(&bytes);
- EXPECT_TRUE(NULL != p);
- EXPECT_EQ(kSize, bytes);
- memcpy(p, in, kSize / 2);
- stream->ConsumeWriteBuffer(kSize / 2);
- p = stream->GetWriteBuffer(&bytes);
- EXPECT_TRUE(NULL != p);
- EXPECT_EQ(kSize / 2, bytes);
- memcpy(p, in + kSize / 2, kSize / 2);
- stream->ConsumeWriteBuffer(kSize / 2);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize));
-
- // Try using GetWriteBuffer in a wraparound case
- // WWWWWWWWWWWW.... 0123456789AB....
- // RRRRRRRRXXXX.... ........89AB....
- // ........XXXXWWWW ........89AB0123
- // WWWW....XXXXXXXX 4567....89AB0123
- // RRRR....RRRRRRRR ................
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize * 3 / 4, &bytes, NULL));
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- p = stream->GetWriteBuffer(&bytes);
- EXPECT_TRUE(NULL != p);
- EXPECT_EQ(kSize / 4, bytes);
- memcpy(p, in, kSize / 4);
- stream->ConsumeWriteBuffer(kSize / 4);
- p = stream->GetWriteBuffer(&bytes);
- EXPECT_TRUE(NULL != p);
- EXPECT_EQ(kSize / 2, bytes);
- memcpy(p, in + kSize / 4, kSize / 4);
- stream->ConsumeWriteBuffer(kSize / 4);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize * 3 / 4, &bytes, NULL));
- EXPECT_EQ(kSize * 3 / 4, bytes);
- EXPECT_EQ(0, memcmp(in + kSize / 2, out, kSize / 4));
- EXPECT_EQ(0, memcmp(in, out + kSize / 4, kSize / 4));
-
- // Check that the stream is now empty
- EXPECT_EQ(SR_BLOCK, stream->Read(out, kSize, &bytes, NULL));
-
- // Try growing the buffer
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_TRUE(buf.SetCapacity(kSize * 2));
- EXPECT_EQ(SR_SUCCESS, stream->Write(in + kSize, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize * 2, &bytes, NULL));
- EXPECT_EQ(kSize * 2, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize * 2));
-
- // Try shrinking the buffer
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_TRUE(buf.SetCapacity(kSize));
- EXPECT_EQ(SR_BLOCK, stream->Write(in, kSize, &bytes, NULL));
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize, &bytes, NULL));
- EXPECT_EQ(kSize, bytes);
- EXPECT_EQ(0, memcmp(in, out, kSize));
-
- // Write to the stream, close it, read the remaining bytes
- EXPECT_EQ(SR_SUCCESS, stream->Write(in, kSize / 2, &bytes, NULL));
- stream->Close();
- EXPECT_EQ(SS_CLOSED, stream->GetState());
- EXPECT_EQ(SR_EOS, stream->Write(in, kSize / 2, &bytes, NULL));
- EXPECT_EQ(SR_SUCCESS, stream->Read(out, kSize / 2, &bytes, NULL));
- EXPECT_EQ(0, memcmp(in, out, kSize / 2));
- EXPECT_EQ(SR_EOS, stream->Read(out, kSize / 2, &bytes, NULL));
-}
-
-TEST(FifoBufferTest, FullBufferCheck) {
- FifoBuffer buff(10);
- buff.ConsumeWriteBuffer(10);
-
- size_t free;
- EXPECT_TRUE(buff.GetWriteBuffer(&free) != NULL);
- EXPECT_EQ(0U, free);
-}
-
-TEST(FifoBufferTest, WriteOffsetAndReadOffset) {
- const size_t kSize = 16;
- const char in[kSize * 2 + 1] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
- char out[kSize * 2];
- FifoBuffer buf(kSize);
-
- // Write 14 bytes.
- EXPECT_EQ(SR_SUCCESS, buf.Write(in, 14, NULL, NULL));
-
- // Make sure data is in |buf|.
- size_t buffered;
- EXPECT_TRUE(buf.GetBuffered(&buffered));
- EXPECT_EQ(14u, buffered);
-
- // Read 10 bytes.
- buf.ConsumeReadData(10);
-
- // There should be now 12 bytes of available space.
- size_t remaining;
- EXPECT_TRUE(buf.GetWriteRemaining(&remaining));
- EXPECT_EQ(12u, remaining);
-
- // Write at offset 12, this should fail.
- EXPECT_EQ(SR_BLOCK, buf.WriteOffset(in, 10, 12, NULL));
-
- // Write 8 bytes at offset 4, this wraps around the buffer.
- EXPECT_EQ(SR_SUCCESS, buf.WriteOffset(in, 8, 4, NULL));
-
- // Number of available space remains the same until we call
- // ConsumeWriteBuffer().
- EXPECT_TRUE(buf.GetWriteRemaining(&remaining));
- EXPECT_EQ(12u, remaining);
- buf.ConsumeWriteBuffer(12);
-
- // There's 4 bytes bypassed and 4 bytes no read so skip them and verify the
- // 8 bytes written.
- size_t read;
- EXPECT_EQ(SR_SUCCESS, buf.ReadOffset(out, 8, 8, &read));
- EXPECT_EQ(8u, read);
- EXPECT_EQ(0, memcmp(out, in, 8));
-
- // There should still be 16 bytes available for reading.
- EXPECT_TRUE(buf.GetBuffered(&buffered));
- EXPECT_EQ(16u, buffered);
-
- // Read at offset 16, this should fail since we don't have that much data.
- EXPECT_EQ(SR_BLOCK, buf.ReadOffset(out, 10, 16, NULL));
-}
-
-TEST(AsyncWriteTest, TestWrite) {
- FifoBuffer* buf = new FifoBuffer(100);
- AsyncWriteStream stream(buf, Thread::Current());
- EXPECT_EQ(SS_OPEN, stream.GetState());
-
- // Write "abc". Will go to the logging thread, which is the current
- // thread.
- stream.Write("abc", 3, NULL, NULL);
- char bytes[100];
- size_t count;
- // Messages on the thread's queue haven't been processed, so "abc"
- // hasn't been written yet.
- EXPECT_NE(SR_SUCCESS, buf->ReadOffset(&bytes, 3, 0, &count));
- // Now we process the messages on the thread's queue, so "abc" has
- // been written.
- EXPECT_TRUE_WAIT(SR_SUCCESS == buf->ReadOffset(&bytes, 3, 0, &count), 10);
- EXPECT_EQ(3u, count);
- EXPECT_EQ(0, memcmp(bytes, "abc", 3));
-
- // Write "def". Will go to the logging thread, which is the current
- // thread.
- stream.Write("d", 1, &count, NULL);
- stream.Write("e", 1, &count, NULL);
- stream.Write("f", 1, &count, NULL);
- EXPECT_EQ(1u, count);
- // Messages on the thread's queue haven't been processed, so "def"
- // hasn't been written yet.
- EXPECT_NE(SR_SUCCESS, buf->ReadOffset(&bytes, 3, 3, &count));
- // Flush() causes the message to be processed, so "def" has now been
- // written.
- stream.Flush();
- EXPECT_EQ(SR_SUCCESS, buf->ReadOffset(&bytes, 3, 3, &count));
- EXPECT_EQ(3u, count);
- EXPECT_EQ(0, memcmp(bytes, "def", 3));
-
- // Write "xyz". Will go to the logging thread, which is the current
- // thread.
- stream.Write("xyz", 3, &count, NULL);
- EXPECT_EQ(3u, count);
- // Messages on the thread's queue haven't been processed, so "xyz"
- // hasn't been written yet.
- EXPECT_NE(SR_SUCCESS, buf->ReadOffset(&bytes, 3, 6, &count));
- // Close() causes the message to be processed, so "xyz" has now been
- // written.
- stream.Close();
- EXPECT_EQ(SR_SUCCESS, buf->ReadOffset(&bytes, 3, 6, &count));
- EXPECT_EQ(3u, count);
- EXPECT_EQ(0, memcmp(bytes, "xyz", 3));
- EXPECT_EQ(SS_CLOSED, stream.GetState());
-
- // Is't closed, so the writes should fail.
- EXPECT_EQ(SR_ERROR, stream.Write("000", 3, NULL, NULL));
-
-}
-
-} // namespace talk_base
diff --git a/base/stringdigest.h b/base/stringdigest.h
deleted file mode 100644
index f03e92e..0000000
--- a/base/stringdigest.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_STRINGDIGEST_H_
-#define TALK_BASE_STRINGDIGEST_H_
-
-// TODO: Update remaining callers to use messagedigest.h instead
-#include "talk/base/messagedigest.h"
-
-#endif // TALK_BASE_STRINGDIGEST_H_
diff --git a/base/stringencode.cc b/base/stringencode.cc
deleted file mode 100644
index 4c88a97..0000000
--- a/base/stringencode.cc
+++ /dev/null
@@ -1,674 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/stringencode.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/stringutils.h"
-
-namespace talk_base {
-
-/////////////////////////////////////////////////////////////////////////////
-// String Encoding Utilities
-/////////////////////////////////////////////////////////////////////////////
-
-size_t escape(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- const char * illegal, char escape) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- if (buflen <= 0)
- return 0;
-
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- char ch = source[srcpos++];
- if ((ch == escape) || ::strchr(illegal, ch)) {
- if (bufpos + 2 >= buflen)
- break;
- buffer[bufpos++] = escape;
- }
- buffer[bufpos++] = ch;
- }
-
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-size_t unescape(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- char escape) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- if (buflen <= 0)
- return 0;
-
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- char ch = source[srcpos++];
- if ((ch == escape) && (srcpos < srclen)) {
- ch = source[srcpos++];
- }
- buffer[bufpos++] = ch;
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-size_t encode(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- const char * illegal, char escape) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- if (buflen <= 0)
- return 0;
-
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- char ch = source[srcpos++];
- if ((ch != escape) && !::strchr(illegal, ch)) {
- buffer[bufpos++] = ch;
- } else if (bufpos + 3 >= buflen) {
- break;
- } else {
- buffer[bufpos+0] = escape;
- buffer[bufpos+1] = hex_encode((static_cast<unsigned char>(ch) >> 4) & 0xF);
- buffer[bufpos+2] = hex_encode((static_cast<unsigned char>(ch) ) & 0xF);
- bufpos += 3;
- }
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-size_t decode(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- char escape) {
- if (buflen <= 0)
- return 0;
-
- unsigned char h1, h2;
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- char ch = source[srcpos++];
- if ((ch == escape)
- && (srcpos + 1 < srclen)
- && hex_decode(source[srcpos], &h1)
- && hex_decode(source[srcpos+1], &h2)) {
- buffer[bufpos++] = (h1 << 4) | h2;
- srcpos += 2;
- } else {
- buffer[bufpos++] = ch;
- }
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-const char* unsafe_filename_characters() {
- // It might be better to have a single specification which is the union of
- // all operating systems, unless one system is overly restrictive.
-#ifdef WIN32
- return "\\/:*?\"<>|";
-#else // !WIN32
- // TODO
- ASSERT(false);
- return "";
-#endif // !WIN23
-}
-
-const unsigned char URL_UNSAFE = 0x1; // 0-33 "#$%&+,/:;<=>?@[\]^`{|} 127
-const unsigned char XML_UNSAFE = 0x2; // "&'<>
-const unsigned char HTML_UNSAFE = 0x2; // "&'<>
-
-// ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 6 5 7 8 9 : ; < = > ?
-//@ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _
-//` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
-
-const unsigned char ASCII_CLASS[128] = {
- 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
- 1,0,3,1,1,1,3,2,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,3,1,3,1,
- 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,
- 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,
-};
-
-size_t url_encode(char * buffer, size_t buflen,
- const char * source, size_t srclen) {
- if (NULL == buffer)
- return srclen * 3 + 1;
- if (buflen <= 0)
- return 0;
-
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- unsigned char ch = source[srcpos++];
- if ((ch < 128) && (ASCII_CLASS[ch] & URL_UNSAFE)) {
- if (bufpos + 3 >= buflen) {
- break;
- }
- buffer[bufpos+0] = '%';
- buffer[bufpos+1] = hex_encode((ch >> 4) & 0xF);
- buffer[bufpos+2] = hex_encode((ch ) & 0xF);
- bufpos += 3;
- } else {
- buffer[bufpos++] = ch;
- }
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-size_t url_decode(char * buffer, size_t buflen,
- const char * source, size_t srclen) {
- if (NULL == buffer)
- return srclen + 1;
- if (buflen <= 0)
- return 0;
-
- unsigned char h1, h2;
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- unsigned char ch = source[srcpos++];
- if (ch == '+') {
- buffer[bufpos++] = ' ';
- } else if ((ch == '%')
- && (srcpos + 1 < srclen)
- && hex_decode(source[srcpos], &h1)
- && hex_decode(source[srcpos+1], &h2))
- {
- buffer[bufpos++] = (h1 << 4) | h2;
- srcpos += 2;
- } else {
- buffer[bufpos++] = ch;
- }
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-size_t utf8_decode(const char* source, size_t srclen, unsigned long* value) {
- const unsigned char* s = reinterpret_cast<const unsigned char*>(source);
- if ((s[0] & 0x80) == 0x00) { // Check s[0] == 0xxxxxxx
- *value = s[0];
- return 1;
- }
- if ((srclen < 2) || ((s[1] & 0xC0) != 0x80)) { // Check s[1] != 10xxxxxx
- return 0;
- }
- // Accumulate the trailer byte values in value16, and combine it with the
- // relevant bits from s[0], once we've determined the sequence length.
- unsigned long value16 = (s[1] & 0x3F);
- if ((s[0] & 0xE0) == 0xC0) { // Check s[0] == 110xxxxx
- *value = ((s[0] & 0x1F) << 6) | value16;
- return 2;
- }
- if ((srclen < 3) || ((s[2] & 0xC0) != 0x80)) { // Check s[2] != 10xxxxxx
- return 0;
- }
- value16 = (value16 << 6) | (s[2] & 0x3F);
- if ((s[0] & 0xF0) == 0xE0) { // Check s[0] == 1110xxxx
- *value = ((s[0] & 0x0F) << 12) | value16;
- return 3;
- }
- if ((srclen < 4) || ((s[3] & 0xC0) != 0x80)) { // Check s[3] != 10xxxxxx
- return 0;
- }
- value16 = (value16 << 6) | (s[3] & 0x3F);
- if ((s[0] & 0xF8) == 0xF0) { // Check s[0] == 11110xxx
- *value = ((s[0] & 0x07) << 18) | value16;
- return 4;
- }
- return 0;
-}
-
-size_t utf8_encode(char* buffer, size_t buflen, unsigned long value) {
- if ((value <= 0x7F) && (buflen >= 1)) {
- buffer[0] = static_cast<unsigned char>(value);
- return 1;
- }
- if ((value <= 0x7FF) && (buflen >= 2)) {
- buffer[0] = 0xC0 | static_cast<unsigned char>(value >> 6);
- buffer[1] = 0x80 | static_cast<unsigned char>(value & 0x3F);
- return 2;
- }
- if ((value <= 0xFFFF) && (buflen >= 3)) {
- buffer[0] = 0xE0 | static_cast<unsigned char>(value >> 12);
- buffer[1] = 0x80 | static_cast<unsigned char>((value >> 6) & 0x3F);
- buffer[2] = 0x80 | static_cast<unsigned char>(value & 0x3F);
- return 3;
- }
- if ((value <= 0x1FFFFF) && (buflen >= 4)) {
- buffer[0] = 0xF0 | static_cast<unsigned char>(value >> 18);
- buffer[1] = 0x80 | static_cast<unsigned char>((value >> 12) & 0x3F);
- buffer[2] = 0x80 | static_cast<unsigned char>((value >> 6) & 0x3F);
- buffer[3] = 0x80 | static_cast<unsigned char>(value & 0x3F);
- return 4;
- }
- return 0;
-}
-
-size_t html_encode(char * buffer, size_t buflen,
- const char * source, size_t srclen) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- if (buflen <= 0)
- return 0;
-
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- unsigned char ch = source[srcpos];
- if (ch < 128) {
- srcpos += 1;
- if (ASCII_CLASS[ch] & HTML_UNSAFE) {
- const char * escseq = 0;
- size_t esclen = 0;
- switch (ch) {
- case '<': escseq = "<"; esclen = 4; break;
- case '>': escseq = ">"; esclen = 4; break;
- case '\'': escseq = "'"; esclen = 5; break;
- case '\"': escseq = """; esclen = 6; break;
- case '&': escseq = "&"; esclen = 5; break;
- default: ASSERT(false);
- }
- if (bufpos + esclen >= buflen) {
- break;
- }
- memcpy(buffer + bufpos, escseq, esclen);
- bufpos += esclen;
- } else {
- buffer[bufpos++] = ch;
- }
- } else {
- // Largest value is 0x1FFFFF => � (10 characters)
- char escseq[11];
- unsigned long val;
- if (size_t vallen = utf8_decode(&source[srcpos], srclen - srcpos, &val)) {
- srcpos += vallen;
- } else {
- // Not a valid utf8 sequence, just use the raw character.
- val = static_cast<unsigned char>(source[srcpos++]);
- }
- size_t esclen = sprintfn(escseq, ARRAY_SIZE(escseq), "&#%lu;", val);
- if (bufpos + esclen >= buflen) {
- break;
- }
- memcpy(buffer + bufpos, escseq, esclen);
- bufpos += esclen;
- }
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-size_t html_decode(char * buffer, size_t buflen,
- const char * source, size_t srclen) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- return xml_decode(buffer, buflen, source, srclen);
-}
-
-size_t xml_encode(char * buffer, size_t buflen,
- const char * source, size_t srclen) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- if (buflen <= 0)
- return 0;
-
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- unsigned char ch = source[srcpos++];
- if ((ch < 128) && (ASCII_CLASS[ch] & XML_UNSAFE)) {
- const char * escseq = 0;
- size_t esclen = 0;
- switch (ch) {
- case '<': escseq = "<"; esclen = 4; break;
- case '>': escseq = ">"; esclen = 4; break;
- case '\'': escseq = "'"; esclen = 6; break;
- case '\"': escseq = """; esclen = 6; break;
- case '&': escseq = "&"; esclen = 5; break;
- default: ASSERT(false);
- }
- if (bufpos + esclen >= buflen) {
- break;
- }
- memcpy(buffer + bufpos, escseq, esclen);
- bufpos += esclen;
- } else {
- buffer[bufpos++] = ch;
- }
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-size_t xml_decode(char * buffer, size_t buflen,
- const char * source, size_t srclen) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- if (buflen <= 0)
- return 0;
-
- size_t srcpos = 0, bufpos = 0;
- while ((srcpos < srclen) && (bufpos + 1 < buflen)) {
- unsigned char ch = source[srcpos++];
- if (ch != '&') {
- buffer[bufpos++] = ch;
- } else if ((srcpos + 2 < srclen)
- && (memcmp(source + srcpos, "lt;", 3) == 0)) {
- buffer[bufpos++] = '<';
- srcpos += 3;
- } else if ((srcpos + 2 < srclen)
- && (memcmp(source + srcpos, "gt;", 3) == 0)) {
- buffer[bufpos++] = '>';
- srcpos += 3;
- } else if ((srcpos + 4 < srclen)
- && (memcmp(source + srcpos, "apos;", 5) == 0)) {
- buffer[bufpos++] = '\'';
- srcpos += 5;
- } else if ((srcpos + 4 < srclen)
- && (memcmp(source + srcpos, "quot;", 5) == 0)) {
- buffer[bufpos++] = '\"';
- srcpos += 5;
- } else if ((srcpos + 3 < srclen)
- && (memcmp(source + srcpos, "amp;", 4) == 0)) {
- buffer[bufpos++] = '&';
- srcpos += 4;
- } else if ((srcpos < srclen) && (source[srcpos] == '#')) {
- int int_base = 10;
- if ((srcpos + 1 < srclen) && (source[srcpos+1] == 'x')) {
- int_base = 16;
- srcpos += 1;
- }
- char * ptr;
- // TODO: Fix hack (ptr may go past end of data)
- unsigned long val = strtoul(source + srcpos + 1, &ptr, int_base);
- if ((static_cast<size_t>(ptr - source) < srclen) && (*ptr == ';')) {
- srcpos = ptr - source + 1;
- } else {
- // Not a valid escape sequence.
- break;
- }
- if (size_t esclen = utf8_encode(buffer + bufpos, buflen - bufpos, val)) {
- bufpos += esclen;
- } else {
- // Not enough room to encode the character, or illegal character
- break;
- }
- } else {
- // Unrecognized escape sequence.
- break;
- }
- }
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-static const char HEX[] = "0123456789abcdef";
-
-char hex_encode(unsigned char val) {
- ASSERT(val < 16);
- return (val < 16) ? HEX[val] : '!';
-}
-
-bool hex_decode(char ch, unsigned char* val) {
- if ((ch >= '0') && (ch <= '9')) {
- *val = ch - '0';
- } else if ((ch >= 'A') && (ch <= 'Z')) {
- *val = (ch - 'A') + 10;
- } else if ((ch >= 'a') && (ch <= 'z')) {
- *val = (ch - 'a') + 10;
- } else {
- return false;
- }
- return true;
-}
-
-size_t hex_encode(char* buffer, size_t buflen,
- const char* csource, size_t srclen) {
- return hex_encode_with_delimiter(buffer, buflen, csource, srclen, 0);
-}
-
-size_t hex_encode_with_delimiter(char* buffer, size_t buflen,
- const char* csource, size_t srclen,
- char delimiter) {
- ASSERT(NULL != buffer); // TODO: estimate output size
- if (buflen == 0)
- return 0;
-
- // Init and check bounds.
- const unsigned char* bsource =
- reinterpret_cast<const unsigned char*>(csource);
- size_t srcpos = 0, bufpos = 0;
- size_t needed = delimiter ? (srclen * 3) : (srclen * 2 + 1);
- if (buflen < needed)
- return 0;
-
- while (srcpos < srclen) {
- unsigned char ch = bsource[srcpos++];
- buffer[bufpos ] = hex_encode((ch >> 4) & 0xF);
- buffer[bufpos+1] = hex_encode((ch ) & 0xF);
- bufpos += 2;
-
- // Don't write a delimiter after the last byte.
- if (delimiter && (srcpos < srclen)) {
- buffer[bufpos] = delimiter;
- ++bufpos;
- }
- }
-
- // Null terminate.
- buffer[bufpos] = '\0';
- return bufpos;
-}
-
-std::string hex_encode(const char* source, size_t srclen) {
- return hex_encode_with_delimiter(source, srclen, 0);
-}
-
-std::string hex_encode_with_delimiter(const char* source, size_t srclen,
- char delimiter) {
- const size_t kBufferSize = srclen * 3;
- char* buffer = STACK_ARRAY(char, kBufferSize);
- size_t length = hex_encode_with_delimiter(buffer, kBufferSize,
- source, srclen, delimiter);
- ASSERT(srclen == 0 || length > 0);
- return std::string(buffer, length);
-}
-
-size_t hex_decode(char * cbuffer, size_t buflen,
- const char * source, size_t srclen) {
- return hex_decode_with_delimiter(cbuffer, buflen, source, srclen, 0);
-}
-
-size_t hex_decode_with_delimiter(char* cbuffer, size_t buflen,
- const char* source, size_t srclen,
- char delimiter) {
- ASSERT(NULL != cbuffer); // TODO: estimate output size
- if (buflen == 0)
- return 0;
-
- // Init and bounds check.
- unsigned char* bbuffer = reinterpret_cast<unsigned char*>(cbuffer);
- size_t srcpos = 0, bufpos = 0;
- size_t needed = (delimiter) ? (srclen + 1) / 3 : srclen / 2;
- if (buflen < needed)
- return 0;
-
- while (srcpos < srclen) {
- if ((srclen - srcpos) < 2) {
- // This means we have an odd number of bytes.
- return 0;
- }
-
- unsigned char h1, h2;
- if (!hex_decode(source[srcpos], &h1) ||
- !hex_decode(source[srcpos + 1], &h2))
- return 0;
-
- bbuffer[bufpos++] = (h1 << 4) | h2;
- srcpos += 2;
-
- // Remove the delimiter if needed.
- if (delimiter && (srclen - srcpos) > 1) {
- if (source[srcpos] != delimiter)
- return 0;
- ++srcpos;
- }
- }
-
- return bufpos;
-}
-
-size_t hex_decode(char* buffer, size_t buflen, const std::string& source) {
- return hex_decode_with_delimiter(buffer, buflen, source, 0);
-}
-size_t hex_decode_with_delimiter(char* buffer, size_t buflen,
- const std::string& source, char delimiter) {
- return hex_decode_with_delimiter(buffer, buflen,
- source.c_str(), source.length(), delimiter);
-}
-
-size_t transform(std::string& value, size_t maxlen, const std::string& source,
- Transform t) {
- char* buffer = STACK_ARRAY(char, maxlen + 1);
- size_t length = t(buffer, maxlen + 1, source.data(), source.length());
- value.assign(buffer, length);
- return length;
-}
-
-std::string s_transform(const std::string& source, Transform t) {
- // Ask transformation function to approximate the destination size (returns upper bound)
- size_t maxlen = t(NULL, 0, source.data(), source.length());
- char * buffer = STACK_ARRAY(char, maxlen);
- size_t len = t(buffer, maxlen, source.data(), source.length());
- std::string result(buffer, len);
- return result;
-}
-
-size_t tokenize(const std::string& source, char delimiter,
- std::vector<std::string>* fields) {
- ASSERT(NULL != fields);
- fields->clear();
- size_t last = 0;
- for (size_t i = 0; i < source.length(); ++i) {
- if (source[i] == delimiter) {
- if (i != last) {
- fields->push_back(source.substr(last, i - last));
- }
- last = i + 1;
- }
- }
- if (last != source.length()) {
- fields->push_back(source.substr(last, source.length() - last));
- }
- return fields->size();
-}
-
-size_t tokenize_append(const std::string& source, char delimiter,
- std::vector<std::string>* fields) {
- if (!fields) return 0;
-
- std::vector<std::string> new_fields;
- tokenize(source, delimiter, &new_fields);
- fields->insert(fields->end(), new_fields.begin(), new_fields.end());
- return fields->size();
-}
-
-size_t tokenize(const std::string& source, char delimiter, char start_mark,
- char end_mark, std::vector<std::string>* fields) {
- if (!fields) return 0;
- fields->clear();
-
- std::string remain_source = source;
- while (!remain_source.empty()) {
- size_t start_pos = remain_source.find(start_mark);
- if (std::string::npos == start_pos) break;
- std::string pre_mark;
- if (start_pos > 0) {
- pre_mark = remain_source.substr(0, start_pos - 1);
- }
-
- ++start_pos;
- size_t end_pos = remain_source.find(end_mark, start_pos);
- if (std::string::npos == end_pos) break;
-
- // We have found the matching marks. First tokenize the pre-mask. Then add
- // the marked part as a single field. Finally, loop back for the post-mark.
- tokenize_append(pre_mark, delimiter, fields);
- fields->push_back(remain_source.substr(start_pos, end_pos - start_pos));
- remain_source = remain_source.substr(end_pos + 1);
- }
-
- return tokenize_append(remain_source, delimiter, fields);
-}
-
-size_t split(const std::string& source, char delimiter,
- std::vector<std::string>* fields) {
- ASSERT(NULL != fields);
- fields->clear();
- size_t last = 0;
- for (size_t i = 0; i < source.length(); ++i) {
- if (source[i] == delimiter) {
- fields->push_back(source.substr(last, i - last));
- last = i + 1;
- }
- }
- fields->push_back(source.substr(last, source.length() - last));
- return fields->size();
-}
-
-char make_char_safe_for_filename(char c) {
- if (c < 32)
- return '_';
-
- switch (c) {
- case '<':
- case '>':
- case ':':
- case '"':
- case '/':
- case '\\':
- case '|':
- case '*':
- case '?':
- return '_';
-
- default:
- return c;
- }
-}
-
-/*
-void sprintf(std::string& value, size_t maxlen, const char * format, ...) {
- char * buffer = STACK_ARRAY(char, maxlen + 1);
- va_list args;
- va_start(args, format);
- value.assign(buffer, vsprintfn(buffer, maxlen + 1, format, args));
- va_end(args);
-}
-*/
-
-/////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/stringencode.h b/base/stringencode.h
deleted file mode 100644
index 872dfd4..0000000
--- a/base/stringencode.h
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_STRINGENCODE_H_
-#define TALK_BASE_STRINGENCODE_H_
-
-#include <string>
-#include <sstream>
-#include <vector>
-
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// String Encoding Utilities
-//////////////////////////////////////////////////////////////////////
-
-// Convert an unsigned value to it's utf8 representation. Returns the length
-// of the encoded string, or 0 if the encoding is longer than buflen - 1.
-size_t utf8_encode(char* buffer, size_t buflen, unsigned long value);
-// Decode the utf8 encoded value pointed to by source. Returns the number of
-// bytes used by the encoding, or 0 if the encoding is invalid.
-size_t utf8_decode(const char* source, size_t srclen, unsigned long* value);
-
-// Escaping prefixes illegal characters with the escape character. Compact, but
-// illegal characters still appear in the string.
-size_t escape(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- const char * illegal, char escape);
-// Note: in-place unescaping (buffer == source) is allowed.
-size_t unescape(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- char escape);
-
-// Encoding replaces illegal characters with the escape character and 2 hex
-// chars, so it's a little less compact than escape, but completely removes
-// illegal characters. note that hex digits should not be used as illegal
-// characters.
-size_t encode(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- const char * illegal, char escape);
-// Note: in-place decoding (buffer == source) is allowed.
-size_t decode(char * buffer, size_t buflen,
- const char * source, size_t srclen,
- char escape);
-
-// Returns a list of characters that may be unsafe for use in the name of a
-// file, suitable for passing to the 'illegal' member of escape or encode.
-const char* unsafe_filename_characters();
-
-// url_encode is an encode operation with a predefined set of illegal characters
-// and escape character (for use in URLs, obviously).
-size_t url_encode(char * buffer, size_t buflen,
- const char * source, size_t srclen);
-// Note: in-place decoding (buffer == source) is allowed.
-size_t url_decode(char * buffer, size_t buflen,
- const char * source, size_t srclen);
-
-// html_encode prevents data embedded in html from containing markup.
-size_t html_encode(char * buffer, size_t buflen,
- const char * source, size_t srclen);
-// Note: in-place decoding (buffer == source) is allowed.
-size_t html_decode(char * buffer, size_t buflen,
- const char * source, size_t srclen);
-
-// xml_encode makes data suitable for inside xml attributes and values.
-size_t xml_encode(char * buffer, size_t buflen,
- const char * source, size_t srclen);
-// Note: in-place decoding (buffer == source) is allowed.
-size_t xml_decode(char * buffer, size_t buflen,
- const char * source, size_t srclen);
-
-// Convert an unsigned value from 0 to 15 to the hex character equivalent...
-char hex_encode(unsigned char val);
-// ...and vice-versa.
-bool hex_decode(char ch, unsigned char* val);
-
-// hex_encode shows the hex representation of binary data in ascii.
-size_t hex_encode(char* buffer, size_t buflen,
- const char* source, size_t srclen);
-
-// hex_encode, but separate each byte representation with a delimiter.
-// |delimiter| == 0 means no delimiter
-// If the buffer is too short, we return 0
-size_t hex_encode_with_delimiter(char* buffer, size_t buflen,
- const char* source, size_t srclen,
- char delimiter);
-
-// Helper functions for hex_encode.
-std::string hex_encode(const char* source, size_t srclen);
-std::string hex_encode_with_delimiter(const char* source, size_t srclen,
- char delimiter);
-
-// hex_decode converts ascii hex to binary.
-size_t hex_decode(char* buffer, size_t buflen,
- const char* source, size_t srclen);
-
-// hex_decode, assuming that there is a delimiter between every byte
-// pair.
-// |delimiter| == 0 means no delimiter
-// If the buffer is too short or the data is invalid, we return 0.
-size_t hex_decode_with_delimiter(char* buffer, size_t buflen,
- const char* source, size_t srclen,
- char delimiter);
-
-// Helper functions for hex_decode.
-size_t hex_decode(char* buffer, size_t buflen, const std::string& source);
-size_t hex_decode_with_delimiter(char* buffer, size_t buflen,
- const std::string& source, char delimiter);
-
-// Apply any suitable string transform (including the ones above) to an STL
-// string. Stack-allocated temporary space is used for the transformation,
-// so value and source may refer to the same string.
-typedef size_t (*Transform)(char * buffer, size_t buflen,
- const char * source, size_t srclen);
-size_t transform(std::string& value, size_t maxlen, const std::string& source,
- Transform t);
-
-// Return the result of applying transform t to source.
-std::string s_transform(const std::string& source, Transform t);
-
-// Convenience wrappers.
-inline std::string s_url_encode(const std::string& source) {
- return s_transform(source, url_encode);
-}
-inline std::string s_url_decode(const std::string& source) {
- return s_transform(source, url_decode);
-}
-
-// Splits the source string into multiple fields separated by delimiter,
-// with duplicates of delimiter creating empty fields.
-size_t split(const std::string& source, char delimiter,
- std::vector<std::string>* fields);
-
-// Splits the source string into multiple fields separated by delimiter,
-// with duplicates of delimiter ignored. Trailing delimiter ignored.
-size_t tokenize(const std::string& source, char delimiter,
- std::vector<std::string>* fields);
-
-// Tokenize and append the tokens to fields. Return the new size of fields.
-size_t tokenize_append(const std::string& source, char delimiter,
- std::vector<std::string>* fields);
-
-// Splits the source string into multiple fields separated by delimiter, with
-// duplicates of delimiter ignored. Trailing delimiter ignored. A substring in
-// between the start_mark and the end_mark is treated as a single field. Return
-// the size of fields. For example, if source is "filename
-// \"/Library/Application Support/media content.txt\"", delimiter is ' ', and
-// the start_mark and end_mark are '"', this method returns two fields:
-// "filename" and "/Library/Application Support/media content.txt".
-size_t tokenize(const std::string& source, char delimiter, char start_mark,
- char end_mark, std::vector<std::string>* fields);
-
-// Safe sprintf to std::string
-//void sprintf(std::string& value, size_t maxlen, const char * format, ...)
-// PRINTF_FORMAT(3);
-
-// Convert arbitrary values to/from a string.
-
-template <class T>
-static bool ToString(const T &t, std::string* s) {
- ASSERT(NULL != s);
- std::ostringstream oss;
- oss << std::boolalpha << t;
- *s = oss.str();
- return !oss.fail();
-}
-
-template <class T>
-static bool FromString(const std::string& s, T* t) {
- ASSERT(NULL != t);
- std::istringstream iss(s);
- iss >> std::boolalpha >> *t;
- return !iss.fail();
-}
-
-// Inline versions of the string conversion routines.
-
-template<typename T>
-static inline std::string ToString(const T& val) {
- std::string str; ToString(val, &str); return str;
-}
-
-template<typename T>
-static inline T FromString(const std::string& str) {
- T val; FromString(str, &val); return val;
-}
-
-template<typename T>
-static inline T FromString(const T& defaultValue, const std::string& str) {
- T val(defaultValue); FromString(str, &val); return val;
-}
-
-// simple function to strip out characters which shouldn't be
-// used in filenames
-char make_char_safe_for_filename(char c);
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_STRINGENCODE_H__
diff --git a/base/stringencode_unittest.cc b/base/stringencode_unittest.cc
deleted file mode 100644
index c1ec53f..0000000
--- a/base/stringencode_unittest.cc
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * libjingle
- * Copyright 2004, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-
-namespace talk_base {
-
-TEST(Utf8EncodeTest, EncodeDecode) {
- const struct Utf8Test {
- const char* encoded;
- size_t encsize, enclen;
- unsigned long decoded;
- } kTests[] = {
- { "a ", 5, 1, 'a' },
- { "\x7F ", 5, 1, 0x7F },
- { "\xC2\x80 ", 5, 2, 0x80 },
- { "\xDF\xBF ", 5, 2, 0x7FF },
- { "\xE0\xA0\x80 ", 5, 3, 0x800 },
- { "\xEF\xBF\xBF ", 5, 3, 0xFFFF },
- { "\xF0\x90\x80\x80 ", 5, 4, 0x10000 },
- { "\xF0\x90\x80\x80 ", 3, 0, 0x10000 },
- { "\xF0\xF0\x80\x80 ", 5, 0, 0 },
- { "\xF0\x90\x80 ", 5, 0, 0 },
- { "\x90\x80\x80 ", 5, 0, 0 },
- { NULL, 0, 0 },
- };
- for (size_t i = 0; kTests[i].encoded; ++i) {
- unsigned long val = 0;
- ASSERT_EQ(kTests[i].enclen, utf8_decode(kTests[i].encoded,
- kTests[i].encsize,
- &val));
- unsigned long result = (kTests[i].enclen == 0) ? 0 : kTests[i].decoded;
- ASSERT_EQ(result, val);
-
- if (kTests[i].decoded == 0) {
- // Not an interesting encoding test case
- continue;
- }
-
- char buffer[5];
- memset(buffer, 0x01, ARRAY_SIZE(buffer));
- ASSERT_EQ(kTests[i].enclen, utf8_encode(buffer,
- kTests[i].encsize,
- kTests[i].decoded));
- ASSERT_TRUE(memcmp(buffer, kTests[i].encoded, kTests[i].enclen) == 0);
- // Make sure remainder of buffer is unchanged
- ASSERT_TRUE(memory_check(buffer + kTests[i].enclen,
- 0x1,
- ARRAY_SIZE(buffer) - kTests[i].enclen));
- }
-}
-
-class HexEncodeTest : public testing::Test {
- public:
- HexEncodeTest() : enc_res_(0), dec_res_(0) {
- for (size_t i = 0; i < sizeof(data_); ++i) {
- data_[i] = (i + 128) & 0xff;
- }
- memset(decoded_, 0x7f, sizeof(decoded_));
- }
-
- char data_[10];
- char encoded_[31];
- char decoded_[11];
- size_t enc_res_;
- size_t dec_res_;
-};
-
-// Test that we can convert to/from hex with no delimiter.
-TEST_F(HexEncodeTest, TestWithNoDelimiter) {
- enc_res_ = hex_encode(encoded_, sizeof(encoded_), data_, sizeof(data_));
- ASSERT_EQ(sizeof(data_) * 2, enc_res_);
- ASSERT_STREQ("80818283848586878889", encoded_);
- dec_res_ = hex_decode(decoded_, sizeof(decoded_), encoded_, enc_res_);
- ASSERT_EQ(sizeof(data_), dec_res_);
- ASSERT_EQ(0, memcmp(data_, decoded_, dec_res_));
-}
-
-// Test that we can convert to/from hex with a colon delimiter.
-TEST_F(HexEncodeTest, TestWithDelimiter) {
- enc_res_ = hex_encode_with_delimiter(encoded_, sizeof(encoded_),
- data_, sizeof(data_), ':');
- ASSERT_EQ(sizeof(data_) * 3 - 1, enc_res_);
- ASSERT_STREQ("80:81:82:83:84:85:86:87:88:89", encoded_);
- dec_res_ = hex_decode_with_delimiter(decoded_, sizeof(decoded_),
- encoded_, enc_res_, ':');
- ASSERT_EQ(sizeof(data_), dec_res_);
- ASSERT_EQ(0, memcmp(data_, decoded_, dec_res_));
-}
-
-// Test that encoding with one delimiter and decoding with another fails.
-TEST_F(HexEncodeTest, TestWithWrongDelimiter) {
- enc_res_ = hex_encode_with_delimiter(encoded_, sizeof(encoded_),
- data_, sizeof(data_), ':');
- ASSERT_EQ(sizeof(data_) * 3 - 1, enc_res_);
- dec_res_ = hex_decode_with_delimiter(decoded_, sizeof(decoded_),
- encoded_, enc_res_, '/');
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that encoding without a delimiter and decoding with one fails.
-TEST_F(HexEncodeTest, TestExpectedDelimiter) {
- enc_res_ = hex_encode(encoded_, sizeof(encoded_), data_, sizeof(data_));
- ASSERT_EQ(sizeof(data_) * 2, enc_res_);
- dec_res_ = hex_decode_with_delimiter(decoded_, sizeof(decoded_),
- encoded_, enc_res_, ':');
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that encoding with a delimiter and decoding without one fails.
-TEST_F(HexEncodeTest, TestExpectedNoDelimiter) {
- enc_res_ = hex_encode_with_delimiter(encoded_, sizeof(encoded_),
- data_, sizeof(data_), ':');
- ASSERT_EQ(sizeof(data_) * 3 - 1, enc_res_);
- dec_res_ = hex_decode(decoded_, sizeof(decoded_), encoded_, enc_res_);
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that we handle a zero-length buffer with no delimiter.
-TEST_F(HexEncodeTest, TestZeroLengthNoDelimiter) {
- enc_res_ = hex_encode(encoded_, sizeof(encoded_), "", 0);
- ASSERT_EQ(0U, enc_res_);
- dec_res_ = hex_decode(decoded_, sizeof(decoded_), encoded_, enc_res_);
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that we handle a zero-length buffer with a delimiter.
-TEST_F(HexEncodeTest, TestZeroLengthWithDelimiter) {
- enc_res_ = hex_encode_with_delimiter(encoded_, sizeof(encoded_), "", 0, ':');
- ASSERT_EQ(0U, enc_res_);
- dec_res_ = hex_decode_with_delimiter(decoded_, sizeof(decoded_),
- encoded_, enc_res_, ':');
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test the std::string variants that take no delimiter.
-TEST_F(HexEncodeTest, TestHelpersNoDelimiter) {
- std::string result = hex_encode(data_, sizeof(data_));
- ASSERT_EQ("80818283848586878889", result);
- dec_res_ = hex_decode(decoded_, sizeof(decoded_), result);
- ASSERT_EQ(sizeof(data_), dec_res_);
- ASSERT_EQ(0, memcmp(data_, decoded_, dec_res_));
-}
-
-// Test the std::string variants that use a delimiter.
-TEST_F(HexEncodeTest, TestHelpersWithDelimiter) {
- std::string result = hex_encode_with_delimiter(data_, sizeof(data_), ':');
- ASSERT_EQ("80:81:82:83:84:85:86:87:88:89", result);
- dec_res_ = hex_decode_with_delimiter(decoded_, sizeof(decoded_), result, ':');
- ASSERT_EQ(sizeof(data_), dec_res_);
- ASSERT_EQ(0, memcmp(data_, decoded_, dec_res_));
-}
-
-// Test that encoding into a too-small output buffer (without delimiter) fails.
-TEST_F(HexEncodeTest, TestEncodeTooShort) {
- enc_res_ = hex_encode_with_delimiter(encoded_, sizeof(data_) * 2,
- data_, sizeof(data_), 0);
- ASSERT_EQ(0U, enc_res_);
-}
-
-// Test that encoding into a too-small output buffer (with delimiter) fails.
-TEST_F(HexEncodeTest, TestEncodeWithDelimiterTooShort) {
- enc_res_ = hex_encode_with_delimiter(encoded_, sizeof(data_) * 3 - 1,
- data_, sizeof(data_), ':');
- ASSERT_EQ(0U, enc_res_);
-}
-
-// Test that decoding into a too-small output buffer fails.
-TEST_F(HexEncodeTest, TestDecodeTooShort) {
- dec_res_ = hex_decode_with_delimiter(decoded_, 4, "0123456789", 10, 0);
- ASSERT_EQ(0U, dec_res_);
- ASSERT_EQ(0x7f, decoded_[4]);
-}
-
-// Test that decoding non-hex data fails.
-TEST_F(HexEncodeTest, TestDecodeBogusData) {
- dec_res_ = hex_decode_with_delimiter(decoded_, sizeof(decoded_), "xyz", 3, 0);
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that decoding an odd number of hex characters fails.
-TEST_F(HexEncodeTest, TestDecodeOddHexDigits) {
- dec_res_ = hex_decode_with_delimiter(decoded_, sizeof(decoded_), "012", 3, 0);
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that decoding a string with too many delimiters fails.
-TEST_F(HexEncodeTest, TestDecodeWithDelimiterTooManyDelimiters) {
- dec_res_ = hex_decode_with_delimiter(decoded_, 4, "01::23::45::67", 14, ':');
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that decoding a string with a leading delimiter fails.
-TEST_F(HexEncodeTest, TestDecodeWithDelimiterLeadingDelimiter) {
- dec_res_ = hex_decode_with_delimiter(decoded_, 4, ":01:23:45:67", 12, ':');
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Test that decoding a string with a trailing delimiter fails.
-TEST_F(HexEncodeTest, TestDecodeWithDelimiterTrailingDelimiter) {
- dec_res_ = hex_decode_with_delimiter(decoded_, 4, "01:23:45:67:", 12, ':');
- ASSERT_EQ(0U, dec_res_);
-}
-
-// Tests counting substrings.
-TEST(TokenizeTest, CountSubstrings) {
- std::vector<std::string> fields;
-
- EXPECT_EQ(5ul, tokenize("one two three four five", ' ', &fields));
- fields.clear();
- EXPECT_EQ(1ul, tokenize("one", ' ', &fields));
-
- // Extra spaces should be ignored.
- fields.clear();
- EXPECT_EQ(5ul, tokenize(" one two three four five ", ' ', &fields));
- fields.clear();
- EXPECT_EQ(1ul, tokenize(" one ", ' ', &fields));
- fields.clear();
- EXPECT_EQ(0ul, tokenize(" ", ' ', &fields));
-}
-
-// Tests comparing substrings.
-TEST(TokenizeTest, CompareSubstrings) {
- std::vector<std::string> fields;
-
- tokenize("find middle one", ' ', &fields);
- ASSERT_EQ(3ul, fields.size());
- ASSERT_STREQ("middle", fields.at(1).c_str());
- fields.clear();
-
- // Extra spaces should be ignored.
- tokenize(" find middle one ", ' ', &fields);
- ASSERT_EQ(3ul, fields.size());
- ASSERT_STREQ("middle", fields.at(1).c_str());
- fields.clear();
- tokenize(" ", ' ', &fields);
- ASSERT_EQ(0ul, fields.size());
-}
-
-TEST(TokenizeTest, TokenizeAppend) {
- ASSERT_EQ(0ul, tokenize_append("A B C", ' ', NULL));
-
- std::vector<std::string> fields;
-
- tokenize_append("A B C", ' ', &fields);
- ASSERT_EQ(3ul, fields.size());
- ASSERT_STREQ("B", fields.at(1).c_str());
-
- tokenize_append("D E", ' ', &fields);
- ASSERT_EQ(5ul, fields.size());
- ASSERT_STREQ("B", fields.at(1).c_str());
- ASSERT_STREQ("E", fields.at(4).c_str());
-}
-
-TEST(TokenizeTest, TokenizeWithMarks) {
- ASSERT_EQ(0ul, tokenize("D \"A B", ' ', '(', ')', NULL));
-
- std::vector<std::string> fields;
- tokenize("A B C", ' ', '"', '"', &fields);
- ASSERT_EQ(3ul, fields.size());
- ASSERT_STREQ("C", fields.at(2).c_str());
-
- tokenize("\"A B\" C", ' ', '"', '"', &fields);
- ASSERT_EQ(2ul, fields.size());
- ASSERT_STREQ("A B", fields.at(0).c_str());
-
- tokenize("D \"A B\" C", ' ', '"', '"', &fields);
- ASSERT_EQ(3ul, fields.size());
- ASSERT_STREQ("D", fields.at(0).c_str());
- ASSERT_STREQ("A B", fields.at(1).c_str());
-
- tokenize("D \"A B\" C \"E F\"", ' ', '"', '"', &fields);
- ASSERT_EQ(4ul, fields.size());
- ASSERT_STREQ("D", fields.at(0).c_str());
- ASSERT_STREQ("A B", fields.at(1).c_str());
- ASSERT_STREQ("E F", fields.at(3).c_str());
-
- // No matching marks.
- tokenize("D \"A B", ' ', '"', '"', &fields);
- ASSERT_EQ(3ul, fields.size());
- ASSERT_STREQ("D", fields.at(0).c_str());
- ASSERT_STREQ("\"A", fields.at(1).c_str());
-
- tokenize("D (A B) C (E F) G", ' ', '(', ')', &fields);
- ASSERT_EQ(5ul, fields.size());
- ASSERT_STREQ("D", fields.at(0).c_str());
- ASSERT_STREQ("A B", fields.at(1).c_str());
- ASSERT_STREQ("E F", fields.at(3).c_str());
-}
-
-// Tests counting substrings.
-TEST(SplitTest, CountSubstrings) {
- std::vector<std::string> fields;
-
- EXPECT_EQ(5ul, split("one,two,three,four,five", ',', &fields));
- fields.clear();
- EXPECT_EQ(1ul, split("one", ',', &fields));
-
- // Empty fields between commas count.
- fields.clear();
- EXPECT_EQ(5ul, split("one,,three,four,five", ',', &fields));
- fields.clear();
- EXPECT_EQ(3ul, split(",three,", ',', &fields));
- fields.clear();
- EXPECT_EQ(1ul, split("", ',', &fields));
-}
-
-// Tests comparing substrings.
-TEST(SplitTest, CompareSubstrings) {
- std::vector<std::string> fields;
-
- split("find,middle,one", ',', &fields);
- ASSERT_EQ(3ul, fields.size());
- ASSERT_STREQ("middle", fields.at(1).c_str());
- fields.clear();
-
- // Empty fields between commas count.
- split("find,,middle,one", ',', &fields);
- ASSERT_EQ(4ul, fields.size());
- ASSERT_STREQ("middle", fields.at(2).c_str());
- fields.clear();
- split("", ',', &fields);
- ASSERT_EQ(1ul, fields.size());
- ASSERT_STREQ("", fields.at(0).c_str());
-}
-
-TEST(BoolTest, DecodeValid) {
- bool value;
- EXPECT_TRUE(FromString("true", &value));
- EXPECT_TRUE(value);
- EXPECT_TRUE(FromString("true,", &value));
- EXPECT_TRUE(value);
- EXPECT_TRUE(FromString("true , true", &value));
- EXPECT_TRUE(value);
- EXPECT_TRUE(FromString("true ,\n false", &value));
- EXPECT_TRUE(value);
- EXPECT_TRUE(FromString(" true \n", &value));
- EXPECT_TRUE(value);
-
- EXPECT_TRUE(FromString("false", &value));
- EXPECT_FALSE(value);
- EXPECT_TRUE(FromString(" false ", &value));
- EXPECT_FALSE(value);
- EXPECT_TRUE(FromString(" false, ", &value));
- EXPECT_FALSE(value);
-
- EXPECT_TRUE(FromString<bool>("true\n"));
- EXPECT_FALSE(FromString<bool>("false\n"));
-}
-
-TEST(BoolTest, DecodeInvalid) {
- bool value;
- EXPECT_FALSE(FromString("True", &value));
- EXPECT_FALSE(FromString("TRUE", &value));
- EXPECT_FALSE(FromString("False", &value));
- EXPECT_FALSE(FromString("FALSE", &value));
- EXPECT_FALSE(FromString("0", &value));
- EXPECT_FALSE(FromString("1", &value));
- EXPECT_FALSE(FromString("0,", &value));
- EXPECT_FALSE(FromString("1,", &value));
- EXPECT_FALSE(FromString("1,0", &value));
- EXPECT_FALSE(FromString("1.", &value));
- EXPECT_FALSE(FromString("1.0", &value));
- EXPECT_FALSE(FromString("", &value));
- EXPECT_FALSE(FromString<bool>("false\nfalse"));
-}
-
-TEST(BoolTest, RoundTrip) {
- bool value;
- EXPECT_TRUE(FromString(ToString(true), &value));
- EXPECT_TRUE(value);
- EXPECT_TRUE(FromString(ToString(false), &value));
- EXPECT_FALSE(value);
-}
-} // namespace talk_base
diff --git a/base/stringutils.cc b/base/stringutils.cc
deleted file mode 100644
index c4c2b2f..0000000
--- a/base/stringutils.cc
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/stringutils.h"
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-bool memory_check(const void* memory, int c, size_t count) {
- const char* char_memory = static_cast<const char*>(memory);
- char char_c = static_cast<char>(c);
- for (size_t i = 0; i < count; ++i) {
- if (char_memory[i] != char_c) {
- return false;
- }
- }
- return true;
-}
-
-bool string_match(const char* target, const char* pattern) {
- while (*pattern) {
- if (*pattern == '*') {
- if (!*++pattern) {
- return true;
- }
- while (*target) {
- if ((toupper(*pattern) == toupper(*target))
- && string_match(target + 1, pattern + 1)) {
- return true;
- }
- ++target;
- }
- return false;
- } else {
- if (toupper(*pattern) != toupper(*target)) {
- return false;
- }
- ++target;
- ++pattern;
- }
- }
- return !*target;
-}
-
-#ifdef WIN32
-int ascii_string_compare(const wchar_t* s1, const char* s2, size_t n,
- CharacterTransformation transformation) {
- wchar_t c1, c2;
- while (true) {
- if (n-- == 0) return 0;
- c1 = transformation(*s1);
- // Double check that characters are not UTF-8
- ASSERT(static_cast<unsigned char>(*s2) < 128);
- // Note: *s2 gets implicitly promoted to wchar_t
- c2 = transformation(*s2);
- if (c1 != c2) return (c1 < c2) ? -1 : 1;
- if (!c1) return 0;
- ++s1;
- ++s2;
- }
-}
-
-size_t asccpyn(wchar_t* buffer, size_t buflen,
- const char* source, size_t srclen) {
- if (buflen <= 0)
- return 0;
-
- if (srclen == SIZE_UNKNOWN) {
- srclen = strlenn(source, buflen - 1);
- } else if (srclen >= buflen) {
- srclen = buflen - 1;
- }
-#if _DEBUG
- // Double check that characters are not UTF-8
- for (size_t pos = 0; pos < srclen; ++pos)
- ASSERT(static_cast<unsigned char>(source[pos]) < 128);
-#endif // _DEBUG
- std::copy(source, source + srclen, buffer);
- buffer[srclen] = 0;
- return srclen;
-}
-
-#endif // WIN32
-
-void replace_substrs(const char *search,
- size_t search_len,
- const char *replace,
- size_t replace_len,
- std::string *s) {
- size_t pos = 0;
- while ((pos = s->find(search, pos, search_len)) != std::string::npos) {
- s->replace(pos, search_len, replace, replace_len);
- pos += replace_len;
- }
-}
-
-bool starts_with(const char *s1, const char *s2) {
- return strncmp(s1, s2, strlen(s2)) == 0;
-}
-
-bool ends_with(const char *s1, const char *s2) {
- size_t s1_length = strlen(s1);
- size_t s2_length = strlen(s2);
-
- if (s2_length > s1_length) {
- return false;
- }
-
- const char* start = s1 + (s1_length - s2_length);
- return strncmp(start, s2, s2_length) == 0;
-}
-
-static const char kWhitespace[] = " \n\r\t";
-
-std::string string_trim(const std::string& s) {
- std::string::size_type first = s.find_first_not_of(kWhitespace);
- std::string::size_type last = s.find_last_not_of(kWhitespace);
-
- if (first == std::string::npos || last == std::string::npos) {
- return std::string("");
- }
-
- return s.substr(first, last - first + 1);
-}
-
-} // namespace talk_base
diff --git a/base/stringutils.h b/base/stringutils.h
deleted file mode 100644
index 2c12118..0000000
--- a/base/stringutils.h
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_STRINGUTILS_H__
-#define TALK_BASE_STRINGUTILS_H__
-
-#include <ctype.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-#ifdef WIN32
-#include <malloc.h>
-#include <wchar.h>
-#define alloca _alloca
-#endif // WIN32
-
-#ifdef POSIX
-#ifdef BSD
-#include <stdlib.h>
-#else // BSD
-#include <alloca.h>
-#endif // !BSD
-#endif // POSIX
-
-#include <string>
-
-#include "talk/base/basictypes.h"
-
-///////////////////////////////////////////////////////////////////////////////
-// Generic string/memory utilities
-///////////////////////////////////////////////////////////////////////////////
-
-#define STACK_ARRAY(TYPE, LEN) static_cast<TYPE*>(::alloca((LEN)*sizeof(TYPE)))
-
-namespace talk_base {
-
-// Complement to memset. Verifies memory consists of count bytes of value c.
-bool memory_check(const void* memory, int c, size_t count);
-
-// Determines whether the simple wildcard pattern matches target.
-// Alpha characters in pattern match case-insensitively.
-// Asterisks in pattern match 0 or more characters.
-// Ex: string_match("www.TEST.GOOGLE.COM", "www.*.com") -> true
-bool string_match(const char* target, const char* pattern);
-
-} // namespace talk_base
-
-///////////////////////////////////////////////////////////////////////////////
-// Rename a bunch of common string functions so they are consistent across
-// platforms and between char and wchar_t variants.
-// Here is the full list of functions that are unified:
-// strlen, strcmp, stricmp, strncmp, strnicmp
-// strchr, vsnprintf, strtoul, tolowercase
-// tolowercase is like tolower, but not compatible with end-of-file value
-//
-// It's not clear if we will ever use wchar_t strings on unix. In theory,
-// all strings should be Utf8 all the time, except when interfacing with Win32
-// APIs that require Utf16.
-///////////////////////////////////////////////////////////////////////////////
-
-inline char tolowercase(char c) {
- return static_cast<char>(tolower(c));
-}
-
-#ifdef WIN32
-
-inline size_t strlen(const wchar_t* s) {
- return wcslen(s);
-}
-inline int strcmp(const wchar_t* s1, const wchar_t* s2) {
- return wcscmp(s1, s2);
-}
-inline int stricmp(const wchar_t* s1, const wchar_t* s2) {
- return _wcsicmp(s1, s2);
-}
-inline int strncmp(const wchar_t* s1, const wchar_t* s2, size_t n) {
- return wcsncmp(s1, s2, n);
-}
-inline int strnicmp(const wchar_t* s1, const wchar_t* s2, size_t n) {
- return _wcsnicmp(s1, s2, n);
-}
-inline const wchar_t* strchr(const wchar_t* s, wchar_t c) {
- return wcschr(s, c);
-}
-inline const wchar_t* strstr(const wchar_t* haystack, const wchar_t* needle) {
- return wcsstr(haystack, needle);
-}
-#ifndef vsnprintf
-inline int vsnprintf(wchar_t* buf, size_t n, const wchar_t* fmt, va_list args) {
- return _vsnwprintf(buf, n, fmt, args);
-}
-#endif // !vsnprintf
-inline unsigned long strtoul(const wchar_t* snum, wchar_t** end, int base) {
- return wcstoul(snum, end, base);
-}
-inline wchar_t tolowercase(wchar_t c) {
- return static_cast<wchar_t>(towlower(c));
-}
-
-#endif // WIN32
-
-#ifdef POSIX
-
-inline int _stricmp(const char* s1, const char* s2) {
- return strcasecmp(s1, s2);
-}
-inline int _strnicmp(const char* s1, const char* s2, size_t n) {
- return strncasecmp(s1, s2, n);
-}
-
-#endif // POSIX
-
-///////////////////////////////////////////////////////////////////////////////
-// Traits simplifies porting string functions to be CTYPE-agnostic
-///////////////////////////////////////////////////////////////////////////////
-
-namespace talk_base {
-
-const size_t SIZE_UNKNOWN = static_cast<size_t>(-1);
-
-template<class CTYPE>
-struct Traits {
- // STL string type
- //typedef XXX string;
- // Null-terminated string
- //inline static const CTYPE* empty_str();
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// String utilities which work with char or wchar_t
-///////////////////////////////////////////////////////////////////////////////
-
-template<class CTYPE>
-inline const CTYPE* nonnull(const CTYPE* str, const CTYPE* def_str = NULL) {
- return str ? str : (def_str ? def_str : Traits<CTYPE>::empty_str());
-}
-
-template<class CTYPE>
-const CTYPE* strchr(const CTYPE* str, const CTYPE* chs) {
- for (size_t i=0; str[i]; ++i) {
- for (size_t j=0; chs[j]; ++j) {
- if (str[i] == chs[j]) {
- return str + i;
- }
- }
- }
- return 0;
-}
-
-template<class CTYPE>
-const CTYPE* strchrn(const CTYPE* str, size_t slen, CTYPE ch) {
- for (size_t i=0; i<slen && str[i]; ++i) {
- if (str[i] == ch) {
- return str + i;
- }
- }
- return 0;
-}
-
-template<class CTYPE>
-size_t strlenn(const CTYPE* buffer, size_t buflen) {
- size_t bufpos = 0;
- while (buffer[bufpos] && (bufpos < buflen)) {
- ++bufpos;
- }
- return bufpos;
-}
-
-// Safe versions of strncpy, strncat, snprintf and vsnprintf that always
-// null-terminate.
-
-template<class CTYPE>
-size_t strcpyn(CTYPE* buffer, size_t buflen,
- const CTYPE* source, size_t srclen = SIZE_UNKNOWN) {
- if (buflen <= 0)
- return 0;
-
- if (srclen == SIZE_UNKNOWN) {
- srclen = strlenn(source, buflen - 1);
- } else if (srclen >= buflen) {
- srclen = buflen - 1;
- }
- memcpy(buffer, source, srclen * sizeof(CTYPE));
- buffer[srclen] = 0;
- return srclen;
-}
-
-template<class CTYPE>
-size_t strcatn(CTYPE* buffer, size_t buflen,
- const CTYPE* source, size_t srclen = SIZE_UNKNOWN) {
- if (buflen <= 0)
- return 0;
-
- size_t bufpos = strlenn(buffer, buflen - 1);
- return bufpos + strcpyn(buffer + bufpos, buflen - bufpos, source, srclen);
-}
-
-// Some compilers (clang specifically) require vsprintfn be defined before
-// sprintfn.
-template<class CTYPE>
-size_t vsprintfn(CTYPE* buffer, size_t buflen, const CTYPE* format,
- va_list args) {
- int len = vsnprintf(buffer, buflen, format, args);
- if ((len < 0) || (static_cast<size_t>(len) >= buflen)) {
- len = static_cast<int>(buflen - 1);
- buffer[len] = 0;
- }
- return len;
-}
-
-template<class CTYPE>
-size_t sprintfn(CTYPE* buffer, size_t buflen, const CTYPE* format, ...);
-template<class CTYPE>
-size_t sprintfn(CTYPE* buffer, size_t buflen, const CTYPE* format, ...) {
- va_list args;
- va_start(args, format);
- size_t len = vsprintfn(buffer, buflen, format, args);
- va_end(args);
- return len;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// Allow safe comparing and copying ascii (not UTF-8) with both wide and
-// non-wide character strings.
-///////////////////////////////////////////////////////////////////////////////
-
-inline int asccmp(const char* s1, const char* s2) {
- return strcmp(s1, s2);
-}
-inline int ascicmp(const char* s1, const char* s2) {
- return _stricmp(s1, s2);
-}
-inline int ascncmp(const char* s1, const char* s2, size_t n) {
- return strncmp(s1, s2, n);
-}
-inline int ascnicmp(const char* s1, const char* s2, size_t n) {
- return _strnicmp(s1, s2, n);
-}
-inline size_t asccpyn(char* buffer, size_t buflen,
- const char* source, size_t srclen = SIZE_UNKNOWN) {
- return strcpyn(buffer, buflen, source, srclen);
-}
-
-#ifdef WIN32
-
-typedef wchar_t(*CharacterTransformation)(wchar_t);
-inline wchar_t identity(wchar_t c) { return c; }
-int ascii_string_compare(const wchar_t* s1, const char* s2, size_t n,
- CharacterTransformation transformation);
-
-inline int asccmp(const wchar_t* s1, const char* s2) {
- return ascii_string_compare(s1, s2, static_cast<size_t>(-1), identity);
-}
-inline int ascicmp(const wchar_t* s1, const char* s2) {
- return ascii_string_compare(s1, s2, static_cast<size_t>(-1), tolowercase);
-}
-inline int ascncmp(const wchar_t* s1, const char* s2, size_t n) {
- return ascii_string_compare(s1, s2, n, identity);
-}
-inline int ascnicmp(const wchar_t* s1, const char* s2, size_t n) {
- return ascii_string_compare(s1, s2, n, tolowercase);
-}
-size_t asccpyn(wchar_t* buffer, size_t buflen,
- const char* source, size_t srclen = SIZE_UNKNOWN);
-
-#endif // WIN32
-
-///////////////////////////////////////////////////////////////////////////////
-// Traits<char> specializations
-///////////////////////////////////////////////////////////////////////////////
-
-template<>
-struct Traits<char> {
- typedef std::string string;
- inline static const char* empty_str() { return ""; }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Traits<wchar_t> specializations (Windows only, currently)
-///////////////////////////////////////////////////////////////////////////////
-
-#ifdef WIN32
-
-template<>
-struct Traits<wchar_t> {
- typedef std::wstring string;
- inline static const wchar_t* Traits<wchar_t>::empty_str() { return L""; }
-};
-
-#endif // WIN32
-
-// Replaces all occurrences of "search" with "replace".
-void replace_substrs(const char *search,
- size_t search_len,
- const char *replace,
- size_t replace_len,
- std::string *s);
-
-// True iff s1 starts with s2.
-bool starts_with(const char *s1, const char *s2);
-
-// True iff s1 ends with s2.
-bool ends_with(const char *s1, const char *s2);
-
-// Remove leading and trailing whitespaces.
-std::string string_trim(const std::string& s);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_STRINGUTILS_H__
diff --git a/base/stringutils_unittest.cc b/base/stringutils_unittest.cc
deleted file mode 100644
index 5611869..0000000
--- a/base/stringutils_unittest.cc
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-// Tests for string_match().
-
-TEST(string_matchTest, Matches) {
- EXPECT_TRUE( string_match("A.B.C.D", "a.b.c.d"));
- EXPECT_TRUE( string_match("www.TEST.GOOGLE.COM", "www.*.com"));
- EXPECT_TRUE( string_match("127.0.0.1", "12*.0.*1"));
- EXPECT_TRUE( string_match("127.1.0.21", "12*.0.*1"));
- EXPECT_FALSE(string_match("127.0.0.0", "12*.0.*1"));
- EXPECT_FALSE(string_match("127.0.0.0", "12*.0.*1"));
- EXPECT_FALSE(string_match("127.1.1.21", "12*.0.*1"));
-}
-
-// It's not clear if we will ever use wchar_t strings on unix. In theory,
-// all strings should be Utf8 all the time, except when interfacing with Win32
-// APIs that require Utf16.
-
-#ifdef WIN32
-
-// Tests for ascii_string_compare().
-
-// Tests NULL input.
-TEST(ascii_string_compareTest, NullInput) {
- // The following results in an access violation in
- // ascii_string_compare. Is this a bug or by design? stringutils.h
- // should document the expected behavior in this case.
-
- // EXPECT_EQ(0, ascii_string_compare(NULL, NULL, 1, identity));
-}
-
-// Tests comparing two strings of different lengths.
-TEST(ascii_string_compareTest, DifferentLengths) {
- EXPECT_EQ(-1, ascii_string_compare(L"Test", "Test1", 5, identity));
-}
-
-// Tests the case where the buffer size is smaller than the string
-// lengths.
-TEST(ascii_string_compareTest, SmallBuffer) {
- EXPECT_EQ(0, ascii_string_compare(L"Test", "Test1", 3, identity));
-}
-
-// Tests the case where the buffer is not full.
-TEST(ascii_string_compareTest, LargeBuffer) {
- EXPECT_EQ(0, ascii_string_compare(L"Test", "Test", 10, identity));
-}
-
-// Tests comparing two eqaul strings.
-TEST(ascii_string_compareTest, Equal) {
- EXPECT_EQ(0, ascii_string_compare(L"Test", "Test", 5, identity));
- EXPECT_EQ(0, ascii_string_compare(L"TeSt", "tEsT", 5, tolowercase));
-}
-
-// Tests comparing a smller string to a larger one.
-TEST(ascii_string_compareTest, LessThan) {
- EXPECT_EQ(-1, ascii_string_compare(L"abc", "abd", 4, identity));
- EXPECT_EQ(-1, ascii_string_compare(L"ABC", "abD", 5, tolowercase));
-}
-
-// Tests comparing a larger string to a smaller one.
-TEST(ascii_string_compareTest, GreaterThan) {
- EXPECT_EQ(1, ascii_string_compare(L"xyz", "xy", 5, identity));
- EXPECT_EQ(1, ascii_string_compare(L"abc", "ABB", 5, tolowercase));
-}
-#endif // WIN32
-
-TEST(string_trim_Test, Trimming) {
- EXPECT_EQ("temp", string_trim("\n\r\t temp \n\r\t"));
- EXPECT_EQ("temp\n\r\t temp", string_trim(" temp\n\r\t temp "));
- EXPECT_EQ("temp temp", string_trim("temp temp"));
- EXPECT_EQ("", string_trim(" \r\n\t"));
- EXPECT_EQ("", string_trim(""));
-}
-
-TEST(string_startsTest, StartsWith) {
- EXPECT_TRUE(starts_with("foobar", "foo"));
- EXPECT_TRUE(starts_with("foobar", "foobar"));
- EXPECT_TRUE(starts_with("foobar", ""));
- EXPECT_TRUE(starts_with("", ""));
- EXPECT_FALSE(starts_with("foobar", "bar"));
- EXPECT_FALSE(starts_with("foobar", "foobarbaz"));
- EXPECT_FALSE(starts_with("", "f"));
-}
-
-TEST(string_endsTest, EndsWith) {
- EXPECT_TRUE(ends_with("foobar", "bar"));
- EXPECT_TRUE(ends_with("foobar", "foobar"));
- EXPECT_TRUE(ends_with("foobar", ""));
- EXPECT_TRUE(ends_with("", ""));
- EXPECT_FALSE(ends_with("foobar", "foo"));
- EXPECT_FALSE(ends_with("foobar", "foobarbaz"));
- EXPECT_FALSE(ends_with("", "f"));
-}
-
-} // namespace talk_base
diff --git a/base/systeminfo.cc b/base/systeminfo.cc
deleted file mode 100644
index ff331ac..0000000
--- a/base/systeminfo.cc
+++ /dev/null
@@ -1,535 +0,0 @@
-/*
- * libjingle
- * Copyright 2008 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/systeminfo.h"
-
-#if defined(WIN32)
-#include <winsock2.h>
-#ifndef EXCLUDE_D3D9
-#include <d3d9.h>
-#endif
-#include <intrin.h> // for __cpuid()
-#elif defined(OSX)
-#include <ApplicationServices/ApplicationServices.h>
-#include <CoreServices/CoreServices.h>
-#elif defined(LINUX) || defined(ANDROID)
-#include <unistd.h>
-#endif
-#if defined(OSX) || defined(IOS)
-#include <sys/sysctl.h>
-#endif
-
-#if defined(WIN32)
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/win32.h"
-#elif defined(OSX)
-#include "talk/base/macconversion.h"
-#elif defined(LINUX) || defined(ANDROID)
-#include "talk/base/linux.h"
-#endif
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-
-namespace talk_base {
-
-// See Also: http://msdn.microsoft.com/en-us/library/ms683194(v=vs.85).aspx
-#if defined(WIN32)
-typedef BOOL (WINAPI *LPFN_GLPI)(
- PSYSTEM_LOGICAL_PROCESSOR_INFORMATION,
- PDWORD);
-
-static void GetProcessorInformation(int* physical_cpus, int* cache_size) {
- // GetLogicalProcessorInformation() is available on Windows XP SP3 and beyond.
- LPFN_GLPI glpi = reinterpret_cast<LPFN_GLPI>(GetProcAddress(
- GetModuleHandle(L"kernel32"),
- "GetLogicalProcessorInformation"));
- if (NULL == glpi) {
- return;
- }
- // Determine buffer size, allocate and get processor information.
- // Size can change between calls (unlikely), so a loop is done.
- DWORD return_length = 0;
- scoped_ptr<SYSTEM_LOGICAL_PROCESSOR_INFORMATION[]> infos;
- while (!glpi(infos.get(), &return_length)) {
- if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
- infos.reset(new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[
- return_length / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)]);
- } else {
- return;
- }
- }
- *physical_cpus = 0;
- *cache_size = 0;
- for (size_t i = 0;
- i < return_length / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ++i) {
- if (infos[i].Relationship == RelationProcessorCore) {
- ++*physical_cpus;
- } else if (infos[i].Relationship == RelationCache) {
- int next_cache_size = static_cast<int>(infos[i].Cache.Size);
- if (next_cache_size >= *cache_size) {
- *cache_size = next_cache_size;
- }
- }
- }
- return;
-}
-#else
-// TODO(fbarchard): Use gcc 4.4 provided cpuid intrinsic
-// 32 bit fpic requires ebx be preserved
-#if (defined(__pic__) || defined(__APPLE__)) && defined(__i386__)
-static inline void __cpuid(int cpu_info[4], int info_type) {
- __asm__ volatile ( // NOLINT
- "mov %%ebx, %%edi\n"
- "cpuid\n"
- "xchg %%edi, %%ebx\n"
- : "=a"(cpu_info[0]), "=D"(cpu_info[1]), "=c"(cpu_info[2]), "=d"(cpu_info[3])
- : "a"(info_type)
- ); // NOLINT
-}
-#elif defined(__i386__) || defined(__x86_64__)
-static inline void __cpuid(int cpu_info[4], int info_type) {
- __asm__ volatile ( // NOLINT
- "cpuid\n"
- : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]), "=d"(cpu_info[3])
- : "a"(info_type)
- ); // NOLINT
-}
-#endif
-#endif // WIN32
-
-// Note(fbarchard):
-// Family and model are extended family and extended model. 8 bits each.
-SystemInfo::SystemInfo()
- : physical_cpus_(1), logical_cpus_(1), cache_size_(0),
- cpu_family_(0), cpu_model_(0), cpu_stepping_(0),
- cpu_speed_(0), memory_(0) {
- // Initialize the basic information.
-#if defined(__arm__) || defined(_M_ARM)
- cpu_arch_ = SI_ARCH_ARM;
-#elif defined(__x86_64__) || defined(_M_X64)
- cpu_arch_ = SI_ARCH_X64;
-#elif defined(__i386__) || defined(_M_IX86)
- cpu_arch_ = SI_ARCH_X86;
-#else
- cpu_arch_ = SI_ARCH_UNKNOWN;
-#endif
-
-#if defined(WIN32)
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- logical_cpus_ = si.dwNumberOfProcessors;
- GetProcessorInformation(&physical_cpus_, &cache_size_);
- if (physical_cpus_ <= 0) {
- physical_cpus_ = logical_cpus_;
- }
- cpu_family_ = si.wProcessorLevel;
- cpu_model_ = si.wProcessorRevision >> 8;
- cpu_stepping_ = si.wProcessorRevision & 0xFF;
-#elif defined(OSX) || defined(IOS)
- uint32_t sysctl_value;
- size_t length = sizeof(sysctl_value);
- if (!sysctlbyname("hw.physicalcpu_max", &sysctl_value, &length, NULL, 0)) {
- physical_cpus_ = static_cast<int>(sysctl_value);
- }
- length = sizeof(sysctl_value);
- if (!sysctlbyname("hw.logicalcpu_max", &sysctl_value, &length, NULL, 0)) {
- logical_cpus_ = static_cast<int>(sysctl_value);
- }
- uint64_t sysctl_value64;
- length = sizeof(sysctl_value64);
- if (!sysctlbyname("hw.l3cachesize", &sysctl_value64, &length, NULL, 0)) {
- cache_size_ = static_cast<int>(sysctl_value64);
- }
- if (!cache_size_) {
- length = sizeof(sysctl_value64);
- if (!sysctlbyname("hw.l2cachesize", &sysctl_value64, &length, NULL, 0)) {
- cache_size_ = static_cast<int>(sysctl_value64);
- }
- }
- length = sizeof(sysctl_value);
- if (!sysctlbyname("machdep.cpu.family", &sysctl_value, &length, NULL, 0)) {
- cpu_family_ = static_cast<int>(sysctl_value);
- }
- length = sizeof(sysctl_value);
- if (!sysctlbyname("machdep.cpu.model", &sysctl_value, &length, NULL, 0)) {
- cpu_model_ = static_cast<int>(sysctl_value);
- }
- length = sizeof(sysctl_value);
- if (!sysctlbyname("machdep.cpu.stepping", &sysctl_value, &length, NULL, 0)) {
- cpu_stepping_ = static_cast<int>(sysctl_value);
- }
-#elif defined(__native_client__)
- // TODO(ryanpetrie): Implement this via PPAPI when it's available.
-#else // LINUX || ANDROID
- ProcCpuInfo proc_info;
- if (proc_info.LoadFromSystem()) {
- proc_info.GetNumCpus(&logical_cpus_);
- proc_info.GetNumPhysicalCpus(&physical_cpus_);
- proc_info.GetCpuFamily(&cpu_family_);
-#if defined(CPU_X86)
- // These values only apply to x86 systems.
- proc_info.GetSectionIntValue(0, "model", &cpu_model_);
- proc_info.GetSectionIntValue(0, "stepping", &cpu_stepping_);
- proc_info.GetSectionIntValue(0, "cpu MHz", &cpu_speed_);
- proc_info.GetSectionIntValue(0, "cache size", &cache_size_);
- cache_size_ *= 1024;
-#endif
- }
- // ProcCpuInfo reads cpu speed from "cpu MHz" under /proc/cpuinfo.
- // But that number is a moving target which can change on-the-fly according to
- // many factors including system workload.
- // See /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors.
- // The one in /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq is more
- // accurate. We use it as our cpu speed when it is available.
- // cpuinfo_max_freq is measured in KHz and requires conversion to MHz.
- int max_freq = talk_base::ReadCpuMaxFreq();
- if (max_freq > 0) {
- cpu_speed_ = max_freq / 1000;
- }
-#endif
-// For L2 CacheSize see also
-// http://www.flounder.com/cpuid_explorer2.htm#CPUID(0x800000006)
-#ifdef CPU_X86
- if (cache_size_ == 0) {
- int cpu_info[4];
- __cpuid(cpu_info, 0x80000000); // query maximum extended cpuid function.
- if (static_cast<uint32>(cpu_info[0]) >= 0x80000006) {
- __cpuid(cpu_info, 0x80000006);
- cache_size_ = (cpu_info[2] >> 16) * 1024;
- }
- }
-#endif
-}
-
-// Return the number of cpu threads available to the system.
-int SystemInfo::GetMaxCpus() {
- return logical_cpus_;
-}
-
-// Return the number of cpu cores available to the system.
-int SystemInfo::GetMaxPhysicalCpus() {
- return physical_cpus_;
-}
-
-// Return the number of cpus available to the process. Since affinity can be
-// changed on the fly, do not cache this value.
-// Can be affected by heat.
-int SystemInfo::GetCurCpus() {
- int cur_cpus;
-#if defined(WIN32)
- DWORD_PTR process_mask, system_mask;
- ::GetProcessAffinityMask(::GetCurrentProcess(), &process_mask, &system_mask);
- for (cur_cpus = 0; process_mask; ++cur_cpus) {
- // Sparse-ones algorithm. There are slightly faster methods out there but
- // they are unintuitive and won't make a difference on a single dword.
- process_mask &= (process_mask - 1);
- }
-#elif defined(OSX) || defined(IOS)
- uint32_t sysctl_value;
- size_t length = sizeof(sysctl_value);
- int error = sysctlbyname("hw.ncpu", &sysctl_value, &length, NULL, 0);
- cur_cpus = !error ? static_cast<int>(sysctl_value) : 1;
-#else
- // Linux, Solaris, ANDROID
- cur_cpus = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
-#endif
- return cur_cpus;
-}
-
-// Return the type of this CPU.
-SystemInfo::Architecture SystemInfo::GetCpuArchitecture() {
- return cpu_arch_;
-}
-
-// Returns the vendor string from the cpu, e.g. "GenuineIntel", "AuthenticAMD".
-// See "Intel Processor Identification and the CPUID Instruction"
-// (Intel document number: 241618)
-std::string SystemInfo::GetCpuVendor() {
- if (cpu_vendor_.empty()) {
-#if defined(CPU_X86)
- int cpu_info[4];
- __cpuid(cpu_info, 0);
- cpu_info[0] = cpu_info[1]; // Reorder output
- cpu_info[1] = cpu_info[3];
- cpu_info[2] = cpu_info[2];
- cpu_info[3] = 0;
- cpu_vendor_ = std::string(reinterpret_cast<char*>(&cpu_info[0]));
-#elif defined(CPU_ARM)
- cpu_vendor_ = std::string("ARM");
-#else
- cpu_vendor_ = std::string("Undefined");
-#endif
- }
- return cpu_vendor_;
-}
-
-int SystemInfo::GetCpuCacheSize() {
- return cache_size_;
-}
-
-// Return the "family" of this CPU.
-int SystemInfo::GetCpuFamily() {
- return cpu_family_;
-}
-
-// Return the "model" of this CPU.
-int SystemInfo::GetCpuModel() {
- return cpu_model_;
-}
-
-// Return the "stepping" of this CPU.
-int SystemInfo::GetCpuStepping() {
- return cpu_stepping_;
-}
-
-// Return the clockrate of the primary processor in Mhz. This value can be
-// cached. Returns -1 on error.
-int SystemInfo::GetMaxCpuSpeed() {
- if (cpu_speed_) {
- return cpu_speed_;
- }
-#if defined(WIN32)
- HKEY key;
- static const WCHAR keyName[] =
- L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0";
-
- if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName , 0, KEY_QUERY_VALUE, &key)
- == ERROR_SUCCESS) {
- DWORD data, len;
- len = sizeof(data);
-
- if (RegQueryValueEx(key, L"~Mhz", 0, 0, reinterpret_cast<LPBYTE>(&data),
- &len) == ERROR_SUCCESS) {
- cpu_speed_ = data;
- } else {
- LOG(LS_WARNING) << "Failed to query registry value HKLM\\" << keyName
- << "\\~Mhz";
- cpu_speed_ = -1;
- }
-
- RegCloseKey(key);
- } else {
- LOG(LS_WARNING) << "Failed to open registry key HKLM\\" << keyName;
- cpu_speed_ = -1;
- }
-#elif defined(IOS) || defined(OSX)
- uint64_t sysctl_value;
- size_t length = sizeof(sysctl_value);
- int error = sysctlbyname("hw.cpufrequency_max", &sysctl_value, &length,
- NULL, 0);
- cpu_speed_ = !error ? static_cast<int>(sysctl_value/1000000) : -1;
-#else
- // TODO(fbarchard): Implement using proc/cpuinfo
- cpu_speed_ = 0;
-#endif
- return cpu_speed_;
-}
-
-// Dynamically check the current clockrate, which could be reduced because of
-// powersaving profiles. Eventually for windows we want to query WMI for
-// root\WMI::ProcessorPerformance.InstanceName="Processor_Number_0".frequency
-int SystemInfo::GetCurCpuSpeed() {
-#if defined(WIN32)
- // TODO(fbarchard): Add WMI check, requires COM initialization
- // NOTE(fbarchard): Testable on Sandy Bridge.
- return GetMaxCpuSpeed();
-#elif defined(IOS) || defined(OSX)
- uint64_t sysctl_value;
- size_t length = sizeof(sysctl_value);
- int error = sysctlbyname("hw.cpufrequency", &sysctl_value, &length, NULL, 0);
- return !error ? static_cast<int>(sysctl_value/1000000) : GetMaxCpuSpeed();
-#else // LINUX || ANDROID
- // TODO(fbarchard): Use proc/cpuinfo for Cur speed on Linux.
- return GetMaxCpuSpeed();
-#endif
-}
-
-// Returns the amount of installed physical memory in Bytes. Cacheable.
-// Returns -1 on error.
-int64 SystemInfo::GetMemorySize() {
- if (memory_) {
- return memory_;
- }
-
-#if defined(WIN32)
- MEMORYSTATUSEX status = {0};
- status.dwLength = sizeof(status);
-
- if (GlobalMemoryStatusEx(&status)) {
- memory_ = status.ullTotalPhys;
- } else {
- LOG_GLE(LS_WARNING) << "GlobalMemoryStatusEx failed.";
- memory_ = -1;
- }
-
-#elif defined(OSX) || defined(IOS)
- size_t len = sizeof(memory_);
- int error = sysctlbyname("hw.memsize", &memory_, &len, NULL, 0);
- if (error || memory_ == 0) {
- memory_ = -1;
- }
-#else // LINUX || ANDROID
- memory_ = static_cast<int64>(sysconf(_SC_PHYS_PAGES)) *
- static_cast<int64>(sysconf(_SC_PAGESIZE));
- if (memory_ < 0) {
- LOG(LS_WARNING) << "sysconf(_SC_PHYS_PAGES) failed."
- << "sysconf(_SC_PHYS_PAGES) " << sysconf(_SC_PHYS_PAGES)
- << "sysconf(_SC_PAGESIZE) " << sysconf(_SC_PAGESIZE);
- memory_ = -1;
- }
-#endif
-
- return memory_;
-}
-
-
-// Return the name of the machine model we are currently running on.
-// This is a human readable string that consists of the name and version
-// number of the hardware, i.e 'MacBookAir1,1'. Returns an empty string if
-// model can not be determined. The string is cached for subsequent calls.
-std::string SystemInfo::GetMachineModel() {
- if (!machine_model_.empty()) {
- return machine_model_;
- }
-
-#if defined(OSX) || defined(IOS)
- char buffer[128];
- size_t length = sizeof(buffer);
- int error = sysctlbyname("hw.model", buffer, &length, NULL, 0);
- if (!error) {
- machine_model_.assign(buffer, length - 1);
- } else {
- machine_model_.clear();
- }
-#else
- machine_model_ = "Not available";
-#endif
-
- return machine_model_;
-}
-
-#ifdef OSX
-// Helper functions to query IOKit for video hardware properties.
-static CFTypeRef SearchForProperty(io_service_t port, CFStringRef name) {
- return IORegistryEntrySearchCFProperty(port, kIOServicePlane,
- name, kCFAllocatorDefault,
- kIORegistryIterateRecursively | kIORegistryIterateParents);
-}
-
-static void GetProperty(io_service_t port, CFStringRef name, int* value) {
- if (!value) return;
- CFTypeRef ref = SearchForProperty(port, name);
- if (ref) {
- CFTypeID refType = CFGetTypeID(ref);
- if (CFNumberGetTypeID() == refType) {
- CFNumberRef number = reinterpret_cast<CFNumberRef>(ref);
- p_convertCFNumberToInt(number, value);
- } else if (CFDataGetTypeID() == refType) {
- CFDataRef data = reinterpret_cast<CFDataRef>(ref);
- if (CFDataGetLength(data) == sizeof(UInt32)) {
- *value = *reinterpret_cast<const UInt32*>(CFDataGetBytePtr(data));
- }
- }
- CFRelease(ref);
- }
-}
-
-static void GetProperty(io_service_t port, CFStringRef name,
- std::string* value) {
- if (!value) return;
- CFTypeRef ref = SearchForProperty(port, name);
- if (ref) {
- CFTypeID refType = CFGetTypeID(ref);
- if (CFStringGetTypeID() == refType) {
- CFStringRef stringRef = reinterpret_cast<CFStringRef>(ref);
- p_convertHostCFStringRefToCPPString(stringRef, *value);
- } else if (CFDataGetTypeID() == refType) {
- CFDataRef dataRef = reinterpret_cast<CFDataRef>(ref);
- *value = std::string(reinterpret_cast<const char*>(
- CFDataGetBytePtr(dataRef)), CFDataGetLength(dataRef));
- }
- CFRelease(ref);
- }
-}
-#endif
-
-// Fills a struct with information on the graphics adapater and returns true
-// iff successful.
-bool SystemInfo::GetGpuInfo(GpuInfo *info) {
- if (!info) return false;
-#if defined(WIN32) && !defined(EXCLUDE_D3D9)
- D3DADAPTER_IDENTIFIER9 identifier;
- HRESULT hr = E_FAIL;
- HINSTANCE d3d_lib = LoadLibrary(L"d3d9.dll");
-
- if (d3d_lib) {
- typedef IDirect3D9* (WINAPI *D3DCreate9Proc)(UINT);
- D3DCreate9Proc d3d_create_proc = reinterpret_cast<D3DCreate9Proc>(
- GetProcAddress(d3d_lib, "Direct3DCreate9"));
- if (d3d_create_proc) {
- IDirect3D9* d3d = d3d_create_proc(D3D_SDK_VERSION);
- if (d3d) {
- hr = d3d->GetAdapterIdentifier(D3DADAPTER_DEFAULT, 0, &identifier);
- d3d->Release();
- }
- }
- FreeLibrary(d3d_lib);
- }
-
- if (hr != D3D_OK) {
- LOG(LS_ERROR) << "Failed to access Direct3D9 information.";
- return false;
- }
-
- info->device_name = identifier.DeviceName;
- info->description = identifier.Description;
- info->vendor_id = identifier.VendorId;
- info->device_id = identifier.DeviceId;
- info->driver = identifier.Driver;
- // driver_version format: product.version.subversion.build
- std::stringstream ss;
- ss << HIWORD(identifier.DriverVersion.HighPart) << "."
- << LOWORD(identifier.DriverVersion.HighPart) << "."
- << HIWORD(identifier.DriverVersion.LowPart) << "."
- << LOWORD(identifier.DriverVersion.LowPart);
- info->driver_version = ss.str();
- return true;
-#elif defined(OSX)
- // We'll query the IOKit for the gpu of the main display.
- io_service_t display_service_port = CGDisplayIOServicePort(
- kCGDirectMainDisplay);
- GetProperty(display_service_port, CFSTR("vendor-id"), &info->vendor_id);
- GetProperty(display_service_port, CFSTR("device-id"), &info->device_id);
- GetProperty(display_service_port, CFSTR("model"), &info->description);
- return true;
-#else // LINUX || ANDROID
- // TODO(fbarchard): Implement this on Linux
- return false;
-#endif
-}
-} // namespace talk_base
diff --git a/base/systeminfo.h b/base/systeminfo.h
deleted file mode 100644
index f84b5fe..0000000
--- a/base/systeminfo.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * libjingle
- * Copyright 2008 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_SYSTEMINFO_H__
-#define TALK_BASE_SYSTEMINFO_H__
-
-#include <string>
-
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-class SystemInfo {
- public:
- enum Architecture {
- SI_ARCH_UNKNOWN = -1,
- SI_ARCH_X86 = 0,
- SI_ARCH_X64 = 1,
- SI_ARCH_ARM = 2
- };
-
- SystemInfo();
-
- // The number of CPU Cores in the system.
- int GetMaxPhysicalCpus();
- // The number of CPU Threads in the system.
- int GetMaxCpus();
- // The number of CPU Threads currently available to this process.
- int GetCurCpus();
- // Identity of the CPUs.
- Architecture GetCpuArchitecture();
- std::string GetCpuVendor();
- int GetCpuFamily();
- int GetCpuModel();
- int GetCpuStepping();
- // Return size of CPU cache in bytes. Uses largest available cache (L3).
- int GetCpuCacheSize();
- // Estimated speed of the CPUs, in MHz. e.g. 2400 for 2.4 GHz
- int GetMaxCpuSpeed();
- int GetCurCpuSpeed();
- // Total amount of physical memory, in bytes.
- int64 GetMemorySize();
- // The model name of the machine, e.g. "MacBookAir1,1"
- std::string GetMachineModel();
-
- // The gpu identifier
- struct GpuInfo {
- GpuInfo() : vendor_id(0), device_id(0) {}
- std::string device_name;
- std::string description;
- int vendor_id;
- int device_id;
- std::string driver;
- std::string driver_version;
- };
- bool GetGpuInfo(GpuInfo *info);
-
- private:
- int physical_cpus_;
- int logical_cpus_;
- int cache_size_;
- Architecture cpu_arch_;
- std::string cpu_vendor_;
- int cpu_family_;
- int cpu_model_;
- int cpu_stepping_;
- int cpu_speed_;
- int64 memory_;
- std::string machine_model_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_SYSTEMINFO_H__
diff --git a/base/systeminfo_unittest.cc b/base/systeminfo_unittest.cc
deleted file mode 100644
index 310b1eb..0000000
--- a/base/systeminfo_unittest.cc
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * libjingle
- * Copyright 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/systeminfo.h"
-
-#if defined(CPU_X86) || defined(CPU_ARM)
-TEST(SystemInfoTest, CpuVendorNonEmpty) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuVendor: " << info.GetCpuVendor();
- EXPECT_FALSE(info.GetCpuVendor().empty());
-}
-
-// Tests Vendor identification is Intel or AMD.
-// See Also http://en.wikipedia.org/wiki/CPUID
-TEST(SystemInfoTest, CpuVendorIntelAMDARM) {
- talk_base::SystemInfo info;
-#if defined(CPU_X86)
- EXPECT_TRUE(talk_base::string_match(info.GetCpuVendor().c_str(),
- "GenuineIntel") ||
- talk_base::string_match(info.GetCpuVendor().c_str(),
- "AuthenticAMD"));
-#elif defined(CPU_ARM)
- EXPECT_TRUE(talk_base::string_match(info.GetCpuVendor().c_str(), "ARM"));
-#endif
-}
-#endif // defined(CPU_X86) || defined(CPU_ARM)
-
-// Tests CpuArchitecture matches expectations.
-TEST(SystemInfoTest, GetCpuArchitecture) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuArchitecture: " << info.GetCpuArchitecture();
- talk_base::SystemInfo::Architecture architecture = info.GetCpuArchitecture();
-#if defined(CPU_X86) || defined(CPU_ARM)
- if (sizeof(intptr_t) == 8) {
- EXPECT_EQ(talk_base::SystemInfo::SI_ARCH_X64, architecture);
- } else if (sizeof(intptr_t) == 4) {
-#if defined(CPU_ARM)
- EXPECT_EQ(talk_base::SystemInfo::SI_ARCH_ARM, architecture);
-#else
- EXPECT_EQ(talk_base::SystemInfo::SI_ARCH_X86, architecture);
-#endif
- }
-#endif
-}
-
-// Tests Cpu Cache Size
-TEST(SystemInfoTest, CpuCacheSize) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuCacheSize: " << info.GetCpuCacheSize();
- EXPECT_GE(info.GetCpuCacheSize(), 8192); // 8 KB min cache
- EXPECT_LE(info.GetCpuCacheSize(), 1024 * 1024 * 1024); // 1 GB max cache
-}
-
-// Tests MachineModel is set. On Mac test machine model is known.
-TEST(SystemInfoTest, MachineModelKnown) {
- talk_base::SystemInfo info;
- EXPECT_FALSE(info.GetMachineModel().empty());
- const char *machine_model = info.GetMachineModel().c_str();
- LOG(LS_INFO) << "MachineModel: " << machine_model;
- bool known = true;
-#if defined(OSX)
- // Full list as of May 2012. Update when new OSX based models are added.
- known = talk_base::string_match(machine_model, "MacBookPro*") ||
- talk_base::string_match(machine_model, "MacBookAir*") ||
- talk_base::string_match(machine_model, "MacBook*") ||
- talk_base::string_match(machine_model, "MacPro*") ||
- talk_base::string_match(machine_model, "Macmini*") ||
- talk_base::string_match(machine_model, "iMac*") ||
- talk_base::string_match(machine_model, "Xserve*");
-#elif !defined(IOS)
- // All other machines return Not available.
- known = talk_base::string_match(info.GetMachineModel().c_str(),
- "Not available");
-#endif
- if (!known) {
- LOG(LS_WARNING) << "Machine Model Unknown: " << machine_model;
- }
-}
-
-// Tests maximum cpu clockrate.
-TEST(SystemInfoTest, CpuMaxCpuSpeed) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "MaxCpuSpeed: " << info.GetMaxCpuSpeed();
- EXPECT_GT(info.GetMaxCpuSpeed(), 0);
- EXPECT_LT(info.GetMaxCpuSpeed(), 100000); // 100 Ghz
-}
-
-// Tests current cpu clockrate.
-TEST(SystemInfoTest, CpuCurCpuSpeed) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "MaxCurSpeed: " << info.GetCurCpuSpeed();
- EXPECT_GT(info.GetCurCpuSpeed(), 0);
- EXPECT_LT(info.GetMaxCpuSpeed(), 100000);
-}
-
-// Tests physical memory size.
-TEST(SystemInfoTest, MemorySize) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "MemorySize: " << info.GetMemorySize();
- EXPECT_GT(info.GetMemorySize(), -1);
-}
-
-// Tests number of logical cpus available to the system.
-TEST(SystemInfoTest, MaxCpus) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "MaxCpus: " << info.GetMaxCpus();
- EXPECT_GT(info.GetMaxCpus(), 0);
-}
-
-// Tests number of physical cpus available to the system.
-TEST(SystemInfoTest, MaxPhysicalCpus) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "MaxPhysicalCpus: " << info.GetMaxPhysicalCpus();
- EXPECT_GT(info.GetMaxPhysicalCpus(), 0);
- EXPECT_LE(info.GetMaxPhysicalCpus(), info.GetMaxCpus());
-}
-
-// Tests number of logical cpus available to the process.
-TEST(SystemInfoTest, CurCpus) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CurCpus: " << info.GetCurCpus();
- EXPECT_GT(info.GetCurCpus(), 0);
- EXPECT_LE(info.GetCurCpus(), info.GetMaxCpus());
-}
-
-#ifdef CPU_X86
-// CPU family/model/stepping is only available on X86. The following tests
-// that they are set when running on x86 CPUs. Valid Family/Model/Stepping
-// values are non-zero on known CPUs.
-
-// Tests Intel CPU Family identification.
-TEST(SystemInfoTest, CpuFamily) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuFamily: " << info.GetCpuFamily();
- EXPECT_GT(info.GetCpuFamily(), 0);
-}
-
-// Tests Intel CPU Model identification.
-TEST(SystemInfoTest, CpuModel) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuModel: " << info.GetCpuModel();
- EXPECT_GT(info.GetCpuModel(), 0);
-}
-
-// Tests Intel CPU Stepping identification.
-TEST(SystemInfoTest, CpuStepping) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuStepping: " << info.GetCpuStepping();
- EXPECT_GT(info.GetCpuStepping(), 0);
-}
-#else // CPU_X86
-// If not running on x86 CPU the following tests expect the functions to
-// return 0.
-TEST(SystemInfoTest, CpuFamily) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuFamily: " << info.GetCpuFamily();
- EXPECT_EQ(0, info.GetCpuFamily());
-}
-
-// Tests Intel CPU Model identification.
-TEST(SystemInfoTest, CpuModel) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuModel: " << info.GetCpuModel();
- EXPECT_EQ(0, info.GetCpuModel());
-}
-
-// Tests Intel CPU Stepping identification.
-TEST(SystemInfoTest, CpuStepping) {
- talk_base::SystemInfo info;
- LOG(LS_INFO) << "CpuStepping: " << info.GetCpuStepping();
- EXPECT_EQ(0, info.GetCpuStepping());
-}
-#endif // CPU_X86
-
-#if WIN32 && !defined(EXCLUDE_D3D9)
-TEST(SystemInfoTest, GpuInfo) {
- talk_base::SystemInfo info;
- talk_base::SystemInfo::GpuInfo gi;
- EXPECT_TRUE(info.GetGpuInfo(&gi));
- LOG(LS_INFO) << "GpuDriver: " << gi.driver;
- EXPECT_FALSE(gi.driver.empty());
- LOG(LS_INFO) << "GpuDriverVersion: " << gi.driver_version;
- EXPECT_FALSE(gi.driver_version.empty());
-}
-#endif
diff --git a/base/task.cc b/base/task.cc
deleted file mode 100644
index c37797c..0000000
--- a/base/task.cc
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/task.h"
-#include "talk/base/common.h"
-#include "talk/base/taskrunner.h"
-
-namespace talk_base {
-
-int32 Task::unique_id_seed_ = 0;
-
-Task::Task(TaskParent *parent)
- : TaskParent(this, parent),
- state_(STATE_INIT),
- blocked_(false),
- done_(false),
- aborted_(false),
- busy_(false),
- error_(false),
- start_time_(0),
- timeout_time_(0),
- timeout_seconds_(0),
- timeout_suspended_(false) {
- unique_id_ = unique_id_seed_++;
-
- // sanity check that we didn't roll-over our id seed
- ASSERT(unique_id_ < unique_id_seed_);
-}
-
-Task::~Task() {
- // Is this task being deleted in the correct manner?
- ASSERT(!done_ || GetRunner()->is_ok_to_delete(this));
- ASSERT(state_ == STATE_INIT || done_);
- ASSERT(state_ == STATE_INIT || blocked_);
-
- // If the task is being deleted without being done, it
- // means that it hasn't been removed from its parent.
- // This happens if a task is deleted outside of TaskRunner.
- if (!done_) {
- Stop();
- }
-}
-
-int64 Task::CurrentTime() {
- return GetRunner()->CurrentTime();
-}
-
-int64 Task::ElapsedTime() {
- return CurrentTime() - start_time_;
-}
-
-void Task::Start() {
- if (state_ != STATE_INIT)
- return;
- // Set the start time before starting the task. Otherwise if the task
- // finishes quickly and deletes the Task object, setting start_time_
- // will crash.
- start_time_ = CurrentTime();
- GetRunner()->StartTask(this);
-}
-
-void Task::Step() {
- if (done_) {
-#ifdef _DEBUG
- // we do not know how !blocked_ happens when done_ - should be impossible.
- // But it causes problems, so in retail build, we force blocked_, and
- // under debug we assert.
- ASSERT(blocked_);
-#else
- blocked_ = true;
-#endif
- return;
- }
-
- // Async Error() was called
- if (error_) {
- done_ = true;
- state_ = STATE_ERROR;
- blocked_ = true;
-// obsolete - an errored task is not considered done now
-// SignalDone();
-
- Stop();
-#ifdef _DEBUG
- // verify that stop removed this from its parent
- ASSERT(!parent()->IsChildTask(this));
-#endif
- return;
- }
-
- busy_ = true;
- int new_state = Process(state_);
- busy_ = false;
-
- if (aborted_) {
- Abort(true); // no need to wake because we're awake
- return;
- }
-
- if (new_state == STATE_BLOCKED) {
- blocked_ = true;
- // Let the timeout continue
- } else {
- state_ = new_state;
- blocked_ = false;
- ResetTimeout();
- }
-
- if (new_state == STATE_DONE) {
- done_ = true;
- } else if (new_state == STATE_ERROR) {
- done_ = true;
- error_ = true;
- }
-
- if (done_) {
-// obsolete - call this yourself
-// SignalDone();
-
- Stop();
-#if _DEBUG
- // verify that stop removed this from its parent
- ASSERT(!parent()->IsChildTask(this));
-#endif
- blocked_ = true;
- }
-}
-
-void Task::Abort(bool nowake) {
- // Why only check for done_ (instead of "aborted_ || done_")?
- //
- // If aborted_ && !done_, it means the logic for aborting still
- // needs to be executed (because busy_ must have been true when
- // Abort() was previously called).
- if (done_)
- return;
- aborted_ = true;
- if (!busy_) {
- done_ = true;
- blocked_ = true;
- error_ = true;
-
- // "done_" is set before calling "Stop()" to ensure that this code
- // doesn't execute more than once (recursively) for the same task.
- Stop();
-#ifdef _DEBUG
- // verify that stop removed this from its parent
- ASSERT(!parent()->IsChildTask(this));
-#endif
- if (!nowake) {
- // WakeTasks to self-delete.
- // Don't call Wake() because it is a no-op after "done_" is set.
- // Even if Wake() did run, it clears "blocked_" which isn't desireable.
- GetRunner()->WakeTasks();
- }
- }
-}
-
-void Task::Wake() {
- if (done_)
- return;
- if (blocked_) {
- blocked_ = false;
- GetRunner()->WakeTasks();
- }
-}
-
-void Task::Error() {
- if (error_ || done_)
- return;
- error_ = true;
- Wake();
-}
-
-std::string Task::GetStateName(int state) const {
- switch (state) {
- case STATE_BLOCKED: return "BLOCKED";
- case STATE_INIT: return "INIT";
- case STATE_START: return "START";
- case STATE_DONE: return "DONE";
- case STATE_ERROR: return "ERROR";
- case STATE_RESPONSE: return "RESPONSE";
- }
- return "??";
-}
-
-int Task::Process(int state) {
- int newstate = STATE_ERROR;
-
- if (TimedOut()) {
- ClearTimeout();
- newstate = OnTimeout();
- SignalTimeout();
- } else {
- switch (state) {
- case STATE_INIT:
- newstate = STATE_START;
- break;
- case STATE_START:
- newstate = ProcessStart();
- break;
- case STATE_RESPONSE:
- newstate = ProcessResponse();
- break;
- case STATE_DONE:
- case STATE_ERROR:
- newstate = STATE_BLOCKED;
- break;
- }
- }
-
- return newstate;
-}
-
-void Task::Stop() {
- // No need to wake because we're either awake or in abort
- TaskParent::OnStopped(this);
-}
-
-void Task::set_timeout_seconds(const int timeout_seconds) {
- timeout_seconds_ = timeout_seconds;
- ResetTimeout();
-}
-
-bool Task::TimedOut() {
- return timeout_seconds_ &&
- timeout_time_ &&
- CurrentTime() >= timeout_time_;
-}
-
-void Task::ResetTimeout() {
- int64 previous_timeout_time = timeout_time_;
- bool timeout_allowed = (state_ != STATE_INIT)
- && (state_ != STATE_DONE)
- && (state_ != STATE_ERROR);
- if (timeout_seconds_ && timeout_allowed && !timeout_suspended_)
- timeout_time_ = CurrentTime() +
- (timeout_seconds_ * kSecToMsec * kMsecTo100ns);
- else
- timeout_time_ = 0;
-
- GetRunner()->UpdateTaskTimeout(this, previous_timeout_time);
-}
-
-void Task::ClearTimeout() {
- int64 previous_timeout_time = timeout_time_;
- timeout_time_ = 0;
- GetRunner()->UpdateTaskTimeout(this, previous_timeout_time);
-}
-
-void Task::SuspendTimeout() {
- if (!timeout_suspended_) {
- timeout_suspended_ = true;
- ResetTimeout();
- }
-}
-
-void Task::ResumeTimeout() {
- if (timeout_suspended_) {
- timeout_suspended_ = false;
- ResetTimeout();
- }
-}
-
-} // namespace talk_base
diff --git a/base/task.h b/base/task.h
deleted file mode 100644
index 10e6f5c..0000000
--- a/base/task.h
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TASK_H__
-#define TALK_BASE_TASK_H__
-
-#include <string>
-#include "talk/base/basictypes.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/taskparent.h"
-
-/////////////////////////////////////////////////////////////////////
-//
-// TASK
-//
-/////////////////////////////////////////////////////////////////////
-//
-// Task is a state machine infrastructure. States are pushed forward by
-// pushing forwards a TaskRunner that holds on to all Tasks. The purpose
-// of Task is threefold:
-//
-// (1) It manages ongoing work on the UI thread. Multitasking without
-// threads, keeping it easy, keeping it real. :-) It does this by
-// organizing a set of states for each task. When you return from your
-// Process*() function, you return an integer for the next state. You do
-// not go onto the next state yourself. Every time you enter a state,
-// you check to see if you can do anything yet. If not, you return
-// STATE_BLOCKED. If you _could_ do anything, do not return
-// STATE_BLOCKED - even if you end up in the same state, return
-// STATE_mysamestate. When you are done, return STATE_DONE and then the
-// task will self-delete sometime afterwards.
-//
-// (2) It helps you avoid all those reentrancy problems when you chain
-// too many triggers on one thread. Basically if you want to tell a task
-// to process something for you, you feed your task some information and
-// then you Wake() it. Don't tell it to process it right away. If it
-// might be working on something as you send it information, you may want
-// to have a queue in the task.
-//
-// (3) Finally it helps manage parent tasks and children. If a parent
-// task gets aborted, all the children tasks are too. The nice thing
-// about this, for example, is if you have one parent task that
-// represents, say, and Xmpp connection, then you can spawn a whole bunch
-// of infinite lifetime child tasks and now worry about cleaning them up.
-// When the parent task goes to STATE_DONE, the task engine will make
-// sure all those children are aborted and get deleted.
-//
-// Notice that Task has a few built-in states, e.g.,
-//
-// STATE_INIT - the task isn't running yet
-// STATE_START - the task is in its first state
-// STATE_RESPONSE - the task is in its second state
-// STATE_DONE - the task is done
-//
-// STATE_ERROR - indicates an error - we should audit the error code in
-// light of any usage of it to see if it should be improved. When I
-// first put down the task stuff I didn't have a good sense of what was
-// needed for Abort and Error, and now the subclasses of Task will ground
-// the design in a stronger way.
-//
-// STATE_NEXT - the first undefined state number. (like WM_USER) - you
-// can start defining more task states there.
-//
-// When you define more task states, just override Process(int state) and
-// add your own switch statement. If you want to delegate to
-// Task::Process, you can effectively delegate to its switch statement.
-// No fancy method pointers or such - this is all just pretty low tech,
-// easy to debug, and fast.
-//
-// Also notice that Task has some primitive built-in timeout functionality.
-//
-// A timeout is defined as "the task stays in STATE_BLOCKED longer than
-// timeout_seconds_."
-//
-// Descendant classes can override this behavior by calling the
-// various protected methods to change the timeout behavior. For
-// instance, a descendand might call SuspendTimeout() when it knows
-// that it isn't waiting for anything that might timeout, but isn't
-// yet in the STATE_DONE state.
-//
-
-namespace talk_base {
-
-// Executes a sequence of steps
-class Task : public TaskParent {
- public:
- Task(TaskParent *parent);
- virtual ~Task();
-
- int32 unique_id() { return unique_id_; }
-
- void Start();
- void Step();
- int GetState() const { return state_; }
- bool HasError() const { return (GetState() == STATE_ERROR); }
- bool Blocked() const { return blocked_; }
- bool IsDone() const { return done_; }
- int64 ElapsedTime();
-
- // Called from outside to stop task without any more callbacks
- void Abort(bool nowake = false);
-
- bool TimedOut();
-
- int64 timeout_time() const { return timeout_time_; }
- int timeout_seconds() const { return timeout_seconds_; }
- void set_timeout_seconds(int timeout_seconds);
-
- sigslot::signal0<> SignalTimeout;
-
- // Called inside the task to signal that the task may be unblocked
- void Wake();
-
- protected:
-
- enum {
- STATE_BLOCKED = -1,
- STATE_INIT = 0,
- STATE_START = 1,
- STATE_DONE = 2,
- STATE_ERROR = 3,
- STATE_RESPONSE = 4,
- STATE_NEXT = 5, // Subclasses which need more states start here and higher
- };
-
- // Called inside to advise that the task should wake and signal an error
- void Error();
-
- int64 CurrentTime();
-
- virtual std::string GetStateName(int state) const;
- virtual int Process(int state);
- virtual void Stop();
- virtual int ProcessStart() = 0;
- virtual int ProcessResponse() { return STATE_DONE; }
-
- void ResetTimeout();
- void ClearTimeout();
-
- void SuspendTimeout();
- void ResumeTimeout();
-
- protected:
- virtual int OnTimeout() {
- // by default, we are finished after timing out
- return STATE_DONE;
- }
-
- private:
- void Done();
-
- int state_;
- bool blocked_;
- bool done_;
- bool aborted_;
- bool busy_;
- bool error_;
- int64 start_time_;
- int64 timeout_time_;
- int timeout_seconds_;
- bool timeout_suspended_;
- int32 unique_id_;
-
- static int32 unique_id_seed_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TASK_H__
diff --git a/base/task_unittest.cc b/base/task_unittest.cc
deleted file mode 100644
index 0c4a7a2..0000000
--- a/base/task_unittest.cc
+++ /dev/null
@@ -1,562 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef POSIX
-#include <sys/time.h>
-#endif // POSIX
-
-// TODO: Remove this once the cause of sporadic failures in these
-// tests is tracked down.
-#include <iostream>
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif // WIN32
-
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/task.h"
-#include "talk/base/taskrunner.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-static int64 GetCurrentTime() {
- return static_cast<int64>(Time()) * 10000;
-}
-
-// feel free to change these numbers. Note that '0' won't work, though
-#define STUCK_TASK_COUNT 5
-#define HAPPY_TASK_COUNT 20
-
-// this is a generic timeout task which, when it signals timeout, will
-// include the unique ID of the task in the signal (we don't use this
-// in production code because we haven't yet had occasion to generate
-// an array of the same types of task)
-
-class IdTimeoutTask : public Task, public sigslot::has_slots<> {
- public:
- explicit IdTimeoutTask(TaskParent *parent) : Task(parent) {
- SignalTimeout.connect(this, &IdTimeoutTask::OnLocalTimeout);
- }
-
- sigslot::signal1<const int> SignalTimeoutId;
- sigslot::signal1<const int> SignalDoneId;
-
- virtual int ProcessStart() {
- return STATE_RESPONSE;
- }
-
- void OnLocalTimeout() {
- SignalTimeoutId(unique_id());
- }
-
- protected:
- virtual void Stop() {
- SignalDoneId(unique_id());
- Task::Stop();
- }
-};
-
-class StuckTask : public IdTimeoutTask {
- public:
- explicit StuckTask(TaskParent *parent) : IdTimeoutTask(parent) {}
- virtual int ProcessStart() {
- return STATE_BLOCKED;
- }
-};
-
-class HappyTask : public IdTimeoutTask {
- public:
- explicit HappyTask(TaskParent *parent) : IdTimeoutTask(parent) {
- time_to_perform_ = rand() % (STUCK_TASK_COUNT / 2);
- }
- virtual int ProcessStart() {
- if (ElapsedTime() > (time_to_perform_ * 1000 * 10000))
- return STATE_RESPONSE;
- else
- return STATE_BLOCKED;
- }
-
- private:
- int time_to_perform_;
-};
-
-// simple implementation of a task runner which uses Windows'
-// GetSystemTimeAsFileTime() to get the current clock ticks
-
-class MyTaskRunner : public TaskRunner {
- public:
- virtual void WakeTasks() { RunTasks(); }
- virtual int64 CurrentTime() {
- return GetCurrentTime();
- }
-
- bool timeout_change() const {
- return timeout_change_;
- }
-
- void clear_timeout_change() {
- timeout_change_ = false;
- }
- protected:
- virtual void OnTimeoutChange() {
- timeout_change_ = true;
- }
- bool timeout_change_;
-};
-
-//
-// this unit test is primarily concerned (for now) with the timeout
-// functionality in tasks. It works as follows:
-//
-// * Create a bunch of tasks, some "stuck" (ie., guaranteed to timeout)
-// and some "happy" (will immediately finish).
-// * Set the timeout on the "stuck" tasks to some number of seconds between
-// 1 and the number of stuck tasks
-// * Start all the stuck & happy tasks in random order
-// * Wait "number of stuck tasks" seconds and make sure everything timed out
-
-class TaskTest : public sigslot::has_slots<> {
- public:
- TaskTest() {}
-
- // no need to delete any tasks; the task runner owns them
- ~TaskTest() {}
-
- void Start() {
- // create and configure tasks
- for (int i = 0; i < STUCK_TASK_COUNT; ++i) {
- stuck_[i].task_ = new StuckTask(&task_runner_);
- stuck_[i].task_->SignalTimeoutId.connect(this,
- &TaskTest::OnTimeoutStuck);
- stuck_[i].timed_out_ = false;
- stuck_[i].xlat_ = stuck_[i].task_->unique_id();
- stuck_[i].task_->set_timeout_seconds(i + 1);
- LOG(LS_INFO) << "Task " << stuck_[i].xlat_ << " created with timeout "
- << stuck_[i].task_->timeout_seconds();
- }
-
- for (int i = 0; i < HAPPY_TASK_COUNT; ++i) {
- happy_[i].task_ = new HappyTask(&task_runner_);
- happy_[i].task_->SignalTimeoutId.connect(this,
- &TaskTest::OnTimeoutHappy);
- happy_[i].task_->SignalDoneId.connect(this,
- &TaskTest::OnDoneHappy);
- happy_[i].timed_out_ = false;
- happy_[i].xlat_ = happy_[i].task_->unique_id();
- }
-
- // start all the tasks in random order
- int stuck_index = 0;
- int happy_index = 0;
- for (int i = 0; i < STUCK_TASK_COUNT + HAPPY_TASK_COUNT; ++i) {
- if ((stuck_index < STUCK_TASK_COUNT) &&
- (happy_index < HAPPY_TASK_COUNT)) {
- if (rand() % 2 == 1) {
- stuck_[stuck_index++].task_->Start();
- } else {
- happy_[happy_index++].task_->Start();
- }
- } else if (stuck_index < STUCK_TASK_COUNT) {
- stuck_[stuck_index++].task_->Start();
- } else {
- happy_[happy_index++].task_->Start();
- }
- }
-
- for (int i = 0; i < STUCK_TASK_COUNT; ++i) {
- std::cout << "Stuck task #" << i << " timeout is " <<
- stuck_[i].task_->timeout_seconds() << " at " <<
- stuck_[i].task_->timeout_time() << std::endl;
- }
-
- // just a little self-check to make sure we started all the tasks
- ASSERT_EQ(STUCK_TASK_COUNT, stuck_index);
- ASSERT_EQ(HAPPY_TASK_COUNT, happy_index);
-
- // run the unblocked tasks
- LOG(LS_INFO) << "Running tasks";
- task_runner_.RunTasks();
-
- std::cout << "Start time is " << GetCurrentTime() << std::endl;
-
- // give all the stuck tasks time to timeout
- for (int i = 0; !task_runner_.AllChildrenDone() && i < STUCK_TASK_COUNT;
- ++i) {
- Thread::Current()->ProcessMessages(1000);
- for (int j = 0; j < HAPPY_TASK_COUNT; ++j) {
- if (happy_[j].task_) {
- happy_[j].task_->Wake();
- }
- }
- LOG(LS_INFO) << "Polling tasks";
- task_runner_.PollTasks();
- }
-
- // We see occasional test failures here due to the stuck tasks not having
- // timed-out yet, which seems like it should be impossible. To help track
- // this down we have added logging of the timing information, which we send
- // directly to stdout so that we get it in opt builds too.
- std::cout << "End time is " << GetCurrentTime() << std::endl;
- }
-
- void OnTimeoutStuck(const int id) {
- LOG(LS_INFO) << "Timed out task " << id;
-
- int i;
- for (i = 0; i < STUCK_TASK_COUNT; ++i) {
- if (stuck_[i].xlat_ == id) {
- stuck_[i].timed_out_ = true;
- stuck_[i].task_ = NULL;
- break;
- }
- }
-
- // getting a bad ID here is a failure, but let's continue
- // running to see what else might go wrong
- EXPECT_LT(i, STUCK_TASK_COUNT);
- }
-
- void OnTimeoutHappy(const int id) {
- int i;
- for (i = 0; i < HAPPY_TASK_COUNT; ++i) {
- if (happy_[i].xlat_ == id) {
- happy_[i].timed_out_ = true;
- happy_[i].task_ = NULL;
- break;
- }
- }
-
- // getting a bad ID here is a failure, but let's continue
- // running to see what else might go wrong
- EXPECT_LT(i, HAPPY_TASK_COUNT);
- }
-
- void OnDoneHappy(const int id) {
- int i;
- for (i = 0; i < HAPPY_TASK_COUNT; ++i) {
- if (happy_[i].xlat_ == id) {
- happy_[i].task_ = NULL;
- break;
- }
- }
-
- // getting a bad ID here is a failure, but let's continue
- // running to see what else might go wrong
- EXPECT_LT(i, HAPPY_TASK_COUNT);
- }
-
- void check_passed() {
- EXPECT_TRUE(task_runner_.AllChildrenDone());
-
- // make sure none of our happy tasks timed out
- for (int i = 0; i < HAPPY_TASK_COUNT; ++i) {
- EXPECT_FALSE(happy_[i].timed_out_);
- }
-
- // make sure all of our stuck tasks timed out
- for (int i = 0; i < STUCK_TASK_COUNT; ++i) {
- EXPECT_TRUE(stuck_[i].timed_out_);
- if (!stuck_[i].timed_out_) {
- std::cout << "Stuck task #" << i << " timeout is at "
- << stuck_[i].task_->timeout_time() << std::endl;
- }
- }
-
- std::cout.flush();
- }
-
- private:
- struct TaskInfo {
- IdTimeoutTask *task_;
- bool timed_out_;
- int xlat_;
- };
-
- MyTaskRunner task_runner_;
- TaskInfo stuck_[STUCK_TASK_COUNT];
- TaskInfo happy_[HAPPY_TASK_COUNT];
-};
-
-TEST(start_task_test, Timeout) {
- TaskTest task_test;
- task_test.Start();
- task_test.check_passed();
-}
-
-// Test for aborting the task while it is running
-
-class AbortTask : public Task {
- public:
- explicit AbortTask(TaskParent *parent) : Task(parent) {
- set_timeout_seconds(1);
- }
-
- virtual int ProcessStart() {
- Abort();
- return STATE_NEXT;
- }
- private:
- DISALLOW_EVIL_CONSTRUCTORS(AbortTask);
-};
-
-class TaskAbortTest : public sigslot::has_slots<> {
- public:
- TaskAbortTest() {}
-
- // no need to delete any tasks; the task runner owns them
- ~TaskAbortTest() {}
-
- void Start() {
- Task *abort_task = new AbortTask(&task_runner_);
- abort_task->SignalTimeout.connect(this, &TaskAbortTest::OnTimeout);
- abort_task->Start();
-
- // run the task
- task_runner_.RunTasks();
- }
-
- private:
- void OnTimeout() {
- FAIL() << "Task timed out instead of aborting.";
- }
-
- MyTaskRunner task_runner_;
- DISALLOW_EVIL_CONSTRUCTORS(TaskAbortTest);
-};
-
-TEST(start_task_test, Abort) {
- TaskAbortTest abort_test;
- abort_test.Start();
-}
-
-// Test for aborting a task to verify that it does the Wake operation
-// which gets it deleted.
-
-class SetBoolOnDeleteTask : public Task {
- public:
- SetBoolOnDeleteTask(TaskParent *parent, bool *set_when_deleted)
- : Task(parent),
- set_when_deleted_(set_when_deleted) {
- EXPECT_TRUE(NULL != set_when_deleted);
- EXPECT_FALSE(*set_when_deleted);
- }
-
- virtual ~SetBoolOnDeleteTask() {
- *set_when_deleted_ = true;
- }
-
- virtual int ProcessStart() {
- return STATE_BLOCKED;
- }
-
- private:
- bool* set_when_deleted_;
- DISALLOW_EVIL_CONSTRUCTORS(SetBoolOnDeleteTask);
-};
-
-class AbortShouldWakeTest : public sigslot::has_slots<> {
- public:
- AbortShouldWakeTest() {}
-
- // no need to delete any tasks; the task runner owns them
- ~AbortShouldWakeTest() {}
-
- void Start() {
- bool task_deleted = false;
- Task *task_to_abort = new SetBoolOnDeleteTask(&task_runner_, &task_deleted);
- task_to_abort->Start();
-
- // Task::Abort() should call TaskRunner::WakeTasks(). WakeTasks calls
- // TaskRunner::RunTasks() immediately which should delete the task.
- task_to_abort->Abort();
- EXPECT_TRUE(task_deleted);
-
- if (!task_deleted) {
- // avoid a crash (due to referencing a local variable)
- // if the test fails.
- task_runner_.RunTasks();
- }
- }
-
- private:
- void OnTimeout() {
- FAIL() << "Task timed out instead of aborting.";
- }
-
- MyTaskRunner task_runner_;
- DISALLOW_EVIL_CONSTRUCTORS(AbortShouldWakeTest);
-};
-
-TEST(start_task_test, AbortShouldWake) {
- AbortShouldWakeTest abort_should_wake_test;
- abort_should_wake_test.Start();
-}
-
-// Validate that TaskRunner's OnTimeoutChange gets called appropriately
-// * When a task calls UpdateTaskTimeout
-// * When the next timeout task time, times out
-class TimeoutChangeTest : public sigslot::has_slots<> {
- public:
- TimeoutChangeTest()
- : task_count_(ARRAY_SIZE(stuck_tasks_)) {}
-
- // no need to delete any tasks; the task runner owns them
- ~TimeoutChangeTest() {}
-
- void Start() {
- for (int i = 0; i < task_count_; ++i) {
- stuck_tasks_[i] = new StuckTask(&task_runner_);
- stuck_tasks_[i]->set_timeout_seconds(i + 2);
- stuck_tasks_[i]->SignalTimeoutId.connect(this,
- &TimeoutChangeTest::OnTimeoutId);
- }
-
- for (int i = task_count_ - 1; i >= 0; --i) {
- stuck_tasks_[i]->Start();
- }
- task_runner_.clear_timeout_change();
-
- // At this point, our timeouts are set as follows
- // task[0] is 2 seconds, task[1] at 3 seconds, etc.
-
- stuck_tasks_[0]->set_timeout_seconds(2);
- // Now, task[0] is 2 seconds, task[1] at 3 seconds...
- // so timeout change shouldn't be called.
- EXPECT_FALSE(task_runner_.timeout_change());
- task_runner_.clear_timeout_change();
-
- stuck_tasks_[0]->set_timeout_seconds(1);
- // task[0] is 1 seconds, task[1] at 3 seconds...
- // The smallest timeout got smaller so timeout change be called.
- EXPECT_TRUE(task_runner_.timeout_change());
- task_runner_.clear_timeout_change();
-
- stuck_tasks_[1]->set_timeout_seconds(2);
- // task[0] is 1 seconds, task[1] at 2 seconds...
- // The smallest timeout is still 1 second so no timeout change.
- EXPECT_FALSE(task_runner_.timeout_change());
- task_runner_.clear_timeout_change();
-
- while (task_count_ > 0) {
- int previous_count = task_count_;
- task_runner_.PollTasks();
- if (previous_count != task_count_) {
- // We only get here when a task times out. When that
- // happens, the timeout change should get called because
- // the smallest timeout is now in the past.
- EXPECT_TRUE(task_runner_.timeout_change());
- task_runner_.clear_timeout_change();
- }
- Thread::Current()->socketserver()->Wait(500, false);
- }
- }
-
- private:
- void OnTimeoutId(const int id) {
- for (int i = 0; i < ARRAY_SIZE(stuck_tasks_); ++i) {
- if (stuck_tasks_[i] && stuck_tasks_[i]->unique_id() == id) {
- task_count_--;
- stuck_tasks_[i] = NULL;
- break;
- }
- }
- }
-
- MyTaskRunner task_runner_;
- StuckTask* (stuck_tasks_[3]);
- int task_count_;
- DISALLOW_EVIL_CONSTRUCTORS(TimeoutChangeTest);
-};
-
-TEST(start_task_test, TimeoutChange) {
- TimeoutChangeTest timeout_change_test;
- timeout_change_test.Start();
-}
-
-class DeleteTestTaskRunner : public TaskRunner {
- public:
- DeleteTestTaskRunner() {
- }
- virtual void WakeTasks() { }
- virtual int64 CurrentTime() {
- return GetCurrentTime();
- }
- private:
- DISALLOW_EVIL_CONSTRUCTORS(DeleteTestTaskRunner);
-};
-
-TEST(unstarted_task_test, DeleteTask) {
- // This test ensures that we don't
- // crash if a task is deleted without running it.
- DeleteTestTaskRunner task_runner;
- HappyTask* happy_task = new HappyTask(&task_runner);
- happy_task->Start();
-
- // try deleting the task directly
- HappyTask* child_happy_task = new HappyTask(happy_task);
- delete child_happy_task;
-
- // run the unblocked tasks
- task_runner.RunTasks();
-}
-
-TEST(unstarted_task_test, DoNotDeleteTask1) {
- // This test ensures that we don't
- // crash if a task runner is deleted without
- // running a certain task.
- DeleteTestTaskRunner task_runner;
- HappyTask* happy_task = new HappyTask(&task_runner);
- happy_task->Start();
-
- HappyTask* child_happy_task = new HappyTask(happy_task);
- child_happy_task->Start();
-
- // Never run the tasks
-}
-
-TEST(unstarted_task_test, DoNotDeleteTask2) {
- // This test ensures that we don't
- // crash if a taskrunner is delete with a
- // task that has never been started.
- DeleteTestTaskRunner task_runner;
- HappyTask* happy_task = new HappyTask(&task_runner);
- happy_task->Start();
-
- // Do not start the task.
- // Note: this leaks memory, so don't do this.
- // Instead, always run your tasks or delete them.
- new HappyTask(happy_task);
-
- // run the unblocked tasks
- task_runner.RunTasks();
-}
-
-} // namespace talk_base
diff --git a/base/taskparent.cc b/base/taskparent.cc
deleted file mode 100644
index f05ee82..0000000
--- a/base/taskparent.cc
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <algorithm>
-
-#include "talk/base/taskparent.h"
-
-#include "talk/base/task.h"
-#include "talk/base/taskrunner.h"
-
-namespace talk_base {
-
-TaskParent::TaskParent(Task* derived_instance, TaskParent *parent)
- : parent_(parent) {
- ASSERT(derived_instance != NULL);
- ASSERT(parent != NULL);
- runner_ = parent->GetRunner();
- parent_->AddChild(derived_instance);
- Initialize();
-}
-
-TaskParent::TaskParent(TaskRunner *derived_instance)
- : parent_(NULL),
- runner_(derived_instance) {
- ASSERT(derived_instance != NULL);
- Initialize();
-}
-
-// Does common initialization of member variables
-void TaskParent::Initialize() {
- children_.reset(new ChildSet());
- child_error_ = false;
-}
-
-void TaskParent::AddChild(Task *child) {
- children_->insert(child);
-}
-
-#ifdef _DEBUG
-bool TaskParent::IsChildTask(Task *task) {
- ASSERT(task != NULL);
- return task->parent_ == this && children_->find(task) != children_->end();
-}
-#endif
-
-bool TaskParent::AllChildrenDone() {
- for (ChildSet::iterator it = children_->begin();
- it != children_->end();
- ++it) {
- if (!(*it)->IsDone())
- return false;
- }
- return true;
-}
-
-bool TaskParent::AnyChildError() {
- return child_error_;
-}
-
-void TaskParent::AbortAllChildren() {
- if (children_->size() > 0) {
-#ifdef _DEBUG
- runner_->IncrementAbortCount();
-#endif
-
- ChildSet copy = *children_;
- for (ChildSet::iterator it = copy.begin(); it != copy.end(); ++it) {
- (*it)->Abort(true); // Note we do not wake
- }
-
-#ifdef _DEBUG
- runner_->DecrementAbortCount();
-#endif
- }
-}
-
-void TaskParent::OnStopped(Task *task) {
- AbortAllChildren();
- parent_->OnChildStopped(task);
-}
-
-void TaskParent::OnChildStopped(Task *child) {
- if (child->HasError())
- child_error_ = true;
- children_->erase(child);
-}
-
-} // namespace talk_base
diff --git a/base/taskparent.h b/base/taskparent.h
deleted file mode 100644
index e2093d6..0000000
--- a/base/taskparent.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TASKPARENT_H__
-#define TALK_BASE_TASKPARENT_H__
-
-#include <set>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-class Task;
-class TaskRunner;
-
-class TaskParent {
- public:
- TaskParent(Task *derived_instance, TaskParent *parent);
- explicit TaskParent(TaskRunner *derived_instance);
- virtual ~TaskParent() { }
-
- TaskParent *GetParent() { return parent_; }
- TaskRunner *GetRunner() { return runner_; }
-
- bool AllChildrenDone();
- bool AnyChildError();
-#ifdef _DEBUG
- bool IsChildTask(Task *task);
-#endif
-
- protected:
- void OnStopped(Task *task);
- void AbortAllChildren();
- TaskParent *parent() {
- return parent_;
- }
-
- private:
- void Initialize();
- void OnChildStopped(Task *child);
- void AddChild(Task *child);
-
- TaskParent *parent_;
- TaskRunner *runner_;
- bool child_error_;
- typedef std::set<Task *> ChildSet;
- scoped_ptr<ChildSet> children_;
- DISALLOW_EVIL_CONSTRUCTORS(TaskParent);
-};
-
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TASKPARENT_H__
diff --git a/base/taskrunner.cc b/base/taskrunner.cc
deleted file mode 100644
index 0c0816c..0000000
--- a/base/taskrunner.cc
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <algorithm>
-
-#include "talk/base/taskrunner.h"
-
-#include "talk/base/common.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/task.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-TaskRunner::TaskRunner()
- : TaskParent(this),
- next_timeout_task_(NULL),
- tasks_running_(false)
-#ifdef _DEBUG
- , abort_count_(0),
- deleting_task_(NULL)
-#endif
-{
-}
-
-TaskRunner::~TaskRunner() {
- // this kills and deletes children silently!
- AbortAllChildren();
- InternalRunTasks(true);
-}
-
-void TaskRunner::StartTask(Task * task) {
- tasks_.push_back(task);
-
- // the task we just started could be about to timeout --
- // make sure our "next timeout task" is correct
- UpdateTaskTimeout(task, 0);
-
- WakeTasks();
-}
-
-void TaskRunner::RunTasks() {
- InternalRunTasks(false);
-}
-
-void TaskRunner::InternalRunTasks(bool in_destructor) {
- // This shouldn't run while an abort is happening.
- // If that occurs, then tasks may be deleted in this method,
- // but pointers to them will still be in the
- // "ChildSet copy" in TaskParent::AbortAllChildren.
- // Subsequent use of those task may cause data corruption or crashes.
- ASSERT(!abort_count_);
- // Running continues until all tasks are Blocked (ok for a small # of tasks)
- if (tasks_running_) {
- return; // don't reenter
- }
-
- tasks_running_ = true;
-
- int64 previous_timeout_time = next_task_timeout();
-
- int did_run = true;
- while (did_run) {
- did_run = false;
- // use indexing instead of iterators because tasks_ may grow
- for (size_t i = 0; i < tasks_.size(); ++i) {
- while (!tasks_[i]->Blocked()) {
- tasks_[i]->Step();
- did_run = true;
- }
- }
- }
- // Tasks are deleted when running has paused
- bool need_timeout_recalc = false;
- for (size_t i = 0; i < tasks_.size(); ++i) {
- if (tasks_[i]->IsDone()) {
- Task* task = tasks_[i];
- if (next_timeout_task_ &&
- task->unique_id() == next_timeout_task_->unique_id()) {
- next_timeout_task_ = NULL;
- need_timeout_recalc = true;
- }
-
-#ifdef _DEBUG
- deleting_task_ = task;
-#endif
- delete task;
-#ifdef _DEBUG
- deleting_task_ = NULL;
-#endif
- tasks_[i] = NULL;
- }
- }
- // Finally, remove nulls
- std::vector<Task *>::iterator it;
- it = std::remove(tasks_.begin(),
- tasks_.end(),
- reinterpret_cast<Task *>(NULL));
-
- tasks_.erase(it, tasks_.end());
-
- if (need_timeout_recalc)
- RecalcNextTimeout(NULL);
-
- // Make sure that adjustments are done to account
- // for any timeout changes (but don't call this
- // while being destroyed since it calls a pure virtual function).
- if (!in_destructor)
- CheckForTimeoutChange(previous_timeout_time);
-
- tasks_running_ = false;
-}
-
-void TaskRunner::PollTasks() {
- // see if our "next potentially timed-out task" has indeed timed out.
- // If it has, wake it up, then queue up the next task in line
- // Repeat while we have new timed-out tasks.
- // TODO: We need to guard against WakeTasks not updating
- // next_timeout_task_. Maybe also add documentation in the header file once
- // we understand this code better.
- Task* old_timeout_task = NULL;
- while (next_timeout_task_ &&
- old_timeout_task != next_timeout_task_ &&
- next_timeout_task_->TimedOut()) {
- old_timeout_task = next_timeout_task_;
- next_timeout_task_->Wake();
- WakeTasks();
- }
-}
-
-int64 TaskRunner::next_task_timeout() const {
- if (next_timeout_task_) {
- return next_timeout_task_->timeout_time();
- }
- return 0;
-}
-
-// this function gets called frequently -- when each task changes
-// state to something other than DONE, ERROR or BLOCKED, it calls
-// ResetTimeout(), which will call this function to make sure that
-// the next timeout-able task hasn't changed. The logic in this function
-// prevents RecalcNextTimeout() from getting called in most cases,
-// effectively making the task scheduler O-1 instead of O-N
-
-void TaskRunner::UpdateTaskTimeout(Task* task,
- int64 previous_task_timeout_time) {
- ASSERT(task != NULL);
- int64 previous_timeout_time = next_task_timeout();
- bool task_is_timeout_task = next_timeout_task_ != NULL &&
- task->unique_id() == next_timeout_task_->unique_id();
- if (task_is_timeout_task) {
- previous_timeout_time = previous_task_timeout_time;
- }
-
- // if the relevant task has a timeout, then
- // check to see if it's closer than the current
- // "about to timeout" task
- if (task->timeout_time()) {
- if (next_timeout_task_ == NULL ||
- (task->timeout_time() <= next_timeout_task_->timeout_time())) {
- next_timeout_task_ = task;
- }
- } else if (task_is_timeout_task) {
- // otherwise, if the task doesn't have a timeout,
- // and it used to be our "about to timeout" task,
- // walk through all the tasks looking for the real
- // "about to timeout" task
- RecalcNextTimeout(task);
- }
-
- // Note when task_running_, then the running routine
- // (TaskRunner::InternalRunTasks) is responsible for calling
- // CheckForTimeoutChange.
- if (!tasks_running_) {
- CheckForTimeoutChange(previous_timeout_time);
- }
-}
-
-void TaskRunner::RecalcNextTimeout(Task *exclude_task) {
- // walk through all the tasks looking for the one
- // which satisfies the following:
- // it's not finished already
- // we're not excluding it
- // it has the closest timeout time
-
- int64 next_timeout_time = 0;
- next_timeout_task_ = NULL;
-
- for (size_t i = 0; i < tasks_.size(); ++i) {
- Task *task = tasks_[i];
- // if the task isn't complete, and it actually has a timeout time
- if (!task->IsDone() && (task->timeout_time() > 0))
- // if it doesn't match our "exclude" task
- if (exclude_task == NULL ||
- exclude_task->unique_id() != task->unique_id())
- // if its timeout time is sooner than our current timeout time
- if (next_timeout_time == 0 ||
- task->timeout_time() <= next_timeout_time) {
- // set this task as our next-to-timeout
- next_timeout_time = task->timeout_time();
- next_timeout_task_ = task;
- }
- }
-}
-
-void TaskRunner::CheckForTimeoutChange(int64 previous_timeout_time) {
- int64 next_timeout = next_task_timeout();
- bool timeout_change = (previous_timeout_time == 0 && next_timeout != 0) ||
- next_timeout < previous_timeout_time ||
- (previous_timeout_time <= CurrentTime() &&
- previous_timeout_time != next_timeout);
- if (timeout_change) {
- OnTimeoutChange();
- }
-}
-
-} // namespace talk_base
diff --git a/base/taskrunner.h b/base/taskrunner.h
deleted file mode 100644
index f34a609..0000000
--- a/base/taskrunner.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TASKRUNNER_H__
-#define TALK_BASE_TASKRUNNER_H__
-
-#include <vector>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/taskparent.h"
-
-namespace talk_base {
-class Task;
-
-const int64 kSecToMsec = 1000;
-const int64 kMsecTo100ns = 10000;
-const int64 kSecTo100ns = kSecToMsec * kMsecTo100ns;
-
-class TaskRunner : public TaskParent, public sigslot::has_slots<> {
- public:
- TaskRunner();
- virtual ~TaskRunner();
-
- virtual void WakeTasks() = 0;
-
- // Returns the current time in 100ns units. It is used for
- // determining timeouts. The origin is not important, only
- // the units and that rollover while the computer is running.
- //
- // On Windows, GetSystemTimeAsFileTime is the typical implementation.
- virtual int64 CurrentTime() = 0 ;
-
- void StartTask(Task *task);
- void RunTasks();
- void PollTasks();
-
- void UpdateTaskTimeout(Task *task, int64 previous_task_timeout_time);
-
-#ifdef _DEBUG
- bool is_ok_to_delete(Task* task) {
- return task == deleting_task_;
- }
-
- void IncrementAbortCount() {
- ++abort_count_;
- }
-
- void DecrementAbortCount() {
- --abort_count_;
- }
-#endif
-
- // Returns the next absolute time when a task times out
- // OR "0" if there is no next timeout.
- int64 next_task_timeout() const;
-
- protected:
- // The primary usage of this method is to know if
- // a callback timer needs to be set-up or adjusted.
- // This method will be called
- // * when the next_task_timeout() becomes a smaller value OR
- // * when next_task_timeout() has changed values and the previous
- // value is in the past.
- //
- // If the next_task_timeout moves to the future, this method will *not*
- // get called (because it subclass should check next_task_timeout()
- // when its timer goes off up to see if it needs to set-up a new timer).
- //
- // Note that this maybe called conservatively. In that it may be
- // called when no time change has happened.
- virtual void OnTimeoutChange() {
- // by default, do nothing.
- }
-
- private:
- void InternalRunTasks(bool in_destructor);
- void CheckForTimeoutChange(int64 previous_timeout_time);
-
- std::vector<Task *> tasks_;
- Task *next_timeout_task_;
- bool tasks_running_;
-#ifdef _DEBUG
- int abort_count_;
- Task* deleting_task_;
-#endif
-
- void RecalcNextTimeout(Task *exclude_task);
-};
-
-} // namespace talk_base
-
-#endif // TASK_BASE_TASKRUNNER_H__
diff --git a/base/template_util.h b/base/template_util.h
deleted file mode 100644
index 00f1d7d..0000000
--- a/base/template_util.h
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TALK_BASE_TEMPLATE_UTIL_H_
-#define TALK_BASE_TEMPLATE_UTIL_H_
-
-#include <stddef.h> // For size_t.
-
-namespace talk_base {
-
-// template definitions from tr1
-
-template<class T, T v>
-struct integral_constant {
- static const T value = v;
- typedef T value_type;
- typedef integral_constant<T, v> type;
-};
-
-template <class T, T v> const T integral_constant<T, v>::value;
-
-typedef integral_constant<bool, true> true_type;
-typedef integral_constant<bool, false> false_type;
-
-template <class T> struct is_pointer : false_type {};
-template <class T> struct is_pointer<T*> : true_type {};
-
-template <class T, class U> struct is_same : public false_type {};
-template <class T> struct is_same<T,T> : true_type {};
-
-template<class> struct is_array : public false_type {};
-template<class T, size_t n> struct is_array<T[n]> : public true_type {};
-template<class T> struct is_array<T[]> : public true_type {};
-
-template <class T> struct is_non_const_reference : false_type {};
-template <class T> struct is_non_const_reference<T&> : true_type {};
-template <class T> struct is_non_const_reference<const T&> : false_type {};
-
-template <class T> struct is_void : false_type {};
-template <> struct is_void<void> : true_type {};
-
-namespace internal {
-
-// Types YesType and NoType are guaranteed such that sizeof(YesType) <
-// sizeof(NoType).
-typedef char YesType;
-
-struct NoType {
- YesType dummy[2];
-};
-
-// This class is an implementation detail for is_convertible, and you
-// don't need to know how it works to use is_convertible. For those
-// who care: we declare two different functions, one whose argument is
-// of type To and one with a variadic argument list. We give them
-// return types of different size, so we can use sizeof to trick the
-// compiler into telling us which function it would have chosen if we
-// had called it with an argument of type From. See Alexandrescu's
-// _Modern C++ Design_ for more details on this sort of trick.
-
-struct ConvertHelper {
- template <typename To>
- static YesType Test(To);
-
- template <typename To>
- static NoType Test(...);
-
- template <typename From>
- static From& Create();
-};
-
-// Used to determine if a type is a struct/union/class. Inspired by Boost's
-// is_class type_trait implementation.
-struct IsClassHelper {
- template <typename C>
- static YesType Test(void(C::*)(void));
-
- template <typename C>
- static NoType Test(...);
-};
-
-} // namespace internal
-
-// Inherits from true_type if From is convertible to To, false_type otherwise.
-//
-// Note that if the type is convertible, this will be a true_type REGARDLESS
-// of whether or not the conversion would emit a warning.
-template <typename From, typename To>
-struct is_convertible
- : integral_constant<bool,
- sizeof(internal::ConvertHelper::Test<To>(
- internal::ConvertHelper::Create<From>())) ==
- sizeof(internal::YesType)> {
-};
-
-template <typename T>
-struct is_class
- : integral_constant<bool,
- sizeof(internal::IsClassHelper::Test<T>(0)) ==
- sizeof(internal::YesType)> {
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TEMPLATE_UTIL_H_
diff --git a/base/testbase64.h b/base/testbase64.h
deleted file mode 100644
index 39dd00c..0000000
--- a/base/testbase64.h
+++ /dev/null
@@ -1,5 +0,0 @@
-/* This file was generated by googleclient/talk/binary2header.sh */
-
-static unsigned char testbase64[] = {
-0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xe1, 0x0d, 0x07, 0x45, 0x78, 0x69, 0x66, 0x00, 0x00, 0x4d, 0x4d, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x01, 0x0e, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x9e, 0x01, 0x0f, 0x00, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0xbe, 0x01, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0xc3, 0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x1a, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xcc, 0x01, 0x1b, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xd4, 0x01, 0x28, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x01, 0x31, 0x00, 0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0xdc, 0x01, 0x32, 0x00, 0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0xf0, 0x01, 0x3c, 0x00, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x01, 0x04, 0x02, 0x13, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x87, 0x69, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x14, 0x00, 0x00, 0x02, 0xc4, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x53, 0x4f, 0x4e, 0x59, 0x00, 0x44, 0x53, 0x43, 0x2d, 0x50, 0x32, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x50, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x20, 0x37, 0x2e, 0x30, 0x00, 0x32, 0x30, 0x30, 0x37, 0x3a, 0x30, 0x31, 0x3a, 0x33, 0x30, 0x20, 0x32, 0x33, 0x3a, 0x31, 0x30, 0x3a, 0x30, 0x34, 0x00, 0x4d, 0x61, 0x63, 0x20, 0x4f, 0x53, 0x20, 0x58, 0x20, 0x31, 0x30, 0x2e, 0x34, 0x2e, 0x38, 0x00, 0x00, 0x1c, 0x82, 0x9a, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x6a, 0x82, 0x9d, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x72, 0x88, 0x22, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x88, 0x27, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x64, 0x00, 0x00, 0x90, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x30, 0x32, 0x32, 0x30, 0x90, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x02, 0x7a, 0x90, 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x02, 0x8e, 0x91, 0x01, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x00, 0x91, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0xa2, 0x92, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0xaa, 0x92, 0x05, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0xb2, 0x92, 0x07, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x92, 0x08, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x92, 0x09, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0f, 0x00, 0x00, 0x92, 0x0a, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0xba, 0xa0, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x30, 0x31, 0x30, 0x30, 0xa0, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0x00, 0x00, 0xa0, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0xa0, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0xa3, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0xa3, 0x01, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0xa4, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x06, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x08, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x09, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xa4, 0x0a, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x0a, 0x32, 0x30, 0x30, 0x37, 0x3a, 0x30, 0x31, 0x3a, 0x32, 0x30, 0x20, 0x32, 0x33, 0x3a, 0x30, 0x35, 0x3a, 0x35, 0x32, 0x00, 0x32, 0x30, 0x30, 0x37, 0x3a, 0x30, 0x31, 0x3a, 0x32, 0x30, 0x20, 0x32, 0x33, 0x3a, 0x30, 0x35, 0x3a, 0x35, 0x32, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x00, 0x00, 0x01, 0x1a, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0x12, 0x01, 0x1b, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0x1a, 0x01, 0x28, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x02, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0x22, 0x02, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x09, 0xdd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xed, 0x00, 0x0c, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x5f, 0x43, 0x4d, 0x00, 0x02, 0xff, 0xee, 0x00, 0x0e, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x00, 0x64, 0x80, 0x00, 0x00, 0x00, 0x01, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x0c, 0x08, 0x08, 0x08, 0x09, 0x08, 0x0c, 0x09, 0x09, 0x0c, 0x11, 0x0b, 0x0a, 0x0b, 0x11, 0x15, 0x0f, 0x0c, 0x0c, 0x0f, 0x15, 0x18, 0x13, 0x13, 0x15, 0x13, 0x13, 0x18, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x01, 0x0d, 0x0b, 0x0b, 0x0d, 0x0e, 0x0d, 0x10, 0x0e, 0x0e, 0x10, 0x14, 0x0e, 0x0e, 0x0e, 0x14, 0x14, 0x0e, 0x0e, 0x0e, 0x0e, 0x14, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x64, 0x00, 0x64, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xdd, 0x00, 0x04, 0x00, 0x07, 0xff, 0xc4, 0x01, 0x3f, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x02, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x01, 0x04, 0x01, 0x03, 0x02, 0x04, 0x02, 0x05, 0x07, 0x06, 0x08, 0x05, 0x03, 0x0c, 0x33, 0x01, 0x00, 0x02, 0x11, 0x03, 0x04, 0x21, 0x12, 0x31, 0x05, 0x41, 0x51, 0x61, 0x13, 0x22, 0x71, 0x81, 0x32, 0x06, 0x14, 0x91, 0xa1, 0xb1, 0x42, 0x23, 0x24, 0x15, 0x52, 0xc1, 0x62, 0x33, 0x34, 0x72, 0x82, 0xd1, 0x43, 0x07, 0x25, 0x92, 0x53, 0xf0, 0xe1, 0xf1, 0x63, 0x73, 0x35, 0x16, 0xa2, 0xb2, 0x83, 0x26, 0x44, 0x93, 0x54, 0x64, 0x45, 0xc2, 0xa3, 0x74, 0x36, 0x17, 0xd2, 0x55, 0xe2, 0x65, 0xf2, 0xb3, 0x84, 0xc3, 0xd3, 0x75, 0xe3, 0xf3, 0x46, 0x27, 0x94, 0xa4, 0x85, 0xb4, 0x95, 0xc4, 0xd4, 0xe4, 0xf4, 0xa5, 0xb5, 0xc5, 0xd5, 0xe5, 0xf5, 0x56, 0x66, 0x76, 0x86, 0x96, 0xa6, 0xb6, 0xc6, 0xd6, 0xe6, 0xf6, 0x37, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xa7, 0xb7, 0xc7, 0xd7, 0xe7, 0xf7, 0x11, 0x00, 0x02, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x05, 0x06, 0x07, 0x07, 0x06, 0x05, 0x35, 0x01, 0x00, 0x02, 0x11, 0x03, 0x21, 0x31, 0x12, 0x04, 0x41, 0x51, 0x61, 0x71, 0x22, 0x13, 0x05, 0x32, 0x81, 0x91, 0x14, 0xa1, 0xb1, 0x42, 0x23, 0xc1, 0x52, 0xd1, 0xf0, 0x33, 0x24, 0x62, 0xe1, 0x72, 0x82, 0x92, 0x43, 0x53, 0x15, 0x63, 0x73, 0x34, 0xf1, 0x25, 0x06, 0x16, 0xa2, 0xb2, 0x83, 0x07, 0x26, 0x35, 0xc2, 0xd2, 0x44, 0x93, 0x54, 0xa3, 0x17, 0x64, 0x45, 0x55, 0x36, 0x74, 0x65, 0xe2, 0xf2, 0xb3, 0x84, 0xc3, 0xd3, 0x75, 0xe3, 0xf3, 0x46, 0x94, 0xa4, 0x85, 0xb4, 0x95, 0xc4, 0xd4, 0xe4, 0xf4, 0xa5, 0xb5, 0xc5, 0xd5, 0xe5, 0xf5, 0x56, 0x66, 0x76, 0x86, 0x96, 0xa6, 0xb6, 0xc6, 0xd6, 0xe6, 0xf6, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xa7, 0xb7, 0xc7, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf2, 0xed, 0xb2, 0x8d, 0x4d, 0x45, 0xcd, 0x2f, 0x3f, 0x44, 0x68, 0x93, 0xc3, 0x58, 0xc8, 0xf1, 0x1f, 0x8a, 0x33, 0x86, 0xda, 0x58, 0xc1, 0xa0, 0x02, 0x4f, 0xc4, 0xa1, 0x69, 0xa5, 0x9b, 0x5b, 0x4b, 0x84, 0x73, 0xdf, 0xc9, 0x15, 0xf8, 0xe3, 0xd1, 0x0e, 0x07, 0x93, 0xf3, 0xd1, 0x0f, 0x1c, 0x17, 0xef, 0x2e, 0x3b, 0x5b, 0xdc, 0xff, 0x00, 0xdf, 0x42, 0xbf, 0x8f, 0x8e, 0xdc, 0x82, 0xca, 0xd8, 0x37, 0x11, 0xa9, 0x3d, 0x82, 0x69, 0x2b, 0xc4, 0x6d, 0xc9, 0x75, 0x25, 0xbc, 0xf7, 0xec, 0xa1, 0xb5, 0x74, 0x19, 0x5d, 0x2e, 0x8a, 0x9a, 0x4b, 0x89, 0x7d, 0xc4, 0x68, 0xc6, 0xf6, 0xfe, 0xb2, 0xa0, 0x30, 0x1d, 0x60, 0x86, 0x88, 0x8d, 0x49, 0x3e, 0x01, 0x11, 0x20, 0xa3, 0x8c, 0xb9, 0xb1, 0xaa, 0x62, 0xad, 0xbf, 0x18, 0x97, 0x43, 0x47, 0x1d, 0xd2, 0xaf, 0x04, 0xd9, 0xb8, 0xc8, 0x0d, 0x68, 0xe4, 0xf7, 0x3e, 0x48, 0xf1, 0x05, 0xbc, 0x25, 0xaa, 0x07, 0x71, 0xd9, 0x14, 0x78, 0xf6, 0x49, 0xb5, 0x90, 0xfd, 0xa7, 0xc6, 0x14, 0xfd, 0x1b, 0x1c, 0xff, 0x00, 0x4d, 0x8d, 0x2e, 0x73, 0x8c, 0x35, 0xa3, 0x52, 0x4f, 0x92, 0x48, 0xa6, 0x1a, 0x24, 0xb6, 0x2a, 0xfa, 0xa5, 0x9e, 0x60, 0x64, 0x39, 0x94, 0x13, 0xcb, 0x27, 0x73, 0x80, 0xf3, 0x0c, 0xf6, 0xff, 0x00, 0xd2, 0x5a, 0x78, 0xbf, 0x53, 0x71, 0xf6, 0x01, 0x75, 0xb6, 0x97, 0x6a, 0x25, 0xa1, 0xad, 0x1f, 0xf4, 0xb7, 0x23, 0x48, 0xb7, 0x94, 0x84, 0x97, 0x5b, 0xff, 0x00, 0x32, 0xa9, 0xdd, 0xfc, 0xed, 0x9b, 0x7e, 0x0d, 0x9e, 0x52, 0x4a, 0x95, 0x61, 0xff, 0xd0, 0xf3, 0x3b, 0xa7, 0x70, 0xee, 0x01, 0x8f, 0xb9, 0x59, 0xfa, 0x7e, 0xdf, 0xe4, 0xc8, 0xf9, 0x2a, 0xc2, 0x5c, 0x63, 0xc3, 0x54, 0x67, 0x87, 0x6e, 0x10, 0x35, 0x68, 0xd4, 0x79, 0x1e, 0x53, 0x4a, 0xe0, 0xdc, 0xe9, 0xb8, 0x1f, 0x6a, 0xda, 0x6c, 0x25, 0x94, 0x37, 0xb0, 0xd0, 0xb8, 0xad, 0x67, 0xe4, 0x55, 0x8a, 0x5b, 0x8b, 0x82, 0xc0, 0x6f, 0x76, 0x80, 0x34, 0x49, 0x05, 0x2e, 0x9e, 0xc6, 0x1c, 0x66, 0x31, 0xba, 0x10, 0x23, 0xe0, 0xaf, 0xe1, 0x61, 0x53, 0x43, 0x8d, 0x81, 0xb3, 0x67, 0xef, 0x9e, 0x49, 0x2a, 0x12, 0x6c, 0xb6, 0x63, 0x1a, 0x0c, 0x31, 0xba, 0x55, 0xcd, 0xac, 0xfa, 0x8e, 0xdf, 0x91, 0x6e, 0x91, 0xd9, 0xb3, 0xc9, 0x73, 0x90, 0x7a, 0xab, 0x6a, 0xc2, 0xa4, 0x60, 0xe2, 0x8f, 0xd2, 0x38, 0x03, 0x7d, 0x9e, 0x0d, 0xff, 0x00, 0xcc, 0xd6, 0xd3, 0x6b, 0x71, 0x67, 0xd2, 0x3e, 0x64, 0x72, 0xab, 0xdb, 0x8d, 0x54, 0x39, 0xc5, 0x83, 0x6b, 0x3d, 0xee, 0x2e, 0xd4, 0x92, 0x3c, 0x4a, 0x56, 0xba, 0xb4, 0x79, 0x5c, 0xf7, 0xb2, 0x96, 0x6c, 0x8d, 0xaf, 0x80, 0x48, 0x3c, 0xf0, 0xb2, 0x1f, 0x63, 0x9c, 0xe9, 0x3f, 0x24, 0x5c, 0xdb, 0xdd, 0x76, 0x43, 0xde, 0xfd, 0x5c, 0xe3, 0x24, 0xfc, 0x50, 0x00, 0x93, 0x0a, 0x78, 0x8a, 0x0d, 0x49, 0xca, 0xcf, 0x93, 0x63, 0x1b, 0x7d, 0xd7, 0x57, 0x50, 0xd5, 0xef, 0x70, 0x6b, 0x4f, 0xc7, 0x45, 0xdb, 0x74, 0x9e, 0x8d, 0x5e, 0x33, 0x83, 0xd8, 0x37, 0xdd, 0xc3, 0xac, 0x3d, 0xbf, 0x92, 0xc5, 0x5b, 0xea, 0xbf, 0xd5, 0x62, 0xc0, 0xdc, 0xbc, 0xbd, 0x2d, 0x22, 0x5a, 0xcf, 0xdd, 0x69, 0xff, 0x00, 0xd1, 0x8e, 0x5d, 0xa5, 0x38, 0xb5, 0xb0, 0x00, 0xc6, 0xc4, 0x24, 0x4a, 0xd6, 0x8d, 0x18, 0x04, 0x49, 0x88, 0x9e, 0x55, 0xd6, 0x61, 0xb0, 0xc1, 0x70, 0x32, 0xdd, 0x3c, 0x95, 0xda, 0xf1, 0xfe, 0xf5, 0x62, 0xbc, 0x76, 0x8e, 0x75, 0x28, 0x02, 0xa2, 0xe7, 0x7d, 0x92, 0xb9, 0x84, 0x96, 0x96, 0xda, 0xf7, 0x70, 0x12, 0x4e, 0x5a, 0xff, 0x00, 0xff, 0xd1, 0xf3, 0x7a, 0x21, 0xaf, 0xde, 0xef, 0xa2, 0x22, 0x55, 0xfc, 0x5a, 0xbd, 0x42, 0xfb, 0x08, 0xfa, 0x67, 0x4f, 0x82, 0xcd, 0x6d, 0x85, 0xc0, 0x56, 0x3b, 0x90, 0xb7, 0xf0, 0x2a, 0x0e, 0x63, 0x58, 0x3b, 0xf2, 0xa3, 0x9e, 0x8c, 0xb8, 0x86, 0xbe, 0x49, 0xf1, 0x2c, 0x0c, 0x86, 0xb4, 0x4c, 0x69, 0xe4, 0xaf, 0x6e, 0xcc, 0x6b, 0x7d, 0x46, 0xb3, 0x70, 0xec, 0x38, 0x51, 0x7d, 0x02, 0x8a, 0xc7, 0xa6, 0xd9, 0x20, 0x68, 0x0f, 0x8f, 0x8a, 0xcf, 0xc9, 0xc2, 0xea, 0x59, 0x5b, 0x48, 0xb0, 0x91, 0xae, 0xe6, 0xc9, 0x03, 0xc9, 0x30, 0x51, 0x66, 0xd4, 0x0d, 0xad, 0xbd, 0x5f, 0x53, 0xcc, 0x6b, 0xb6, 0x90, 0x5a, 0x3b, 0x83, 0x0b, 0x43, 0x17, 0x31, 0xd6, 0xc3, 0x6e, 0x12, 0x3b, 0x79, 0xac, 0xc1, 0x89, 0x47, 0xd9, 0xe8, 0x63, 0x98, 0x45, 0xed, 0x6c, 0x5a, 0xf1, 0xa0, 0x27, 0xc5, 0x5b, 0xc3, 0x6f, 0xa6, 0xe0, 0x1c, 0x7d, 0xb3, 0xa2, 0x69, 0x34, 0x7b, 0xae, 0x1a, 0x8d, 0x45, 0x17, 0x9d, 0xeb, 0xfd, 0x21, 0xd8, 0xb9, 0xae, 0xb5, 0x80, 0xbb, 0x1e, 0xd2, 0x5c, 0xd7, 0x78, 0x13, 0xf9, 0xae, 0x4b, 0xea, 0xc7, 0x4a, 0x39, 0xbd, 0x55, 0xb3, 0xed, 0x66, 0x38, 0xf5, 0x09, 0x22, 0x41, 0x23, 0xe8, 0x37, 0xfb, 0x4b, 0xa1, 0xeb, 0xd6, 0xfe, 0x88, 0x31, 0xbf, 0x41, 0xc0, 0xee, 0xd2, 0x74, 0x02, 0x78, 0x53, 0xfa, 0x97, 0x43, 0x19, 0x85, 0x65, 0xff, 0x00, 0x9d, 0x71, 0x33, 0xe4, 0x1a, 0x7d, 0x8d, 0x53, 0x42, 0x56, 0x35, 0x6b, 0xe5, 0x80, 0x06, 0xc7, 0x57, 0xa7, 0xc4, 0xa9, 0xdb, 0xb6, 0x81, 0x1f, 0xeb, 0xd9, 0x69, 0x56, 0xc2, 0xd0, 0x00, 0xe5, 0x55, 0xc0, 0x12, 0xc2, 0xd7, 0x4e, 0xa2, 0x5a, 0x7c, 0x0a, 0xd0, 0x63, 0x9a, 0xd1, 0xaf, 0xd2, 0xe2, 0x3c, 0x12, 0x62, 0x66, 0xc6, 0x42, 0x23, 0x5a, 0x49, 0x8f, 0x10, 0xa2, 0xd2, 0x3e, 0x28, 0x9d, 0xc4, 0x88, 0x09, 0x29, 0x16, 0xc3, 0x3c, 0x24, 0x8d, 0xe6, 0x92, 0x72, 0x1f, 0xff, 0xd2, 0xf3, 0xbb, 0xb0, 0xfe, 0xcb, 0x99, 0xe9, 0xce, 0xf6, 0x88, 0x2d, 0x77, 0x91, 0x5b, 0x3d, 0x3d, 0xd0, 0xe6, 0x90, 0xa9, 0x65, 0x57, 0x38, 0x95, 0xdd, 0xcb, 0x9a, 0x7d, 0xce, 0xf2, 0x3f, 0x44, 0x23, 0x60, 0x58, 0x76, 0xe9, 0xca, 0x8c, 0xea, 0x1b, 0x31, 0x02, 0x32, 0x23, 0xea, 0xee, 0xb1, 0xcd, 0xb0, 0xc7, 0x87, 0x74, 0x7a, 0xeb, 0x70, 0x1a, 0x71, 0xe1, 0xfe, 0xe4, 0x1c, 0x1d, 0xae, 0xe5, 0x69, 0xd8, 0xfa, 0x99, 0x50, 0x0d, 0x1a, 0xf7, 0x2a, 0x3a, 0x0c, 0xf4, 0x1a, 0x8e, 0xc7, 0x27, 0x5d, 0xbf, 0x18, 0x41, 0xdc, 0xc2, 0xf0, 0x7f, 0x74, 0xf6, 0x3a, 0x22, 0x66, 0xdb, 0x68, 0xc6, 0x80, 0x48, 0x6b, 0x88, 0x06, 0x39, 0x0d, 0xee, 0xaa, 0x1f, 0xb3, 0xd5, 0x1b, 0x83, 0xd8, 0x3b, 0x38, 0x8f, 0x69, 0xfe, 0xdf, 0xd1, 0x4d, 0x29, 0xa1, 0x4c, 0x7a, 0xf4, 0xbf, 0xa7, 0x92, 0xcf, 0xa5, 0x20, 0x08, 0xf3, 0xf6, 0xff, 0x00, 0x15, 0xbb, 0xd1, 0x31, 0xd9, 0x5e, 0x3d, 0x75, 0x56, 0x36, 0x88, 0x00, 0x81, 0xe0, 0x16, 0x5e, 0x55, 0x74, 0x3f, 0x00, 0x9d, 0xe0, 0xcc, 0x69, 0xe7, 0x3a, 0x2d, 0xbe, 0x90, 0x00, 0xa9, 0xae, 0xef, 0x1f, 0x95, 0x4b, 0x0d, 0x9a, 0xdc, 0xc7, 0x45, 0xfe, 0xb1, 0x7d, 0x60, 0xa7, 0xa1, 0xe0, 0x1f, 0x4e, 0x1d, 0x99, 0x69, 0x02, 0x9a, 0xcf, 0x1f, 0xca, 0x7b, 0xbf, 0x90, 0xc5, 0xc2, 0xb3, 0xeb, 0x57, 0xd6, 0x03, 0x6b, 0xae, 0x39, 0xb6, 0x82, 0xe3, 0x31, 0xa1, 0x68, 0xf2, 0x6b, 0x5c, 0x12, 0xfa, 0xe1, 0x91, 0x66, 0x47, 0x5d, 0xb8, 0x3b, 0x4f, 0x44, 0x36, 0xb6, 0x8f, 0x28, 0xdd, 0xff, 0x00, 0x7e, 0x46, 0xab, 0x12, 0x2b, 0x65, 0x55, 0x32, 0xa7, 0x62, 0xb6, 0xbd, 0xf7, 0x64, 0x10, 0xdb, 0x03, 0x9f, 0x1b, 0x9e, 0xc7, 0xd9, 0xb8, 0x3b, 0x1f, 0x67, 0xf3, 0x6c, 0x52, 0x80, 0xd7, 0x7d, 0x0f, 0xea, 0x7f, 0x5d, 0x1d, 0x67, 0xa6, 0x0b, 0x1e, 0x47, 0xda, 0x69, 0x3b, 0x2e, 0x03, 0xc7, 0xf3, 0x5f, 0x1f, 0xf0, 0x8b, 0xa1, 0x02, 0x46, 0xba, 0x79, 0xaf, 0x32, 0xff, 0x00, 0x16, 0xad, 0xca, 0x1d, 0x57, 0x2a, 0xdc, 0x79, 0x18, 0x41, 0xb0, 0xf6, 0x9e, 0xe4, 0x9f, 0xd0, 0x8f, 0xeb, 0x31, 0xab, 0xd2, 0x83, 0xa4, 0xcb, 0x8c, 0xb8, 0xa0, 0x42, 0x12, 0x7b, 0x67, 0x9f, 0x2f, 0xf5, 0x09, 0x26, 0x96, 0xc4, 0xce, 0xa9, 0x20, 0xa7, 0xff, 0xd3, 0xf3, 0x2f, 0xb4, 0x5d, 0xe9, 0x0a, 0xb7, 0x9f, 0x4c, 0x19, 0xdb, 0x3a, 0x2d, 0x5e, 0x94, 0xfd, 0xc4, 0xb7, 0xc5, 0x62, 0xf9, 0x2b, 0xfd, 0x2e, 0xe3, 0x5d, 0xe0, 0x7c, 0x13, 0x48, 0xd1, 0x92, 0x12, 0xa9, 0x0b, 0x7a, 0xbc, 0x2d, 0xc2, 0x7f, 0x92, 0x60, 0xab, 0x4e, 0x79, 0x2e, 0x00, 0xf0, 0xaa, 0xe1, 0xda, 0x3d, 0x43, 0xfc, 0xad, 0x55, 0xbb, 0x80, 0x79, 0x81, 0xa0, 0xe6, 0x54, 0x32, 0x6d, 0x02, 0xbe, 0xf3, 0x61, 0x81, 0xa8, 0x44, 0x14, 0x03, 0x59, 0x0e, 0x1c, 0xf6, 0x1f, 0xdc, 0xb2, 0xec, 0xa3, 0x23, 0x77, 0xe8, 0x6e, 0x70, 0xf2, 0x25, 0x1f, 0x1f, 0x17, 0xa9, 0x6d, 0x71, 0x36, 0x97, 0x47, 0x00, 0xa4, 0x02, 0xe0, 0x2c, 0x7c, 0xc1, 0xab, 0xd5, 0x31, 0x85, 0x35, 0xd4, 0xe6, 0x13, 0x02, 0xd6, 0x4b, 0x67, 0x48, 0x2b, 0xa9, 0xe9, 0x2e, 0x02, 0xb6, 0x4f, 0x82, 0xe5, 0x7a, 0x95, 0x19, 0xc6, 0x87, 0x3d, 0xfb, 0xa2, 0xb8, 0x79, 0x1e, 0x4d, 0x3b, 0x96, 0xcf, 0x4f, 0xbd, 0xcd, 0xa2, 0xa2, 0x1f, 0xa0, 0x82, 0xd3, 0xfc, 0x97, 0x05, 0x24, 0x36, 0x6b, 0xf3, 0x31, 0xa2, 0x35, 0x79, 0xef, 0xad, 0xf8, 0xae, 0xaf, 0xaf, 0xd8, 0xf2, 0xd8, 0x6d, 0xed, 0x6b, 0xda, 0x7b, 0x18, 0x1b, 0x5d, 0xff, 0x00, 0x52, 0xb1, 0x6d, 0xf0, 0x81, 0x31, 0xca, 0xf4, 0x6e, 0xb1, 0x80, 0xce, 0xb1, 0x84, 0xc0, 0x21, 0xb7, 0xd6, 0x77, 0x31, 0xd1, 0x27, 0xc1, 0xcd, 0xfe, 0xd2, 0xe3, 0xec, 0xe8, 0x1d, 0x45, 0x96, 0xb0, 0x9a, 0xb7, 0x87, 0x3f, 0x68, 0x2d, 0xf7, 0x01, 0x1f, 0xbe, 0xd1, 0xf4, 0x7f, 0xb4, 0xa4, 0x0d, 0x77, 0xbb, 0xfa, 0x8f, 0x80, 0x3a, 0x7f, 0x43, 0xaa, 0xe2, 0xdf, 0xd2, 0x65, 0x7e, 0x95, 0xe4, 0x0f, 0x1f, 0xa1, 0xfe, 0x6b, 0x16, 0x9f, 0x52, 0xfa, 0xc1, 0xd3, 0xba, 0x6d, 0x26, 0xdc, 0xac, 0x86, 0xd4, 0xd9, 0x0d, 0x31, 0x2e, 0x74, 0x9e, 0xdb, 0x59, 0x2e, 0x55, 0xe8, 0xc9, 0xb2, 0x96, 0xd5, 0x4b, 0x9f, 0xb8, 0x6d, 0xda, 0x1c, 0x04, 0x09, 0x03, 0xfe, 0x8a, 0xc6, 0xfa, 0xd3, 0xf5, 0x6a, 0xbe, 0xbb, 0x5b, 0x2e, 0xc6, 0xb5, 0x94, 0xe6, 0xd5, 0x20, 0x97, 0x7d, 0x1b, 0x1b, 0xf9, 0xad, 0x7c, 0x7d, 0x17, 0xb7, 0xf3, 0x1e, 0x92, 0x1b, 0x7f, 0xf8, 0xe0, 0x7d, 0x59, 0xdd, 0xfd, 0x32, 0xd8, 0x8f, 0xa5, 0xe8, 0x3a, 0x12, 0x5c, 0x3f, 0xfc, 0xc4, 0xfa, 0xc3, 0xb3, 0x77, 0xa7, 0x56, 0xed, 0xdb, 0x76, 0x7a, 0x8d, 0xdd, 0x1f, 0xbf, 0xfd, 0x44, 0x92, 0x56, 0x8f, 0xff, 0xd4, 0xf2, 0xe8, 0x86, 0x17, 0x1e, 0xfa, 0x04, 0x56, 0x4b, 0x43, 0x6c, 0x6f, 0x2d, 0xe5, 0x46, 0x01, 0x64, 0x2b, 0x14, 0x32, 0x5b, 0xb4, 0xa0, 0x52, 0x1d, 0xde, 0x9b, 0x94, 0xdb, 0xab, 0x6b, 0x81, 0xf7, 0x05, 0xb0, 0xd7, 0x07, 0xb2, 0x27, 0x55, 0xc6, 0x57, 0x65, 0xd8, 0x76, 0x6e, 0x64, 0xed, 0xee, 0x16, 0xce, 0x27, 0x57, 0x63, 0xda, 0x0c, 0xc2, 0x8e, 0x51, 0x67, 0x84, 0xfa, 0x1d, 0xdd, 0x62, 0xc7, 0x07, 0xe9, 0xf7, 0xa3, 0xd6, 0x6c, 0x02, 0x41, 0x55, 0x31, 0xf3, 0x2b, 0xb3, 0xba, 0x2b, 0x2e, 0x68, 0x24, 0x1d, 0x47, 0x64, 0xca, 0xa6, 0x50, 0x41, 0x65, 0x90, 0x6c, 0xb1, 0xa5, 0xae, 0x33, 0x23, 0x51, 0xe4, 0xab, 0x7d, 0x5d, 0xcb, 0xb6, 0xcc, 0x37, 0xd0, 0x40, 0x73, 0x71, 0xde, 0x58, 0x09, 0xe7, 0x6f, 0x2c, 0x44, 0xc9, 0xc9, 0xae, 0xba, 0x9d, 0x63, 0x88, 0x01, 0xa0, 0x95, 0x9d, 0xf5, 0x3f, 0x2a, 0xe6, 0x67, 0xdb, 0x50, 0x83, 0x55, 0xad, 0x36, 0x3e, 0x78, 0x10, 0x74, 0x77, 0xfd, 0x2d, 0xaa, 0x4c, 0x7d, 0x58, 0x73, 0x91, 0xa0, 0x0f, 0x51, 0x45, 0xb7, 0x33, 0xdd, 0x58, 0x69, 0x1d, 0xd8, 0x0c, 0x9f, 0x96, 0x88, 0x19, 0x99, 0x19, 0xac, 0xcf, 0xa3, 0xd2, 0xad, 0xb5, 0xdb, 0x76, 0x8f, 0xad, 0xc4, 0xea, 0xcf, 0xdf, 0x7e, 0xdf, 0xdd, 0xfc, 0xd5, 0xa3, 0x5e, 0x43, 0x2b, 0x6b, 0xb2, 0xad, 0x3b, 0x6a, 0xa4, 0x13, 0xa7, 0x04, 0xac, 0x7a, 0x6f, 0xb3, 0x23, 0x26, 0xcc, 0xfb, 0xb4, 0x75, 0x8e, 0x01, 0x83, 0xf7, 0x58, 0x3e, 0x8b, 0x53, 0xa7, 0x2a, 0x1a, 0x31, 0x42, 0x36, 0x5d, 0x4c, 0x9a, 0xf2, 0xdc, 0xc6, 0xfe, 0x98, 0xb4, 0x34, 0xcb, 0x48, 0x0a, 0x8f, 0xdb, 0xb2, 0xeb, 0x76, 0xd6, 0x07, 0x5c, 0x59, 0xc9, 0x64, 0x8f, 0x93, 0xa7, 0x73, 0x16, 0x83, 0xaf, 0x0e, 0xa4, 0x33, 0xef, 0x50, 0xc5, 0x0c, 0xda, 0x59, 0x10, 0x06, 0x8a, 0x2e, 0x29, 0x0e, 0xac, 0xc2, 0x31, 0x3d, 0x36, 0x69, 0x7e, 0xd6, 0xcc, 0xf5, 0x3d, 0x6f, 0xb3, 0xeb, 0x1b, 0x76, 0xef, 0x3b, 0xa3, 0xfa, 0xc9, 0x2b, 0x5f, 0x66, 0x6f, 0xa9, 0x1e, 0x73, 0xf2, 0x49, 0x2e, 0x39, 0xf7, 0x4f, 0xb7, 0x8d, 0xff, 0xd5, 0xf3, 0x26, 0xfe, 0x0a, 0xc5, 0x1b, 0xa7, 0xcb, 0xb2, 0xcf, 0x49, 0x03, 0xb2, 0x46, 0xee, 0xd9, 0xd9, 0xb3, 0xf4, 0x9f, 0x25, 0x4a, 0xdf, 0x4b, 0x77, 0xe8, 0x27, 0xd4, 0xef, 0x1c, 0x2a, 0x29, 0x26, 0xc5, 0x7c, 0x9d, 0x6c, 0x7f, 0xb7, 0x6e, 0x1b, 0x26, 0x7f, 0x05, 0xa3, 0xfe, 0x53, 0x8d, 0x62, 0x57, 0x30, 0x92, 0x12, 0xfa, 0x2f, 0x86, 0xdf, 0xa4, 0xec, 0x67, 0xfe, 0xd0, 0xf4, 0xff, 0x00, 0x4d, 0xfc, 0xdf, 0x78, 0xe1, 0x68, 0x7d, 0x54, 0x99, 0xbf, 0x6f, 0xf3, 0xbe, 0xdf, 0x8e, 0xdd, 0x7f, 0xef, 0xeb, 0x97, 0x49, 0x3e, 0x3b, 0x7f, 0x06, 0x2c, 0x9f, 0x37, 0x5f, 0xf0, 0x9f, 0x4c, 0xeb, 0x7b, 0xbf, 0x67, 0x55, 0xe8, 0xff, 0x00, 0x31, 0xbc, 0x7a, 0x9e, 0x31, 0xdb, 0xfe, 0x92, 0xae, 0x37, 0x7a, 0x4d, 0xdb, 0xe2, 0x17, 0x9d, 0xa4, 0xa3, 0xc9, 0xba, 0xfc, 0x7b, 0x7d, 0x5f, 0x52, 0xa7, 0x7e, 0xd1, 0x28, 0xf8, 0xf3, 0xb0, 0xc7, 0x32, 0xbc, 0x99, 0x24, 0xc5, 0xe3, 0xab, 0xeb, 0x1f, 0xa4, 0xf5, 0xfc, 0xe1, 0x25, 0xe4, 0xe9, 0x24, 0x97, 0xff, 0xd9, 0xff, 0xed, 0x2e, 0x1c, 0x50, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x20, 0x33, 0x2e, 0x30, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x1c, 0x02, 0x00, 0x00, 0x02, 0x00, 0x02, 0x1c, 0x02, 0x78, 0x00, 0x1f, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xfb, 0x09, 0xa6, 0xbd, 0x07, 0x4c, 0x2a, 0x36, 0x9d, 0x8f, 0xe2, 0xcc, 0x57, 0xa9, 0xac, 0x85, 0x38, 0x42, 0x49, 0x4d, 0x03, 0xea, 0x00, 0x00, 0x00, 0x00, 0x1d, 0xb0, 0x3c, 0x3f, 0x78, 0x6d, 0x6c, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x31, 0x2e, 0x30, 0x22, 0x20, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x3d, 0x22, 0x55, 0x54, 0x46, 0x2d, 0x38, 0x22, 0x3f, 0x3e, 0x0a, 0x3c, 0x21, 0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45, 0x20, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x50, 0x55, 0x42, 0x4c, 0x49, 0x43, 0x20, 0x22, 0x2d, 0x2f, 0x2f, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x2f, 0x44, 0x54, 0x44, 0x20, 0x50, 0x4c, 0x49, 0x53, 0x54, 0x20, 0x31, 0x2e, 0x30, 0x2f, 0x2f, 0x45, 0x4e, 0x22, 0x20, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x44, 0x54, 0x44, 0x73, 0x2f, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x79, 0x4c, 0x69, 0x73, 0x74, 0x2d, 0x31, 0x2e, 0x30, 0x2e, 0x64, 0x74, 0x64, 0x22, 0x3e, 0x0a, 0x3c, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3d, 0x22, 0x31, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x48, 0x6f, 0x72, 0x69, 0x7a, 0x6f, 0x6e, 0x74, 0x61, 0x6c, 0x52, 0x65, 0x73, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x48, 0x6f, 0x72, 0x69, 0x7a, 0x6f, 0x6e, 0x74, 0x61, 0x6c, 0x52, 0x65, 0x73, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x31, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x53, 0x63, 0x61, 0x6c, 0x69, 0x6e, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x53, 0x63, 0x61, 0x6c, 0x69, 0x6e, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x31, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x52, 0x65, 0x73, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x52, 0x65, 0x73, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x37, 0x32, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x53, 0x63, 0x61, 0x6c, 0x69, 0x6e, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x6c, 0x53, 0x63, 0x61, 0x6c, 0x69, 0x6e, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x31, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x73, 0x75, 0x62, 0x54, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x70, 0x61, 0x70, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x5f, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x41, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x41, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x30, 0x2e, 0x30, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x30, 0x2e, 0x30, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x37, 0x33, 0x34, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x35, 0x37, 0x36, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x41, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x70, 0x65, 0x72, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x50, 0x4d, 0x41, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x70, 0x65, 0x72, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x2d, 0x31, 0x38, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x2d, 0x31, 0x38, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x37, 0x37, 0x34, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x35, 0x39, 0x34, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x4d, 0x50, 0x61, 0x70, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x70, 0x6d, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x53, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x4d, 0x50, 0x61, 0x70, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x6e, 0x61, 0x2d, 0x6c, 0x65, 0x74, 0x74, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x70, 0x6d, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x53, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x54, 0x31, 0x37, 0x3a, 0x34, 0x39, 0x3a, 0x33, 0x36, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x31, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x4d, 0x55, 0x6e, 0x61, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x70, 0x6d, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x53, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x4d, 0x55, 0x6e, 0x61, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x67, 0x65, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x30, 0x2e, 0x30, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x30, 0x2e, 0x30, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x37, 0x33, 0x34, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x35, 0x37, 0x36, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x4d, 0x55, 0x6e, 0x61, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x70, 0x65, 0x72, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x70, 0x6d, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x53, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x50, 0x4d, 0x55, 0x6e, 0x61, 0x64, 0x6a, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x61, 0x70, 0x65, 0x72, 0x52, 0x65, 0x63, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x2d, 0x31, 0x38, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x2d, 0x31, 0x38, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x37, 0x37, 0x34, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x35, 0x39, 0x34, 0x3c, 0x2f, 0x72, 0x65, 0x61, 0x6c, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x2d, 0x33, 0x30, 0x54, 0x32, 0x32, 0x3a, 0x30, 0x38, 0x3a, 0x34, 0x31, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x30, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x70, 0x64, 0x2e, 0x50, 0x4d, 0x50, 0x61, 0x70, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x6f, 0x72, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x70, 0x6d, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x53, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x41, 0x72, 0x72, 0x61, 0x79, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x70, 0x64, 0x2e, 0x50, 0x4d, 0x50, 0x61, 0x70, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x55, 0x53, 0x20, 0x4c, 0x65, 0x74, 0x74, 0x65, 0x72, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x70, 0x6d, 0x2e, 0x50, 0x6f, 0x73, 0x74, 0x53, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x6d, 0x6f, 0x64, 0x44, 0x61, 0x74, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x30, 0x37, 0x2d, 0x30, 0x31, 0x54, 0x31, 0x37, 0x3a, 0x34, 0x39, 0x3a, 0x33, 0x36, 0x5a, 0x3c, 0x2f, 0x64, 0x61, 0x74, 0x65, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x65, 0x46, 0x6c, 0x61, 0x67, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x31, 0x3c, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x09, 0x3c, 0x2f, 0x61, 0x72, 0x72, 0x61, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x41, 0x50, 0x49, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x30, 0x30, 0x2e, 0x32, 0x30, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4c, 0x6f, 0x63, 0x6b, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x2f, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x70, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x54, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x41, 0x50, 0x49, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x30, 0x30, 0x2e, 0x32, 0x30, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x4c, 0x6f, 0x63, 0x6b, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x2f, 0x3e, 0x0a, 0x09, 0x3c, 0x6b, 0x65, 0x79, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x74, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x3c, 0x2f, 0x6b, 0x65, 0x79, 0x3e, 0x0a, 0x09, 0x3c, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x50, 0x61, 0x67, 0x65, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x54, 0x69, 0x63, 0x6b, 0x65, 0x74, 0x3c, 0x2f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3e, 0x0a, 0x3c, 0x2f, 0x64, 0x69, 0x63, 0x74, 0x3e, 0x0a, 0x3c, 0x2f, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x3e, 0x0a, 0x38, 0x42, 0x49, 0x4d, 0x03, 0xe9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x03, 0x00, 0x00, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x02, 0xde, 0x02, 0x40, 0xff, 0xee, 0xff, 0xee, 0x03, 0x06, 0x02, 0x52, 0x03, 0x67, 0x05, 0x28, 0x03, 0xfc, 0x00, 0x02, 0x00, 0x00, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x02, 0xd8, 0x02, 0x28, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x01, 0x7f, 0xff, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x08, 0x00, 0x19, 0x01, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x03, 0xed, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x80, 0x00, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x1e, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x1e, 0x38, 0x42, 0x49, 0x4d, 0x03, 0xf3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x27, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x38, 0x42, 0x49, 0x4d, 0x03, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x2f, 0x66, 0x66, 0x00, 0x01, 0x00, 0x6c, 0x66, 0x66, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x2f, 0x66, 0x66, 0x00, 0x01, 0x00, 0xa1, 0x99, 0x9a, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x32, 0x00, 0x00, 0x00, 0x01, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x35, 0x00, 0x00, 0x00, 0x01, 0x00, 0x2d, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x38, 0x42, 0x49, 0x4d, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xe8, 0x00, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x03, 0x45, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x08, 0x00, 0x44, 0x00, 0x53, 0x00, 0x43, 0x00, 0x30, 0x00, 0x32, 0x00, 0x33, 0x00, 0x32, 0x00, 0x35, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6e, 0x75, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x73, 0x4f, 0x62, 0x6a, 0x63, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x63, 0x74, 0x31, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x54, 0x6f, 0x70, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x65, 0x66, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x74, 0x6f, 0x6d, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x52, 0x67, 0x68, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x06, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x73, 0x56, 0x6c, 0x4c, 0x73, 0x00, 0x00, 0x00, 0x01, 0x4f, 0x62, 0x6a, 0x63, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x07, 0x73, 0x6c, 0x69, 0x63, 0x65, 0x49, 0x44, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x49, 0x44, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x65, 0x6e, 0x75, 0x6d, 0x00, 0x00, 0x00, 0x0c, 0x45, 0x53, 0x6c, 0x69, 0x63, 0x65, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x6f, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x00, 0x00, 0x00, 0x00, 0x54, 0x79, 0x70, 0x65, 0x65, 0x6e, 0x75, 0x6d, 0x00, 0x00, 0x00, 0x0a, 0x45, 0x53, 0x6c, 0x69, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00, 0x00, 0x49, 0x6d, 0x67, 0x20, 0x00, 0x00, 0x00, 0x06, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x73, 0x4f, 0x62, 0x6a, 0x63, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x63, 0x74, 0x31, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x54, 0x6f, 0x70, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x65, 0x66, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x74, 0x6f, 0x6d, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x52, 0x67, 0x68, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72, 0x6c, 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6e, 0x75, 0x6c, 0x6c, 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4d, 0x73, 0x67, 0x65, 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x61, 0x6c, 0x74, 0x54, 0x61, 0x67, 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x63, 0x65, 0x6c, 0x6c, 0x54, 0x65, 0x78, 0x74, 0x49, 0x73, 0x48, 0x54, 0x4d, 0x4c, 0x62, 0x6f, 0x6f, 0x6c, 0x01, 0x00, 0x00, 0x00, 0x08, 0x63, 0x65, 0x6c, 0x6c, 0x54, 0x65, 0x78, 0x74, 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x68, 0x6f, 0x72, 0x7a, 0x41, 0x6c, 0x69, 0x67, 0x6e, 0x65, 0x6e, 0x75, 0x6d, 0x00, 0x00, 0x00, 0x0f, 0x45, 0x53, 0x6c, 0x69, 0x63, 0x65, 0x48, 0x6f, 0x72, 0x7a, 0x41, 0x6c, 0x69, 0x67, 0x6e, 0x00, 0x00, 0x00, 0x07, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x00, 0x00, 0x00, 0x09, 0x76, 0x65, 0x72, 0x74, 0x41, 0x6c, 0x69, 0x67, 0x6e, 0x65, 0x6e, 0x75, 0x6d, 0x00, 0x00, 0x00, 0x0f, 0x45, 0x53, 0x6c, 0x69, 0x63, 0x65, 0x56, 0x65, 0x72, 0x74, 0x41, 0x6c, 0x69, 0x67, 0x6e, 0x00, 0x00, 0x00, 0x07, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x00, 0x00, 0x00, 0x0b, 0x62, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x54, 0x79, 0x70, 0x65, 0x65, 0x6e, 0x75, 0x6d, 0x00, 0x00, 0x00, 0x11, 0x45, 0x53, 0x6c, 0x69, 0x63, 0x65, 0x42, 0x47, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x54, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00, 0x00, 0x4e, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x00, 0x09, 0x74, 0x6f, 0x70, 0x4f, 0x75, 0x74, 0x73, 0x65, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x6c, 0x65, 0x66, 0x74, 0x4f, 0x75, 0x74, 0x73, 0x65, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x62, 0x6f, 0x74, 0x74, 0x6f, 0x6d, 0x4f, 0x75, 0x74, 0x73, 0x65, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x72, 0x69, 0x67, 0x68, 0x74, 0x4f, 0x75, 0x74, 0x73, 0x65, 0x74, 0x6c, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x09, 0xf9, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x75, 0x30, 0x00, 0x00, 0x09, 0xdd, 0x00, 0x18, 0x00, 0x01, 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xed, 0x00, 0x0c, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x5f, 0x43, 0x4d, 0x00, 0x02, 0xff, 0xee, 0x00, 0x0e, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x00, 0x64, 0x80, 0x00, 0x00, 0x00, 0x01, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x0c, 0x08, 0x08, 0x08, 0x09, 0x08, 0x0c, 0x09, 0x09, 0x0c, 0x11, 0x0b, 0x0a, 0x0b, 0x11, 0x15, 0x0f, 0x0c, 0x0c, 0x0f, 0x15, 0x18, 0x13, 0x13, 0x15, 0x13, 0x13, 0x18, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x01, 0x0d, 0x0b, 0x0b, 0x0d, 0x0e, 0x0d, 0x10, 0x0e, 0x0e, 0x10, 0x14, 0x0e, 0x0e, 0x0e, 0x14, 0x14, 0x0e, 0x0e, 0x0e, 0x0e, 0x14, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x64, 0x00, 0x64, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xdd, 0x00, 0x04, 0x00, 0x07, 0xff, 0xc4, 0x01, 0x3f, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x02, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x01, 0x04, 0x01, 0x03, 0x02, 0x04, 0x02, 0x05, 0x07, 0x06, 0x08, 0x05, 0x03, 0x0c, 0x33, 0x01, 0x00, 0x02, 0x11, 0x03, 0x04, 0x21, 0x12, 0x31, 0x05, 0x41, 0x51, 0x61, 0x13, 0x22, 0x71, 0x81, 0x32, 0x06, 0x14, 0x91, 0xa1, 0xb1, 0x42, 0x23, 0x24, 0x15, 0x52, 0xc1, 0x62, 0x33, 0x34, 0x72, 0x82, 0xd1, 0x43, 0x07, 0x25, 0x92, 0x53, 0xf0, 0xe1, 0xf1, 0x63, 0x73, 0x35, 0x16, 0xa2, 0xb2, 0x83, 0x26, 0x44, 0x93, 0x54, 0x64, 0x45, 0xc2, 0xa3, 0x74, 0x36, 0x17, 0xd2, 0x55, 0xe2, 0x65, 0xf2, 0xb3, 0x84, 0xc3, 0xd3, 0x75, 0xe3, 0xf3, 0x46, 0x27, 0x94, 0xa4, 0x85, 0xb4, 0x95, 0xc4, 0xd4, 0xe4, 0xf4, 0xa5, 0xb5, 0xc5, 0xd5, 0xe5, 0xf5, 0x56, 0x66, 0x76, 0x86, 0x96, 0xa6, 0xb6, 0xc6, 0xd6, 0xe6, 0xf6, 0x37, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xa7, 0xb7, 0xc7, 0xd7, 0xe7, 0xf7, 0x11, 0x00, 0x02, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x05, 0x06, 0x07, 0x07, 0x06, 0x05, 0x35, 0x01, 0x00, 0x02, 0x11, 0x03, 0x21, 0x31, 0x12, 0x04, 0x41, 0x51, 0x61, 0x71, 0x22, 0x13, 0x05, 0x32, 0x81, 0x91, 0x14, 0xa1, 0xb1, 0x42, 0x23, 0xc1, 0x52, 0xd1, 0xf0, 0x33, 0x24, 0x62, 0xe1, 0x72, 0x82, 0x92, 0x43, 0x53, 0x15, 0x63, 0x73, 0x34, 0xf1, 0x25, 0x06, 0x16, 0xa2, 0xb2, 0x83, 0x07, 0x26, 0x35, 0xc2, 0xd2, 0x44, 0x93, 0x54, 0xa3, 0x17, 0x64, 0x45, 0x55, 0x36, 0x74, 0x65, 0xe2, 0xf2, 0xb3, 0x84, 0xc3, 0xd3, 0x75, 0xe3, 0xf3, 0x46, 0x94, 0xa4, 0x85, 0xb4, 0x95, 0xc4, 0xd4, 0xe4, 0xf4, 0xa5, 0xb5, 0xc5, 0xd5, 0xe5, 0xf5, 0x56, 0x66, 0x76, 0x86, 0x96, 0xa6, 0xb6, 0xc6, 0xd6, 0xe6, 0xf6, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xa7, 0xb7, 0xc7, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf2, 0xed, 0xb2, 0x8d, 0x4d, 0x45, 0xcd, 0x2f, 0x3f, 0x44, 0x68, 0x93, 0xc3, 0x58, 0xc8, 0xf1, 0x1f, 0x8a, 0x33, 0x86, 0xda, 0x58, 0xc1, 0xa0, 0x02, 0x4f, 0xc4, 0xa1, 0x69, 0xa5, 0x9b, 0x5b, 0x4b, 0x84, 0x73, 0xdf, 0xc9, 0x15, 0xf8, 0xe3, 0xd1, 0x0e, 0x07, 0x93, 0xf3, 0xd1, 0x0f, 0x1c, 0x17, 0xef, 0x2e, 0x3b, 0x5b, 0xdc, 0xff, 0x00, 0xdf, 0x42, 0xbf, 0x8f, 0x8e, 0xdc, 0x82, 0xca, 0xd8, 0x37, 0x11, 0xa9, 0x3d, 0x82, 0x69, 0x2b, 0xc4, 0x6d, 0xc9, 0x75, 0x25, 0xbc, 0xf7, 0xec, 0xa1, 0xb5, 0x74, 0x19, 0x5d, 0x2e, 0x8a, 0x9a, 0x4b, 0x89, 0x7d, 0xc4, 0x68, 0xc6, 0xf6, 0xfe, 0xb2, 0xa0, 0x30, 0x1d, 0x60, 0x86, 0x88, 0x8d, 0x49, 0x3e, 0x01, 0x11, 0x20, 0xa3, 0x8c, 0xb9, 0xb1, 0xaa, 0x62, 0xad, 0xbf, 0x18, 0x97, 0x43, 0x47, 0x1d, 0xd2, 0xaf, 0x04, 0xd9, 0xb8, 0xc8, 0x0d, 0x68, 0xe4, 0xf7, 0x3e, 0x48, 0xf1, 0x05, 0xbc, 0x25, 0xaa, 0x07, 0x71, 0xd9, 0x14, 0x78, 0xf6, 0x49, 0xb5, 0x90, 0xfd, 0xa7, 0xc6, 0x14, 0xfd, 0x1b, 0x1c, 0xff, 0x00, 0x4d, 0x8d, 0x2e, 0x73, 0x8c, 0x35, 0xa3, 0x52, 0x4f, 0x92, 0x48, 0xa6, 0x1a, 0x24, 0xb6, 0x2a, 0xfa, 0xa5, 0x9e, 0x60, 0x64, 0x39, 0x94, 0x13, 0xcb, 0x27, 0x73, 0x80, 0xf3, 0x0c, 0xf6, 0xff, 0x00, 0xd2, 0x5a, 0x78, 0xbf, 0x53, 0x71, 0xf6, 0x01, 0x75, 0xb6, 0x97, 0x6a, 0x25, 0xa1, 0xad, 0x1f, 0xf4, 0xb7, 0x23, 0x48, 0xb7, 0x94, 0x84, 0x97, 0x5b, 0xff, 0x00, 0x32, 0xa9, 0xdd, 0xfc, 0xed, 0x9b, 0x7e, 0x0d, 0x9e, 0x52, 0x4a, 0x95, 0x61, 0xff, 0xd0, 0xf3, 0x3b, 0xa7, 0x70, 0xee, 0x01, 0x8f, 0xb9, 0x59, 0xfa, 0x7e, 0xdf, 0xe4, 0xc8, 0xf9, 0x2a, 0xc2, 0x5c, 0x63, 0xc3, 0x54, 0x67, 0x87, 0x6e, 0x10, 0x35, 0x68, 0xd4, 0x79, 0x1e, 0x53, 0x4a, 0xe0, 0xdc, 0xe9, 0xb8, 0x1f, 0x6a, 0xda, 0x6c, 0x25, 0x94, 0x37, 0xb0, 0xd0, 0xb8, 0xad, 0x67, 0xe4, 0x55, 0x8a, 0x5b, 0x8b, 0x82, 0xc0, 0x6f, 0x76, 0x80, 0x34, 0x49, 0x05, 0x2e, 0x9e, 0xc6, 0x1c, 0x66, 0x31, 0xba, 0x10, 0x23, 0xe0, 0xaf, 0xe1, 0x61, 0x53, 0x43, 0x8d, 0x81, 0xb3, 0x67, 0xef, 0x9e, 0x49, 0x2a, 0x12, 0x6c, 0xb6, 0x63, 0x1a, 0x0c, 0x31, 0xba, 0x55, 0xcd, 0xac, 0xfa, 0x8e, 0xdf, 0x91, 0x6e, 0x91, 0xd9, 0xb3, 0xc9, 0x73, 0x90, 0x7a, 0xab, 0x6a, 0xc2, 0xa4, 0x60, 0xe2, 0x8f, 0xd2, 0x38, 0x03, 0x7d, 0x9e, 0x0d, 0xff, 0x00, 0xcc, 0xd6, 0xd3, 0x6b, 0x71, 0x67, 0xd2, 0x3e, 0x64, 0x72, 0xab, 0xdb, 0x8d, 0x54, 0x39, 0xc5, 0x83, 0x6b, 0x3d, 0xee, 0x2e, 0xd4, 0x92, 0x3c, 0x4a, 0x56, 0xba, 0xb4, 0x79, 0x5c, 0xf7, 0xb2, 0x96, 0x6c, 0x8d, 0xaf, 0x80, 0x48, 0x3c, 0xf0, 0xb2, 0x1f, 0x63, 0x9c, 0xe9, 0x3f, 0x24, 0x5c, 0xdb, 0xdd, 0x76, 0x43, 0xde, 0xfd, 0x5c, 0xe3, 0x24, 0xfc, 0x50, 0x00, 0x93, 0x0a, 0x78, 0x8a, 0x0d, 0x49, 0xca, 0xcf, 0x93, 0x63, 0x1b, 0x7d, 0xd7, 0x57, 0x50, 0xd5, 0xef, 0x70, 0x6b, 0x4f, 0xc7, 0x45, 0xdb, 0x74, 0x9e, 0x8d, 0x5e, 0x33, 0x83, 0xd8, 0x37, 0xdd, 0xc3, 0xac, 0x3d, 0xbf, 0x92, 0xc5, 0x5b, 0xea, 0xbf, 0xd5, 0x62, 0xc0, 0xdc, 0xbc, 0xbd, 0x2d, 0x22, 0x5a, 0xcf, 0xdd, 0x69, 0xff, 0x00, 0xd1, 0x8e, 0x5d, 0xa5, 0x38, 0xb5, 0xb0, 0x00, 0xc6, 0xc4, 0x24, 0x4a, 0xd6, 0x8d, 0x18, 0x04, 0x49, 0x88, 0x9e, 0x55, 0xd6, 0x61, 0xb0, 0xc1, 0x70, 0x32, 0xdd, 0x3c, 0x95, 0xda, 0xf1, 0xfe, 0xf5, 0x62, 0xbc, 0x76, 0x8e, 0x75, 0x28, 0x02, 0xa2, 0xe7, 0x7d, 0x92, 0xb9, 0x84, 0x96, 0x96, 0xda, 0xf7, 0x70, 0x12, 0x4e, 0x5a, 0xff, 0x00, 0xff, 0xd1, 0xf3, 0x7a, 0x21, 0xaf, 0xde, 0xef, 0xa2, 0x22, 0x55, 0xfc, 0x5a, 0xbd, 0x42, 0xfb, 0x08, 0xfa, 0x67, 0x4f, 0x82, 0xcd, 0x6d, 0x85, 0xc0, 0x56, 0x3b, 0x90, 0xb7, 0xf0, 0x2a, 0x0e, 0x63, 0x58, 0x3b, 0xf2, 0xa3, 0x9e, 0x8c, 0xb8, 0x86, 0xbe, 0x49, 0xf1, 0x2c, 0x0c, 0x86, 0xb4, 0x4c, 0x69, 0xe4, 0xaf, 0x6e, 0xcc, 0x6b, 0x7d, 0x46, 0xb3, 0x70, 0xec, 0x38, 0x51, 0x7d, 0x02, 0x8a, 0xc7, 0xa6, 0xd9, 0x20, 0x68, 0x0f, 0x8f, 0x8a, 0xcf, 0xc9, 0xc2, 0xea, 0x59, 0x5b, 0x48, 0xb0, 0x91, 0xae, 0xe6, 0xc9, 0x03, 0xc9, 0x30, 0x51, 0x66, 0xd4, 0x0d, 0xad, 0xbd, 0x5f, 0x53, 0xcc, 0x6b, 0xb6, 0x90, 0x5a, 0x3b, 0x83, 0x0b, 0x43, 0x17, 0x31, 0xd6, 0xc3, 0x6e, 0x12, 0x3b, 0x79, 0xac, 0xc1, 0x89, 0x47, 0xd9, 0xe8, 0x63, 0x98, 0x45, 0xed, 0x6c, 0x5a, 0xf1, 0xa0, 0x27, 0xc5, 0x5b, 0xc3, 0x6f, 0xa6, 0xe0, 0x1c, 0x7d, 0xb3, 0xa2, 0x69, 0x34, 0x7b, 0xae, 0x1a, 0x8d, 0x45, 0x17, 0x9d, 0xeb, 0xfd, 0x21, 0xd8, 0xb9, 0xae, 0xb5, 0x80, 0xbb, 0x1e, 0xd2, 0x5c, 0xd7, 0x78, 0x13, 0xf9, 0xae, 0x4b, 0xea, 0xc7, 0x4a, 0x39, 0xbd, 0x55, 0xb3, 0xed, 0x66, 0x38, 0xf5, 0x09, 0x22, 0x41, 0x23, 0xe8, 0x37, 0xfb, 0x4b, 0xa1, 0xeb, 0xd6, 0xfe, 0x88, 0x31, 0xbf, 0x41, 0xc0, 0xee, 0xd2, 0x74, 0x02, 0x78, 0x53, 0xfa, 0x97, 0x43, 0x19, 0x85, 0x65, 0xff, 0x00, 0x9d, 0x71, 0x33, 0xe4, 0x1a, 0x7d, 0x8d, 0x53, 0x42, 0x56, 0x35, 0x6b, 0xe5, 0x80, 0x06, 0xc7, 0x57, 0xa7, 0xc4, 0xa9, 0xdb, 0xb6, 0x81, 0x1f, 0xeb, 0xd9, 0x69, 0x56, 0xc2, 0xd0, 0x00, 0xe5, 0x55, 0xc0, 0x12, 0xc2, 0xd7, 0x4e, 0xa2, 0x5a, 0x7c, 0x0a, 0xd0, 0x63, 0x9a, 0xd1, 0xaf, 0xd2, 0xe2, 0x3c, 0x12, 0x62, 0x66, 0xc6, 0x42, 0x23, 0x5a, 0x49, 0x8f, 0x10, 0xa2, 0xd2, 0x3e, 0x28, 0x9d, 0xc4, 0x88, 0x09, 0x29, 0x16, 0xc3, 0x3c, 0x24, 0x8d, 0xe6, 0x92, 0x72, 0x1f, 0xff, 0xd2, 0xf3, 0xbb, 0xb0, 0xfe, 0xcb, 0x99, 0xe9, 0xce, 0xf6, 0x88, 0x2d, 0x77, 0x91, 0x5b, 0x3d, 0x3d, 0xd0, 0xe6, 0x90, 0xa9, 0x65, 0x57, 0x38, 0x95, 0xdd, 0xcb, 0x9a, 0x7d, 0xce, 0xf2, 0x3f, 0x44, 0x23, 0x60, 0x58, 0x76, 0xe9, 0xca, 0x8c, 0xea, 0x1b, 0x31, 0x02, 0x32, 0x23, 0xea, 0xee, 0xb1, 0xcd, 0xb0, 0xc7, 0x87, 0x74, 0x7a, 0xeb, 0x70, 0x1a, 0x71, 0xe1, 0xfe, 0xe4, 0x1c, 0x1d, 0xae, 0xe5, 0x69, 0xd8, 0xfa, 0x99, 0x50, 0x0d, 0x1a, 0xf7, 0x2a, 0x3a, 0x0c, 0xf4, 0x1a, 0x8e, 0xc7, 0x27, 0x5d, 0xbf, 0x18, 0x41, 0xdc, 0xc2, 0xf0, 0x7f, 0x74, 0xf6, 0x3a, 0x22, 0x66, 0xdb, 0x68, 0xc6, 0x80, 0x48, 0x6b, 0x88, 0x06, 0x39, 0x0d, 0xee, 0xaa, 0x1f, 0xb3, 0xd5, 0x1b, 0x83, 0xd8, 0x3b, 0x38, 0x8f, 0x69, 0xfe, 0xdf, 0xd1, 0x4d, 0x29, 0xa1, 0x4c, 0x7a, 0xf4, 0xbf, 0xa7, 0x92, 0xcf, 0xa5, 0x20, 0x08, 0xf3, 0xf6, 0xff, 0x00, 0x15, 0xbb, 0xd1, 0x31, 0xd9, 0x5e, 0x3d, 0x75, 0x56, 0x36, 0x88, 0x00, 0x81, 0xe0, 0x16, 0x5e, 0x55, 0x74, 0x3f, 0x00, 0x9d, 0xe0, 0xcc, 0x69, 0xe7, 0x3a, 0x2d, 0xbe, 0x90, 0x00, 0xa9, 0xae, 0xef, 0x1f, 0x95, 0x4b, 0x0d, 0x9a, 0xdc, 0xc7, 0x45, 0xfe, 0xb1, 0x7d, 0x60, 0xa7, 0xa1, 0xe0, 0x1f, 0x4e, 0x1d, 0x99, 0x69, 0x02, 0x9a, 0xcf, 0x1f, 0xca, 0x7b, 0xbf, 0x90, 0xc5, 0xc2, 0xb3, 0xeb, 0x57, 0xd6, 0x03, 0x6b, 0xae, 0x39, 0xb6, 0x82, 0xe3, 0x31, 0xa1, 0x68, 0xf2, 0x6b, 0x5c, 0x12, 0xfa, 0xe1, 0x91, 0x66, 0x47, 0x5d, 0xb8, 0x3b, 0x4f, 0x44, 0x36, 0xb6, 0x8f, 0x28, 0xdd, 0xff, 0x00, 0x7e, 0x46, 0xab, 0x12, 0x2b, 0x65, 0x55, 0x32, 0xa7, 0x62, 0xb6, 0xbd, 0xf7, 0x64, 0x10, 0xdb, 0x03, 0x9f, 0x1b, 0x9e, 0xc7, 0xd9, 0xb8, 0x3b, 0x1f, 0x67, 0xf3, 0x6c, 0x52, 0x80, 0xd7, 0x7d, 0x0f, 0xea, 0x7f, 0x5d, 0x1d, 0x67, 0xa6, 0x0b, 0x1e, 0x47, 0xda, 0x69, 0x3b, 0x2e, 0x03, 0xc7, 0xf3, 0x5f, 0x1f, 0xf0, 0x8b, 0xa1, 0x02, 0x46, 0xba, 0x79, 0xaf, 0x32, 0xff, 0x00, 0x16, 0xad, 0xca, 0x1d, 0x57, 0x2a, 0xdc, 0x79, 0x18, 0x41, 0xb0, 0xf6, 0x9e, 0xe4, 0x9f, 0xd0, 0x8f, 0xeb, 0x31, 0xab, 0xd2, 0x83, 0xa4, 0xcb, 0x8c, 0xb8, 0xa0, 0x42, 0x12, 0x7b, 0x67, 0x9f, 0x2f, 0xf5, 0x09, 0x26, 0x96, 0xc4, 0xce, 0xa9, 0x20, 0xa7, 0xff, 0xd3, 0xf3, 0x2f, 0xb4, 0x5d, 0xe9, 0x0a, 0xb7, 0x9f, 0x4c, 0x19, 0xdb, 0x3a, 0x2d, 0x5e, 0x94, 0xfd, 0xc4, 0xb7, 0xc5, 0x62, 0xf9, 0x2b, 0xfd, 0x2e, 0xe3, 0x5d, 0xe0, 0x7c, 0x13, 0x48, 0xd1, 0x92, 0x12, 0xa9, 0x0b, 0x7a, 0xbc, 0x2d, 0xc2, 0x7f, 0x92, 0x60, 0xab, 0x4e, 0x79, 0x2e, 0x00, 0xf0, 0xaa, 0xe1, 0xda, 0x3d, 0x43, 0xfc, 0xad, 0x55, 0xbb, 0x80, 0x79, 0x81, 0xa0, 0xe6, 0x54, 0x32, 0x6d, 0x02, 0xbe, 0xf3, 0x61, 0x81, 0xa8, 0x44, 0x14, 0x03, 0x59, 0x0e, 0x1c, 0xf6, 0x1f, 0xdc, 0xb2, 0xec, 0xa3, 0x23, 0x77, 0xe8, 0x6e, 0x70, 0xf2, 0x25, 0x1f, 0x1f, 0x17, 0xa9, 0x6d, 0x71, 0x36, 0x97, 0x47, 0x00, 0xa4, 0x02, 0xe0, 0x2c, 0x7c, 0xc1, 0xab, 0xd5, 0x31, 0x85, 0x35, 0xd4, 0xe6, 0x13, 0x02, 0xd6, 0x4b, 0x67, 0x48, 0x2b, 0xa9, 0xe9, 0x2e, 0x02, 0xb6, 0x4f, 0x82, 0xe5, 0x7a, 0x95, 0x19, 0xc6, 0x87, 0x3d, 0xfb, 0xa2, 0xb8, 0x79, 0x1e, 0x4d, 0x3b, 0x96, 0xcf, 0x4f, 0xbd, 0xcd, 0xa2, 0xa2, 0x1f, 0xa0, 0x82, 0xd3, 0xfc, 0x97, 0x05, 0x24, 0x36, 0x6b, 0xf3, 0x31, 0xa2, 0x35, 0x79, 0xef, 0xad, 0xf8, 0xae, 0xaf, 0xaf, 0xd8, 0xf2, 0xd8, 0x6d, 0xed, 0x6b, 0xda, 0x7b, 0x18, 0x1b, 0x5d, 0xff, 0x00, 0x52, 0xb1, 0x6d, 0xf0, 0x81, 0x31, 0xca, 0xf4, 0x6e, 0xb1, 0x80, 0xce, 0xb1, 0x84, 0xc0, 0x21, 0xb7, 0xd6, 0x77, 0x31, 0xd1, 0x27, 0xc1, 0xcd, 0xfe, 0xd2, 0xe3, 0xec, 0xe8, 0x1d, 0x45, 0x96, 0xb0, 0x9a, 0xb7, 0x87, 0x3f, 0x68, 0x2d, 0xf7, 0x01, 0x1f, 0xbe, 0xd1, 0xf4, 0x7f, 0xb4, 0xa4, 0x0d, 0x77, 0xbb, 0xfa, 0x8f, 0x80, 0x3a, 0x7f, 0x43, 0xaa, 0xe2, 0xdf, 0xd2, 0x65, 0x7e, 0x95, 0xe4, 0x0f, 0x1f, 0xa1, 0xfe, 0x6b, 0x16, 0x9f, 0x52, 0xfa, 0xc1, 0xd3, 0xba, 0x6d, 0x26, 0xdc, 0xac, 0x86, 0xd4, 0xd9, 0x0d, 0x31, 0x2e, 0x74, 0x9e, 0xdb, 0x59, 0x2e, 0x55, 0xe8, 0xc9, 0xb2, 0x96, 0xd5, 0x4b, 0x9f, 0xb8, 0x6d, 0xda, 0x1c, 0x04, 0x09, 0x03, 0xfe, 0x8a, 0xc6, 0xfa, 0xd3, 0xf5, 0x6a, 0xbe, 0xbb, 0x5b, 0x2e, 0xc6, 0xb5, 0x94, 0xe6, 0xd5, 0x20, 0x97, 0x7d, 0x1b, 0x1b, 0xf9, 0xad, 0x7c, 0x7d, 0x17, 0xb7, 0xf3, 0x1e, 0x92, 0x1b, 0x7f, 0xf8, 0xe0, 0x7d, 0x59, 0xdd, 0xfd, 0x32, 0xd8, 0x8f, 0xa5, 0xe8, 0x3a, 0x12, 0x5c, 0x3f, 0xfc, 0xc4, 0xfa, 0xc3, 0xb3, 0x77, 0xa7, 0x56, 0xed, 0xdb, 0x76, 0x7a, 0x8d, 0xdd, 0x1f, 0xbf, 0xfd, 0x44, 0x92, 0x56, 0x8f, 0xff, 0xd4, 0xf2, 0xe8, 0x86, 0x17, 0x1e, 0xfa, 0x04, 0x56, 0x4b, 0x43, 0x6c, 0x6f, 0x2d, 0xe5, 0x46, 0x01, 0x64, 0x2b, 0x14, 0x32, 0x5b, 0xb4, 0xa0, 0x52, 0x1d, 0xde, 0x9b, 0x94, 0xdb, 0xab, 0x6b, 0x81, 0xf7, 0x05, 0xb0, 0xd7, 0x07, 0xb2, 0x27, 0x55, 0xc6, 0x57, 0x65, 0xd8, 0x76, 0x6e, 0x64, 0xed, 0xee, 0x16, 0xce, 0x27, 0x57, 0x63, 0xda, 0x0c, 0xc2, 0x8e, 0x51, 0x67, 0x84, 0xfa, 0x1d, 0xdd, 0x62, 0xc7, 0x07, 0xe9, 0xf7, 0xa3, 0xd6, 0x6c, 0x02, 0x41, 0x55, 0x31, 0xf3, 0x2b, 0xb3, 0xba, 0x2b, 0x2e, 0x68, 0x24, 0x1d, 0x47, 0x64, 0xca, 0xa6, 0x50, 0x41, 0x65, 0x90, 0x6c, 0xb1, 0xa5, 0xae, 0x33, 0x23, 0x51, 0xe4, 0xab, 0x7d, 0x5d, 0xcb, 0xb6, 0xcc, 0x37, 0xd0, 0x40, 0x73, 0x71, 0xde, 0x58, 0x09, 0xe7, 0x6f, 0x2c, 0x44, 0xc9, 0xc9, 0xae, 0xba, 0x9d, 0x63, 0x88, 0x01, 0xa0, 0x95, 0x9d, 0xf5, 0x3f, 0x2a, 0xe6, 0x67, 0xdb, 0x50, 0x83, 0x55, 0xad, 0x36, 0x3e, 0x78, 0x10, 0x74, 0x77, 0xfd, 0x2d, 0xaa, 0x4c, 0x7d, 0x58, 0x73, 0x91, 0xa0, 0x0f, 0x51, 0x45, 0xb7, 0x33, 0xdd, 0x58, 0x69, 0x1d, 0xd8, 0x0c, 0x9f, 0x96, 0x88, 0x19, 0x99, 0x19, 0xac, 0xcf, 0xa3, 0xd2, 0xad, 0xb5, 0xdb, 0x76, 0x8f, 0xad, 0xc4, 0xea, 0xcf, 0xdf, 0x7e, 0xdf, 0xdd, 0xfc, 0xd5, 0xa3, 0x5e, 0x43, 0x2b, 0x6b, 0xb2, 0xad, 0x3b, 0x6a, 0xa4, 0x13, 0xa7, 0x04, 0xac, 0x7a, 0x6f, 0xb3, 0x23, 0x26, 0xcc, 0xfb, 0xb4, 0x75, 0x8e, 0x01, 0x83, 0xf7, 0x58, 0x3e, 0x8b, 0x53, 0xa7, 0x2a, 0x1a, 0x31, 0x42, 0x36, 0x5d, 0x4c, 0x9a, 0xf2, 0xdc, 0xc6, 0xfe, 0x98, 0xb4, 0x34, 0xcb, 0x48, 0x0a, 0x8f, 0xdb, 0xb2, 0xeb, 0x76, 0xd6, 0x07, 0x5c, 0x59, 0xc9, 0x64, 0x8f, 0x93, 0xa7, 0x73, 0x16, 0x83, 0xaf, 0x0e, 0xa4, 0x33, 0xef, 0x50, 0xc5, 0x0c, 0xda, 0x59, 0x10, 0x06, 0x8a, 0x2e, 0x29, 0x0e, 0xac, 0xc2, 0x31, 0x3d, 0x36, 0x69, 0x7e, 0xd6, 0xcc, 0xf5, 0x3d, 0x6f, 0xb3, 0xeb, 0x1b, 0x76, 0xef, 0x3b, 0xa3, 0xfa, 0xc9, 0x2b, 0x5f, 0x66, 0x6f, 0xa9, 0x1e, 0x73, 0xf2, 0x49, 0x2e, 0x39, 0xf7, 0x4f, 0xb7, 0x8d, 0xff, 0xd5, 0xf3, 0x26, 0xfe, 0x0a, 0xc5, 0x1b, 0xa7, 0xcb, 0xb2, 0xcf, 0x49, 0x03, 0xb2, 0x46, 0xee, 0xd9, 0xd9, 0xb3, 0xf4, 0x9f, 0x25, 0x4a, 0xdf, 0x4b, 0x77, 0xe8, 0x27, 0xd4, 0xef, 0x1c, 0x2a, 0x29, 0x26, 0xc5, 0x7c, 0x9d, 0x6c, 0x7f, 0xb7, 0x6e, 0x1b, 0x26, 0x7f, 0x05, 0xa3, 0xfe, 0x53, 0x8d, 0x62, 0x57, 0x30, 0x92, 0x12, 0xfa, 0x2f, 0x86, 0xdf, 0xa4, 0xec, 0x67, 0xfe, 0xd0, 0xf4, 0xff, 0x00, 0x4d, 0xfc, 0xdf, 0x78, 0xe1, 0x68, 0x7d, 0x54, 0x99, 0xbf, 0x6f, 0xf3, 0xbe, 0xdf, 0x8e, 0xdd, 0x7f, 0xef, 0xeb, 0x97, 0x49, 0x3e, 0x3b, 0x7f, 0x06, 0x2c, 0x9f, 0x37, 0x5f, 0xf0, 0x9f, 0x4c, 0xeb, 0x7b, 0xbf, 0x67, 0x55, 0xe8, 0xff, 0x00, 0x31, 0xbc, 0x7a, 0x9e, 0x31, 0xdb, 0xfe, 0x92, 0xae, 0x37, 0x7a, 0x4d, 0xdb, 0xe2, 0x17, 0x9d, 0xa4, 0xa3, 0xc9, 0xba, 0xfc, 0x7b, 0x7d, 0x5f, 0x52, 0xa7, 0x7e, 0xd1, 0x28, 0xf8, 0xf3, 0xb0, 0xc7, 0x32, 0xbc, 0x99, 0x24, 0xc5, 0xe3, 0xab, 0xeb, 0x1f, 0xa4, 0xf5, 0xfc, 0xe1, 0x25, 0xe4, 0xe9, 0x24, 0x97, 0xff, 0xd9, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x41, 0x00, 0x64, 0x00, 0x6f, 0x00, 0x62, 0x00, 0x65, 0x00, 0x20, 0x00, 0x50, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x74, 0x00, 0x6f, 0x00, 0x73, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x70, 0x00, 0x00, 0x00, 0x13, 0x00, 0x41, 0x00, 0x64, 0x00, 0x6f, 0x00, 0x62, 0x00, 0x65, 0x00, 0x20, 0x00, 0x50, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x74, 0x00, 0x6f, 0x00, 0x73, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x70, 0x00, 0x20, 0x00, 0x37, 0x00, 0x2e, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x38, 0x42, 0x49, 0x4d, 0x04, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0xff, 0xe1, 0x15, 0x67, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x00, 0x3c, 0x3f, 0x78, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x62, 0x65, 0x67, 0x69, 0x6e, 0x3d, 0x27, 0xef, 0xbb, 0xbf, 0x27, 0x20, 0x69, 0x64, 0x3d, 0x27, 0x57, 0x35, 0x4d, 0x30, 0x4d, 0x70, 0x43, 0x65, 0x68, 0x69, 0x48, 0x7a, 0x72, 0x65, 0x53, 0x7a, 0x4e, 0x54, 0x63, 0x7a, 0x6b, 0x63, 0x39, 0x64, 0x27, 0x3f, 0x3e, 0x0a, 0x3c, 0x3f, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2d, 0x78, 0x61, 0x70, 0x2d, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x20, 0x65, 0x73, 0x63, 0x3d, 0x22, 0x43, 0x52, 0x22, 0x3f, 0x3e, 0x0a, 0x3c, 0x78, 0x3a, 0x78, 0x61, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x27, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74, 0x61, 0x2f, 0x27, 0x20, 0x78, 0x3a, 0x78, 0x61, 0x70, 0x74, 0x6b, 0x3d, 0x27, 0x58, 0x4d, 0x50, 0x20, 0x74, 0x6f, 0x6f, 0x6c, 0x6b, 0x69, 0x74, 0x20, 0x32, 0x2e, 0x38, 0x2e, 0x32, 0x2d, 0x33, 0x33, 0x2c, 0x20, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x31, 0x2e, 0x35, 0x27, 0x3e, 0x0a, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x72, 0x64, 0x66, 0x3d, 0x27, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64, 0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23, 0x27, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x69, 0x58, 0x3d, 0x27, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x58, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x27, 0x3e, 0x0a, 0x0a, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x27, 0x75, 0x75, 0x69, 0x64, 0x3a, 0x32, 0x32, 0x64, 0x30, 0x32, 0x62, 0x30, 0x61, 0x2d, 0x62, 0x32, 0x34, 0x39, 0x2d, 0x31, 0x31, 0x64, 0x62, 0x2d, 0x38, 0x61, 0x66, 0x38, 0x2d, 0x39, 0x31, 0x64, 0x35, 0x34, 0x30, 0x33, 0x66, 0x39, 0x32, 0x66, 0x39, 0x27, 0x0a, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x70, 0x64, 0x66, 0x3d, 0x27, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x70, 0x64, 0x66, 0x2f, 0x31, 0x2e, 0x33, 0x2f, 0x27, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x21, 0x2d, 0x2d, 0x20, 0x70, 0x64, 0x66, 0x3a, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x69, 0x73, 0x20, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x64, 0x20, 0x2d, 0x2d, 0x3e, 0x0a, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x0a, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x27, 0x75, 0x75, 0x69, 0x64, 0x3a, 0x32, 0x32, 0x64, 0x30, 0x32, 0x62, 0x30, 0x61, 0x2d, 0x62, 0x32, 0x34, 0x39, 0x2d, 0x31, 0x31, 0x64, 0x62, 0x2d, 0x38, 0x61, 0x66, 0x38, 0x2d, 0x39, 0x31, 0x64, 0x35, 0x34, 0x30, 0x33, 0x66, 0x39, 0x32, 0x66, 0x39, 0x27, 0x0a, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x70, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x3d, 0x27, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x70, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x27, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x21, 0x2d, 0x2d, 0x20, 0x70, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x3a, 0x43, 0x61, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x73, 0x20, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x64, 0x20, 0x2d, 0x2d, 0x3e, 0x0a, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x0a, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x27, 0x75, 0x75, 0x69, 0x64, 0x3a, 0x32, 0x32, 0x64, 0x30, 0x32, 0x62, 0x30, 0x61, 0x2d, 0x62, 0x32, 0x34, 0x39, 0x2d, 0x31, 0x31, 0x64, 0x62, 0x2d, 0x38, 0x61, 0x66, 0x38, 0x2d, 0x39, 0x31, 0x64, 0x35, 0x34, 0x30, 0x33, 0x66, 0x39, 0x32, 0x66, 0x39, 0x27, 0x0a, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x61, 0x70, 0x3d, 0x27, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x27, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x21, 0x2d, 0x2d, 0x20, 0x78, 0x61, 0x70, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x73, 0x20, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x64, 0x20, 0x2d, 0x2d, 0x3e, 0x0a, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x0a, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x27, 0x75, 0x75, 0x69, 0x64, 0x3a, 0x32, 0x32, 0x64, 0x30, 0x32, 0x62, 0x30, 0x61, 0x2d, 0x62, 0x32, 0x34, 0x39, 0x2d, 0x31, 0x31, 0x64, 0x62, 0x2d, 0x38, 0x61, 0x66, 0x38, 0x2d, 0x39, 0x31, 0x64, 0x35, 0x34, 0x30, 0x33, 0x66, 0x39, 0x32, 0x66, 0x39, 0x27, 0x0a, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x61, 0x70, 0x4d, 0x4d, 0x3d, 0x27, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x61, 0x70, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x6d, 0x6d, 0x2f, 0x27, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x78, 0x61, 0x70, 0x4d, 0x4d, 0x3a, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x3e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x64, 0x6f, 0x63, 0x69, 0x64, 0x3a, 0x70, 0x68, 0x6f, 0x74, 0x6f, 0x73, 0x68, 0x6f, 0x70, 0x3a, 0x32, 0x32, 0x64, 0x30, 0x32, 0x62, 0x30, 0x36, 0x2d, 0x62, 0x32, 0x34, 0x39, 0x2d, 0x31, 0x31, 0x64, 0x62, 0x2d, 0x38, 0x61, 0x66, 0x38, 0x2d, 0x39, 0x31, 0x64, 0x35, 0x34, 0x30, 0x33, 0x66, 0x39, 0x32, 0x66, 0x39, 0x3c, 0x2f, 0x78, 0x61, 0x70, 0x4d, 0x4d, 0x3a, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x49, 0x44, 0x3e, 0x0a, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x0a, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d, 0x27, 0x75, 0x75, 0x69, 0x64, 0x3a, 0x32, 0x32, 0x64, 0x30, 0x32, 0x62, 0x30, 0x61, 0x2d, 0x62, 0x32, 0x34, 0x39, 0x2d, 0x31, 0x31, 0x64, 0x62, 0x2d, 0x38, 0x61, 0x66, 0x38, 0x2d, 0x39, 0x31, 0x64, 0x35, 0x34, 0x30, 0x33, 0x66, 0x39, 0x32, 0x66, 0x39, 0x27, 0x0a, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x64, 0x63, 0x3d, 0x27, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x70, 0x75, 0x72, 0x6c, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x64, 0x63, 0x2f, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x31, 0x2e, 0x31, 0x2f, 0x27, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x63, 0x3a, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x41, 0x6c, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64, 0x66, 0x3a, 0x6c, 0x69, 0x20, 0x78, 0x6d, 0x6c, 0x3a, 0x6c, 0x61, 0x6e, 0x67, 0x3d, 0x27, 0x78, 0x2d, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x27, 0x3e, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x6c, 0x69, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x41, 0x6c, 0x74, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x63, 0x3a, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x0a, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46, 0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x61, 0x70, 0x6d, 0x65, 0x74, 0x61, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x3c, 0x3f, 0x78, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x65, 0x6e, 0x64, 0x3d, 0x27, 0x77, 0x27, 0x3f, 0x3e, 0xff, 0xee, 0x00, 0x0e, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x00, 0x64, 0x40, 0x00, 0x00, 0x00, 0x01, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x03, 0x03, 0x04, 0x06, 0x04, 0x03, 0x04, 0x06, 0x07, 0x05, 0x04, 0x04, 0x05, 0x07, 0x08, 0x06, 0x06, 0x07, 0x06, 0x06, 0x08, 0x0a, 0x08, 0x09, 0x09, 0x09, 0x09, 0x08, 0x0a, 0x0a, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0a, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x01, 0x04, 0x05, 0x05, 0x08, 0x07, 0x08, 0x0f, 0x0a, 0x0a, 0x0f, 0x14, 0x0e, 0x0e, 0x0e, 0x14, 0x14, 0x0e, 0x0e, 0x0e, 0x0e, 0x14, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x11, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x64, 0x00, 0x64, 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xdd, 0x00, 0x04, 0x00, 0x0d, 0xff, 0xc4, 0x01, 0xa2, 0x00, 0x00, 0x00, 0x07, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x05, 0x03, 0x02, 0x06, 0x01, 0x00, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x02, 0x02, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x02, 0x06, 0x07, 0x03, 0x04, 0x02, 0x06, 0x02, 0x73, 0x01, 0x02, 0x03, 0x11, 0x04, 0x00, 0x05, 0x21, 0x12, 0x31, 0x41, 0x51, 0x06, 0x13, 0x61, 0x22, 0x71, 0x81, 0x14, 0x32, 0x91, 0xa1, 0x07, 0x15, 0xb1, 0x42, 0x23, 0xc1, 0x52, 0xd1, 0xe1, 0x33, 0x16, 0x62, 0xf0, 0x24, 0x72, 0x82, 0xf1, 0x25, 0x43, 0x34, 0x53, 0x92, 0xa2, 0xb2, 0x63, 0x73, 0xc2, 0x35, 0x44, 0x27, 0x93, 0xa3, 0xb3, 0x36, 0x17, 0x54, 0x64, 0x74, 0xc3, 0xd2, 0xe2, 0x08, 0x26, 0x83, 0x09, 0x0a, 0x18, 0x19, 0x84, 0x94, 0x45, 0x46, 0xa4, 0xb4, 0x56, 0xd3, 0x55, 0x28, 0x1a, 0xf2, 0xe3, 0xf3, 0xc4, 0xd4, 0xe4, 0xf4, 0x65, 0x75, 0x85, 0x95, 0xa5, 0xb5, 0xc5, 0xd5, 0xe5, 0xf5, 0x66, 0x76, 0x86, 0x96, 0xa6, 0xb6, 0xc6, 0xd6, 0xe6, 0xf6, 0x37, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xa7, 0xb7, 0xc7, 0xd7, 0xe7, 0xf7, 0x38, 0x48, 0x58, 0x68, 0x78, 0x88, 0x98, 0xa8, 0xb8, 0xc8, 0xd8, 0xe8, 0xf8, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79, 0x89, 0x99, 0xa9, 0xb9, 0xc9, 0xd9, 0xe9, 0xf9, 0x2a, 0x3a, 0x4a, 0x5a, 0x6a, 0x7a, 0x8a, 0x9a, 0xaa, 0xba, 0xca, 0xda, 0xea, 0xfa, 0x11, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x05, 0x05, 0x04, 0x05, 0x06, 0x04, 0x08, 0x03, 0x03, 0x6d, 0x01, 0x00, 0x02, 0x11, 0x03, 0x04, 0x21, 0x12, 0x31, 0x41, 0x05, 0x51, 0x13, 0x61, 0x22, 0x06, 0x71, 0x81, 0x91, 0x32, 0xa1, 0xb1, 0xf0, 0x14, 0xc1, 0xd1, 0xe1, 0x23, 0x42, 0x15, 0x52, 0x62, 0x72, 0xf1, 0x33, 0x24, 0x34, 0x43, 0x82, 0x16, 0x92, 0x53, 0x25, 0xa2, 0x63, 0xb2, 0xc2, 0x07, 0x73, 0xd2, 0x35, 0xe2, 0x44, 0x83, 0x17, 0x54, 0x93, 0x08, 0x09, 0x0a, 0x18, 0x19, 0x26, 0x36, 0x45, 0x1a, 0x27, 0x64, 0x74, 0x55, 0x37, 0xf2, 0xa3, 0xb3, 0xc3, 0x28, 0x29, 0xd3, 0xe3, 0xf3, 0x84, 0x94, 0xa4, 0xb4, 0xc4, 0xd4, 0xe4, 0xf4, 0x65, 0x75, 0x85, 0x95, 0xa5, 0xb5, 0xc5, 0xd5, 0xe5, 0xf5, 0x46, 0x56, 0x66, 0x76, 0x86, 0x96, 0xa6, 0xb6, 0xc6, 0xd6, 0xe6, 0xf6, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xa7, 0xb7, 0xc7, 0xd7, 0xe7, 0xf7, 0x38, 0x48, 0x58, 0x68, 0x78, 0x88, 0x98, 0xa8, 0xb8, 0xc8, 0xd8, 0xe8, 0xf8, 0x39, 0x49, 0x59, 0x69, 0x79, 0x89, 0x99, 0xa9, 0xb9, 0xc9, 0xd9, 0xe9, 0xf9, 0x2a, 0x3a, 0x4a, 0x5a, 0x6a, 0x7a, 0x8a, 0x9a, 0xaa, 0xba, 0xca, 0xda, 0xea, 0xfa, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf0, 0x67, 0xa6, 0x5c, 0x0f, 0x01, 0xd4, 0x7e, 0x18, 0x12, 0x98, 0xe9, 0xd6, 0x2d, 0x34, 0x6d, 0x70, 0xdf, 0xdc, 0xa1, 0xe3, 0xec, 0x5b, 0xfb, 0x32, 0x24, 0xb2, 0x01, 0x1f, 0x15, 0xa4, 0x52, 0x4a, 0x82, 0x31, 0xf1, 0xfe, 0xd1, 0x3d, 0x14, 0x64, 0x49, 0x64, 0x22, 0x98, 0xcf, 0xa5, 0x46, 0x6c, 0x16, 0x55, 0x71, 0x56, 0x62, 0x28, 0x07, 0xc5, 0x45, 0x15, 0xa0, 0xc8, 0x89, 0x33, 0xe1, 0x63, 0xd2, 0xd8, 0x34, 0x44, 0x17, 0xa0, 0x2c, 0x4d, 0x16, 0xbb, 0xed, 0xdc, 0xf8, 0x64, 0xc1, 0x6b, 0x31, 0x42, 0x18, 0x8e, 0xc7, 0xb5, 0x2a, 0x7d, 0xb2, 0x56, 0xc5, 0x61, 0x8c, 0xf2, 0xa0, 0x1b, 0x1e, 0x83, 0x0d, 0xa1, 0x63, 0x50, 0x1f, 0x97, 0x7c, 0x2a, 0xa9, 0x1a, 0x9a, 0x86, 0x4f, 0xb4, 0xb4, 0x38, 0x0a, 0xa6, 0x0b, 0xb8, 0x0c, 0x05, 0x14, 0xf8, 0x76, 0x3e, 0x19, 0x14, 0xb6, 0x78, 0xf8, 0x8c, 0x2a, 0xd5, 0x01, 0xdc, 0x6f, 0x8a, 0x1a, 0xe3, 0x8d, 0xab, 0xff, 0xd0, 0xf0, 0xec, 0xe9, 0x15, 0xb5, 0xb9, 0x5a, 0x7c, 0x4c, 0xa2, 0x9e, 0x24, 0xf5, 0xca, 0xc6, 0xe5, 0x99, 0xd9, 0x34, 0x99, 0x04, 0x3a, 0x7d, 0xb5, 0xba, 0xd5, 0x51, 0x63, 0x0e, 0xc7, 0xc5, 0x9b, 0x73, 0xf8, 0xe4, 0x6f, 0x76, 0xca, 0xd9, 0xda, 0x54, 0x6d, 0x72, 0x2e, 0x1a, 0x57, 0x11, 0x44, 0x40, 0x0d, 0x27, 0x7a, 0x0f, 0xd9, 0x5f, 0x12, 0x69, 0x4c, 0x84, 0xcd, 0x36, 0xe3, 0x85, 0xb2, 0xcd, 0x2f, 0x4a, 0x8b, 0x58, 0x36, 0xf6, 0x76, 0xa8, 0x64, 0x64, 0x3c, 0xa4, 0x93, 0xaa, 0x25, 0x3c, 0x49, 0xda, 0xa4, 0xe5, 0x26, 0x54, 0xe4, 0x8c, 0x7c, 0x5c, 0x93, 0x4d, 0x67, 0xc9, 0x3a, 0x6e, 0x9f, 0x13, 0xb4, 0xce, 0xf7, 0x3a, 0x9b, 0xad, 0x52, 0xd6, 0x2a, 0xd1, 0x49, 0xee, 0xc7, 0xf8, 0x64, 0x46, 0x42, 0x4e, 0xcd, 0x92, 0xc2, 0x00, 0xdd, 0x8a, 0x47, 0xe5, 0x69, 0x6e, 0xd4, 0xa4, 0x08, 0x16, 0x83, 0x9c, 0x8c, 0xdd, 0x95, 0x6b, 0xb9, 0xf6, 0xef, 0x97, 0x78, 0x94, 0xe3, 0x78, 0x04, 0xa4, 0xf3, 0xe8, 0xee, 0x64, 0xe1, 0x12, 0x10, 0x05, 0x6a, 0xc7, 0xc0, 0x6f, 0x53, 0xf3, 0xc9, 0x89, 0xb4, 0x9c, 0x4e, 0xb4, 0xf2, 0xd3, 0xde, 0x7a, 0xd2, 0x19, 0x16, 0x38, 0x61, 0x5d, 0xd9, 0x88, 0x05, 0x9c, 0xf4, 0x0a, 0x0f, 0x5f, 0x73, 0x84, 0xe4, 0xa4, 0xc7, 0x0d, 0xa5, 0xf1, 0x59, 0xba, 0x5c, 0x08, 0x98, 0x6f, 0xc8, 0x20, 0xfa, 0x4e, 0x4e, 0xf6, 0x69, 0xe1, 0xa2, 0x89, 0xfd, 0x1f, 0x77, 0x2c, 0xe6, 0xce, 0xd6, 0x17, 0x9a, 0x69, 0xdb, 0xd3, 0x86, 0x18, 0xc1, 0x67, 0x77, 0x26, 0x80, 0x28, 0x1b, 0x93, 0x88, 0x41, 0x0f, 0x40, 0xb0, 0xfc, 0x87, 0xf3, 0x43, 0x98, 0xd7, 0x58, 0x96, 0xdb, 0x4d, 0x91, 0x88, 0xe5, 0x6c, 0x58, 0xdc, 0x5c, 0x2a, 0xf7, 0x2c, 0xb1, 0xfc, 0x20, 0x8f, 0x02, 0xd9, 0x65, 0x06, 0xbe, 0x26, 0x6f, 0xa2, 0x7f, 0xce, 0x3d, 0x69, 0x26, 0xdd, 0x13, 0x52, 0xbf, 0xbd, 0x92, 0x62, 0x59, 0x4c, 0x90, 0xac, 0x50, 0x45, 0x5e, 0xbb, 0x09, 0x03, 0x12, 0x29, 0x84, 0x00, 0xc4, 0xc9, 0x11, 0xff, 0x00, 0x42, 0xe7, 0xa7, 0x7a, 0xd4, 0xfd, 0x21, 0x79, 0xe9, 0x78, 0x71, 0x8b, 0x95, 0x39, 0x75, 0xaf, 0x4e, 0x98, 0x78, 0x42, 0x38, 0xdf, 0xff, 0xd1, 0xf0, 0xe6, 0xa0, 0x58, 0xc8, 0x84, 0x9a, 0xaa, 0x30, 0x55, 0xf9, 0x0a, 0x6f, 0x90, 0x0c, 0xca, 0x72, 0x48, 0xb8, 0x1e, 0x89, 0xa7, 0x23, 0x17, 0x24, 0xff, 0x00, 0x61, 0xb6, 0x54, 0x76, 0x6e, 0x1b, 0xa7, 0xbe, 0x50, 0xf2, 0xc1, 0xd7, 0x4c, 0x52, 0x5e, 0x33, 0x5b, 0xe9, 0x10, 0xf4, 0x54, 0x3c, 0x5e, 0x77, 0xee, 0x49, 0xec, 0x2b, 0xb6, 0x63, 0xe4, 0xc9, 0xc3, 0xef, 0x73, 0xf0, 0xe1, 0x32, 0x1b, 0xf2, 0x7a, 0x05, 0xce, 0xad, 0x65, 0xa1, 0x98, 0xb4, 0x0f, 0x2a, 0x5b, 0x23, 0xeb, 0x12, 0x00, 0x88, 0xb0, 0xa8, 0x66, 0x46, 0x3d, 0xea, 0x7b, 0xfb, 0x9e, 0x99, 0x89, 0xbc, 0x8d, 0x97, 0x3a, 0x34, 0x05, 0x32, 0x5d, 0x1f, 0xc9, 0x1a, 0x8c, 0x36, 0x8c, 0x6f, 0x66, 0xfa, 0xc6, 0xb7, 0x7d, 0xf0, 0x94, 0x04, 0xf0, 0x88, 0xc9, 0xd5, 0x9d, 0x8d, 0x4b, 0x11, 0xd4, 0x9f, 0xbb, 0x25, 0xc5, 0xdc, 0xa2, 0x03, 0x99, 0x4b, 0xbc, 0xf3, 0x0d, 0x97, 0x96, 0x74, 0xe5, 0xf2, 0xb6, 0x80, 0x95, 0xbd, 0x99, 0x15, 0xf5, 0x4b, 0xd2, 0x37, 0x58, 0x46, 0xd4, 0x27, 0xc5, 0xce, 0xc1, 0x7c, 0x30, 0x8e, 0x68, 0x94, 0x7b, 0x9e, 0x6d, 0xe6, 0x7b, 0x9b, 0x5d, 0x3a, 0xd8, 0xdb, 0x32, 0xfa, 0x77, 0x65, 0x15, 0xe4, 0x57, 0xa7, 0x21, 0x55, 0x04, 0x57, 0xef, 0xd8, 0x66, 0x56, 0x38, 0x19, 0x1b, 0xe8, 0xe0, 0x67, 0x98, 0xc7, 0x1a, 0x1c, 0xde, 0x71, 0x71, 0x79, 0x2c, 0xf2, 0xfa, 0x8c, 0x48, 0xec, 0xb5, 0x24, 0x9a, 0x0c, 0xce, 0x75, 0x29, 0xae, 0x8c, 0x67, 0xd4, 0xb5, 0x0b, 0x4b, 0x04, 0x05, 0xef, 0x2e, 0x66, 0x8e, 0x18, 0x08, 0x15, 0xdd, 0x8f, 0x11, 0xb0, 0xeb, 0x4c, 0x04, 0x5b, 0x21, 0x2a, 0x7d, 0x41, 0xe4, 0x4f, 0xcb, 0xcb, 0x5d, 0x12, 0x45, 0xb8, 0xb7, 0x53, 0x71, 0xaa, 0x9f, 0x86, 0x5b, 0xd6, 0x50, 0x4a, 0xed, 0xba, 0x46, 0x77, 0x00, 0x13, 0xd4, 0x8c, 0x85, 0xd3, 0x12, 0x6d, 0xeb, 0x1a, 0x67, 0x95, 0xd9, 0x39, 0x39, 0x50, 0xac, 0xff, 0x00, 0x6f, 0xc4, 0xff, 0x00, 0x1c, 0x81, 0x92, 0xb2, 0x6b, 0x6d, 0x02, 0xdd, 0xbd, 0x36, 0x92, 0x36, 0x2d, 0x1f, 0xc0, 0x2a, 0x0b, 0x28, 0x1b, 0x91, 0x41, 0xf4, 0x9c, 0xb6, 0x25, 0x81, 0x46, 0xfe, 0x81, 0xb5, 0xad, 0x3d, 0xba, 0x57, 0xb7, 0xf9, 0xf6, 0xc9, 0xb0, 0x7f, 0xff, 0xd2, 0xf0, 0xe2, 0x86, 0x95, 0xc4, 0x67, 0x7e, 0x3f, 0x11, 0xf7, 0xa8, 0x19, 0x06, 0x69, 0x8d, 0xca, 0xca, 0x24, 0x8f, 0xd3, 0x52, 0x24, 0x89, 0x47, 0x25, 0x1f, 0xcb, 0x20, 0xf8, 0xb2, 0xb2, 0x76, 0x6e, 0x88, 0x36, 0xf6, 0x6f, 0x2a, 0xc1, 0x6e, 0xfa, 0x45, 0xad, 0xbc, 0x3f, 0x0b, 0x46, 0x81, 0x4d, 0x46, 0xea, 0x7a, 0x9a, 0x83, 0x9a, 0xa9, 0xdd, 0xbb, 0xec, 0x7b, 0x06, 0x5b, 0xe5, 0xcf, 0x2e, 0x69, 0xfa, 0x5c, 0xcd, 0x7b, 0x14, 0x5e, 0xa5, 0xee, 0xf5, 0xb8, 0x7d, 0xdd, 0x99, 0xba, 0xef, 0x91, 0x16, 0x5b, 0x36, 0xb6, 0x65, 0x0d, 0xac, 0xb2, 0x5b, 0xed, 0x34, 0x81, 0x7a, 0xbb, 0x46, 0x40, 0x6a, 0x9e, 0xb4, 0x39, 0x31, 0x13, 0x49, 0xda, 0xd2, 0x9b, 0xed, 0x1e, 0xc4, 0x24, 0xb3, 0x35, 0xb2, 0x88, 0x60, 0x06, 0xe6, 0x56, 0x98, 0x96, 0x79, 0x1e, 0x31, 0x51, 0xc9, 0x8f, 0xcb, 0x00, 0xe6, 0xb3, 0xe4, 0xf9, 0x2b, 0xcc, 0x7a, 0x94, 0xda, 0x96, 0xa9, 0x71, 0x77, 0x70, 0x79, 0xcd, 0x33, 0x97, 0x76, 0x3f, 0xcc, 0xc6, 0xa6, 0x9f, 0x2e, 0x99, 0xb9, 0xc6, 0x2a, 0x21, 0xe6, 0x73, 0xca, 0xe6, 0x4a, 0x51, 0x1a, 0x99, 0x1c, 0x28, 0x04, 0x93, 0xd0, 0x0e, 0xa4, 0xe4, 0xda, 0x5f, 0x50, 0xfe, 0x4a, 0xfe, 0x48, 0xb5, 0xb2, 0xc1, 0xe6, 0x1f, 0x31, 0x7e, 0xef, 0x52, 0x91, 0x43, 0xc3, 0x6e, 0x77, 0xf4, 0x22, 0x6d, 0xbf, 0xe4, 0x63, 0x0e, 0xbf, 0xca, 0x36, 0xeb, 0x5c, 0x84, 0xa5, 0x48, 0x7d, 0x3b, 0x61, 0xa1, 0xdb, 0x5b, 0x2c, 0x71, 0xda, 0x45, 0xc4, 0x28, 0x00, 0x81, 0xdb, 0x31, 0xc9, 0xb4, 0xb2, 0x3b, 0x5d, 0x27, 0xa5, 0x05, 0x1b, 0xc7, 0xdb, 0x10, 0xa9, 0xbd, 0xa6, 0x93, 0x0c, 0x75, 0xe4, 0x39, 0x35, 0x41, 0x3d, 0xc5, 0x06, 0xdb, 0x8e, 0xfd, 0x46, 0x5b, 0x1d, 0x98, 0x95, 0x4f, 0x46, 0xdb, 0xd5, 0xfb, 0x29, 0x5e, 0x9d, 0x0d, 0x32, 0xeb, 0x61, 0x4f, 0xff, 0xd3, 0xf1, 0x46, 0x9a, 0x16, 0x1b, 0x91, 0x71, 0x28, 0xac, 0x4a, 0x14, 0x30, 0x3e, 0x19, 0x54, 0xb9, 0x36, 0xc7, 0x9b, 0x2d, 0xd1, 0x6c, 0x45, 0xe3, 0xdc, 0xde, 0xc8, 0x95, 0x5b, 0x87, 0xf8, 0x41, 0x1d, 0x10, 0x54, 0x01, 0x98, 0x79, 0x25, 0xd1, 0xda, 0xe9, 0xe1, 0xb5, 0x9e, 0xac, 0xeb, 0x42, 0xba, 0x8e, 0xdf, 0x8c, 0x31, 0x21, 0x70, 0xb4, 0x5d, 0xbe, 0xc5, 0x7c, 0x2b, 0xed, 0xe1, 0x94, 0x18, 0xb9, 0x51, 0x3d, 0x03, 0x2c, 0x13, 0x6b, 0xf1, 0x42, 0x6e, 0xe2, 0xb7, 0x12, 0xa0, 0xdd, 0x50, 0x9f, 0x4f, 0x6f, 0xa7, 0x6f, 0xc7, 0x03, 0x61, 0xa0, 0x83, 0xb5, 0xf3, 0x97, 0x98, 0x20, 0x9c, 0x44, 0xea, 0xd0, 0xad, 0x48, 0x64, 0x90, 0x21, 0xd8, 0x9f, 0xa7, 0xa6, 0x44, 0xca, 0x99, 0xc6, 0x36, 0xcb, 0x74, 0x5d, 0x7e, 0x5b, 0xfe, 0x31, 0x6a, 0x31, 0xf3, 0x8c, 0xd0, 0xad, 0x40, 0xa3, 0x1f, 0x7c, 0x44, 0xd6, 0x51, 0xd9, 0xe0, 0x5f, 0x9a, 0x7e, 0x41, 0x9f, 0x40, 0xf3, 0x14, 0xba, 0x85, 0xba, 0x34, 0xba, 0x2d, 0xfb, 0x34, 0xd0, 0xcf, 0x4f, 0xb0, 0xce, 0x6a, 0x51, 0xe9, 0xb0, 0x20, 0xf4, 0xf1, 0x19, 0xb2, 0xc3, 0x90, 0x11, 0x4e, 0x97, 0x55, 0x80, 0x83, 0xc4, 0x17, 0x7e, 0x4c, 0x79, 0x19, 0xfc, 0xd1, 0xe7, 0x78, 0x4b, 0x91, 0x1d, 0xae, 0x92, 0xa6, 0xf6, 0x46, 0x75, 0xe4, 0xad, 0x22, 0x1f, 0xdd, 0xa1, 0x07, 0xb3, 0x1e, 0xfe, 0xd9, 0x92, 0xeb, 0x4b, 0xed, 0xfd, 0x0a, 0xc2, 0x63, 0x27, 0xa4, 0x88, 0x17, 0x60, 0x49, 0x35, 0xdc, 0x8e, 0xa5, 0x7d, 0xab, 0xd3, 0x28, 0x90, 0x50, 0xcd, 0xed, 0x2d, 0xda, 0x15, 0x55, 0x51, 0xf1, 0x1a, 0x0a, 0xf7, 0x39, 0x5d, 0xaa, 0x77, 0x6f, 0x01, 0x8e, 0xa7, 0x7d, 0xfa, 0xff, 0x00, 0x66, 0x10, 0xa8, 0xb8, 0x63, 0x76, 0x90, 0xa8, 0x20, 0x06, 0x56, 0xdb, 0x61, 0xda, 0xbd, 0x4f, 0xcb, 0x24, 0x15, 0x0f, 0xf5, 0x66, 0xe5, 0x5f, 0x4c, 0x53, 0xc3, 0xb7, 0xce, 0x99, 0x6b, 0x17, 0xff, 0xd4, 0xf0, 0xec, 0x57, 0x6f, 0x32, 0xa5, 0xa4, 0x43, 0x76, 0x75, 0xa9, 0xf1, 0x03, 0xfa, 0x64, 0x08, 0x6c, 0x8e, 0xfb, 0x3d, 0x7f, 0xcb, 0x16, 0x2b, 0x3d, 0xbc, 0x16, 0xa3, 0x66, 0x6d, 0x98, 0xfb, 0x1e, 0xb9, 0xac, 0xc8, 0x77, 0xb7, 0x7d, 0x01, 0xb3, 0x37, 0xb8, 0xd3, 0x46, 0x95, 0x68, 0x86, 0xd2, 0x2e, 0x4e, 0xab, 0xf0, 0x23, 0x11, 0x4e, 0x5f, 0xcd, 0x98, 0xe7, 0x25, 0x96, 0x71, 0x83, 0x0f, 0xd6, 0x3c, 0xb9, 0xe7, 0x0d, 0x7c, 0x41, 0x22, 0x5e, 0xb3, 0x20, 0x0c, 0x65, 0x80, 0xc8, 0x63, 0x8e, 0xbb, 0x95, 0xa5, 0x07, 0xeb, 0xcc, 0xac, 0x73, 0x83, 0x4e, 0x5c, 0x59, 0x09, 0xd8, 0xec, 0xc8, 0x57, 0x41, 0xd3, 0x4e, 0x95, 0xa5, 0x5b, 0x4b, 0x6a, 0xcb, 0xab, 0x43, 0x10, 0x4b, 0xeb, 0x85, 0xa2, 0x2c, 0x8e, 0x3f, 0x68, 0x54, 0xf5, 0x00, 0xd3, 0x97, 0x7a, 0x65, 0x79, 0xa6, 0x24, 0x76, 0x6f, 0xd3, 0x62, 0x96, 0x30, 0x78, 0xcb, 0x21, 0xf2, 0xf4, 0x22, 0xce, 0x54, 0x8e, 0x46, 0x26, 0x10, 0x7e, 0x0a, 0xf5, 0xd8, 0xf5, 0x1f, 0x31, 0x98, 0x83, 0x73, 0xb3, 0x91, 0xcd, 0x67, 0xe6, 0x7d, 0xe8, 0x16, 0x69, 0x6f, 0x10, 0x1f, 0x54, 0x9a, 0x37, 0xf5, 0x41, 0x5e, 0x7f, 0x0a, 0x29, 0x62, 0x02, 0xf8, 0x9c, 0xc8, 0x8c, 0x77, 0x6a, 0x99, 0xa0, 0x89, 0xff, 0x00, 0x9c, 0x74, 0xd2, 0xed, 0xed, 0xfc, 0xbb, 0x7b, 0xaa, 0x9a, 0x7d, 0x62, 0xfe, 0x46, 0x2d, 0xfe, 0x4c, 0x51, 0x31, 0x11, 0xa9, 0xf6, 0xef, 0x9b, 0x30, 0x5e, 0x7b, 0x38, 0xdd, 0xf4, 0x7f, 0x95, 0x94, 0xbc, 0x12, 0x43, 0x30, 0x6a, 0xb2, 0xf3, 0x86, 0x40, 0x3e, 0xcb, 0xd7, 0x6a, 0xd7, 0xb1, 0xe9, 0x8f, 0x37, 0x19, 0x97, 0x41, 0x2c, 0x71, 0x20, 0xf5, 0x36, 0x9c, 0x55, 0x78, 0x1d, 0x8a, 0x91, 0xd7, 0x11, 0x14, 0x5a, 0x3e, 0x19, 0x03, 0x10, 0x6b, 0xca, 0xbd, 0x86, 0xf8, 0x9d, 0x95, 0x18, 0x36, 0x65, 0x2e, 0xbc, 0x54, 0x1f, 0xa2, 0x99, 0x00, 0x59, 0x2a, 0x6f, 0x5e, 0x55, 0x15, 0xe9, 0x5f, 0xc3, 0x2f, 0xb6, 0x14, 0xff, 0x00, 0xff, 0xd5, 0xf1, 0x95, 0xfe, 0x80, 0x74, 0x0d, 0x7c, 0xd9, 0x89, 0x3d, 0x78, 0x57, 0x8b, 0xc5, 0x28, 0xe8, 0x55, 0xf7, 0x1f, 0x48, 0xca, 0x38, 0xb8, 0x83, 0x9f, 0x93, 0x07, 0x85, 0x3a, 0x7a, 0x6f, 0x95, 0x66, 0x2b, 0x2c, 0x4c, 0x0d, 0x14, 0x00, 0x3e, 0x9c, 0xc3, 0x98, 0x76, 0xb8, 0x45, 0xbd, 0x02, 0xde, 0x48, 0xee, 0xdc, 0xa0, 0x15, 0xe2, 0x2b, 0xc8, 0x8a, 0x8a, 0xfd, 0x3b, 0x66, 0x3f, 0x00, 0x73, 0x84, 0x2d, 0x36, 0xb5, 0xb5, 0x9e, 0x35, 0x1c, 0x29, 0xc4, 0xfe, 0xc8, 0x04, 0x7f, 0xc4, 0x69, 0x91, 0xe1, 0x67, 0x2c, 0x4a, 0xd2, 0xe9, 0x4e, 0xe3, 0xd4, 0xf4, 0x81, 0x5a, 0x12, 0xc5, 0x41, 0x3f, 0x79, 0x38, 0x9b, 0x60, 0x20, 0x07, 0x34, 0xb0, 0xc9, 0x03, 0x5c, 0x23, 0x03, 0x53, 0x13, 0x56, 0x88, 0xdf, 0x09, 0xda, 0x9b, 0xd3, 0xb6, 0x52, 0x0e, 0xec, 0xe4, 0x29, 0x24, 0xfc, 0xd0, 0xe7, 0x75, 0xe5, 0x57, 0x6b, 0x61, 0xfb, 0xf0, 0xca, 0xaa, 0x57, 0xa8, 0xe6, 0x78, 0x1a, 0x7d, 0xf9, 0x95, 0x8a, 0x5e, 0xa0, 0xe3, 0x67, 0x8f, 0xa0, 0xbd, 0x5b, 0xf2, 0xdf, 0x4a, 0x82, 0xcb, 0x4a, 0xb3, 0xb0, 0xb4, 0x41, 0x0a, 0x70, 0x48, 0xd9, 0x57, 0x60, 0x51, 0x3a, 0x8f, 0xbc, 0xe6, 0x7b, 0xcb, 0xe4, 0x3b, 0xa7, 0x3f, 0x9b, 0x9f, 0x9a, 0xba, 0x77, 0xe5, 0x5f, 0x95, 0x9c, 0x59, 0x94, 0x9f, 0xcd, 0x37, 0x8c, 0xa9, 0xa6, 0xd9, 0x39, 0xaa, 0xd0, 0x7d, 0xa9, 0x1c, 0x03, 0x5e, 0x09, 0xff, 0x00, 0x0c, 0x76, 0xcb, 0x62, 0x2d, 0xa5, 0xf2, 0x85, 0xbf, 0xe7, 0x87, 0xe6, 0xa3, 0x5e, 0x4d, 0xa8, 0xc9, 0xe6, 0x8b, 0xd5, 0x69, 0x5c, 0xb0, 0x4a, 0xab, 0xc4, 0xb5, 0x35, 0x0a, 0xaa, 0xea, 0x40, 0x03, 0xa0, 0xf6, 0xcb, 0x40, 0x4d, 0x3e, 0xdb, 0xff, 0x00, 0x9c, 0x7f, 0xfc, 0xce, 0x4f, 0xcc, 0xbf, 0x26, 0x25, 0xe5, 0xd3, 0x2f, 0xe9, 0xdd, 0x3d, 0xfe, 0xab, 0xa9, 0xaa, 0xd2, 0xa6, 0x40, 0x2a, 0xb2, 0x71, 0x00, 0x01, 0xea, 0x0d, 0xe8, 0x3a, 0x64, 0x25, 0x16, 0x1c, 0x8b, 0xd9, 0x51, 0x39, 0x28, 0x12, 0x51, 0x41, 0xfd, 0xa3, 0xd2, 0xb9, 0x4f, 0x0d, 0x33, 0xb5, 0xf4, 0x87, 0x9d, 0x79, 0x0e, 0xb4, 0xaf, 0x6a, 0xf8, 0xf1, 0xf0, 0xc9, 0xda, 0xbf, 0xff, 0xd6, 0xf2, 0xc6, 0xb5, 0x68, 0x64, 0xd0, 0x6d, 0x35, 0x20, 0x39, 0xcd, 0x13, 0x0f, 0x5e, 0x61, 0xfc, 0x8f, 0x40, 0x8b, 0x5e, 0xe0, 0x66, 0x1c, 0x4f, 0xaa, 0x9d, 0xe6, 0xa6, 0x1e, 0x91, 0x2e, 0xa9, 0x87, 0x95, 0xee, 0x9c, 0xc5, 0x55, 0x34, 0x60, 0x40, 0xae, 0x57, 0x30, 0xd9, 0xa7, 0x95, 0xbd, 0x6f, 0xcb, 0x26, 0x39, 0x40, 0x0d, 0x4e, 0xc0, 0x9f, 0x9e, 0x50, 0x5d, 0xac, 0x79, 0x33, 0x8b, 0xbb, 0x9b, 0x3b, 0x6b, 0x35, 0x48, 0x54, 0x09, 0x29, 0x56, 0x7f, 0xe1, 0x86, 0x72, 0x00, 0x2c, 0x6e, 0xf7, 0x63, 0x3e, 0x63, 0xbd, 0xbd, 0x5d, 0x20, 0x2a, 0xb3, 0xa4, 0x33, 0x48, 0xab, 0x21, 0x43, 0xf1, 0x2c, 0x47, 0xed, 0x1d, 0xbc, 0x73, 0x18, 0x9b, 0x64, 0x28, 0x96, 0x3a, 0xc7, 0x49, 0xb0, 0xf4, 0xcc, 0xe9, 0x73, 0x6c, 0xb4, 0xf8, 0x67, 0x92, 0x32, 0x21, 0x70, 0x7b, 0x89, 0x05, 0x57, 0xef, 0x38, 0x28, 0x94, 0x4a, 0x7d, 0x13, 0x7d, 0x6a, 0xd3, 0x4c, 0xb8, 0xf2, 0xc3, 0xc8, 0x2e, 0x03, 0xf3, 0xe2, 0x7d, 0x33, 0xb7, 0xc5, 0xcc, 0x71, 0x03, 0xc6, 0xb9, 0x64, 0x06, 0xe2, 0x9a, 0xf2, 0x4f, 0xd2, 0x6d, 0xe9, 0xfe, 0x41, 0x45, 0x5b, 0x18, 0x66, 0xa5, 0x64, 0x09, 0xf4, 0xd5, 0xb7, 0xcd, 0x93, 0xc7, 0xcf, 0x9b, 0xe5, 0x6f, 0xf9, 0xc8, 0x0d, 0x56, 0xeb, 0x59, 0xfc, 0xce, 0xd5, 0x12, 0x61, 0xc4, 0x69, 0xe9, 0x0d, 0xa4, 0x4b, 0xfe, 0x48, 0x40, 0xd5, 0x3e, 0xe4, 0xb6, 0x64, 0x8e, 0x4c, 0x02, 0x61, 0x65, 0xa0, 0x14, 0xb4, 0xb6, 0xb0, 0xb1, 0xb6, 0xb2, 0x97, 0xcb, 0xf1, 0x5a, 0x2d, 0xc6, 0xa5, 0xac, 0xb4, 0x70, 0x5d, 0xc7, 0x3d, 0xc1, 0x51, 0x24, 0x91, 0xc9, 0x31, 0x75, 0x6b, 0x70, 0x9f, 0x14, 0x68, 0x01, 0x46, 0xe4, 0xb5, 0xa3, 0x17, 0xcb, 0x40, 0x61, 0x6f, 0x47, 0xff, 0x00, 0x9c, 0x3a, 0x8f, 0x5b, 0x4f, 0x3c, 0x6b, 0xb7, 0xfa, 0x30, 0x91, 0x3c, 0xa4, 0xb1, 0x95, 0xb9, 0x82, 0x42, 0x0a, 0xbc, 0x8e, 0xe4, 0xdb, 0xa9, 0xef, 0xc9, 0x17, 0x91, 0x24, 0x7c, 0xb2, 0x05, 0x64, 0xfb, 0x75, 0x64, 0x32, 0x39, 0x69, 0x5b, 0x9c, 0xad, 0xb9, 0xdb, 0xa7, 0xb5, 0x3b, 0x53, 0x2a, 0x21, 0x41, 0x44, 0xf3, 0x8b, 0x8f, 0x2e, 0x43, 0x9d, 0x2b, 0xd4, 0x57, 0x23, 0x41, 0x36, 0xff, 0x00, 0xff, 0xd7, 0xf0, 0xc0, 0xd5, 0xb5, 0x11, 0x64, 0xb6, 0x3f, 0x59, 0x90, 0xd9, 0xab, 0x06, 0xf4, 0x79, 0x7c, 0x3b, 0x74, 0xc8, 0x08, 0x8b, 0xb6, 0xe3, 0x96, 0x55, 0x57, 0xb3, 0x3e, 0xf2, 0x35, 0xc7, 0xd6, 0x0b, 0x45, 0x5d, 0xdc, 0x8a, 0x7d, 0xd9, 0x8d, 0x94, 0x3b, 0x3d, 0x1c, 0x9e, 0xc3, 0xe5, 0xc3, 0x2c, 0x7c, 0xc5, 0x0f, 0xee, 0xdb, 0x8b, 0x0c, 0xc4, 0x26, 0x9d, 0xa0, 0x9a, 0x7d, 0x2c, 0xe5, 0xe4, 0x55, 0x7f, 0xee, 0xc1, 0x15, 0x04, 0xd0, 0x12, 0x3c, 0x72, 0x89, 0x1b, 0x2c, 0xcc, 0xa8, 0x2a, 0x8b, 0x87, 0xbb, 0x63, 0x1a, 0x28, 0x65, 0xf0, 0xed, 0xf2, 0xc3, 0xc2, 0x0a, 0x06, 0x4a, 0x46, 0xc7, 0xa5, 0xa3, 0x59, 0xc8, 0xb2, 0xc7, 0x45, 0x22, 0x9c, 0x14, 0x54, 0x10, 0x46, 0xf5, 0x1d, 0x32, 0x5c, 0x14, 0x14, 0xe4, 0x32, 0x2f, 0x3a, 0xf3, 0xb6, 0x90, 0x9a, 0x6d, 0xae, 0x9f, 0x3d, 0xab, 0xb8, 0x8a, 0x3b, 0xf8, 0x39, 0x44, 0x58, 0xf0, 0x08, 0xd5, 0x14, 0xa5, 0x7b, 0x65, 0x98, 0x8e, 0xfb, 0xb5, 0x67, 0x87, 0xa5, 0xef, 0x5e, 0x44, 0x96, 0x35, 0xb5, 0xb6, 0x59, 0x36, 0xfd, 0xd8, 0xa0, 0xf1, 0x20, 0x53, 0x33, 0xc0, 0x79, 0x59, 0x73, 0x7c, 0xd7, 0xf9, 0xfb, 0xa2, 0xcd, 0x67, 0xf9, 0xa7, 0x7b, 0x72, 0xf1, 0x71, 0x83, 0x53, 0x86, 0x0b, 0x98, 0x24, 0x22, 0x8a, 0xcc, 0x88, 0x23, 0x7f, 0xb8, 0xae, 0xf9, 0x7c, 0x50, 0x1e, 0x5f, 0x7c, 0x48, 0x21, 0x44, 0x6b, 0xce, 0x9b, 0xb0, 0x1b, 0x9e, 0xf5, 0xaf, 0x8e, 0x4d, 0x5f, 0x7a, 0x7f, 0xce, 0x34, 0xf9, 0x5d, 0x3c, 0xa3, 0xf9, 0x69, 0x63, 0xa9, 0x3c, 0x27, 0xeb, 0xda, 0xe1, 0x37, 0xd7, 0x2e, 0xaa, 0xdb, 0x06, 0xda, 0x30, 0x49, 0xfe, 0x54, 0x03, 0x03, 0x49, 0xdc, 0xb3, 0xaf, 0x38, 0xfe, 0x6a, 0xf9, 0x47, 0xc9, 0x3a, 0x74, 0x97, 0xfa, 0xf6, 0xaf, 0x15, 0x85, 0xb8, 0x75, 0x89, 0xb8, 0x87, 0x9a, 0x72, 0xee, 0x2a, 0x14, 0x24, 0x60, 0xb1, 0xa8, 0xdf, 0x07, 0x0b, 0x2d, 0xcb, 0xcf, 0x7f, 0xe8, 0x6a, 0xff, 0x00, 0x26, 0xbd, 0x6a, 0x7f, 0x89, 0x2f, 0xf8, 0x52, 0x9e, 0xb7, 0xe8, 0xb9, 0xb8, 0x57, 0xc2, 0x95, 0xe9, 0x8f, 0x08, 0x5a, 0x2f, 0xff, 0xd0, 0xf0, 0x4d, 0x40, 0xaa, 0xd7, 0x00, 0x64, 0xcb, 0x3c, 0x97, 0xa8, 0xb5, 0x9e, 0xa3, 0x1a, 0xd6, 0x84, 0x95, 0x3f, 0x45, 0x72, 0x9c, 0xa2, 0xc3, 0x99, 0xa5, 0x9d, 0x49, 0xf4, 0x17, 0x97, 0xaf, 0x63, 0x17, 0x52, 0x6f, 0xf0, 0xc8, 0x43, 0x6f, 0x9a, 0xe9, 0x07, 0x70, 0x0e, 0xec, 0x83, 0x51, 0x44, 0xb8, 0x61, 0x1a, 0x9e, 0x11, 0xd3, 0x91, 0x60, 0x68, 0x6b, 0xd3, 0x31, 0x4f, 0x36, 0xd3, 0x4c, 0x52, 0xef, 0x4c, 0xd5, 0x0c, 0xc4, 0x69, 0xda, 0x94, 0xc8, 0x3a, 0xf0, 0x66, 0x07, 0x73, 0xe0, 0x40, 0xfd, 0x79, 0x93, 0x12, 0x1c, 0x9c, 0x32, 0xc7, 0xfc, 0x41, 0x33, 0xd2, 0xb4, 0x6f, 0x38, 0x98, 0x65, 0x76, 0xbf, 0x69, 0x42, 0xd0, 0xaa, 0xc9, 0xde, 0x95, 0xad, 0x28, 0x46, 0x4e, 0xac, 0x39, 0x77, 0x80, 0x11, 0xbf, 0xd8, 0xc7, 0x7c, 0xe1, 0xa5, 0xf9, 0x92, 0x4d, 0x32, 0x5b, 0x8b, 0x93, 0x27, 0xa7, 0x68, 0x56, 0xe2, 0x45, 0xda, 0x85, 0x61, 0x6e, 0x67, 0xad, 0x6b, 0xb0, 0x38, 0xc2, 0x81, 0xe4, 0xc7, 0x52, 0x31, 0x1c, 0x67, 0x86, 0x5b, 0xbd, 0x37, 0xca, 0x7a, 0x94, 0xb1, 0x69, 0xb6, 0x2e, 0xb7, 0x15, 0x48, 0xc2, 0xb4, 0x52, 0x53, 0xac, 0x32, 0xaf, 0xb1, 0xed, 0x9b, 0x10, 0x36, 0x78, 0x5c, 0x9f, 0x51, 0x64, 0x1f, 0x98, 0x3e, 0x58, 0xb6, 0xfc, 0xc8, 0xf2, 0xe5, 0xbc, 0x68, 0x52, 0x2d, 0x5a, 0xd1, 0x84, 0xb6, 0xf3, 0x95, 0x0e, 0xc0, 0x85, 0xe2, 0xcb, 0xd8, 0xd1, 0xbb, 0xe4, 0xc1, 0xa6, 0x97, 0xce, 0x17, 0x5f, 0x95, 0xde, 0x6d, 0xb6, 0xbe, 0xb7, 0x69, 0x34, 0xf3, 0x3c, 0x72, 0xcf, 0xe8, 0xa3, 0x45, 0x49, 0x95, 0x4a, 0x90, 0x3e, 0x35, 0x5a, 0x95, 0x1d, 0xfe, 0x21, 0x93, 0x4d, 0xbe, 0xd2, 0xd2, 0xf5, 0x8b, 0xbd, 0x32, 0x2d, 0x3f, 0x4c, 0x9a, 0xe4, 0xca, 0x9e, 0x90, 0x85, 0x65, 0x55, 0x08, 0x85, 0x91, 0x01, 0x3b, 0x0a, 0x05, 0xe9, 0xb0, 0xc0, 0x5a, 0xc3, 0xcd, 0x3f, 0x3b, 0x7f, 0x26, 0xec, 0xff, 0x00, 0x35, 0x6d, 0x6d, 0xb5, 0x3d, 0x16, 0xfe, 0x0d, 0x3b, 0xcd, 0x96, 0x01, 0x92, 0x46, 0x9e, 0xa2, 0x0b, 0xc8, 0xb7, 0x28, 0x92, 0x71, 0xfb, 0x2e, 0xa7, 0xec, 0x3d, 0x0f, 0xc2, 0x68, 0x71, 0x05, 0x95, 0xd3, 0xe7, 0x9f, 0xfa, 0x16, 0x2f, 0xcd, 0x7f, 0x43, 0xd6, 0xfa, 0xa5, 0x97, 0xab, 0xeb, 0x7a, 0x5f, 0x55, 0xfa, 0xec, 0x5e, 0xaf, 0x0f, 0xf7, 0xed, 0x2b, 0x4e, 0x15, 0xff, 0x00, 0x65, 0xdf, 0x8e, 0x14, 0xf1, 0xbf, 0xff, 0xd1, 0xf0, 0x5a, 0xa7, 0x18, 0x5e, 0x56, 0x1f, 0x68, 0x71, 0x5f, 0xa7, 0xbe, 0x2a, 0x98, 0xdb, 0xfa, 0x90, 0x24, 0x37, 0xb0, 0xfd, 0xb8, 0xa8, 0x58, 0x78, 0xae, 0x43, 0xc9, 0xb4, 0x6d, 0xbb, 0xda, 0x3c, 0xa1, 0xad, 0x43, 0xa8, 0xda, 0xc5, 0x2a, 0x3d, 0x26, 0x5a, 0x02, 0x2b, 0xbe, 0x60, 0x64, 0x8d, 0x17, 0x6f, 0x8b, 0x20, 0x90, 0x7a, 0x3c, 0x32, 0x8b, 0xa8, 0x02, 0xf3, 0xfd, 0xe0, 0x1b, 0x11, 0x98, 0x66, 0x3b, 0xb9, 0x62, 0x54, 0x83, 0x36, 0xf2, 0xa4, 0xe4, 0x29, 0x34, 0xeb, 0xc8, 0x74, 0xae, 0x0d, 0xc3, 0x65, 0x82, 0x13, 0x6b, 0x57, 0xba, 0x54, 0xe4, 0x8c, 0x41, 0x1b, 0x75, 0xa7, 0xe0, 0x72, 0x5c, 0x4c, 0x84, 0x50, 0x5a, 0xb3, 0xdd, 0xdd, 0xc3, 0x24, 0x33, 0xb1, 0x60, 0xe0, 0x86, 0x52, 0x45, 0x38, 0xd2, 0x87, 0x24, 0x26, 0x6d, 0x8c, 0xe1, 0x41, 0x25, 0xfc, 0xa3, 0xd7, 0x2f, 0x6f, 0x3c, 0xbf, 0x73, 0xa5, 0xb2, 0x2c, 0xd1, 0x69, 0x17, 0x2f, 0x6b, 0x14, 0x8c, 0x0f, 0x21, 0x0d, 0x79, 0x46, 0x09, 0x15, 0xed, 0xb7, 0x4e, 0xd9, 0xb9, 0x8b, 0xcb, 0xe4, 0xa2, 0x5e, 0xa3, 0xa6, 0xdf, 0x6a, 0x36, 0xe4, 0xcd, 0x69, 0x1c, 0x4e, 0x84, 0x7c, 0x76, 0xab, 0x21, 0x67, 0xa8, 0xa7, 0xd9, 0xf8, 0x4d, 0x2b, 0xf3, 0xc3, 0x4d, 0x49, 0x57, 0x98, 0x75, 0x6f, 0x31, 0xda, 0xf9, 0xa3, 0x4b, 0xfd, 0x1f, 0x69, 0x1d, 0xae, 0xa1, 0xa9, 0x7e, 0xee, 0xe6, 0xd2, 0x79, 0x18, 0xf3, 0xb5, 0x1f, 0xee, 0xd9, 0x0a, 0x01, 0x4e, 0x3f, 0xb3, 0x4d, 0xf2, 0x9c, 0xb9, 0x04, 0x05, 0xb7, 0xe2, 0x87, 0x1e, 0xdd, 0x19, 0x3e, 0xaf, 0x6b, 0xae, 0xcb, 0x6d, 0x13, 0x0d, 0x45, 0xa2, 0x8e, 0x06, 0xe5, 0x13, 0x2a, 0x02, 0x01, 0x5e, 0x82, 0xb5, 0x04, 0xe6, 0x11, 0xd4, 0xcd, 0xda, 0x43, 0x49, 0x8e, 0xb7, 0xdc, 0xb1, 0x51, 0xe6, 0x4d, 0x76, 0xd2, 0x61, 0x15, 0xaa, 0x4b, 0xa8, 0xc9, 0x6e, 0x49, 0x79, 0x20, 0xe6, 0x8c, 0x49, 0xad, 0x43, 0x16, 0xe4, 0xa7, 0xaf, 0x43, 0xd3, 0x26, 0x35, 0x75, 0xcd, 0xa8, 0xe8, 0x87, 0x46, 0xbf, 0xc7, 0x9a, 0xff, 0x00, 0xd6, 0xbf, 0x48, 0xfe, 0x88, 0xfd, 0xe7, 0x0f, 0xab, 0xfa, 0x3f, 0x58, 0x7f, 0x5f, 0x8d, 0x3f, 0x9f, 0xa7, 0x5e, 0xd4, 0xc3, 0xf9, 0xd1, 0x7c, 0xb6, 0x47, 0xe4, 0x3a, 0x5b, 0xff, 0xd2, 0xf0, 0xb7, 0xa6, 0x1e, 0xdf, 0xd3, 0xf6, 0xa5, 0x71, 0x54, 0xdb, 0x4b, 0x80, 0x3c, 0x42, 0x26, 0xee, 0x29, 0xbe, 0x51, 0x23, 0x4e, 0x44, 0x05, 0x84, 0x45, 0xa5, 0xd5, 0xf7, 0x97, 0x2e, 0xfd, 0x6b, 0x6a, 0x98, 0x09, 0xab, 0xc7, 0xfc, 0x46, 0x3b, 0x4c, 0x26, 0x32, 0x30, 0x3e, 0x4f, 0x49, 0xd0, 0xfc, 0xfb, 0x05, 0xd4, 0x4a, 0x7d, 0x40, 0xac, 0x3a, 0x8e, 0x84, 0x1c, 0xc5, 0x96, 0x2a, 0x73, 0xe1, 0x9c, 0x16, 0x6d, 0xa5, 0x79, 0x86, 0xd6, 0xec, 0x80, 0x5a, 0xa0, 0xf5, 0xca, 0xcc, 0x5c, 0xa1, 0x2b, 0x1b, 0x26, 0x30, 0x6a, 0x31, 0x46, 0xcf, 0x1c, 0x87, 0x94, 0x64, 0x9e, 0x3d, 0xb6, 0xf0, 0xca, 0xa8, 0x39, 0x51, 0x99, 0x42, 0x6b, 0x1a, 0xc5, 0xa5, 0xa5, 0x94, 0xf7, 0x92, 0xc8, 0xaa, 0xb1, 0x23, 0x30, 0x04, 0xf8, 0x0e, 0x9f, 0x4e, 0x4a, 0x11, 0xb2, 0xd5, 0x9b, 0x25, 0x06, 0x1b, 0xff, 0x00, 0x38, 0xfd, 0xad, 0xdf, 0xda, 0xf9, 0xa2, 0xfe, 0xc5, 0x42, 0xbe, 0x9b, 0x7f, 0x0b, 0xdd, 0xdd, 0x07, 0xaf, 0x14, 0x68, 0xd8, 0x71, 0x6d, 0xbb, 0x90, 0xfc, 0x73, 0x6e, 0xf2, 0xf2, 0xdd, 0xf4, 0xad, 0xa6, 0xab, 0x6d, 0x69, 0x14, 0xfa, 0xee, 0xa0, 0xe2, 0x0b, 0x0d, 0x39, 0x19, 0xfe, 0x11, 0xc5, 0x1a, 0x4a, 0x1d, 0x8f, 0x73, 0x4f, 0xf8, 0x96, 0x0b, 0x40, 0x8d, 0xec, 0xf3, 0x6d, 0x3f, 0x52, 0xba, 0xd6, 0x35, 0x8b, 0xbf, 0x36, 0x6a, 0x5f, 0x0d, 0xc5, 0xdc, 0xa8, 0xb6, 0xa8, 0x7a, 0xc5, 0x6c, 0x9b, 0x22, 0x0f, 0xa3, 0x73, 0x9a, 0xbc, 0xb3, 0xe2, 0x36, 0xed, 0xb1, 0x43, 0x80, 0x53, 0xd0, 0xa7, 0xd4, 0x44, 0xfa, 0x7a, 0xda, 0x83, 0xbd, 0x3e, 0x2f, 0xa7, 0x2b, 0xad, 0x9b, 0xb8, 0x8d, 0xa8, 0xe8, 0x91, 0xdb, 0xfa, 0x2d, 0x6f, 0xc3, 0x8a, 0x2d, 0x56, 0xa3, 0xad, 0x4f, 0x5c, 0xa4, 0x0d, 0xdc, 0xa3, 0xca, 0xd0, 0xbf, 0xa1, 0xe3, 0xfa, 0xe7, 0x0f, 0xf2, 0xb9, 0x57, 0xbf, 0x1a, 0xe4, 0xb8, 0x57, 0xc5, 0xdd, 0xff, 0xd3, 0xf0, 0xcc, 0x5d, 0x7b, 0x70, 0xc5, 0x53, 0x6d, 0x2f, 0xd5, 0xe4, 0x69, 0xfd, 0xdf, 0xec, 0xd7, 0xad, 0x7d, 0xb2, 0x8c, 0x8d, 0xd8, 0xed, 0x91, 0x9f, 0x43, 0xea, 0xe7, 0xeb, 0x94, 0xad, 0x3e, 0x1e, 0x95, 0xfc, 0x72, 0x81, 0x7d, 0x1c, 0x9d, 0xba, 0xb1, 0x7b, 0xdf, 0xa9, 0x7a, 0xdf, 0xee, 0x2f, 0xd4, 0xfa, 0xe7, 0xed, 0x7a, 0x7f, 0xdd, 0xff, 0x00, 0xb2, 0xae, 0x64, 0x0b, 0xea, 0xe3, 0x9a, 0xbf, 0x4a, 0x6f, 0xa4, 0xff, 0x00, 0x89, 0xbd, 0x45, 0xfa, 0xb5, 0x79, 0xf7, 0xeb, 0xc7, 0xe9, 0xae, 0x57, 0x2e, 0x17, 0x23, 0x1f, 0x89, 0xd1, 0x99, 0x8f, 0xf1, 0xa7, 0x11, 0xcf, 0xd3, 0xf5, 0x29, 0xb5, 0x6b, 0xd3, 0xe8, 0xcc, 0x7f, 0x45, 0xb9, 0xa3, 0xc5, 0x62, 0xbe, 0x68, 0xff, 0x00, 0x15, 0xfd, 0x4c, 0xfe, 0x90, 0xaf, 0xd4, 0xab, 0xf1, 0x7a, 0x7f, 0x62, 0x9d, 0xab, 0xdf, 0x32, 0xb1, 0x70, 0x5e, 0xdc, 0xdc, 0x2d, 0x47, 0x8b, 0x5e, 0xae, 0x4c, 0xbf, 0xf2, 0x37, 0x9f, 0x3d, 0x5b, 0xd2, 0xff, 0x00, 0x8e, 0x87, 0xee, 0x29, 0x5a, 0xf2, 0xf4, 0xaa, 0xd4, 0xa5, 0x36, 0xa7, 0x3a, 0x57, 0xfd, 0x8e, 0x64, 0x3a, 0xf2, 0xf6, 0xbf, 0xcc, 0x7f, 0x5b, 0xfc, 0x23, 0xa7, 0xfe, 0x8e, 0xff, 0x00, 0x8e, 0x37, 0xd6, 0x63, 0xfa, 0xe5, 0x2b, 0xcb, 0x87, 0xec, 0xd6, 0xbd, 0xb9, 0x7d, 0xac, 0xc7, 0xcd, 0x7c, 0x2d, 0xf8, 0x2b, 0x89, 0x26, 0x8f, 0xd4, 0xfa, 0x94, 0x3e, 0x85, 0x29, 0xc9, 0x69, 0xfc, 0x33, 0x58, 0x5d, 0x9c, 0x79, 0xb2, 0xbb, 0x0f, 0xac, 0x7a, 0x2b, 0xea, 0x75, 0xef, 0x92, 0x0c, 0x53, 0x3d, 0x2f, 0xd4, 0xfa, 0xbb, 0xfa, 0x74, 0xf5, 0x39, 0x9a, 0xd7, 0xe7, 0x80, 0x53, 0x79, 0xba, 0x5b, 0xfe, 0x97, 0xfa, 0x4b, 0xfc, 0xba, 0x7f, 0xb1, 0xc7, 0xab, 0x1e, 0x8f, 0xff, 0xd9
-};
diff --git a/base/testclient.cc b/base/testclient.cc
deleted file mode 100644
index 92e1f39..0000000
--- a/base/testclient.cc
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/testclient.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-// DESIGN: Each packet received is put it into a list of packets.
-// Callers can retrieve received packets from any thread by calling
-// NextPacket.
-
-TestClient::TestClient(AsyncPacketSocket* socket)
- : socket_(socket), ready_to_send_(false) {
- packets_ = new std::vector<Packet*>();
- socket_->SignalReadPacket.connect(this, &TestClient::OnPacket);
- socket_->SignalReadyToSend.connect(this, &TestClient::OnReadyToSend);
-}
-
-TestClient::~TestClient() {
- delete socket_;
- for (unsigned i = 0; i < packets_->size(); i++)
- delete (*packets_)[i];
- delete packets_;
-}
-
-bool TestClient::CheckConnState(AsyncPacketSocket::State state) {
- // Wait for our timeout value until the socket reaches the desired state.
- uint32 end = TimeAfter(kTimeout);
- while (socket_->GetState() != state && TimeUntil(end) > 0)
- Thread::Current()->ProcessMessages(1);
- return (socket_->GetState() == state);
-}
-
-int TestClient::Send(const char* buf, size_t size) {
- talk_base::PacketOptions options;
- return socket_->Send(buf, size, options);
-}
-
-int TestClient::SendTo(const char* buf, size_t size,
- const SocketAddress& dest) {
- talk_base::PacketOptions options;
- return socket_->SendTo(buf, size, dest, options);
-}
-
-TestClient::Packet* TestClient::NextPacket() {
- // If no packets are currently available, we go into a get/dispatch loop for
- // at most 1 second. If, during the loop, a packet arrives, then we can stop
- // early and return it.
-
- // Note that the case where no packet arrives is important. We often want to
- // test that a packet does not arrive.
-
- // Note also that we only try to pump our current thread's message queue.
- // Pumping another thread's queue could lead to messages being dispatched from
- // the wrong thread to non-thread-safe objects.
-
- uint32 end = TimeAfter(kTimeout);
- while (TimeUntil(end) > 0) {
- {
- CritScope cs(&crit_);
- if (packets_->size() != 0) {
- break;
- }
- }
- Thread::Current()->ProcessMessages(1);
- }
-
- // Return the first packet placed in the queue.
- Packet* packet = NULL;
- CritScope cs(&crit_);
- if (packets_->size() > 0) {
- packet = packets_->front();
- packets_->erase(packets_->begin());
- }
-
- return packet;
-}
-
-bool TestClient::CheckNextPacket(const char* buf, size_t size,
- SocketAddress* addr) {
- bool res = false;
- Packet* packet = NextPacket();
- if (packet) {
- res = (packet->size == size && memcmp(packet->buf, buf, size) == 0);
- if (addr)
- *addr = packet->addr;
- delete packet;
- }
- return res;
-}
-
-bool TestClient::CheckNoPacket() {
- bool res;
- Packet* packet = NextPacket();
- res = (packet == NULL);
- delete packet;
- return res;
-}
-
-int TestClient::GetError() {
- return socket_->GetError();
-}
-
-int TestClient::SetOption(Socket::Option opt, int value) {
- return socket_->SetOption(opt, value);
-}
-
-bool TestClient::ready_to_send() const {
- return ready_to_send_;
-}
-
-void TestClient::OnPacket(AsyncPacketSocket* socket, const char* buf,
- size_t size, const SocketAddress& remote_addr,
- const PacketTime& packet_time) {
- CritScope cs(&crit_);
- packets_->push_back(new Packet(remote_addr, buf, size));
-}
-
-void TestClient::OnReadyToSend(AsyncPacketSocket* socket) {
- ready_to_send_ = true;
-}
-
-TestClient::Packet::Packet(const SocketAddress& a, const char* b, size_t s)
- : addr(a), buf(0), size(s) {
- buf = new char[size];
- memcpy(buf, b, size);
-}
-
-TestClient::Packet::Packet(const Packet& p)
- : addr(p.addr), buf(0), size(p.size) {
- buf = new char[size];
- memcpy(buf, p.buf, size);
-}
-
-TestClient::Packet::~Packet() {
- delete[] buf;
-}
-
-} // namespace talk_base
diff --git a/base/testclient.h b/base/testclient.h
deleted file mode 100644
index 87e32df..0000000
--- a/base/testclient.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TESTCLIENT_H_
-#define TALK_BASE_TESTCLIENT_H_
-
-#include <vector>
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/criticalsection.h"
-
-namespace talk_base {
-
-// A simple client that can send TCP or UDP data and check that it receives
-// what it expects to receive. Useful for testing server functionality.
-class TestClient : public sigslot::has_slots<> {
- public:
- // Records the contents of a packet that was received.
- struct Packet {
- Packet(const SocketAddress& a, const char* b, size_t s);
- Packet(const Packet& p);
- virtual ~Packet();
-
- SocketAddress addr;
- char* buf;
- size_t size;
- };
-
- // Creates a client that will send and receive with the given socket and
- // will post itself messages with the given thread.
- explicit TestClient(AsyncPacketSocket* socket);
- ~TestClient();
-
- SocketAddress address() const { return socket_->GetLocalAddress(); }
- SocketAddress remote_address() const { return socket_->GetRemoteAddress(); }
-
- // Checks that the socket moves to the specified connect state.
- bool CheckConnState(AsyncPacketSocket::State state);
-
- // Checks that the socket is connected to the remote side.
- bool CheckConnected() {
- return CheckConnState(AsyncPacketSocket::STATE_CONNECTED);
- }
-
- // Sends using the clients socket.
- int Send(const char* buf, size_t size);
-
- // Sends using the clients socket to the given destination.
- int SendTo(const char* buf, size_t size, const SocketAddress& dest);
-
- // Returns the next packet received by the client or 0 if none is received
- // within a reasonable amount of time. The caller must delete the packet
- // when done with it.
- Packet* NextPacket();
-
- // Checks that the next packet has the given contents. Returns the remote
- // address that the packet was sent from.
- bool CheckNextPacket(const char* buf, size_t len, SocketAddress* addr);
-
- // Checks that no packets have arrived or will arrive in the next second.
- bool CheckNoPacket();
-
- int GetError();
- int SetOption(Socket::Option opt, int value);
-
- bool ready_to_send() const;
-
- private:
- static const int kTimeout = 1000;
- // Workaround for the fact that AsyncPacketSocket::GetConnState doesn't exist.
- Socket::ConnState GetState();
- // Slot for packets read on the socket.
- void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t len,
- const SocketAddress& remote_addr,
- const PacketTime& packet_time);
- void OnReadyToSend(AsyncPacketSocket* socket);
-
- CriticalSection crit_;
- AsyncPacketSocket* socket_;
- std::vector<Packet*>* packets_;
- bool ready_to_send_;
- DISALLOW_EVIL_CONSTRUCTORS(TestClient);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TESTCLIENT_H_
diff --git a/base/testclient_unittest.cc b/base/testclient_unittest.cc
deleted file mode 100644
index c1411f0..0000000
--- a/base/testclient_unittest.cc
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/testclient.h"
-#include "talk/base/testechoserver.h"
-#include "talk/base/thread.h"
-
-using namespace talk_base;
-
-void TestUdpInternal(const SocketAddress& loopback) {
- Thread *main = Thread::Current();
- AsyncSocket* socket = main->socketserver()
- ->CreateAsyncSocket(loopback.family(), SOCK_DGRAM);
- socket->Bind(loopback);
-
- TestClient client(new AsyncUDPSocket(socket));
- SocketAddress addr = client.address(), from;
- EXPECT_EQ(3, client.SendTo("foo", 3, addr));
- EXPECT_TRUE(client.CheckNextPacket("foo", 3, &from));
- EXPECT_EQ(from, addr);
- EXPECT_TRUE(client.CheckNoPacket());
-}
-
-void TestTcpInternal(const SocketAddress& loopback) {
- Thread *main = Thread::Current();
- TestEchoServer server(main, loopback);
-
- AsyncSocket* socket = main->socketserver()
- ->CreateAsyncSocket(loopback.family(), SOCK_STREAM);
- AsyncTCPSocket* tcp_socket = AsyncTCPSocket::Create(
- socket, loopback, server.address());
- ASSERT_TRUE(tcp_socket != NULL);
-
- TestClient client(tcp_socket);
- SocketAddress addr = client.address(), from;
- EXPECT_TRUE(client.CheckConnected());
- EXPECT_EQ(3, client.Send("foo", 3));
- EXPECT_TRUE(client.CheckNextPacket("foo", 3, &from));
- EXPECT_EQ(from, server.address());
- EXPECT_TRUE(client.CheckNoPacket());
-}
-
-// Tests whether the TestClient can send UDP to itself.
-TEST(TestClientTest, TestUdpIPv4) {
- TestUdpInternal(SocketAddress("127.0.0.1", 0));
-}
-
-TEST(TestClientTest, TestUdpIPv6) {
- if (HasIPv6Enabled()) {
- TestUdpInternal(SocketAddress("::1", 0));
- } else {
- LOG(LS_INFO) << "Skipping IPv6 test.";
- }
-}
-
-// Tests whether the TestClient can connect to a server and exchange data.
-TEST(TestClientTest, TestTcpIPv4) {
- TestTcpInternal(SocketAddress("127.0.0.1", 0));
-}
-
-TEST(TestClientTest, TestTcpIPv6) {
- if (HasIPv6Enabled()) {
- TestTcpInternal(SocketAddress("::1", 0));
- } else {
- LOG(LS_INFO) << "Skipping IPv6 test.";
- }
-}
diff --git a/base/testechoserver.h b/base/testechoserver.h
deleted file mode 100644
index 380f961..0000000
--- a/base/testechoserver.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TESTECHOSERVER_H_
-#define TALK_BASE_TESTECHOSERVER_H_
-
-#include <list>
-#include "talk/base/asynctcpsocket.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-// A test echo server, echoes back any packets sent to it.
-// Useful for unit tests.
-class TestEchoServer : public sigslot::has_slots<> {
- public:
- TestEchoServer(Thread* thread, const SocketAddress& addr)
- : server_socket_(thread->socketserver()->CreateAsyncSocket(addr.family(),
- SOCK_STREAM)) {
- server_socket_->Bind(addr);
- server_socket_->Listen(5);
- server_socket_->SignalReadEvent.connect(this, &TestEchoServer::OnAccept);
- }
- ~TestEchoServer() {
- for (ClientList::iterator it = client_sockets_.begin();
- it != client_sockets_.end(); ++it) {
- delete *it;
- }
- }
-
- SocketAddress address() const { return server_socket_->GetLocalAddress(); }
-
- private:
- void OnAccept(AsyncSocket* socket) {
- AsyncSocket* raw_socket = socket->Accept(NULL);
- if (raw_socket) {
- AsyncTCPSocket* packet_socket = new AsyncTCPSocket(raw_socket, false);
- packet_socket->SignalReadPacket.connect(this, &TestEchoServer::OnPacket);
- packet_socket->SignalClose.connect(this, &TestEchoServer::OnClose);
- client_sockets_.push_back(packet_socket);
- }
- }
- void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
- const SocketAddress& remote_addr,
- const PacketTime& packet_time) {
- talk_base::PacketOptions options;
- socket->Send(buf, size, options);
- }
- void OnClose(AsyncPacketSocket* socket, int err) {
- ClientList::iterator it =
- std::find(client_sockets_.begin(), client_sockets_.end(), socket);
- client_sockets_.erase(it);
- Thread::Current()->Dispose(socket);
- }
-
- typedef std::list<AsyncTCPSocket*> ClientList;
- scoped_ptr<AsyncSocket> server_socket_;
- ClientList client_sockets_;
- DISALLOW_EVIL_CONSTRUCTORS(TestEchoServer);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TESTECHOSERVER_H_
diff --git a/base/testutils.h b/base/testutils.h
deleted file mode 100644
index 86e946f..0000000
--- a/base/testutils.h
+++ /dev/null
@@ -1,646 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TESTUTILS_H__
-#define TALK_BASE_TESTUTILS_H__
-
-// Utilities for testing talk_base infrastructure in unittests
-
-#ifdef LINUX
-#include <X11/Xlib.h>
-#include <X11/extensions/Xrandr.h>
-
-// X defines a few macros that stomp on types that gunit.h uses.
-#undef None
-#undef Bool
-#endif
-
-#include <map>
-#include <vector>
-#include "talk/base/asyncsocket.h"
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-
-namespace testing {
-
-using namespace talk_base;
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamSink - Monitor asynchronously signalled events from StreamInterface
-// or AsyncSocket (which should probably be a StreamInterface.
-///////////////////////////////////////////////////////////////////////////////
-
-// Note: Any event that is an error is treaded as SSE_ERROR instead of that
-// event.
-
-enum StreamSinkEvent {
- SSE_OPEN = SE_OPEN,
- SSE_READ = SE_READ,
- SSE_WRITE = SE_WRITE,
- SSE_CLOSE = SE_CLOSE,
- SSE_ERROR = 16
-};
-
-class StreamSink : public sigslot::has_slots<> {
- public:
- void Monitor(StreamInterface* stream) {
- stream->SignalEvent.connect(this, &StreamSink::OnEvent);
- events_.erase(stream);
- }
- void Unmonitor(StreamInterface* stream) {
- stream->SignalEvent.disconnect(this);
- // In case you forgot to unmonitor a previous object with this address
- events_.erase(stream);
- }
- bool Check(StreamInterface* stream, StreamSinkEvent event, bool reset = true) {
- return DoCheck(stream, event, reset);
- }
- int Events(StreamInterface* stream, bool reset = true) {
- return DoEvents(stream, reset);
- }
-
- void Monitor(AsyncSocket* socket) {
- socket->SignalConnectEvent.connect(this, &StreamSink::OnConnectEvent);
- socket->SignalReadEvent.connect(this, &StreamSink::OnReadEvent);
- socket->SignalWriteEvent.connect(this, &StreamSink::OnWriteEvent);
- socket->SignalCloseEvent.connect(this, &StreamSink::OnCloseEvent);
- // In case you forgot to unmonitor a previous object with this address
- events_.erase(socket);
- }
- void Unmonitor(AsyncSocket* socket) {
- socket->SignalConnectEvent.disconnect(this);
- socket->SignalReadEvent.disconnect(this);
- socket->SignalWriteEvent.disconnect(this);
- socket->SignalCloseEvent.disconnect(this);
- events_.erase(socket);
- }
- bool Check(AsyncSocket* socket, StreamSinkEvent event, bool reset = true) {
- return DoCheck(socket, event, reset);
- }
- int Events(AsyncSocket* socket, bool reset = true) {
- return DoEvents(socket, reset);
- }
-
- private:
- typedef std::map<void*,int> EventMap;
-
- void OnEvent(StreamInterface* stream, int events, int error) {
- if (error) {
- events = SSE_ERROR;
- }
- AddEvents(stream, events);
- }
- void OnConnectEvent(AsyncSocket* socket) {
- AddEvents(socket, SSE_OPEN);
- }
- void OnReadEvent(AsyncSocket* socket) {
- AddEvents(socket, SSE_READ);
- }
- void OnWriteEvent(AsyncSocket* socket) {
- AddEvents(socket, SSE_WRITE);
- }
- void OnCloseEvent(AsyncSocket* socket, int error) {
- AddEvents(socket, (0 == error) ? SSE_CLOSE : SSE_ERROR);
- }
-
- void AddEvents(void* obj, int events) {
- EventMap::iterator it = events_.find(obj);
- if (events_.end() == it) {
- events_.insert(EventMap::value_type(obj, events));
- } else {
- it->second |= events;
- }
- }
- bool DoCheck(void* obj, StreamSinkEvent event, bool reset) {
- EventMap::iterator it = events_.find(obj);
- if ((events_.end() == it) || (0 == (it->second & event))) {
- return false;
- }
- if (reset) {
- it->second &= ~event;
- }
- return true;
- }
- int DoEvents(void* obj, bool reset) {
- EventMap::iterator it = events_.find(obj);
- if (events_.end() == it)
- return 0;
- int events = it->second;
- if (reset) {
- it->second = 0;
- }
- return events;
- }
-
- EventMap events_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamSource - Implements stream interface and simulates asynchronous
-// events on the stream, without a network. Also buffers written data.
-///////////////////////////////////////////////////////////////////////////////
-
-class StreamSource : public StreamInterface {
-public:
- StreamSource() {
- Clear();
- }
-
- void Clear() {
- readable_data_.clear();
- written_data_.clear();
- state_ = SS_CLOSED;
- read_block_ = 0;
- write_block_ = SIZE_UNKNOWN;
- }
- void QueueString(const char* data) {
- QueueData(data, strlen(data));
- }
- void QueueStringF(const char* format, ...) {
- va_list args;
- va_start(args, format);
- char buffer[1024];
- size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
- ASSERT(len < sizeof(buffer) - 1);
- va_end(args);
- QueueData(buffer, len);
- }
- void QueueData(const char* data, size_t len) {
- readable_data_.insert(readable_data_.end(), data, data + len);
- if ((SS_OPEN == state_) && (readable_data_.size() == len)) {
- SignalEvent(this, SE_READ, 0);
- }
- }
- std::string ReadData() {
- std::string data;
- // avoid accessing written_data_[0] if it is undefined
- if (written_data_.size() > 0) {
- data.insert(0, &written_data_[0], written_data_.size());
- }
- written_data_.clear();
- return data;
- }
- void SetState(StreamState state) {
- int events = 0;
- if ((SS_OPENING == state_) && (SS_OPEN == state)) {
- events |= SE_OPEN;
- if (!readable_data_.empty()) {
- events |= SE_READ;
- }
- } else if ((SS_CLOSED != state_) && (SS_CLOSED == state)) {
- events |= SE_CLOSE;
- }
- state_ = state;
- if (events) {
- SignalEvent(this, events, 0);
- }
- }
- // Will cause Read to block when there are pos bytes in the read queue.
- void SetReadBlock(size_t pos) { read_block_ = pos; }
- // Will cause Write to block when there are pos bytes in the write queue.
- void SetWriteBlock(size_t pos) { write_block_ = pos; }
-
- virtual StreamState GetState() const { return state_; }
- virtual StreamResult Read(void* buffer, size_t buffer_len,
- size_t* read, int* error) {
- if (SS_CLOSED == state_) {
- if (error) *error = -1;
- return SR_ERROR;
- }
- if ((SS_OPENING == state_) || (readable_data_.size() <= read_block_)) {
- return SR_BLOCK;
- }
- size_t count = _min(buffer_len, readable_data_.size() - read_block_);
- memcpy(buffer, &readable_data_[0], count);
- size_t new_size = readable_data_.size() - count;
- // Avoid undefined access beyond the last element of the vector.
- // This only happens when new_size is 0.
- if (count < readable_data_.size()) {
- memmove(&readable_data_[0], &readable_data_[count], new_size);
- }
- readable_data_.resize(new_size);
- if (read) *read = count;
- return SR_SUCCESS;
- }
- virtual StreamResult Write(const void* data, size_t data_len,
- size_t* written, int* error) {
- if (SS_CLOSED == state_) {
- if (error) *error = -1;
- return SR_ERROR;
- }
- if (SS_OPENING == state_) {
- return SR_BLOCK;
- }
- if (SIZE_UNKNOWN != write_block_) {
- if (written_data_.size() >= write_block_) {
- return SR_BLOCK;
- }
- if (data_len > (write_block_ - written_data_.size())) {
- data_len = write_block_ - written_data_.size();
- }
- }
- if (written) *written = data_len;
- const char* cdata = static_cast<const char*>(data);
- written_data_.insert(written_data_.end(), cdata, cdata + data_len);
- return SR_SUCCESS;
- }
- virtual void Close() { state_ = SS_CLOSED; }
-
-private:
- typedef std::vector<char> Buffer;
- Buffer readable_data_, written_data_;
- StreamState state_;
- size_t read_block_, write_block_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// SocketTestClient
-// Creates a simulated client for testing. Works on real and virtual networks.
-///////////////////////////////////////////////////////////////////////////////
-
-class SocketTestClient : public sigslot::has_slots<> {
-public:
- SocketTestClient() {
- Init(NULL, AF_INET);
- }
- SocketTestClient(AsyncSocket* socket) {
- Init(socket, socket->GetLocalAddress().family());
- }
- SocketTestClient(const SocketAddress& address) {
- Init(NULL, address.family());
- socket_->Connect(address);
- }
-
- AsyncSocket* socket() { return socket_.get(); }
-
- void QueueString(const char* data) {
- QueueData(data, strlen(data));
- }
- void QueueStringF(const char* format, ...) {
- va_list args;
- va_start(args, format);
- char buffer[1024];
- size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
- ASSERT(len < sizeof(buffer) - 1);
- va_end(args);
- QueueData(buffer, len);
- }
- void QueueData(const char* data, size_t len) {
- send_buffer_.insert(send_buffer_.end(), data, data + len);
- if (Socket::CS_CONNECTED == socket_->GetState()) {
- Flush();
- }
- }
- std::string ReadData() {
- std::string data(&recv_buffer_[0], recv_buffer_.size());
- recv_buffer_.clear();
- return data;
- }
-
- bool IsConnected() const {
- return (Socket::CS_CONNECTED == socket_->GetState());
- }
- bool IsClosed() const {
- return (Socket::CS_CLOSED == socket_->GetState());
- }
-
-private:
- typedef std::vector<char> Buffer;
-
- void Init(AsyncSocket* socket, int family) {
- if (!socket) {
- socket = Thread::Current()->socketserver()
- ->CreateAsyncSocket(family, SOCK_STREAM);
- }
- socket_.reset(socket);
- socket_->SignalConnectEvent.connect(this,
- &SocketTestClient::OnConnectEvent);
- socket_->SignalReadEvent.connect(this, &SocketTestClient::OnReadEvent);
- socket_->SignalWriteEvent.connect(this, &SocketTestClient::OnWriteEvent);
- socket_->SignalCloseEvent.connect(this, &SocketTestClient::OnCloseEvent);
- }
-
- void Flush() {
- size_t sent = 0;
- while (sent < send_buffer_.size()) {
- int result = socket_->Send(&send_buffer_[sent],
- send_buffer_.size() - sent);
- if (result > 0) {
- sent += result;
- } else {
- break;
- }
- }
- size_t new_size = send_buffer_.size() - sent;
- memmove(&send_buffer_[0], &send_buffer_[sent], new_size);
- send_buffer_.resize(new_size);
- }
-
- void OnConnectEvent(AsyncSocket* socket) {
- if (!send_buffer_.empty()) {
- Flush();
- }
- }
- void OnReadEvent(AsyncSocket* socket) {
- char data[64 * 1024];
- int result = socket_->Recv(data, ARRAY_SIZE(data));
- if (result > 0) {
- recv_buffer_.insert(recv_buffer_.end(), data, data + result);
- }
- }
- void OnWriteEvent(AsyncSocket* socket) {
- if (!send_buffer_.empty()) {
- Flush();
- }
- }
- void OnCloseEvent(AsyncSocket* socket, int error) {
- }
-
- scoped_ptr<AsyncSocket> socket_;
- Buffer send_buffer_, recv_buffer_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// SocketTestServer
-// Creates a simulated server for testing. Works on real and virtual networks.
-///////////////////////////////////////////////////////////////////////////////
-
-class SocketTestServer : public sigslot::has_slots<> {
- public:
- SocketTestServer(const SocketAddress& address)
- : socket_(Thread::Current()->socketserver()
- ->CreateAsyncSocket(address.family(), SOCK_STREAM))
- {
- socket_->SignalReadEvent.connect(this, &SocketTestServer::OnReadEvent);
- socket_->Bind(address);
- socket_->Listen(5);
- }
- virtual ~SocketTestServer() {
- clear();
- }
-
- size_t size() const { return clients_.size(); }
- SocketTestClient* client(size_t index) const { return clients_[index]; }
- SocketTestClient* operator[](size_t index) const { return client(index); }
-
- void clear() {
- for (size_t i=0; i<clients_.size(); ++i) {
- delete clients_[i];
- }
- clients_.clear();
- }
-
- private:
- void OnReadEvent(AsyncSocket* socket) {
- AsyncSocket* accepted =
- static_cast<AsyncSocket*>(socket_->Accept(NULL));
- if (!accepted)
- return;
- clients_.push_back(new SocketTestClient(accepted));
- }
-
- scoped_ptr<AsyncSocket> socket_;
- std::vector<SocketTestClient*> clients_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Generic Utilities
-///////////////////////////////////////////////////////////////////////////////
-
-inline bool ReadFile(const char* filename, std::string* contents) {
- FILE* fp = fopen(filename, "rb");
- if (!fp)
- return false;
- char buffer[1024*64];
- size_t read;
- contents->clear();
- while ((read = fread(buffer, 1, sizeof(buffer), fp))) {
- contents->append(buffer, read);
- }
- bool success = (0 != feof(fp));
- fclose(fp);
- return success;
-}
-
-// Look in parent dir for parallel directory.
-inline talk_base::Pathname GetSiblingDirectory(
- const std::string& parallel_dir) {
- talk_base::Pathname path = talk_base::Filesystem::GetCurrentDirectory();
- while (!path.empty()) {
- talk_base::Pathname potential_parallel_dir = path;
- potential_parallel_dir.AppendFolder(parallel_dir);
- if (talk_base::Filesystem::IsFolder(potential_parallel_dir)) {
- return potential_parallel_dir;
- }
-
- path.SetFolder(path.parent_folder());
- }
- return path;
-}
-
-inline talk_base::Pathname GetGoogle3Directory() {
- return GetSiblingDirectory("google3");
-}
-
-inline talk_base::Pathname GetTalkDirectory() {
- return GetSiblingDirectory("talk");
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// Unittest predicates which are similar to STREQ, but for raw memory
-///////////////////////////////////////////////////////////////////////////////
-
-inline AssertionResult CmpHelperMemEq(const char* expected_expression,
- const char* expected_length_expression,
- const char* actual_expression,
- const char* actual_length_expression,
- const void* expected,
- size_t expected_length,
- const void* actual,
- size_t actual_length)
-{
- if ((expected_length == actual_length)
- && (0 == memcmp(expected, actual, expected_length))) {
- return AssertionSuccess();
- }
-
- Message msg;
- msg << "Value of: " << actual_expression
- << " [" << actual_length_expression << "]";
- if (true) { //!actual_value.Equals(actual_expression)) {
- size_t buffer_size = actual_length * 2 + 1;
- char* buffer = STACK_ARRAY(char, buffer_size);
- hex_encode(buffer, buffer_size,
- reinterpret_cast<const char*>(actual), actual_length);
- msg << "\n Actual: " << buffer << " [" << actual_length << "]";
- }
-
- msg << "\nExpected: " << expected_expression
- << " [" << expected_length_expression << "]";
- if (true) { //!expected_value.Equals(expected_expression)) {
- size_t buffer_size = expected_length * 2 + 1;
- char* buffer = STACK_ARRAY(char, buffer_size);
- hex_encode(buffer, buffer_size,
- reinterpret_cast<const char*>(expected), expected_length);
- msg << "\nWhich is: " << buffer << " [" << expected_length << "]";
- }
-
- return AssertionFailure(msg);
-}
-
-inline AssertionResult CmpHelperFileEq(const char* expected_expression,
- const char* expected_length_expression,
- const char* actual_filename,
- const void* expected,
- size_t expected_length,
- const char* filename)
-{
- std::string contents;
- if (!ReadFile(filename, &contents)) {
- Message msg;
- msg << "File '" << filename << "' could not be read.";
- return AssertionFailure(msg);
- }
- return CmpHelperMemEq(expected_expression, expected_length_expression,
- actual_filename, "",
- expected, expected_length,
- contents.c_str(), contents.size());
-}
-
-#define EXPECT_MEMEQ(expected, expected_length, actual, actual_length) \
- EXPECT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
- actual, actual_length)
-
-#define ASSERT_MEMEQ(expected, expected_length, actual, actual_length) \
- ASSERT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
- actual, actual_length)
-
-#define EXPECT_FILEEQ(expected, expected_length, filename) \
- EXPECT_PRED_FORMAT3(::testing::CmpHelperFileEq, expected, expected_length, \
- filename)
-
-#define ASSERT_FILEEQ(expected, expected_length, filename) \
- ASSERT_PRED_FORMAT3(::testing::CmpHelperFileEq, expected, expected_length, \
- filename)
-
-///////////////////////////////////////////////////////////////////////////////
-// Helpers for initializing constant memory with integers in a particular byte
-// order
-///////////////////////////////////////////////////////////////////////////////
-
-#define BYTE_CAST(x) static_cast<uint8>((x) & 0xFF)
-
-// Declare a N-bit integer as a little-endian sequence of bytes
-#define LE16(x) BYTE_CAST(((uint16)x) >> 0), BYTE_CAST(((uint16)x) >> 8)
-
-#define LE32(x) BYTE_CAST(((uint32)x) >> 0), BYTE_CAST(((uint32)x) >> 8), \
- BYTE_CAST(((uint32)x) >> 16), BYTE_CAST(((uint32)x) >> 24)
-
-#define LE64(x) BYTE_CAST(((uint64)x) >> 0), BYTE_CAST(((uint64)x) >> 8), \
- BYTE_CAST(((uint64)x) >> 16), BYTE_CAST(((uint64)x) >> 24), \
- BYTE_CAST(((uint64)x) >> 32), BYTE_CAST(((uint64)x) >> 40), \
- BYTE_CAST(((uint64)x) >> 48), BYTE_CAST(((uint64)x) >> 56)
-
-// Declare a N-bit integer as a big-endian (Internet) sequence of bytes
-#define BE16(x) BYTE_CAST(((uint16)x) >> 8), BYTE_CAST(((uint16)x) >> 0)
-
-#define BE32(x) BYTE_CAST(((uint32)x) >> 24), BYTE_CAST(((uint32)x) >> 16), \
- BYTE_CAST(((uint32)x) >> 8), BYTE_CAST(((uint32)x) >> 0)
-
-#define BE64(x) BYTE_CAST(((uint64)x) >> 56), BYTE_CAST(((uint64)x) >> 48), \
- BYTE_CAST(((uint64)x) >> 40), BYTE_CAST(((uint64)x) >> 32), \
- BYTE_CAST(((uint64)x) >> 24), BYTE_CAST(((uint64)x) >> 16), \
- BYTE_CAST(((uint64)x) >> 8), BYTE_CAST(((uint64)x) >> 0)
-
-// Declare a N-bit integer as a this-endian (local machine) sequence of bytes
-#ifndef BIG_ENDIAN
-#define BIG_ENDIAN 1
-#endif // BIG_ENDIAN
-
-#if BIG_ENDIAN
-#define TE16 BE16
-#define TE32 BE32
-#define TE64 BE64
-#else // !BIG_ENDIAN
-#define TE16 LE16
-#define TE32 LE32
-#define TE64 LE64
-#endif // !BIG_ENDIAN
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Helpers for determining if X/screencasting is available (on linux).
-
-#define MAYBE_SKIP_SCREENCAST_TEST() \
- if (!testing::IsScreencastingAvailable()) { \
- LOG(LS_WARNING) << "Skipping test, since it doesn't have the requisite " \
- << "X environment for screen capture."; \
- return; \
- } \
-
-#ifdef LINUX
-struct XDisplay {
- XDisplay() : display_(XOpenDisplay(NULL)) { }
- ~XDisplay() { if (display_) XCloseDisplay(display_); }
- bool IsValid() const { return display_ != NULL; }
- operator Display*() { return display_; }
- private:
- Display* display_;
-};
-#endif
-
-// Returns true if screencasting is available. When false, anything that uses
-// screencasting features may fail.
-inline bool IsScreencastingAvailable() {
-#ifdef LINUX
- XDisplay display;
- if (!display.IsValid()) {
- LOG(LS_WARNING) << "No X Display available.";
- return false;
- }
- int ignored_int, major_version, minor_version;
- if (!XRRQueryExtension(display, &ignored_int, &ignored_int) ||
- !XRRQueryVersion(display, &major_version, &minor_version) ||
- major_version < 1 ||
- (major_version < 2 && minor_version < 3)) {
- LOG(LS_WARNING) << "XRandr version: " << major_version << "."
- << minor_version;
- LOG(LS_WARNING) << "XRandr is not supported or is too old (pre 1.3).";
- return false;
- }
-#endif
- return true;
-}
-} // namespace testing
-
-#endif // TALK_BASE_TESTUTILS_H__
diff --git a/base/thread.cc b/base/thread.cc
deleted file mode 100644
index 87e4fff..0000000
--- a/base/thread.cc
+++ /dev/null
@@ -1,577 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/thread.h"
-
-#ifndef __has_feature
-#define __has_feature(x) 0 // Compatibility with non-clang or LLVM compilers.
-#endif // __has_feature
-
-#if defined(WIN32)
-#include <comdef.h>
-#elif defined(POSIX)
-#include <time.h>
-#endif
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/timeutils.h"
-
-#if !__has_feature(objc_arc) && (defined(OSX) || defined(IOS))
-#include "talk/base/maccocoathreadhelper.h"
-#include "talk/base/scoped_autorelease_pool.h"
-#endif
-
-namespace talk_base {
-
-ThreadManager* ThreadManager::Instance() {
- LIBJINGLE_DEFINE_STATIC_LOCAL(ThreadManager, thread_manager, ());
- return &thread_manager;
-}
-
-// static
-Thread* Thread::Current() {
- return ThreadManager::Instance()->CurrentThread();
-}
-
-#ifdef POSIX
-ThreadManager::ThreadManager() {
- pthread_key_create(&key_, NULL);
-#ifndef NO_MAIN_THREAD_WRAPPING
- WrapCurrentThread();
-#endif
-#if !__has_feature(objc_arc) && (defined(OSX) || defined(IOS))
- // Under Automatic Reference Counting (ARC), you cannot use autorelease pools
- // directly. Instead, you use @autoreleasepool blocks instead. Also, we are
- // maintaining thread safety using immutability within context of GCD dispatch
- // queues in this case.
- InitCocoaMultiThreading();
-#endif
-}
-
-ThreadManager::~ThreadManager() {
-#if __has_feature(objc_arc)
- @autoreleasepool
-#elif defined(OSX) || defined(IOS)
- // This is called during exit, at which point apparently no NSAutoreleasePools
- // are available; but we might still need them to do cleanup (or we get the
- // "no autoreleasepool in place, just leaking" warning when exiting).
- ScopedAutoreleasePool pool;
-#endif
- {
- UnwrapCurrentThread();
- pthread_key_delete(key_);
- }
-}
-
-Thread *ThreadManager::CurrentThread() {
- return static_cast<Thread *>(pthread_getspecific(key_));
-}
-
-void ThreadManager::SetCurrentThread(Thread *thread) {
- pthread_setspecific(key_, thread);
-}
-#endif
-
-#ifdef WIN32
-ThreadManager::ThreadManager() {
- key_ = TlsAlloc();
-#ifndef NO_MAIN_THREAD_WRAPPING
- WrapCurrentThread();
-#endif
-}
-
-ThreadManager::~ThreadManager() {
- UnwrapCurrentThread();
- TlsFree(key_);
-}
-
-Thread *ThreadManager::CurrentThread() {
- return static_cast<Thread *>(TlsGetValue(key_));
-}
-
-void ThreadManager::SetCurrentThread(Thread *thread) {
- TlsSetValue(key_, thread);
-}
-#endif
-
-Thread *ThreadManager::WrapCurrentThread() {
- Thread* result = CurrentThread();
- if (NULL == result) {
- result = new Thread();
- result->WrapCurrentWithThreadManager(this);
- }
- return result;
-}
-
-void ThreadManager::UnwrapCurrentThread() {
- Thread* t = CurrentThread();
- if (t && !(t->IsOwned())) {
- t->UnwrapCurrent();
- delete t;
- }
-}
-
-struct ThreadInit {
- Thread* thread;
- Runnable* runnable;
-};
-
-Thread::Thread(SocketServer* ss)
- : MessageQueue(ss),
- priority_(PRIORITY_NORMAL),
- running_(true, false),
-#if defined(WIN32)
- thread_(NULL),
- thread_id_(0),
-#endif
- owned_(true) {
- SetName("Thread", this); // default name
-}
-
-Thread::~Thread() {
- Stop();
- Clear(NULL);
-}
-
-bool Thread::SleepMs(int milliseconds) {
-#ifdef WIN32
- ::Sleep(milliseconds);
- return true;
-#else
- // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
- // so we use nanosleep() even though it has greater precision than necessary.
- struct timespec ts;
- ts.tv_sec = milliseconds / 1000;
- ts.tv_nsec = (milliseconds % 1000) * 1000000;
- int ret = nanosleep(&ts, NULL);
- if (ret != 0) {
- LOG_ERR(LS_WARNING) << "nanosleep() returning early";
- return false;
- }
- return true;
-#endif
-}
-
-bool Thread::SetName(const std::string& name, const void* obj) {
- if (running()) return false;
- name_ = name;
- if (obj) {
- char buf[16];
- sprintfn(buf, sizeof(buf), " 0x%p", obj);
- name_ += buf;
- }
- return true;
-}
-
-bool Thread::SetPriority(ThreadPriority priority) {
-#if defined(WIN32)
- if (running()) {
- BOOL ret = FALSE;
- if (priority == PRIORITY_NORMAL) {
- ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_NORMAL);
- } else if (priority == PRIORITY_HIGH) {
- ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_HIGHEST);
- } else if (priority == PRIORITY_ABOVE_NORMAL) {
- ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);
- } else if (priority == PRIORITY_IDLE) {
- ret = ::SetThreadPriority(thread_, THREAD_PRIORITY_IDLE);
- }
- if (!ret) {
- return false;
- }
- }
- priority_ = priority;
- return true;
-#else
- // TODO: Implement for Linux/Mac if possible.
- if (running()) return false;
- priority_ = priority;
- return true;
-#endif
-}
-
-bool Thread::Start(Runnable* runnable) {
- ASSERT(owned_);
- if (!owned_) return false;
- ASSERT(!running());
- if (running()) return false;
-
- Restart(); // reset fStop_ if the thread is being restarted
-
- // Make sure that ThreadManager is created on the main thread before
- // we start a new thread.
- ThreadManager::Instance();
-
- ThreadInit* init = new ThreadInit;
- init->thread = this;
- init->runnable = runnable;
-#if defined(WIN32)
- DWORD flags = 0;
- if (priority_ != PRIORITY_NORMAL) {
- flags = CREATE_SUSPENDED;
- }
- thread_ = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PreRun, init, flags,
- &thread_id_);
- if (thread_) {
- running_.Set();
- if (priority_ != PRIORITY_NORMAL) {
- SetPriority(priority_);
- ::ResumeThread(thread_);
- }
- } else {
- return false;
- }
-#elif defined(POSIX)
- pthread_attr_t attr;
- pthread_attr_init(&attr);
-
- // Thread priorities are not supported in NaCl.
-#if !defined(__native_client__)
- if (priority_ != PRIORITY_NORMAL) {
- if (priority_ == PRIORITY_IDLE) {
- // There is no POSIX-standard way to set a below-normal priority for an
- // individual thread (only whole process), so let's not support it.
- LOG(LS_WARNING) << "PRIORITY_IDLE not supported";
- } else {
- // Set real-time round-robin policy.
- if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) {
- LOG(LS_ERROR) << "pthread_attr_setschedpolicy";
- }
- struct sched_param param;
- if (pthread_attr_getschedparam(&attr, ¶m) != 0) {
- LOG(LS_ERROR) << "pthread_attr_getschedparam";
- } else {
- // The numbers here are arbitrary.
- if (priority_ == PRIORITY_HIGH) {
- param.sched_priority = 6; // 6 = HIGH
- } else {
- ASSERT(priority_ == PRIORITY_ABOVE_NORMAL);
- param.sched_priority = 4; // 4 = ABOVE_NORMAL
- }
- if (pthread_attr_setschedparam(&attr, ¶m) != 0) {
- LOG(LS_ERROR) << "pthread_attr_setschedparam";
- }
- }
- }
- }
-#endif // !defined(__native_client__)
-
- int error_code = pthread_create(&thread_, &attr, PreRun, init);
- if (0 != error_code) {
- LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
- return false;
- }
- running_.Set();
-#endif
- return true;
-}
-
-void Thread::Join() {
- if (running()) {
- ASSERT(!IsCurrent());
-#if defined(WIN32)
- WaitForSingleObject(thread_, INFINITE);
- CloseHandle(thread_);
- thread_ = NULL;
- thread_id_ = 0;
-#elif defined(POSIX)
- void *pv;
- pthread_join(thread_, &pv);
-#endif
- running_.Reset();
- }
-}
-
-#ifdef WIN32
-// As seen on MSDN.
-// http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx
-#define MSDEV_SET_THREAD_NAME 0x406D1388
-typedef struct tagTHREADNAME_INFO {
- DWORD dwType;
- LPCSTR szName;
- DWORD dwThreadID;
- DWORD dwFlags;
-} THREADNAME_INFO;
-
-void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) {
- THREADNAME_INFO info;
- info.dwType = 0x1000;
- info.szName = szThreadName;
- info.dwThreadID = dwThreadID;
- info.dwFlags = 0;
-
- __try {
- RaiseException(MSDEV_SET_THREAD_NAME, 0, sizeof(info) / sizeof(DWORD),
- reinterpret_cast<ULONG_PTR*>(&info));
- }
- __except(EXCEPTION_CONTINUE_EXECUTION) {
- }
-}
-#endif // WIN32
-
-void* Thread::PreRun(void* pv) {
- ThreadInit* init = static_cast<ThreadInit*>(pv);
- ThreadManager::Instance()->SetCurrentThread(init->thread);
-#if defined(WIN32)
- SetThreadName(GetCurrentThreadId(), init->thread->name_.c_str());
-#elif defined(POSIX)
- // TODO: See if naming exists for pthreads.
-#endif
-#if __has_feature(objc_arc)
- @autoreleasepool
-#elif defined(OSX) || defined(IOS)
- // Make sure the new thread has an autoreleasepool
- ScopedAutoreleasePool pool;
-#endif
- {
- if (init->runnable) {
- init->runnable->Run(init->thread);
- } else {
- init->thread->Run();
- }
- delete init;
- return NULL;
- }
-}
-
-void Thread::Run() {
- ProcessMessages(kForever);
-}
-
-bool Thread::IsOwned() {
- return owned_;
-}
-
-void Thread::Stop() {
- MessageQueue::Quit();
- Join();
-}
-
-void Thread::Send(MessageHandler *phandler, uint32 id, MessageData *pdata) {
- if (fStop_)
- return;
-
- // Sent messages are sent to the MessageHandler directly, in the context
- // of "thread", like Win32 SendMessage. If in the right context,
- // call the handler directly.
-
- Message msg;
- msg.phandler = phandler;
- msg.message_id = id;
- msg.pdata = pdata;
- if (IsCurrent()) {
- phandler->OnMessage(&msg);
- return;
- }
-
- AutoThread thread;
- Thread *current_thread = Thread::Current();
- ASSERT(current_thread != NULL); // AutoThread ensures this
-
- bool ready = false;
- {
- CritScope cs(&crit_);
- _SendMessage smsg;
- smsg.thread = current_thread;
- smsg.msg = msg;
- smsg.ready = &ready;
- sendlist_.push_back(smsg);
- }
-
- // Wait for a reply
-
- ss_->WakeUp();
-
- bool waited = false;
- crit_.Enter();
- while (!ready) {
- crit_.Leave();
- current_thread->ReceiveSends();
- current_thread->socketserver()->Wait(kForever, false);
- waited = true;
- crit_.Enter();
- }
- crit_.Leave();
-
- // Our Wait loop above may have consumed some WakeUp events for this
- // MessageQueue, that weren't relevant to this Send. Losing these WakeUps can
- // cause problems for some SocketServers.
- //
- // Concrete example:
- // Win32SocketServer on thread A calls Send on thread B. While processing the
- // message, thread B Posts a message to A. We consume the wakeup for that
- // Post while waiting for the Send to complete, which means that when we exit
- // this loop, we need to issue another WakeUp, or else the Posted message
- // won't be processed in a timely manner.
-
- if (waited) {
- current_thread->socketserver()->WakeUp();
- }
-}
-
-void Thread::ReceiveSends() {
- // Receive a sent message. Cleanup scenarios:
- // - thread sending exits: We don't allow this, since thread can exit
- // only via Join, so Send must complete.
- // - thread receiving exits: Wakeup/set ready in Thread::Clear()
- // - object target cleared: Wakeup/set ready in Thread::Clear()
- crit_.Enter();
- while (!sendlist_.empty()) {
- _SendMessage smsg = sendlist_.front();
- sendlist_.pop_front();
- crit_.Leave();
- smsg.msg.phandler->OnMessage(&smsg.msg);
- crit_.Enter();
- *smsg.ready = true;
- smsg.thread->socketserver()->WakeUp();
- }
- crit_.Leave();
-}
-
-void Thread::Clear(MessageHandler *phandler, uint32 id,
- MessageList* removed) {
- CritScope cs(&crit_);
-
- // Remove messages on sendlist_ with phandler
- // Object target cleared: remove from send list, wakeup/set ready
- // if sender not NULL.
-
- std::list<_SendMessage>::iterator iter = sendlist_.begin();
- while (iter != sendlist_.end()) {
- _SendMessage smsg = *iter;
- if (smsg.msg.Match(phandler, id)) {
- if (removed) {
- removed->push_back(smsg.msg);
- } else {
- delete smsg.msg.pdata;
- }
- iter = sendlist_.erase(iter);
- *smsg.ready = true;
- smsg.thread->socketserver()->WakeUp();
- continue;
- }
- ++iter;
- }
-
- MessageQueue::Clear(phandler, id, removed);
-}
-
-bool Thread::ProcessMessages(int cmsLoop) {
- uint32 msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
- int cmsNext = cmsLoop;
-
- while (true) {
-#if __has_feature(objc_arc)
- @autoreleasepool
-#elif defined(OSX) || defined(IOS)
- // see: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html
- // Each thread is supposed to have an autorelease pool. Also for event loops
- // like this, autorelease pool needs to be created and drained/released
- // for each cycle.
- ScopedAutoreleasePool pool;
-#endif
- {
- Message msg;
- if (!Get(&msg, cmsNext))
- return !IsQuitting();
- Dispatch(&msg);
-
- if (cmsLoop != kForever) {
- cmsNext = TimeUntil(msEnd);
- if (cmsNext < 0)
- return true;
- }
- }
- }
-}
-
-bool Thread::WrapCurrent() {
- return WrapCurrentWithThreadManager(ThreadManager::Instance());
-}
-
-bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager) {
- if (running())
- return false;
-#if defined(WIN32)
- // We explicitly ask for no rights other than synchronization.
- // This gives us the best chance of succeeding.
- thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
- if (!thread_) {
- LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
- return false;
- }
- thread_id_ = GetCurrentThreadId();
-#elif defined(POSIX)
- thread_ = pthread_self();
-#endif
- owned_ = false;
- running_.Set();
- thread_manager->SetCurrentThread(this);
- return true;
-}
-
-void Thread::UnwrapCurrent() {
- // Clears the platform-specific thread-specific storage.
- ThreadManager::Instance()->SetCurrentThread(NULL);
-#ifdef WIN32
- if (!CloseHandle(thread_)) {
- LOG_GLE(LS_ERROR) << "When unwrapping thread, failed to close handle.";
- }
-#endif
- running_.Reset();
-}
-
-
-AutoThread::AutoThread(SocketServer* ss) : Thread(ss) {
- if (!ThreadManager::Instance()->CurrentThread()) {
- ThreadManager::Instance()->SetCurrentThread(this);
- }
-}
-
-AutoThread::~AutoThread() {
- Stop();
- if (ThreadManager::Instance()->CurrentThread() == this) {
- ThreadManager::Instance()->SetCurrentThread(NULL);
- }
-}
-
-#ifdef WIN32
-void ComThread::Run() {
- HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
- ASSERT(SUCCEEDED(hr));
- if (SUCCEEDED(hr)) {
- Thread::Run();
- CoUninitialize();
- } else {
- LOG(LS_ERROR) << "CoInitialize failed, hr=" << hr;
- }
-}
-#endif
-
-} // namespace talk_base
diff --git a/base/thread.h b/base/thread.h
deleted file mode 100644
index 4cbf721..0000000
--- a/base/thread.h
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_THREAD_H_
-#define TALK_BASE_THREAD_H_
-
-#include <algorithm>
-#include <list>
-#include <string>
-#include <vector>
-
-#ifdef POSIX
-#include <pthread.h>
-#endif
-#include "talk/base/constructormagic.h"
-#include "talk/base/event.h"
-#include "talk/base/messagequeue.h"
-
-#ifdef WIN32
-#include "talk/base/win32.h"
-#endif
-
-namespace talk_base {
-
-class Thread;
-
-class ThreadManager {
- public:
- ThreadManager();
- ~ThreadManager();
-
- static ThreadManager* Instance();
-
- Thread* CurrentThread();
- void SetCurrentThread(Thread* thread);
-
- // Returns a thread object with its thread_ ivar set
- // to whatever the OS uses to represent the thread.
- // If there already *is* a Thread object corresponding to this thread,
- // this method will return that. Otherwise it creates a new Thread
- // object whose wrapped() method will return true, and whose
- // handle will, on Win32, be opened with only synchronization privileges -
- // if you need more privilegs, rather than changing this method, please
- // write additional code to adjust the privileges, or call a different
- // factory method of your own devising, because this one gets used in
- // unexpected contexts (like inside browser plugins) and it would be a
- // shame to break it. It is also conceivable on Win32 that we won't even
- // be able to get synchronization privileges, in which case the result
- // will have a NULL handle.
- Thread *WrapCurrentThread();
- void UnwrapCurrentThread();
-
- private:
-#ifdef POSIX
- pthread_key_t key_;
-#endif
-
-#ifdef WIN32
- DWORD key_;
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(ThreadManager);
-};
-
-struct _SendMessage {
- _SendMessage() {}
- Thread *thread;
- Message msg;
- bool *ready;
-};
-
-enum ThreadPriority {
- PRIORITY_IDLE = -1,
- PRIORITY_NORMAL = 0,
- PRIORITY_ABOVE_NORMAL = 1,
- PRIORITY_HIGH = 2,
-};
-
-class Runnable {
- public:
- virtual ~Runnable() {}
- virtual void Run(Thread* thread) = 0;
-
- protected:
- Runnable() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Runnable);
-};
-
-// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
-
-class Thread : public MessageQueue {
- public:
- explicit Thread(SocketServer* ss = NULL);
- // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
- // guarantee Stop() is explicitly called before the subclass is destroyed).
- // This is required to avoid a data race between the destructor modifying the
- // vtable, and the Thread::PreRun calling the virtual method Run().
- virtual ~Thread();
-
- static Thread* Current();
-
- bool IsCurrent() const {
- return Current() == this;
- }
-
- // Sleeps the calling thread for the specified number of milliseconds, during
- // which time no processing is performed. Returns false if sleeping was
- // interrupted by a signal (POSIX only).
- static bool SleepMs(int millis);
-
- // Sets the thread's name, for debugging. Must be called before Start().
- // If |obj| is non-NULL, its value is appended to |name|.
- const std::string& name() const { return name_; }
- bool SetName(const std::string& name, const void* obj);
-
- // Sets the thread's priority. Must be called before Start().
- ThreadPriority priority() const { return priority_; }
- bool SetPriority(ThreadPriority priority);
-
- // Starts the execution of the thread.
- bool Start(Runnable* runnable = NULL);
-
- // Tells the thread to stop and waits until it is joined.
- // Never call Stop on the current thread. Instead use the inherited Quit
- // function which will exit the base MessageQueue without terminating the
- // underlying OS thread.
- virtual void Stop();
-
- // By default, Thread::Run() calls ProcessMessages(kForever). To do other
- // work, override Run(). To receive and dispatch messages, call
- // ProcessMessages occasionally.
- virtual void Run();
-
- virtual void Send(MessageHandler *phandler, uint32 id = 0,
- MessageData *pdata = NULL);
-
- // Convenience method to invoke a functor on another thread. Caller must
- // provide the |ReturnT| template argument, which cannot (easily) be deduced.
- // Uses Send() internally, which blocks the current thread until execution
- // is complete.
- // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool);
- template <class ReturnT, class FunctorT>
- ReturnT Invoke(const FunctorT& functor) {
- FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
- Send(&handler);
- return handler.result();
- }
-
- // From MessageQueue
- virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY,
- MessageList* removed = NULL);
- virtual void ReceiveSends();
-
- // ProcessMessages will process I/O and dispatch messages until:
- // 1) cms milliseconds have elapsed (returns true)
- // 2) Stop() is called (returns false)
- bool ProcessMessages(int cms);
-
- // Returns true if this is a thread that we created using the standard
- // constructor, false if it was created by a call to
- // ThreadManager::WrapCurrentThread(). The main thread of an application
- // is generally not owned, since the OS representation of the thread
- // obviously exists before we can get to it.
- // You cannot call Start on non-owned threads.
- bool IsOwned();
-
-#ifdef WIN32
- HANDLE GetHandle() const {
- return thread_;
- }
- DWORD GetId() const {
- return thread_id_;
- }
-#elif POSIX
- pthread_t GetPThread() {
- return thread_;
- }
-#endif
-
- // This method should be called when thread is created using non standard
- // method, like derived implementation of talk_base::Thread and it can not be
- // started by calling Start(). This will set started flag to true and
- // owned to false. This must be called from the current thread.
- // NOTE: These methods should be used by the derived classes only, added here
- // only for testing.
- bool WrapCurrent();
- void UnwrapCurrent();
-
- // Expose private method running() for tests.
- //
- // DANGER: this is a terrible public API. Most callers that might want to
- // call this likely do not have enough control/knowledge of the Thread in
- // question to guarantee that the returned value remains true for the duration
- // of whatever code is conditionally executing because of the return value!
- bool RunningForTest() { return running(); }
- // This is a legacy call-site that probably doesn't need to exist in the first
- // place.
- // TODO(fischman): delete once the ASSERT added in channelmanager.cc sticks
- // for a month (ETA 2014/06/22).
- bool RunningForChannelManager() { return running(); }
-
- protected:
- // Blocks the calling thread until this thread has terminated.
- void Join();
-
- private:
- static void *PreRun(void *pv);
-
- // ThreadManager calls this instead WrapCurrent() because
- // ThreadManager::Instance() cannot be used while ThreadManager is
- // being created.
- bool WrapCurrentWithThreadManager(ThreadManager* thread_manager);
-
- // Return true if the thread was started and hasn't yet stopped.
- bool running() { return running_.Wait(0); }
-
- std::list<_SendMessage> sendlist_;
- std::string name_;
- ThreadPriority priority_;
- Event running_; // Signalled means running.
-
-#ifdef POSIX
- pthread_t thread_;
-#endif
-
-#ifdef WIN32
- HANDLE thread_;
- DWORD thread_id_;
-#endif
-
- bool owned_;
-
- friend class ThreadManager;
-
- DISALLOW_COPY_AND_ASSIGN(Thread);
-};
-
-// AutoThread automatically installs itself at construction
-// uninstalls at destruction, if a Thread object is
-// _not already_ associated with the current OS thread.
-
-class AutoThread : public Thread {
- public:
- explicit AutoThread(SocketServer* ss = 0);
- virtual ~AutoThread();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(AutoThread);
-};
-
-// Win32 extension for threads that need to use COM
-#ifdef WIN32
-class ComThread : public Thread {
- public:
- ComThread() {}
- virtual ~ComThread() { Stop(); }
-
- protected:
- virtual void Run();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(ComThread);
-};
-#endif
-
-// Provides an easy way to install/uninstall a socketserver on a thread.
-class SocketServerScope {
- public:
- explicit SocketServerScope(SocketServer* ss) {
- old_ss_ = Thread::Current()->socketserver();
- Thread::Current()->set_socketserver(ss);
- }
- ~SocketServerScope() {
- Thread::Current()->set_socketserver(old_ss_);
- }
-
- private:
- SocketServer* old_ss_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_THREAD_H_
diff --git a/base/thread_unittest.cc b/base/thread_unittest.cc
deleted file mode 100644
index d7d6a01..0000000
--- a/base/thread_unittest.cc
+++ /dev/null
@@ -1,461 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/asyncinvoker.h"
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/event.h"
-#include "talk/base/gunit.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/thread.h"
-
-#ifdef WIN32
-#include <comdef.h> // NOLINT
-#endif
-
-using namespace talk_base;
-
-// Generates a sequence of numbers (collaboratively).
-class TestGenerator {
- public:
- TestGenerator() : last(0), count(0) {}
-
- int Next(int prev) {
- int result = prev + last;
- last = result;
- count += 1;
- return result;
- }
-
- int last;
- int count;
-};
-
-struct TestMessage : public MessageData {
- explicit TestMessage(int v) : value(v) {}
- virtual ~TestMessage() {}
-
- int value;
-};
-
-// Receives on a socket and sends by posting messages.
-class SocketClient : public TestGenerator, public sigslot::has_slots<> {
- public:
- SocketClient(AsyncSocket* socket, const SocketAddress& addr,
- Thread* post_thread, MessageHandler* phandler)
- : socket_(AsyncUDPSocket::Create(socket, addr)),
- post_thread_(post_thread),
- post_handler_(phandler) {
- socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
- }
-
- ~SocketClient() {
- delete socket_;
- }
-
- SocketAddress address() const { return socket_->GetLocalAddress(); }
-
- void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
- const SocketAddress& remote_addr,
- const PacketTime& packet_time) {
- EXPECT_EQ(size, sizeof(uint32));
- uint32 prev = reinterpret_cast<const uint32*>(buf)[0];
- uint32 result = Next(prev);
-
- post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
- }
-
- private:
- AsyncUDPSocket* socket_;
- Thread* post_thread_;
- MessageHandler* post_handler_;
-};
-
-// Receives messages and sends on a socket.
-class MessageClient : public MessageHandler, public TestGenerator {
- public:
- MessageClient(Thread* pth, Socket* socket)
- : socket_(socket) {
- }
-
- virtual ~MessageClient() {
- delete socket_;
- }
-
- virtual void OnMessage(Message *pmsg) {
- TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
- int result = Next(msg->value);
- EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
- delete msg;
- }
-
- private:
- Socket* socket_;
-};
-
-class CustomThread : public talk_base::Thread {
- public:
- CustomThread() {}
- virtual ~CustomThread() { Stop(); }
- bool Start() { return false; }
-};
-
-
-// A thread that does nothing when it runs and signals an event
-// when it is destroyed.
-class SignalWhenDestroyedThread : public Thread {
- public:
- SignalWhenDestroyedThread(Event* event)
- : event_(event) {
- }
-
- virtual ~SignalWhenDestroyedThread() {
- Stop();
- event_->Set();
- }
-
- virtual void Run() {
- // Do nothing.
- }
-
- private:
- Event* event_;
-};
-
-// Function objects to test Thread::Invoke.
-struct FunctorA {
- int operator()() { return 42; }
-};
-class FunctorB {
- public:
- explicit FunctorB(bool* flag) : flag_(flag) {}
- void operator()() { if (flag_) *flag_ = true; }
- private:
- bool* flag_;
-};
-struct FunctorC {
- int operator()() {
- Thread::Current()->ProcessMessages(50);
- return 24;
- }
-};
-
-// See: https://code.google.com/p/webrtc/issues/detail?id=2409
-TEST(ThreadTest, DISABLED_Main) {
- const SocketAddress addr("127.0.0.1", 0);
-
- // Create the messaging client on its own thread.
- Thread th1;
- Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
- SOCK_DGRAM);
- MessageClient msg_client(&th1, socket);
-
- // Create the socket client on its own thread.
- Thread th2;
- AsyncSocket* asocket =
- th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
- SocketClient sock_client(asocket, addr, &th1, &msg_client);
-
- socket->Connect(sock_client.address());
-
- th1.Start();
- th2.Start();
-
- // Get the messages started.
- th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
-
- // Give the clients a little while to run.
- // Messages will be processed at 100, 300, 500, 700, 900.
- Thread* th_main = Thread::Current();
- th_main->ProcessMessages(1000);
-
- // Stop the sending client. Give the receiver a bit longer to run, in case
- // it is running on a machine that is under load (e.g. the build machine).
- th1.Stop();
- th_main->ProcessMessages(200);
- th2.Stop();
-
- // Make sure the results were correct
- EXPECT_EQ(5, msg_client.count);
- EXPECT_EQ(34, msg_client.last);
- EXPECT_EQ(5, sock_client.count);
- EXPECT_EQ(55, sock_client.last);
-}
-
-// Test that setting thread names doesn't cause a malfunction.
-// There's no easy way to verify the name was set properly at this time.
-TEST(ThreadTest, Names) {
- // Default name
- Thread *thread;
- thread = new Thread();
- EXPECT_TRUE(thread->Start());
- thread->Stop();
- delete thread;
- thread = new Thread();
- // Name with no object parameter
- EXPECT_TRUE(thread->SetName("No object", NULL));
- EXPECT_TRUE(thread->Start());
- thread->Stop();
- delete thread;
- // Really long name
- thread = new Thread();
- EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
- EXPECT_TRUE(thread->Start());
- thread->Stop();
- delete thread;
-}
-
-// Test that setting thread priorities doesn't cause a malfunction.
-// There's no easy way to verify the priority was set properly at this time.
-TEST(ThreadTest, Priorities) {
- Thread *thread;
- thread = new Thread();
- EXPECT_TRUE(thread->SetPriority(PRIORITY_HIGH));
- EXPECT_TRUE(thread->Start());
- thread->Stop();
- delete thread;
- thread = new Thread();
- EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
- EXPECT_TRUE(thread->Start());
- thread->Stop();
- delete thread;
-
- thread = new Thread();
- EXPECT_TRUE(thread->Start());
-#ifdef WIN32
- EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
-#else
- EXPECT_FALSE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
-#endif
- thread->Stop();
- delete thread;
-
-}
-
-TEST(ThreadTest, Wrap) {
- Thread* current_thread = Thread::Current();
- current_thread->UnwrapCurrent();
- CustomThread* cthread = new CustomThread();
- EXPECT_TRUE(cthread->WrapCurrent());
- EXPECT_TRUE(cthread->RunningForTest());
- EXPECT_FALSE(cthread->IsOwned());
- cthread->UnwrapCurrent();
- EXPECT_FALSE(cthread->RunningForTest());
- delete cthread;
- current_thread->WrapCurrent();
-}
-
-TEST(ThreadTest, Invoke) {
- // Create and start the thread.
- Thread thread;
- thread.Start();
- // Try calling functors.
- EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
- bool called = false;
- FunctorB f2(&called);
- thread.Invoke<void>(f2);
- EXPECT_TRUE(called);
- // Try calling bare functions.
- struct LocalFuncs {
- static int Func1() { return 999; }
- static void Func2() {}
- };
- EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
- thread.Invoke<void>(&LocalFuncs::Func2);
-}
-
-class AsyncInvokeTest : public testing::Test {
- public:
- void IntCallback(int value) {
- EXPECT_EQ(expected_thread_, Thread::Current());
- int_value_ = value;
- }
- void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
- expected_thread_ = thread;
- invoker->AsyncInvoke(thread, FunctorC(),
- &AsyncInvokeTest::IntCallback,
- static_cast<AsyncInvokeTest*>(this));
- invoke_started_.Set();
- }
- void SetExpectedThreadForIntCallback(Thread* thread) {
- expected_thread_ = thread;
- }
-
- protected:
- enum { kWaitTimeout = 1000 };
- AsyncInvokeTest()
- : int_value_(0),
- invoke_started_(true, false),
- expected_thread_(NULL) {}
-
- int int_value_;
- Event invoke_started_;
- Thread* expected_thread_;
-};
-
-TEST_F(AsyncInvokeTest, FireAndForget) {
- AsyncInvoker invoker;
- // Create and start the thread.
- Thread thread;
- thread.Start();
- // Try calling functor.
- bool called = false;
- invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
- EXPECT_TRUE_WAIT(called, kWaitTimeout);
-}
-
-TEST_F(AsyncInvokeTest, WithCallback) {
- AsyncInvoker invoker;
- // Create and start the thread.
- Thread thread;
- thread.Start();
- // Try calling functor.
- SetExpectedThreadForIntCallback(Thread::Current());
- invoker.AsyncInvoke(&thread, FunctorA(),
- &AsyncInvokeTest::IntCallback,
- static_cast<AsyncInvokeTest*>(this));
- EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
-}
-
-TEST_F(AsyncInvokeTest, CancelInvoker) {
- // Create and start the thread.
- Thread thread;
- thread.Start();
- // Try destroying invoker during call.
- {
- AsyncInvoker invoker;
- invoker.AsyncInvoke(&thread, FunctorC(),
- &AsyncInvokeTest::IntCallback,
- static_cast<AsyncInvokeTest*>(this));
- }
- // With invoker gone, callback should be cancelled.
- Thread::Current()->ProcessMessages(kWaitTimeout);
- EXPECT_EQ(0, int_value_);
-}
-
-TEST_F(AsyncInvokeTest, CancelCallingThread) {
- AsyncInvoker invoker;
- { // Create and start the thread.
- Thread thread;
- thread.Start();
- // Try calling functor.
- thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
- static_cast<AsyncInvokeTest*>(this),
- &invoker, Thread::Current()));
- // Wait for the call to begin.
- ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
- }
- // Calling thread is gone. Return message shouldn't happen.
- Thread::Current()->ProcessMessages(kWaitTimeout);
- EXPECT_EQ(0, int_value_);
-}
-
-TEST_F(AsyncInvokeTest, KillInvokerBeforeExecute) {
- Thread thread;
- thread.Start();
- {
- AsyncInvoker invoker;
- // Try calling functor.
- thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
- static_cast<AsyncInvokeTest*>(this),
- &invoker, Thread::Current()));
- // Wait for the call to begin.
- ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
- }
- // Invoker is destroyed. Function should not execute.
- Thread::Current()->ProcessMessages(kWaitTimeout);
- EXPECT_EQ(0, int_value_);
-}
-
-TEST_F(AsyncInvokeTest, Flush) {
- AsyncInvoker invoker;
- bool flag1 = false;
- bool flag2 = false;
- // Queue two async calls to the current thread.
- invoker.AsyncInvoke<void>(Thread::Current(),
- FunctorB(&flag1));
- invoker.AsyncInvoke<void>(Thread::Current(),
- FunctorB(&flag2));
- // Because we haven't pumped messages, these should not have run yet.
- EXPECT_FALSE(flag1);
- EXPECT_FALSE(flag2);
- // Force them to run now.
- invoker.Flush(Thread::Current());
- EXPECT_TRUE(flag1);
- EXPECT_TRUE(flag2);
-}
-
-TEST_F(AsyncInvokeTest, FlushWithIds) {
- AsyncInvoker invoker;
- bool flag1 = false;
- bool flag2 = false;
- // Queue two async calls to the current thread, one with a message id.
- invoker.AsyncInvoke<void>(Thread::Current(),
- FunctorB(&flag1),
- 5);
- invoker.AsyncInvoke<void>(Thread::Current(),
- FunctorB(&flag2));
- // Because we haven't pumped messages, these should not have run yet.
- EXPECT_FALSE(flag1);
- EXPECT_FALSE(flag2);
- // Execute pending calls with id == 5.
- invoker.Flush(Thread::Current(), 5);
- EXPECT_TRUE(flag1);
- EXPECT_FALSE(flag2);
- flag1 = false;
- // Execute all pending calls. The id == 5 call should not execute again.
- invoker.Flush(Thread::Current());
- EXPECT_FALSE(flag1);
- EXPECT_TRUE(flag2);
-}
-
-
-#ifdef WIN32
-class ComThreadTest : public testing::Test, public MessageHandler {
- public:
- ComThreadTest() : done_(false) {}
- protected:
- virtual void OnMessage(Message* message) {
- HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
- // S_FALSE means the thread was already inited for a multithread apartment.
- EXPECT_EQ(S_FALSE, hr);
- if (SUCCEEDED(hr)) {
- CoUninitialize();
- }
- done_ = true;
- }
- bool done_;
-};
-
-TEST_F(ComThreadTest, ComInited) {
- Thread* thread = new ComThread();
- EXPECT_TRUE(thread->Start());
- thread->Post(this, 0);
- EXPECT_TRUE_WAIT(done_, 1000);
- delete thread;
-}
-#endif
diff --git a/base/timeutils.cc b/base/timeutils.cc
deleted file mode 100644
index c4e84cc..0000000
--- a/base/timeutils.cc
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stdint.h>
-
-#ifdef POSIX
-#include <sys/time.h>
-#if defined(OSX) || defined(IOS)
-#include <mach/mach_time.h>
-#endif
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <mmsystem.h>
-#endif
-
-#include "talk/base/common.h"
-#include "talk/base/timeutils.h"
-
-#define EFFICIENT_IMPLEMENTATION 1
-
-namespace talk_base {
-
-const uint32 HALF = 0x80000000;
-
-uint64 TimeNanos() {
- int64 ticks = 0;
-#if defined(OSX) || defined(IOS)
- static mach_timebase_info_data_t timebase;
- if (timebase.denom == 0) {
- // Get the timebase if this is the first time we run.
- // Recommended by Apple's QA1398.
- VERIFY(KERN_SUCCESS == mach_timebase_info(&timebase));
- }
- // Use timebase to convert absolute time tick units into nanoseconds.
- ticks = mach_absolute_time() * timebase.numer / timebase.denom;
-#elif defined(POSIX)
- struct timespec ts;
- // TODO: Do we need to handle the case when CLOCK_MONOTONIC
- // is not supported?
- clock_gettime(CLOCK_MONOTONIC, &ts);
- ticks = kNumNanosecsPerSec * static_cast<int64>(ts.tv_sec) +
- static_cast<int64>(ts.tv_nsec);
-#elif defined(WIN32)
- static volatile LONG last_timegettime = 0;
- static volatile int64 num_wrap_timegettime = 0;
- volatile LONG* last_timegettime_ptr = &last_timegettime;
- DWORD now = timeGetTime();
- // Atomically update the last gotten time
- DWORD old = InterlockedExchange(last_timegettime_ptr, now);
- if (now < old) {
- // If now is earlier than old, there may have been a race between
- // threads.
- // 0x0fffffff ~3.1 days, the code will not take that long to execute
- // so it must have been a wrap around.
- if (old > 0xf0000000 && now < 0x0fffffff) {
- num_wrap_timegettime++;
- }
- }
- ticks = now + (num_wrap_timegettime << 32);
- // TODO: Calculate with nanosecond precision. Otherwise, we're just
- // wasting a multiply and divide when doing Time() on Windows.
- ticks = ticks * kNumNanosecsPerMillisec;
-#endif
- return ticks;
-}
-
-uint32 Time() {
- return static_cast<uint32>(TimeNanos() / kNumNanosecsPerMillisec);
-}
-
-uint64 TimeMicros() {
- return static_cast<uint64>(TimeNanos() / kNumNanosecsPerMicrosec);
-}
-
-#if defined(WIN32)
-static const uint64 kFileTimeToUnixTimeEpochOffset = 116444736000000000ULL;
-
-struct timeval {
- long tv_sec, tv_usec; // NOLINT
-};
-
-// Emulate POSIX gettimeofday().
-// Based on breakpad/src/third_party/glog/src/utilities.cc
-static int gettimeofday(struct timeval *tv, void *tz) {
- // FILETIME is measured in tens of microseconds since 1601-01-01 UTC.
- FILETIME ft;
- GetSystemTimeAsFileTime(&ft);
-
- LARGE_INTEGER li;
- li.LowPart = ft.dwLowDateTime;
- li.HighPart = ft.dwHighDateTime;
-
- // Convert to seconds and microseconds since Unix time Epoch.
- int64 micros = (li.QuadPart - kFileTimeToUnixTimeEpochOffset) / 10;
- tv->tv_sec = static_cast<long>(micros / kNumMicrosecsPerSec); // NOLINT
- tv->tv_usec = static_cast<long>(micros % kNumMicrosecsPerSec); // NOLINT
-
- return 0;
-}
-
-// Emulate POSIX gmtime_r().
-static struct tm *gmtime_r(const time_t *timep, struct tm *result) {
- // On Windows, gmtime is thread safe.
- struct tm *tm = gmtime(timep); // NOLINT
- if (tm == NULL) {
- return NULL;
- }
- *result = *tm;
- return result;
-}
-#endif // WIN32
-
-void CurrentTmTime(struct tm *tm, int *microseconds) {
- struct timeval timeval;
- if (gettimeofday(&timeval, NULL) < 0) {
- // Incredibly unlikely code path.
- timeval.tv_sec = timeval.tv_usec = 0;
- }
- time_t secs = timeval.tv_sec;
- gmtime_r(&secs, tm);
- *microseconds = timeval.tv_usec;
-}
-
-uint32 TimeAfter(int32 elapsed) {
- ASSERT(elapsed >= 0);
- ASSERT(static_cast<uint32>(elapsed) < HALF);
- return Time() + elapsed;
-}
-
-bool TimeIsBetween(uint32 earlier, uint32 middle, uint32 later) {
- if (earlier <= later) {
- return ((earlier <= middle) && (middle <= later));
- } else {
- return !((later < middle) && (middle < earlier));
- }
-}
-
-bool TimeIsLaterOrEqual(uint32 earlier, uint32 later) {
-#if EFFICIENT_IMPLEMENTATION
- int32 diff = later - earlier;
- return (diff >= 0 && static_cast<uint32>(diff) < HALF);
-#else
- const bool later_or_equal = TimeIsBetween(earlier, later, earlier + HALF);
- return later_or_equal;
-#endif
-}
-
-bool TimeIsLater(uint32 earlier, uint32 later) {
-#if EFFICIENT_IMPLEMENTATION
- int32 diff = later - earlier;
- return (diff > 0 && static_cast<uint32>(diff) < HALF);
-#else
- const bool earlier_or_equal = TimeIsBetween(later, earlier, later + HALF);
- return !earlier_or_equal;
-#endif
-}
-
-int32 TimeDiff(uint32 later, uint32 earlier) {
-#if EFFICIENT_IMPLEMENTATION
- return later - earlier;
-#else
- const bool later_or_equal = TimeIsBetween(earlier, later, earlier + HALF);
- if (later_or_equal) {
- if (earlier <= later) {
- return static_cast<long>(later - earlier);
- } else {
- return static_cast<long>(later + (UINT32_MAX - earlier) + 1);
- }
- } else {
- if (later <= earlier) {
- return -static_cast<long>(earlier - later);
- } else {
- return -static_cast<long>(earlier + (UINT32_MAX - later) + 1);
- }
- }
-#endif
-}
-
-TimestampWrapAroundHandler::TimestampWrapAroundHandler()
- : last_ts_(0), num_wrap_(0) {}
-
-int64 TimestampWrapAroundHandler::Unwrap(uint32 ts) {
- if (ts < last_ts_) {
- if (last_ts_ > 0xf0000000 && ts < 0x0fffffff) {
- ++num_wrap_;
- }
- }
- last_ts_ = ts;
- int64_t unwrapped_ts = ts + (num_wrap_ << 32);
- return unwrapped_ts;
-}
-
-} // namespace talk_base
diff --git a/base/timeutils.h b/base/timeutils.h
deleted file mode 100644
index 6de9df6..0000000
--- a/base/timeutils.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * libjingle
- * Copyright 2005 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TIMEUTILS_H_
-#define TALK_BASE_TIMEUTILS_H_
-
-#include <time.h>
-
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-static const int64 kNumMillisecsPerSec = INT64_C(1000);
-static const int64 kNumMicrosecsPerSec = INT64_C(1000000);
-static const int64 kNumNanosecsPerSec = INT64_C(1000000000);
-
-static const int64 kNumMicrosecsPerMillisec = kNumMicrosecsPerSec /
- kNumMillisecsPerSec;
-static const int64 kNumNanosecsPerMillisec = kNumNanosecsPerSec /
- kNumMillisecsPerSec;
-static const int64 kNumNanosecsPerMicrosec = kNumNanosecsPerSec /
- kNumMicrosecsPerSec;
-
-// January 1970, in NTP milliseconds.
-static const int64 kJan1970AsNtpMillisecs = INT64_C(2208988800000);
-
-typedef uint32 TimeStamp;
-
-// Returns the current time in milliseconds.
-uint32 Time();
-// Returns the current time in microseconds.
-uint64 TimeMicros();
-// Returns the current time in nanoseconds.
-uint64 TimeNanos();
-
-// Stores current time in *tm and microseconds in *microseconds.
-void CurrentTmTime(struct tm *tm, int *microseconds);
-
-// Returns a future timestamp, 'elapsed' milliseconds from now.
-uint32 TimeAfter(int32 elapsed);
-
-// Comparisons between time values, which can wrap around.
-bool TimeIsBetween(uint32 earlier, uint32 middle, uint32 later); // Inclusive
-bool TimeIsLaterOrEqual(uint32 earlier, uint32 later); // Inclusive
-bool TimeIsLater(uint32 earlier, uint32 later); // Exclusive
-
-// Returns the later of two timestamps.
-inline uint32 TimeMax(uint32 ts1, uint32 ts2) {
- return TimeIsLaterOrEqual(ts1, ts2) ? ts2 : ts1;
-}
-
-// Returns the earlier of two timestamps.
-inline uint32 TimeMin(uint32 ts1, uint32 ts2) {
- return TimeIsLaterOrEqual(ts1, ts2) ? ts1 : ts2;
-}
-
-// Number of milliseconds that would elapse between 'earlier' and 'later'
-// timestamps. The value is negative if 'later' occurs before 'earlier'.
-int32 TimeDiff(uint32 later, uint32 earlier);
-
-// The number of milliseconds that have elapsed since 'earlier'.
-inline int32 TimeSince(uint32 earlier) {
- return TimeDiff(Time(), earlier);
-}
-
-// The number of milliseconds that will elapse between now and 'later'.
-inline int32 TimeUntil(uint32 later) {
- return TimeDiff(later, Time());
-}
-
-// Converts a unix timestamp in nanoseconds to an NTP timestamp in ms.
-inline int64 UnixTimestampNanosecsToNtpMillisecs(int64 unix_ts_ns) {
- return unix_ts_ns / kNumNanosecsPerMillisec + kJan1970AsNtpMillisecs;
-}
-
-class TimestampWrapAroundHandler {
- public:
- TimestampWrapAroundHandler();
-
- int64 Unwrap(uint32 ts);
-
- private:
- uint32 last_ts_;
- int64 num_wrap_;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TIMEUTILS_H_
diff --git a/base/timeutils_unittest.cc b/base/timeutils_unittest.cc
deleted file mode 100644
index a078abe..0000000
--- a/base/timeutils_unittest.cc
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-
-TEST(TimeTest, TimeInMs) {
- uint32 ts_earlier = Time();
- Thread::SleepMs(100);
- uint32 ts_now = Time();
- // Allow for the thread to wakeup ~20ms early.
- EXPECT_GE(ts_now, ts_earlier + 80);
- // Make sure the Time is not returning in smaller unit like microseconds.
- EXPECT_LT(ts_now, ts_earlier + 1000);
-}
-
-TEST(TimeTest, Comparison) {
- // Obtain two different times, in known order
- TimeStamp ts_earlier = Time();
- Thread::SleepMs(100);
- TimeStamp ts_now = Time();
- EXPECT_NE(ts_earlier, ts_now);
-
- // Common comparisons
- EXPECT_TRUE( TimeIsLaterOrEqual(ts_earlier, ts_now));
- EXPECT_TRUE( TimeIsLater( ts_earlier, ts_now));
- EXPECT_FALSE(TimeIsLaterOrEqual(ts_now, ts_earlier));
- EXPECT_FALSE(TimeIsLater( ts_now, ts_earlier));
-
- // Edge cases
- EXPECT_TRUE( TimeIsLaterOrEqual(ts_earlier, ts_earlier));
- EXPECT_FALSE(TimeIsLater( ts_earlier, ts_earlier));
-
- // Obtain a third time
- TimeStamp ts_later = TimeAfter(100);
- EXPECT_NE(ts_now, ts_later);
- EXPECT_TRUE( TimeIsLater(ts_now, ts_later));
- EXPECT_TRUE( TimeIsLater(ts_earlier, ts_later));
-
- // Common comparisons
- EXPECT_TRUE( TimeIsBetween(ts_earlier, ts_now, ts_later));
- EXPECT_FALSE(TimeIsBetween(ts_earlier, ts_later, ts_now));
- EXPECT_FALSE(TimeIsBetween(ts_now, ts_earlier, ts_later));
- EXPECT_TRUE( TimeIsBetween(ts_now, ts_later, ts_earlier));
- EXPECT_TRUE( TimeIsBetween(ts_later, ts_earlier, ts_now));
- EXPECT_FALSE(TimeIsBetween(ts_later, ts_now, ts_earlier));
-
- // Edge cases
- EXPECT_TRUE( TimeIsBetween(ts_earlier, ts_earlier, ts_earlier));
- EXPECT_TRUE( TimeIsBetween(ts_earlier, ts_earlier, ts_later));
- EXPECT_TRUE( TimeIsBetween(ts_earlier, ts_later, ts_later));
-
- // Earlier of two times
- EXPECT_EQ(ts_earlier, TimeMin(ts_earlier, ts_earlier));
- EXPECT_EQ(ts_earlier, TimeMin(ts_earlier, ts_now));
- EXPECT_EQ(ts_earlier, TimeMin(ts_earlier, ts_later));
- EXPECT_EQ(ts_earlier, TimeMin(ts_now, ts_earlier));
- EXPECT_EQ(ts_earlier, TimeMin(ts_later, ts_earlier));
-
- // Later of two times
- EXPECT_EQ(ts_earlier, TimeMax(ts_earlier, ts_earlier));
- EXPECT_EQ(ts_now, TimeMax(ts_earlier, ts_now));
- EXPECT_EQ(ts_later, TimeMax(ts_earlier, ts_later));
- EXPECT_EQ(ts_now, TimeMax(ts_now, ts_earlier));
- EXPECT_EQ(ts_later, TimeMax(ts_later, ts_earlier));
-}
-
-TEST(TimeTest, Intervals) {
- TimeStamp ts_earlier = Time();
- TimeStamp ts_later = TimeAfter(500);
-
- // We can't depend on ts_later and ts_earlier to be exactly 500 apart
- // since time elapses between the calls to Time() and TimeAfter(500)
- EXPECT_LE(500, TimeDiff(ts_later, ts_earlier));
- EXPECT_GE(-500, TimeDiff(ts_earlier, ts_later));
-
- // Time has elapsed since ts_earlier
- EXPECT_GE(TimeSince(ts_earlier), 0);
-
- // ts_earlier is earlier than now, so TimeUntil ts_earlier is -ve
- EXPECT_LE(TimeUntil(ts_earlier), 0);
-
- // ts_later likely hasn't happened yet, so TimeSince could be -ve
- // but within 500
- EXPECT_GE(TimeSince(ts_later), -500);
-
- // TimeUntil ts_later is at most 500
- EXPECT_LE(TimeUntil(ts_later), 500);
-}
-
-TEST(TimeTest, BoundaryComparison) {
- // Obtain two different times, in known order
- TimeStamp ts_earlier = static_cast<TimeStamp>(-50);
- TimeStamp ts_later = ts_earlier + 100;
- EXPECT_NE(ts_earlier, ts_later);
-
- // Common comparisons
- EXPECT_TRUE( TimeIsLaterOrEqual(ts_earlier, ts_later));
- EXPECT_TRUE( TimeIsLater( ts_earlier, ts_later));
- EXPECT_FALSE(TimeIsLaterOrEqual(ts_later, ts_earlier));
- EXPECT_FALSE(TimeIsLater( ts_later, ts_earlier));
-
- // Earlier of two times
- EXPECT_EQ(ts_earlier, TimeMin(ts_earlier, ts_earlier));
- EXPECT_EQ(ts_earlier, TimeMin(ts_earlier, ts_later));
- EXPECT_EQ(ts_earlier, TimeMin(ts_later, ts_earlier));
-
- // Later of two times
- EXPECT_EQ(ts_earlier, TimeMax(ts_earlier, ts_earlier));
- EXPECT_EQ(ts_later, TimeMax(ts_earlier, ts_later));
- EXPECT_EQ(ts_later, TimeMax(ts_later, ts_earlier));
-
- // Interval
- EXPECT_EQ(100, TimeDiff(ts_later, ts_earlier));
- EXPECT_EQ(-100, TimeDiff(ts_earlier, ts_later));
-}
-
-TEST(TimeTest, DISABLED_CurrentTmTime) {
- struct tm tm;
- int microseconds;
-
- time_t before = ::time(NULL);
- CurrentTmTime(&tm, µseconds);
- time_t after = ::time(NULL);
-
- // Assert that 'tm' represents a time between 'before' and 'after'.
- // mktime() uses local time, so we have to compensate for that.
- time_t local_delta = before - ::mktime(::gmtime(&before)); // NOLINT
- time_t t = ::mktime(&tm) + local_delta;
-
- EXPECT_TRUE(before <= t && t <= after);
- EXPECT_TRUE(0 <= microseconds && microseconds < 1000000);
-}
-
-class TimestampWrapAroundHandlerTest : public testing::Test {
- public:
- TimestampWrapAroundHandlerTest() {}
-
- protected:
- TimestampWrapAroundHandler wraparound_handler_;
-};
-
-TEST_F(TimestampWrapAroundHandlerTest, Unwrap) {
- uint32 ts = 0xfffffff2;
- int64 unwrapped_ts = ts;
- EXPECT_EQ(ts, wraparound_handler_.Unwrap(ts));
- ts = 2;
- unwrapped_ts += 0x10;
- EXPECT_EQ(unwrapped_ts, wraparound_handler_.Unwrap(ts));
- ts = 0xfffffff2;
- unwrapped_ts += 0xfffffff0;
- EXPECT_EQ(unwrapped_ts, wraparound_handler_.Unwrap(ts));
- ts = 0;
- unwrapped_ts += 0xe;
- EXPECT_EQ(unwrapped_ts, wraparound_handler_.Unwrap(ts));
-}
-
-} // namespace talk_base
diff --git a/base/timing.cc b/base/timing.cc
deleted file mode 100644
index 4df9f1f..0000000
--- a/base/timing.cc
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/timing.h"
-#include "talk/base/timeutils.h"
-
-#if defined(POSIX)
-#include <errno.h>
-#include <math.h>
-#include <sys/time.h>
-#if defined(OSX)
-#include <mach/mach.h>
-#include <mach/clock.h>
-#endif
-#elif defined(WIN32)
-#include <sys/timeb.h>
-#include "talk/base/win32.h"
-#endif
-
-namespace talk_base {
-
-Timing::Timing() {
-#if defined(WIN32)
- // This may fail, but we handle failure gracefully in the methods
- // that use it (use alternative sleep method).
- //
- // TODO: Make it possible for user to tell if IdleWait will
- // be done at lesser resolution because of this.
- timer_handle_ = CreateWaitableTimer(NULL, // Security attributes.
- FALSE, // Manual reset?
- NULL); // Timer name.
-#endif
-}
-
-Timing::~Timing() {
-#if defined(WIN32)
- if (timer_handle_ != NULL)
- CloseHandle(timer_handle_);
-#endif
-}
-
-double Timing::WallTimeNow() {
-#if defined(POSIX)
- struct timeval time;
- gettimeofday(&time, NULL);
- // Convert from second (1.0) and microsecond (1e-6).
- return (static_cast<double>(time.tv_sec) +
- static_cast<double>(time.tv_usec) * 1.0e-6);
-
-#elif defined(WIN32)
- struct _timeb time;
- _ftime(&time);
- // Convert from second (1.0) and milliseconds (1e-3).
- return (static_cast<double>(time.time) +
- static_cast<double>(time.millitm) * 1.0e-3);
-#endif
-}
-
-double Timing::TimerNow() {
- return (static_cast<double>(TimeNanos()) / kNumNanosecsPerSec);
-}
-
-double Timing::BusyWait(double period) {
- double start_time = TimerNow();
- while (TimerNow() - start_time < period) {
- }
- return TimerNow() - start_time;
-}
-
-double Timing::IdleWait(double period) {
- double start_time = TimerNow();
-
-#if defined(POSIX)
- double sec_int, sec_frac = modf(period, &sec_int);
- struct timespec ts;
- ts.tv_sec = static_cast<time_t>(sec_int);
- ts.tv_nsec = static_cast<long>(sec_frac * 1.0e9); // NOLINT
-
- // NOTE(liulk): for the NOLINT above, long is the appropriate POSIX
- // type.
-
- // POSIX nanosleep may be interrupted by signals.
- while (nanosleep(&ts, &ts) == -1 && errno == EINTR) {
- }
-
-#elif defined(WIN32)
- if (timer_handle_ != NULL) {
- LARGE_INTEGER due_time;
-
- // Negative indicates relative time. The unit is 100 nanoseconds.
- due_time.QuadPart = -LONGLONG(period * 1.0e7);
-
- SetWaitableTimer(timer_handle_, &due_time, 0, NULL, NULL, TRUE);
- WaitForSingleObject(timer_handle_, INFINITE);
- } else {
- // Still attempts to sleep with lesser resolution.
- // The unit is in milliseconds.
- Sleep(DWORD(period * 1.0e3));
- }
-#endif
-
- return TimerNow() - start_time;
-}
-
-} // namespace talk_base
diff --git a/base/timing.h b/base/timing.h
deleted file mode 100644
index f2bf013..0000000
--- a/base/timing.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TIMING_H_
-#define TALK_BASE_TIMING_H_
-
-#if defined(WIN32)
-#include "talk/base/win32.h"
-#endif
-
-namespace talk_base {
-
-class Timing {
- public:
- Timing();
- virtual ~Timing();
-
- // WallTimeNow() returns the current wall-clock time in seconds,
- // within 10 milliseconds resolution.
- virtual double WallTimeNow();
-
- // TimerNow() is like WallTimeNow(), but is monotonically
- // increasing. It returns seconds in resolution of 10 microseconds
- // or better. Although timer and wall-clock time have the same
- // timing unit, they do not necessarily correlate because wall-clock
- // time may be adjusted backwards, hence not monotonic.
- // Made virtual so we can make a fake one.
- virtual double TimerNow();
-
- // BusyWait() exhausts CPU as long as the time elapsed is less than
- // the specified interval in seconds. Returns the actual waiting
- // time based on TimerNow() measurement.
- double BusyWait(double period);
-
- // IdleWait() relinquishes control of CPU for specified period in
- // seconds. It uses highest resolution sleep mechanism as possible,
- // but does not otherwise guarantee the accuracy. Returns the
- // actual waiting time based on TimerNow() measurement.
- //
- // This function is not re-entrant for an object. Create a fresh
- // Timing object for each thread.
- double IdleWait(double period);
-
- private:
-#if defined(WIN32)
- HANDLE timer_handle_;
-#endif
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TIMING_H_
diff --git a/base/transformadapter.cc b/base/transformadapter.cc
deleted file mode 100644
index 2a240eb..0000000
--- a/base/transformadapter.cc
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/transformadapter.h"
-
-#include <string.h>
-
-#include "talk/base/common.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-TransformAdapter::TransformAdapter(StreamInterface * stream,
- TransformInterface * transform,
- bool direction_read)
- : StreamAdapterInterface(stream), transform_(transform),
- direction_read_(direction_read), state_(ST_PROCESSING), len_(0) {
-}
-
-TransformAdapter::~TransformAdapter() {
- TransformAdapter::Close();
- delete transform_;
-}
-
-StreamResult
-TransformAdapter::Read(void * buffer, size_t buffer_len,
- size_t * read, int * error) {
- if (!direction_read_)
- return SR_EOS;
-
- while (state_ != ST_ERROR) {
- if (state_ == ST_COMPLETE)
- return SR_EOS;
-
- // Buffer more data
- if ((state_ == ST_PROCESSING) && (len_ < sizeof(buffer_))) {
- size_t subread;
- StreamResult result = StreamAdapterInterface::Read(
- buffer_ + len_,
- sizeof(buffer_) - len_,
- &subread,
- &error_);
- if (result == SR_BLOCK) {
- return SR_BLOCK;
- } else if (result == SR_ERROR) {
- state_ = ST_ERROR;
- break;
- } else if (result == SR_EOS) {
- state_ = ST_FLUSHING;
- } else {
- len_ += subread;
- }
- }
-
- // Process buffered data
- size_t in_len = len_;
- size_t out_len = buffer_len;
- StreamResult result = transform_->Transform(buffer_, &in_len,
- buffer, &out_len,
- (state_ == ST_FLUSHING));
- ASSERT(result != SR_BLOCK);
- if (result == SR_EOS) {
- // Note: Don't signal SR_EOS this iteration, unless out_len is zero
- state_ = ST_COMPLETE;
- } else if (result == SR_ERROR) {
- state_ = ST_ERROR;
- error_ = -1; // TODO: propagate error
- break;
- } else if ((out_len == 0) && (state_ == ST_FLUSHING)) {
- // If there is no output AND no more input, then something is wrong
- state_ = ST_ERROR;
- error_ = -1; // TODO: better error code?
- break;
- }
-
- len_ -= in_len;
- if (len_ > 0)
- memmove(buffer_, buffer_ + in_len, len_);
-
- if (out_len == 0)
- continue;
-
- if (read)
- *read = out_len;
- return SR_SUCCESS;
- }
-
- if (error)
- *error = error_;
- return SR_ERROR;
-}
-
-StreamResult
-TransformAdapter::Write(const void * data, size_t data_len,
- size_t * written, int * error) {
- if (direction_read_)
- return SR_EOS;
-
- size_t bytes_written = 0;
- while (state_ != ST_ERROR) {
- if (state_ == ST_COMPLETE)
- return SR_EOS;
-
- if (len_ < sizeof(buffer_)) {
- // Process buffered data
- size_t in_len = data_len;
- size_t out_len = sizeof(buffer_) - len_;
- StreamResult result = transform_->Transform(data, &in_len,
- buffer_ + len_, &out_len,
- (state_ == ST_FLUSHING));
-
- ASSERT(result != SR_BLOCK);
- if (result == SR_EOS) {
- // Note: Don't signal SR_EOS this iteration, unless no data written
- state_ = ST_COMPLETE;
- } else if (result == SR_ERROR) {
- ASSERT(false); // When this happens, think about what should be done
- state_ = ST_ERROR;
- error_ = -1; // TODO: propagate error
- break;
- }
-
- len_ = out_len;
- bytes_written = in_len;
- }
-
- size_t pos = 0;
- while (pos < len_) {
- size_t subwritten;
- StreamResult result = StreamAdapterInterface::Write(buffer_ + pos,
- len_ - pos,
- &subwritten,
- &error_);
- if (result == SR_BLOCK) {
- ASSERT(false); // TODO: we should handle this
- return SR_BLOCK;
- } else if (result == SR_ERROR) {
- state_ = ST_ERROR;
- break;
- } else if (result == SR_EOS) {
- state_ = ST_COMPLETE;
- break;
- }
-
- pos += subwritten;
- }
-
- len_ -= pos;
- if (len_ > 0)
- memmove(buffer_, buffer_ + pos, len_);
-
- if (bytes_written == 0)
- continue;
-
- if (written)
- *written = bytes_written;
- return SR_SUCCESS;
- }
-
- if (error)
- *error = error_;
- return SR_ERROR;
-}
-
-void
-TransformAdapter::Close() {
- if (!direction_read_ && (state_ == ST_PROCESSING)) {
- state_ = ST_FLUSHING;
- do {
- Write(0, 0, NULL, NULL);
- } while (state_ == ST_FLUSHING);
- }
- state_ = ST_COMPLETE;
- StreamAdapterInterface::Close();
-}
-
-} // namespace talk_base
diff --git a/base/transformadapter.h b/base/transformadapter.h
deleted file mode 100644
index e96a13d..0000000
--- a/base/transformadapter.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_TRANSFORMADAPTER_H__
-#define TALK_BASE_TRANSFORMADAPTER_H__
-
-#include "talk/base/stream.h"
-
-namespace talk_base {
-///////////////////////////////////////////////////////////////////////////////
-
-class TransformInterface {
-public:
- virtual ~TransformInterface() { }
-
- // Transform should convert the in_len bytes of input into the out_len-sized
- // output buffer. If flush is true, there will be no more data following
- // input.
- // After the transformation, in_len contains the number of bytes consumed, and
- // out_len contains the number of bytes ready in output.
- // Note: Transform should not return SR_BLOCK, as there is no asynchronous
- // notification available.
- virtual StreamResult Transform(const void * input, size_t * in_len,
- void * output, size_t * out_len,
- bool flush) = 0;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-// TransformAdapter causes all data passed through to be transformed by the
-// supplied TransformInterface object, which may apply compression, encryption,
-// etc.
-
-class TransformAdapter : public StreamAdapterInterface {
-public:
- // Note that the transformation is unidirectional, in the direction specified
- // by the constructor. Operations in the opposite direction result in SR_EOS.
- TransformAdapter(StreamInterface * stream,
- TransformInterface * transform,
- bool direction_read);
- virtual ~TransformAdapter();
-
- virtual StreamResult Read(void * buffer, size_t buffer_len,
- size_t * read, int * error);
- virtual StreamResult Write(const void * data, size_t data_len,
- size_t * written, int * error);
- virtual void Close();
-
- // Apriori, we can't tell what the transformation does to the stream length.
- virtual bool GetAvailable(size_t* size) const { return false; }
- virtual bool ReserveSize(size_t size) { return true; }
-
- // Transformations might not be restartable
- virtual bool Rewind() { return false; }
-
-private:
- enum State { ST_PROCESSING, ST_FLUSHING, ST_COMPLETE, ST_ERROR };
- enum { BUFFER_SIZE = 1024 };
-
- TransformInterface * transform_;
- bool direction_read_;
- State state_;
- int error_;
-
- char buffer_[BUFFER_SIZE];
- size_t len_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_TRANSFORMADAPTER_H__
diff --git a/base/unittest_main.cc b/base/unittest_main.cc
deleted file mode 100644
index def763c..0000000
--- a/base/unittest_main.cc
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2007 Google Inc. All Rights Reserved.
-
-// juberti@google.com (Justin Uberti)
-//
-// A reuseable entry point for gunit tests.
-
-#ifdef WIN32
-#include <crtdbg.h>
-#endif
-
-#include "talk/base/flags.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-
-DEFINE_bool(help, false, "prints this message");
-DEFINE_string(log, "", "logging options to use");
-#ifdef WIN32
-DEFINE_int(crt_break_alloc, -1, "memory allocation to break on");
-DEFINE_bool(default_error_handlers, false,
- "leave the default exception/dbg handler functions in place");
-
-void TestInvalidParameterHandler(const wchar_t* expression,
- const wchar_t* function,
- const wchar_t* file,
- unsigned int line,
- uintptr_t pReserved) {
- LOG(LS_ERROR) << "InvalidParameter Handler called. Exiting.";
- LOG(LS_ERROR) << expression << std::endl << function << std::endl << file
- << std::endl << line;
- exit(1);
-}
-void TestPureCallHandler() {
- LOG(LS_ERROR) << "Purecall Handler called. Exiting.";
- exit(1);
-}
-int TestCrtReportHandler(int report_type, char* msg, int* retval) {
- LOG(LS_ERROR) << "CrtReport Handler called...";
- LOG(LS_ERROR) << msg;
- if (report_type == _CRT_ASSERT) {
- exit(1);
- } else {
- *retval = 0;
- return TRUE;
- }
-}
-#endif // WIN32
-
-int main(int argc, char** argv) {
- testing::InitGoogleTest(&argc, argv);
- FlagList::SetFlagsFromCommandLine(&argc, argv, false);
- if (FLAG_help) {
- FlagList::Print(NULL, false);
- return 0;
- }
-
-#ifdef WIN32
- if (!FLAG_default_error_handlers) {
- // Make sure any errors don't throw dialogs hanging the test run.
- _set_invalid_parameter_handler(TestInvalidParameterHandler);
- _set_purecall_handler(TestPureCallHandler);
- _CrtSetReportHook2(_CRT_RPTHOOK_INSTALL, TestCrtReportHandler);
- }
-
-#ifdef _DEBUG // Turn on memory leak checking on Windows.
- _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF |_CRTDBG_LEAK_CHECK_DF);
- if (FLAG_crt_break_alloc >= 0) {
- _crtBreakAlloc = FLAG_crt_break_alloc;
- }
-#endif // _DEBUG
-#endif // WIN32
-
- talk_base::Filesystem::SetOrganizationName("google");
- talk_base::Filesystem::SetApplicationName("unittest");
-
- // By default, log timestamps. Allow overrides by used of a --log flag.
- talk_base::LogMessage::LogTimestamps();
- if (*FLAG_log != '\0') {
- talk_base::LogMessage::ConfigureLogging(FLAG_log, "unittest.log");
- }
-
- int res = RUN_ALL_TESTS();
-
- // clean up logging so we don't appear to leak memory.
- talk_base::LogMessage::ConfigureLogging("", "");
-
-#ifdef WIN32
- // Unhook crt function so that we don't ever log after statics have been
- // uninitialized.
- if (!FLAG_default_error_handlers)
- _CrtSetReportHook2(_CRT_RPTHOOK_REMOVE, TestCrtReportHandler);
-#endif
-
- return res;
-}
diff --git a/base/unixfilesystem.cc b/base/unixfilesystem.cc
deleted file mode 100644
index 8ac7499..0000000
--- a/base/unixfilesystem.cc
+++ /dev/null
@@ -1,589 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/unixfilesystem.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#ifdef OSX
-#include <Carbon/Carbon.h>
-#include <IOKit/IOCFBundle.h>
-#include <sys/statvfs.h>
-#include "talk/base/macutils.h"
-#endif // OSX
-
-#if defined(POSIX) && !defined(OSX)
-#include <sys/types.h>
-#if defined(ANDROID)
-#include <sys/statfs.h>
-#elif !defined(__native_client__)
-#include <sys/statvfs.h>
-#endif // !defined(__native_client__)
-#include <limits.h>
-#include <pwd.h>
-#include <stdio.h>
-#endif // POSIX && !OSX
-
-#if defined(LINUX)
-#include <ctype.h>
-#include <algorithm>
-#endif
-
-#if defined(__native_client__) && !defined(__GLIBC__)
-#include <sys/syslimits.h>
-#endif
-
-#include "talk/base/fileutils.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringutils.h"
-
-#if defined(IOS)
-// Defined in iosfilesystem.mm. No header file to discourage use
-// elsewhere; other places should use GetApp{Data,Temp}Folder() in
-// this file. Don't copy/paste. I mean it.
-char* IOSDataDirectory();
-char* IOSTempDirectory();
-void IOSAppName(talk_base::Pathname* path);
-#endif
-
-namespace talk_base {
-
-#if !defined(ANDROID) && !defined(IOS)
-char* UnixFilesystem::app_temp_path_ = NULL;
-#else
-char* UnixFilesystem::provided_app_data_folder_ = NULL;
-char* UnixFilesystem::provided_app_temp_folder_ = NULL;
-
-void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
- delete [] provided_app_data_folder_;
- provided_app_data_folder_ = CopyString(folder);
-}
-
-void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
- delete [] provided_app_temp_folder_;
- provided_app_temp_folder_ = CopyString(folder);
-}
-#endif
-
-UnixFilesystem::UnixFilesystem() {
-#if defined(IOS)
- if (!provided_app_data_folder_)
- provided_app_data_folder_ = IOSDataDirectory();
- if (!provided_app_temp_folder_)
- provided_app_temp_folder_ = IOSTempDirectory();
-#endif
-}
-
-UnixFilesystem::~UnixFilesystem() {}
-
-bool UnixFilesystem::CreateFolder(const Pathname &path, mode_t mode) {
- std::string pathname(path.pathname());
- int len = pathname.length();
- if ((len == 0) || (pathname[len - 1] != '/'))
- return false;
-
- struct stat st;
- int res = ::stat(pathname.c_str(), &st);
- if (res == 0) {
- // Something exists at this location, check if it is a directory
- return S_ISDIR(st.st_mode) != 0;
- } else if (errno != ENOENT) {
- // Unexpected error
- return false;
- }
-
- // Directory doesn't exist, look up one directory level
- do {
- --len;
- } while ((len > 0) && (pathname[len - 1] != '/'));
-
- if (!CreateFolder(Pathname(pathname.substr(0, len)), mode)) {
- return false;
- }
-
- LOG(LS_INFO) << "Creating folder: " << pathname;
- return (0 == ::mkdir(pathname.c_str(), mode));
-}
-
-bool UnixFilesystem::CreateFolder(const Pathname &path) {
- return CreateFolder(path, 0755);
-}
-
-FileStream *UnixFilesystem::OpenFile(const Pathname &filename,
- const std::string &mode) {
- FileStream *fs = new FileStream();
- if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
- delete fs;
- fs = NULL;
- }
- return fs;
-}
-
-bool UnixFilesystem::CreatePrivateFile(const Pathname &filename) {
- int fd = open(filename.pathname().c_str(),
- O_RDWR | O_CREAT | O_EXCL,
- S_IRUSR | S_IWUSR);
- if (fd < 0) {
- LOG_ERR(LS_ERROR) << "open() failed.";
- return false;
- }
- // Don't need to keep the file descriptor.
- if (close(fd) < 0) {
- LOG_ERR(LS_ERROR) << "close() failed.";
- // Continue.
- }
- return true;
-}
-
-bool UnixFilesystem::DeleteFile(const Pathname &filename) {
- LOG(LS_INFO) << "Deleting file:" << filename.pathname();
-
- if (!IsFile(filename)) {
- ASSERT(IsFile(filename));
- return false;
- }
- return ::unlink(filename.pathname().c_str()) == 0;
-}
-
-bool UnixFilesystem::DeleteEmptyFolder(const Pathname &folder) {
- LOG(LS_INFO) << "Deleting folder" << folder.pathname();
-
- if (!IsFolder(folder)) {
- ASSERT(IsFolder(folder));
- return false;
- }
- std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
- return ::rmdir(no_slash.c_str()) == 0;
-}
-
-bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
- const std::string *append) {
-#ifdef OSX
- FSRef fr;
- if (0 != FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType,
- kCreateFolder, &fr))
- return false;
- unsigned char buffer[NAME_MAX+1];
- if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
- return false;
- pathname.SetPathname(reinterpret_cast<char*>(buffer), "");
-#elif defined(ANDROID) || defined(IOS)
- ASSERT(provided_app_temp_folder_ != NULL);
- pathname.SetPathname(provided_app_temp_folder_, "");
-#else // !OSX && !ANDROID
- if (const char* tmpdir = getenv("TMPDIR")) {
- pathname.SetPathname(tmpdir, "");
- } else if (const char* tmp = getenv("TMP")) {
- pathname.SetPathname(tmp, "");
- } else {
-#ifdef P_tmpdir
- pathname.SetPathname(P_tmpdir, "");
-#else // !P_tmpdir
- pathname.SetPathname("/tmp/", "");
-#endif // !P_tmpdir
- }
-#endif // !OSX && !ANDROID
- if (append) {
- ASSERT(!append->empty());
- pathname.AppendFolder(*append);
- }
- return !create || CreateFolder(pathname);
-}
-
-std::string UnixFilesystem::TempFilename(const Pathname &dir,
- const std::string &prefix) {
- int len = dir.pathname().size() + prefix.size() + 2 + 6;
- char *tempname = new char[len];
-
- snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
- prefix.c_str());
- int fd = ::mkstemp(tempname);
- if (fd != -1)
- ::close(fd);
- std::string ret(tempname);
- delete[] tempname;
-
- return ret;
-}
-
-bool UnixFilesystem::MoveFile(const Pathname &old_path,
- const Pathname &new_path) {
- if (!IsFile(old_path)) {
- ASSERT(IsFile(old_path));
- return false;
- }
- LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
- << " to " << new_path.pathname();
- if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
- if (errno != EXDEV)
- return false;
- if (!CopyFile(old_path, new_path))
- return false;
- if (!DeleteFile(old_path))
- return false;
- }
- return true;
-}
-
-bool UnixFilesystem::MoveFolder(const Pathname &old_path,
- const Pathname &new_path) {
- if (!IsFolder(old_path)) {
- ASSERT(IsFolder(old_path));
- return false;
- }
- LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
- << " to " << new_path.pathname();
- if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
- if (errno != EXDEV)
- return false;
- if (!CopyFolder(old_path, new_path))
- return false;
- if (!DeleteFolderAndContents(old_path))
- return false;
- }
- return true;
-}
-
-bool UnixFilesystem::IsFolder(const Pathname &path) {
- struct stat st;
- if (stat(path.pathname().c_str(), &st) < 0)
- return false;
- return S_ISDIR(st.st_mode);
-}
-
-bool UnixFilesystem::CopyFile(const Pathname &old_path,
- const Pathname &new_path) {
- LOG(LS_VERBOSE) << "Copying " << old_path.pathname()
- << " to " << new_path.pathname();
- char buf[256];
- size_t len;
-
- StreamInterface *source = OpenFile(old_path, "rb");
- if (!source)
- return false;
-
- StreamInterface *dest = OpenFile(new_path, "wb");
- if (!dest) {
- delete source;
- return false;
- }
-
- while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
- dest->Write(buf, len, NULL, NULL);
-
- delete source;
- delete dest;
- return true;
-}
-
-bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
-#if defined(ANDROID) || defined(IOS)
- ASSERT(provided_app_temp_folder_ != NULL);
-#endif
-
- const char* const kTempPrefixes[] = {
-#if defined(ANDROID) || defined(IOS)
- provided_app_temp_folder_,
-#else
- "/tmp/", "/var/tmp/",
-#ifdef OSX
- "/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
-#endif // OSX
-#endif // ANDROID || IOS
- };
- for (size_t i = 0; i < ARRAY_SIZE(kTempPrefixes); ++i) {
- if (0 == strncmp(pathname.pathname().c_str(), kTempPrefixes[i],
- strlen(kTempPrefixes[i])))
- return true;
- }
- return false;
-}
-
-bool UnixFilesystem::IsFile(const Pathname& pathname) {
- struct stat st;
- int res = ::stat(pathname.pathname().c_str(), &st);
- // Treat symlinks, named pipes, etc. all as files.
- return res == 0 && !S_ISDIR(st.st_mode);
-}
-
-bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
- struct stat st;
- int res = ::stat(pathname.pathname().c_str(), &st);
- // Note: we specifically maintain ENOTDIR as an error, because that implies
- // that you could not call CreateFolder(pathname).
- return res != 0 && ENOENT == errno;
-}
-
-bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
- struct stat st;
- if (::stat(pathname.pathname().c_str(), &st) != 0)
- return false;
- *size = st.st_size;
- return true;
-}
-
-bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
- time_t* time) {
- struct stat st;
- if (::stat(path.pathname().c_str(), &st) != 0)
- return false;
- switch (which) {
- case FTT_CREATED:
- *time = st.st_ctime;
- break;
- case FTT_MODIFIED:
- *time = st.st_mtime;
- break;
- case FTT_ACCESSED:
- *time = st.st_atime;
- break;
- default:
- return false;
- }
- return true;
-}
-
-bool UnixFilesystem::GetAppPathname(Pathname* path) {
-#ifdef OSX
- ProcessSerialNumber psn = { 0, kCurrentProcess };
- CFDictionaryRef procinfo = ProcessInformationCopyDictionary(&psn,
- kProcessDictionaryIncludeAllInformationMask);
- if (NULL == procinfo)
- return false;
- CFStringRef cfpath = (CFStringRef) CFDictionaryGetValue(procinfo,
- kIOBundleExecutableKey);
- std::string path8;
- bool success = ToUtf8(cfpath, &path8);
- CFRelease(procinfo);
- if (success)
- path->SetPathname(path8);
- return success;
-#elif defined(__native_client__)
- return false;
-#elif IOS
- IOSAppName(path);
- return true;
-#else // OSX
- char buffer[PATH_MAX + 2];
- ssize_t len = readlink("/proc/self/exe", buffer, ARRAY_SIZE(buffer) - 1);
- if ((len <= 0) || (len == PATH_MAX + 1))
- return false;
- buffer[len] = '\0';
- path->SetPathname(buffer);
- return true;
-#endif // OSX
-}
-
-bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
- ASSERT(!organization_name_.empty());
- ASSERT(!application_name_.empty());
-
- // First get the base directory for app data.
-#ifdef OSX
- if (per_user) {
- // Use ~/Library/Application Support/<orgname>/<appname>/
- FSRef fr;
- if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
- kCreateFolder, &fr))
- return false;
- unsigned char buffer[NAME_MAX+1];
- if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
- return false;
- path->SetPathname(reinterpret_cast<char*>(buffer), "");
- } else {
- // TODO
- return false;
- }
-#elif defined(ANDROID) || defined(IOS) // && !OSX
- ASSERT(provided_app_data_folder_ != NULL);
- path->SetPathname(provided_app_data_folder_, "");
-#elif defined(LINUX) // && !OSX && !defined(ANDROID) && !defined(IOS)
- if (per_user) {
- // We follow the recommendations in
- // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
- // It specifies separate directories for data and config files, but
- // GetAppDataFolder() does not distinguish. We just return the config dir
- // path.
- const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
- if (xdg_config_home) {
- path->SetPathname(xdg_config_home, "");
- } else {
- // XDG says to default to $HOME/.config. We also support falling back to
- // other synonyms for HOME if for some reason it is not defined.
- const char* homedir;
- if (const char* home = getenv("HOME")) {
- homedir = home;
- } else if (const char* dotdir = getenv("DOTDIR")) {
- homedir = dotdir;
- } else if (passwd* pw = getpwuid(geteuid())) {
- homedir = pw->pw_dir;
- } else {
- return false;
- }
- path->SetPathname(homedir, "");
- path->AppendFolder(".config");
- }
- } else {
- // XDG does not define a standard directory for writable global data. Let's
- // just use this.
- path->SetPathname("/var/cache/", "");
- }
-#endif // !OSX && !defined(ANDROID) && !defined(LINUX)
-
- // Now add on a sub-path for our app.
-#if defined(OSX) || defined(ANDROID) || defined(IOS)
- path->AppendFolder(organization_name_);
- path->AppendFolder(application_name_);
-#elif defined(LINUX)
- // XDG says to use a single directory level, so we concatenate the org and app
- // name with a hyphen. We also do the Linuxy thing and convert to all
- // lowercase with no spaces.
- std::string subdir(organization_name_);
- subdir.append("-");
- subdir.append(application_name_);
- replace_substrs(" ", 1, "", 0, &subdir);
- std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
- path->AppendFolder(subdir);
-#endif
- if (!CreateFolder(*path, 0700)) {
- return false;
- }
-#if !defined(__native_client__)
- // If the folder already exists, it may have the wrong mode or be owned by
- // someone else, both of which are security problems. Setting the mode
- // avoids both issues since it will fail if the path is not owned by us.
- if (0 != ::chmod(path->pathname().c_str(), 0700)) {
- LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
- return false;
- }
-#endif
- return true;
-}
-
-bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
-#if defined(ANDROID) || defined(IOS)
- ASSERT(provided_app_temp_folder_ != NULL);
- path->SetPathname(provided_app_temp_folder_);
- return true;
-#else
- ASSERT(!application_name_.empty());
- // TODO: Consider whether we are worried about thread safety.
- if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
- path->SetPathname(app_temp_path_);
- return true;
- }
-
- // Create a random directory as /tmp/<appname>-<pid>-<timestamp>
- char buffer[128];
- sprintfn(buffer, ARRAY_SIZE(buffer), "-%d-%d",
- static_cast<int>(getpid()),
- static_cast<int>(time(0)));
- std::string folder(application_name_);
- folder.append(buffer);
- if (!GetTemporaryFolder(*path, true, &folder))
- return false;
-
- delete [] app_temp_path_;
- app_temp_path_ = CopyString(path->pathname());
- // TODO: atexit(DeleteFolderAndContents(app_temp_path_));
- return true;
-#endif
-}
-
-bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path, int64 *freebytes) {
-#ifdef __native_client__
- return false;
-#else // __native_client__
- ASSERT(NULL != freebytes);
- // TODO: Consider making relative paths absolute using cwd.
- // TODO: When popping off a symlink, push back on the components of the
- // symlink, so we don't jump out of the target disk inadvertently.
- Pathname existing_path(path.folder(), "");
- while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
- existing_path.SetFolder(existing_path.parent_folder());
- }
-#ifdef ANDROID
- struct statfs vfs;
- memset(&vfs, 0, sizeof(vfs));
- if (0 != statfs(existing_path.pathname().c_str(), &vfs))
- return false;
-#else
- struct statvfs vfs;
- memset(&vfs, 0, sizeof(vfs));
- if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
- return false;
-#endif // ANDROID
-#if defined(LINUX) || defined(ANDROID)
- *freebytes = static_cast<int64>(vfs.f_bsize) * vfs.f_bavail;
-#elif defined(OSX) || defined(IOS)
- *freebytes = static_cast<int64>(vfs.f_frsize) * vfs.f_bavail;
-#endif
-
- return true;
-#endif // !__native_client__
-}
-
-Pathname UnixFilesystem::GetCurrentDirectory() {
- Pathname cwd;
- char buffer[PATH_MAX];
- char *path = getcwd(buffer, PATH_MAX);
-
- if (!path) {
- LOG_ERR(LS_ERROR) << "getcwd() failed";
- return cwd; // returns empty pathname
- }
- cwd.SetFolder(std::string(path));
-
- return cwd;
-}
-
-char* UnixFilesystem::CopyString(const std::string& str) {
- size_t size = str.length() + 1;
-
- char* buf = new char[size];
- if (!buf) {
- return NULL;
- }
-
- strcpyn(buf, size, str.c_str());
- return buf;
-}
-
-} // namespace talk_base
-
-#if defined(__native_client__)
-extern "C" int __attribute__((weak))
-link(const char* oldpath, const char* newpath) {
- errno = EACCES;
- return -1;
-}
-#endif
diff --git a/base/unixfilesystem.h b/base/unixfilesystem.h
deleted file mode 100644
index d709115..0000000
--- a/base/unixfilesystem.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_UNIXFILESYSTEM_H_
-#define TALK_BASE_UNIXFILESYSTEM_H_
-
-#include <sys/types.h>
-
-#include "talk/base/fileutils.h"
-
-namespace talk_base {
-
-class UnixFilesystem : public FilesystemInterface {
- public:
- UnixFilesystem();
- virtual ~UnixFilesystem();
-
-#if defined(ANDROID) || defined(IOS)
- // Android does not have a native code API to fetch the app data or temp
- // folders. That needs to be passed into this class from Java. Similarly, iOS
- // only supports an Objective-C API for fetching the folder locations, so that
- // needs to be passed in here from Objective-C. Or at least that used to be
- // the case; now the ctor will do the work if necessary and possible.
- // TODO(fischman): add an Android version that uses JNI and drop the
- // SetApp*Folder() APIs once external users stop using them.
- static void SetAppDataFolder(const std::string& folder);
- static void SetAppTempFolder(const std::string& folder);
-#endif
-
- // Opens a file. Returns an open StreamInterface if function succeeds.
- // Otherwise, returns NULL.
- virtual FileStream *OpenFile(const Pathname &filename,
- const std::string &mode);
-
- // Atomically creates an empty file accessible only to the current user if one
- // does not already exist at the given path, otherwise fails.
- virtual bool CreatePrivateFile(const Pathname &filename);
-
- // This will attempt to delete the file located at filename.
- // It will fail with VERIY if you pass it a non-existant file, or a directory.
- virtual bool DeleteFile(const Pathname &filename);
-
- // This will attempt to delete the folder located at 'folder'
- // It ASSERTs and returns false if you pass it a non-existant folder or a
- // plain file.
- virtual bool DeleteEmptyFolder(const Pathname &folder);
-
- // Creates a directory. This will call itself recursively to create /foo/bar
- // even if /foo does not exist. All created directories are created with the
- // given mode.
- // Returns TRUE if function succeeds
- virtual bool CreateFolder(const Pathname &pathname, mode_t mode);
-
- // As above, with mode = 0755.
- virtual bool CreateFolder(const Pathname &pathname);
-
- // This moves a file from old_path to new_path, where "file" can be a plain
- // file or directory, which will be moved recursively.
- // Returns true if function succeeds.
- virtual bool MoveFile(const Pathname &old_path, const Pathname &new_path);
- virtual bool MoveFolder(const Pathname &old_path, const Pathname &new_path);
-
- // This copies a file from old_path to _new_path where "file" can be a plain
- // file or directory, which will be copied recursively.
- // Returns true if function succeeds
- virtual bool CopyFile(const Pathname &old_path, const Pathname &new_path);
-
- // Returns true if a pathname is a directory
- virtual bool IsFolder(const Pathname& pathname);
-
- // Returns true if pathname represents a temporary location on the system.
- virtual bool IsTemporaryPath(const Pathname& pathname);
-
- // Returns true of pathname represents an existing file
- virtual bool IsFile(const Pathname& pathname);
-
- // Returns true if pathname refers to no filesystem object, every parent
- // directory either exists, or is also absent.
- virtual bool IsAbsent(const Pathname& pathname);
-
- virtual std::string TempFilename(const Pathname &dir,
- const std::string &prefix);
-
- // A folder appropriate for storing temporary files (Contents are
- // automatically deleted when the program exists)
- virtual bool GetTemporaryFolder(Pathname &path, bool create,
- const std::string *append);
-
- virtual bool GetFileSize(const Pathname& path, size_t* size);
- virtual bool GetFileTime(const Pathname& path, FileTimeType which,
- time_t* time);
-
- // Returns the path to the running application.
- virtual bool GetAppPathname(Pathname* path);
-
- virtual bool GetAppDataFolder(Pathname* path, bool per_user);
-
- // Get a temporary folder that is unique to the current user and application.
- virtual bool GetAppTempFolder(Pathname* path);
-
- virtual bool GetDiskFreeSpace(const Pathname& path, int64 *freebytes);
-
- // Returns the absolute path of the current directory.
- virtual Pathname GetCurrentDirectory();
-
- private:
-#if defined(ANDROID) || defined(IOS)
- static char* provided_app_data_folder_;
- static char* provided_app_temp_folder_;
-#else
- static char* app_temp_path_;
-#endif
-
- static char* CopyString(const std::string& str);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_UNIXFILESYSTEM_H_
diff --git a/base/urlencode.cc b/base/urlencode.cc
deleted file mode 100644
index 6fe7178..0000000
--- a/base/urlencode.cc
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/urlencode.h"
-
-#include "talk/base/common.h"
-#include "talk/base/stringutils.h"
-
-static int HexPairValue(const char * code) {
- int value = 0;
- const char * pch = code;
- for (;;) {
- int digit = *pch++;
- if (digit >= '0' && digit <= '9') {
- value += digit - '0';
- }
- else if (digit >= 'A' && digit <= 'F') {
- value += digit - 'A' + 10;
- }
- else if (digit >= 'a' && digit <= 'f') {
- value += digit - 'a' + 10;
- }
- else {
- return -1;
- }
- if (pch == code + 2)
- return value;
- value <<= 4;
- }
-}
-
-int InternalUrlDecode(const char *source, char *dest,
- bool encode_space_as_plus) {
- char * start = dest;
-
- while (*source) {
- switch (*source) {
- case '+':
- if (encode_space_as_plus) {
- *(dest++) = ' ';
- } else {
- *dest++ = *source;
- }
- break;
- case '%':
- if (source[1] && source[2]) {
- int value = HexPairValue(source + 1);
- if (value >= 0) {
- *(dest++) = value;
- source += 2;
- }
- else {
- *dest++ = '?';
- }
- }
- else {
- *dest++ = '?';
- }
- break;
- default:
- *dest++ = *source;
- }
- source++;
- }
-
- *dest = 0;
- return static_cast<int>(dest - start);
-}
-
-int UrlDecode(const char *source, char *dest) {
- return InternalUrlDecode(source, dest, true);
-}
-
-int UrlDecodeWithoutEncodingSpaceAsPlus(const char *source, char *dest) {
- return InternalUrlDecode(source, dest, false);
-}
-
-bool IsValidUrlChar(char ch, bool unsafe_only) {
- if (unsafe_only) {
- return !(ch <= ' ' || strchr("\\\"^&`<>[]{}", ch));
- } else {
- return isalnum(ch) || strchr("-_.!~*'()", ch);
- }
-}
-
-int InternalUrlEncode(const char *source, char *dest, unsigned int max,
- bool encode_space_as_plus, bool unsafe_only) {
- static const char *digits = "0123456789ABCDEF";
- if (max == 0) {
- return 0;
- }
-
- char *start = dest;
- while (static_cast<unsigned>(dest - start) < max && *source) {
- unsigned char ch = static_cast<unsigned char>(*source);
- if (*source == ' ' && encode_space_as_plus && !unsafe_only) {
- *dest++ = '+';
- } else if (IsValidUrlChar(ch, unsafe_only)) {
- *dest++ = *source;
- } else {
- if (static_cast<unsigned>(dest - start) + 4 > max) {
- break;
- }
- *dest++ = '%';
- *dest++ = digits[(ch >> 4) & 0x0F];
- *dest++ = digits[ ch & 0x0F];
- }
- source++;
- }
- ASSERT(static_cast<unsigned int>(dest - start) < max);
- *dest = 0;
-
- return static_cast<int>(dest - start);
-}
-
-int UrlEncode(const char *source, char *dest, unsigned max) {
- return InternalUrlEncode(source, dest, max, true, false);
-}
-
-int UrlEncodeWithoutEncodingSpaceAsPlus(const char *source, char *dest,
- unsigned max) {
- return InternalUrlEncode(source, dest, max, false, false);
-}
-
-int UrlEncodeOnlyUnsafeChars(const char *source, char *dest, unsigned max) {
- return InternalUrlEncode(source, dest, max, false, true);
-}
-
-std::string
-InternalUrlDecodeString(const std::string & encoded,
- bool encode_space_as_plus) {
- size_t needed_length = encoded.length() + 1;
- char* buf = STACK_ARRAY(char, needed_length);
- InternalUrlDecode(encoded.c_str(), buf, encode_space_as_plus);
- return buf;
-}
-
-std::string
-UrlDecodeString(const std::string & encoded) {
- return InternalUrlDecodeString(encoded, true);
-}
-
-std::string
-UrlDecodeStringWithoutEncodingSpaceAsPlus(const std::string & encoded) {
- return InternalUrlDecodeString(encoded, false);
-}
-
-std::string
-InternalUrlEncodeString(const std::string & decoded,
- bool encode_space_as_plus,
- bool unsafe_only) {
- int needed_length = static_cast<int>(decoded.length()) * 3 + 1;
- char* buf = STACK_ARRAY(char, needed_length);
- InternalUrlEncode(decoded.c_str(), buf, needed_length,
- encode_space_as_plus, unsafe_only);
- return buf;
-}
-
-std::string
-UrlEncodeString(const std::string & decoded) {
- return InternalUrlEncodeString(decoded, true, false);
-}
-
-std::string
-UrlEncodeStringWithoutEncodingSpaceAsPlus(const std::string & decoded) {
- return InternalUrlEncodeString(decoded, false, false);
-}
-
-std::string
-UrlEncodeStringForOnlyUnsafeChars(const std::string & decoded) {
- return InternalUrlEncodeString(decoded, false, true);
-}
diff --git a/base/urlencode.h b/base/urlencode.h
deleted file mode 100644
index 05165e8..0000000
--- a/base/urlencode.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * libjingle
- * Copyright 2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _URLENCODE_H_
-#define _URLENCODE_H_
-
-#include <string>
-
-// Decode all encoded characters. Also decode + as space.
-int UrlDecode(const char *source, char *dest);
-
-// Decode all encoded characters.
-int UrlDecodeWithoutEncodingSpaceAsPlus(const char *source, char *dest);
-
-// Encode all characters except alphas, numbers, and -_.!~*'()
-// Also encode space as +.
-int UrlEncode(const char *source, char *dest, unsigned max);
-
-// Encode all characters except alphas, numbers, and -_.!~*'()
-int UrlEncodeWithoutEncodingSpaceAsPlus(const char *source, char *dest,
- unsigned max);
-
-// Encode only unsafe chars, including \ "^&`<>[]{}
-// Also encode space as %20, instead of +
-int UrlEncodeOnlyUnsafeChars(const char *source, char *dest, unsigned max);
-
-std::string UrlDecodeString(const std::string & encoded);
-std::string UrlDecodeStringWithoutEncodingSpaceAsPlus(
- const std::string & encoded);
-std::string UrlEncodeString(const std::string & decoded);
-std::string UrlEncodeStringWithoutEncodingSpaceAsPlus(
- const std::string & decoded);
-std::string UrlEncodeStringForOnlyUnsafeChars(const std::string & decoded);
-
-#endif
-
diff --git a/base/urlencode_unittest.cc b/base/urlencode_unittest.cc
deleted file mode 100644
index f71cd75..0000000
--- a/base/urlencode_unittest.cc
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2011, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
-#include "talk/base/urlencode.h"
-
-TEST(Urlencode, SourceTooLong) {
- char source[] = "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
- "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^";
- char dest[1];
- ASSERT_EQ(0, UrlEncode(source, dest, ARRAY_SIZE(dest)));
- ASSERT_EQ('\0', dest[0]);
-
- dest[0] = 'a';
- ASSERT_EQ(0, UrlEncode(source, dest, 0));
- ASSERT_EQ('a', dest[0]);
-}
-
-TEST(Urlencode, OneCharacterConversion) {
- char source[] = "^";
- char dest[4];
- ASSERT_EQ(3, UrlEncode(source, dest, ARRAY_SIZE(dest)));
- ASSERT_STREQ("%5E", dest);
-}
-
-TEST(Urlencode, ShortDestinationNoEncoding) {
- // In this case we have a destination that would not be
- // big enough to hold an encoding but is big enough to
- // hold the text given.
- char source[] = "aa";
- char dest[3];
- ASSERT_EQ(2, UrlEncode(source, dest, ARRAY_SIZE(dest)));
- ASSERT_STREQ("aa", dest);
-}
-
-TEST(Urlencode, ShortDestinationEncoding) {
- // In this case we have a destination that is not
- // big enough to hold the encoding.
- char source[] = "&";
- char dest[3];
- ASSERT_EQ(0, UrlEncode(source, dest, ARRAY_SIZE(dest)));
- ASSERT_EQ('\0', dest[0]);
-}
-
-TEST(Urlencode, Encoding1) {
- char source[] = "A^ ";
- char dest[8];
- ASSERT_EQ(5, UrlEncode(source, dest, ARRAY_SIZE(dest)));
- ASSERT_STREQ("A%5E+", dest);
-}
-
-TEST(Urlencode, Encoding2) {
- char source[] = "A^ ";
- char dest[8];
- ASSERT_EQ(7, UrlEncodeWithoutEncodingSpaceAsPlus(source, dest,
- ARRAY_SIZE(dest)));
- ASSERT_STREQ("A%5E%20", dest);
-}
-
-TEST(Urldecode, Decoding1) {
- char source[] = "A%5E+";
- char dest[8];
- ASSERT_EQ(3, UrlDecode(source, dest));
- ASSERT_STREQ("A^ ", dest);
-}
-
-TEST(Urldecode, Decoding2) {
- char source[] = "A%5E+";
- char dest[8];
- ASSERT_EQ(3, UrlDecodeWithoutEncodingSpaceAsPlus(source, dest));
- ASSERT_STREQ("A^+", dest);
-}
diff --git a/base/versionparsing.cc b/base/versionparsing.cc
deleted file mode 100644
index 6a57dc9..0000000
--- a/base/versionparsing.cc
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/versionparsing.h"
-
-#include <stdlib.h>
-
-namespace talk_base {
-
-bool ParseVersionString(const std::string& version_str,
- int num_expected_segments,
- int version[]) {
- size_t pos = 0;
- for (int i = 0;;) {
- size_t dot_pos = version_str.find('.', pos);
- size_t n;
- if (dot_pos == std::string::npos) {
- // npos here is a special value meaning "to the end of the string"
- n = std::string::npos;
- } else {
- n = dot_pos - pos;
- }
-
- version[i] = atoi(version_str.substr(pos, n).c_str());
-
- if (++i >= num_expected_segments) break;
-
- if (dot_pos == std::string::npos) {
- // Previous segment was not terminated by a dot, but there's supposed to
- // be more segments, so that's an error.
- return false;
- }
- pos = dot_pos + 1;
- }
- return true;
-}
-
-int CompareVersions(const int version1[],
- const int version2[],
- int num_segments) {
- for (int i = 0; i < num_segments; ++i) {
- int diff = version1[i] - version2[i];
- if (diff != 0) {
- return diff;
- }
- }
- return 0;
-}
-
-} // namespace talk_base
diff --git a/base/versionparsing.h b/base/versionparsing.h
deleted file mode 100644
index c66ad25..0000000
--- a/base/versionparsing.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_VERSIONPARSING_H_
-#define TALK_BASE_VERSIONPARSING_H_
-
-#include <string>
-
-namespace talk_base {
-
-// Parses a version string into an array. "num_expected_segments" must be the
-// number of numerical segments that the version is expected to have (e.g.,
-// "1.1.2.0" has 4). "version" must be an array of that length to hold the
-// parsed numbers.
-// Returns "true" iff successful.
-bool ParseVersionString(const std::string& version_str,
- int num_expected_segments,
- int version[]);
-
-// Computes the lexicographical order of two versions. The return value
-// indicates the order in the standard way (e.g., see strcmp()).
-int CompareVersions(const int version1[],
- const int version2[],
- int num_segments);
-
-} // namespace talk_base
-
-#endif // TALK_BASE_VERSIONPARSING_H_
diff --git a/base/versionparsing_unittest.cc b/base/versionparsing_unittest.cc
deleted file mode 100644
index b083265..0000000
--- a/base/versionparsing_unittest.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/versionparsing.h"
-
-#include "talk/base/gunit.h"
-
-namespace talk_base {
-
-static const int kExampleSegments = 4;
-
-typedef int ExampleVersion[kExampleSegments];
-
-TEST(VersionParsing, TestGoodParse) {
- ExampleVersion ver;
- std::string str1("1.1.2.0");
- static const ExampleVersion expect1 = {1, 1, 2, 0};
- EXPECT_TRUE(ParseVersionString(str1, kExampleSegments, ver));
- EXPECT_EQ(0, CompareVersions(ver, expect1, kExampleSegments));
- std::string str2("2.0.0.1");
- static const ExampleVersion expect2 = {2, 0, 0, 1};
- EXPECT_TRUE(ParseVersionString(str2, kExampleSegments, ver));
- EXPECT_EQ(0, CompareVersions(ver, expect2, kExampleSegments));
-}
-
-TEST(VersionParsing, TestBadParse) {
- ExampleVersion ver;
- std::string str1("1.1.2");
- EXPECT_FALSE(ParseVersionString(str1, kExampleSegments, ver));
- std::string str2("");
- EXPECT_FALSE(ParseVersionString(str2, kExampleSegments, ver));
- std::string str3("garbarge");
- EXPECT_FALSE(ParseVersionString(str3, kExampleSegments, ver));
-}
-
-TEST(VersionParsing, TestCompare) {
- static const ExampleVersion ver1 = {1, 0, 21, 0};
- static const ExampleVersion ver2 = {1, 1, 2, 0};
- static const ExampleVersion ver3 = {1, 1, 3, 0};
- static const ExampleVersion ver4 = {1, 1, 3, 9861};
-
- // Test that every combination of comparisons has the expected outcome.
- EXPECT_EQ(0, CompareVersions(ver1, ver1, kExampleSegments));
- EXPECT_EQ(0, CompareVersions(ver2, ver2, kExampleSegments));
- EXPECT_EQ(0, CompareVersions(ver3, ver3, kExampleSegments));
- EXPECT_EQ(0, CompareVersions(ver4, ver4, kExampleSegments));
-
- EXPECT_GT(0, CompareVersions(ver1, ver2, kExampleSegments));
- EXPECT_LT(0, CompareVersions(ver2, ver1, kExampleSegments));
-
- EXPECT_GT(0, CompareVersions(ver1, ver3, kExampleSegments));
- EXPECT_LT(0, CompareVersions(ver3, ver1, kExampleSegments));
-
- EXPECT_GT(0, CompareVersions(ver1, ver4, kExampleSegments));
- EXPECT_LT(0, CompareVersions(ver4, ver1, kExampleSegments));
-
- EXPECT_GT(0, CompareVersions(ver2, ver3, kExampleSegments));
- EXPECT_LT(0, CompareVersions(ver3, ver2, kExampleSegments));
-
- EXPECT_GT(0, CompareVersions(ver2, ver4, kExampleSegments));
- EXPECT_LT(0, CompareVersions(ver4, ver2, kExampleSegments));
-
- EXPECT_GT(0, CompareVersions(ver3, ver4, kExampleSegments));
- EXPECT_LT(0, CompareVersions(ver4, ver3, kExampleSegments));
-}
-
-} // namespace talk_base
diff --git a/base/virtualsocket_unittest.cc b/base/virtualsocket_unittest.cc
deleted file mode 100644
index 58dab14..0000000
--- a/base/virtualsocket_unittest.cc
+++ /dev/null
@@ -1,1018 +0,0 @@
-/*
- * libjingle
- * Copyright 2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <math.h>
-#include <time.h>
-#ifdef POSIX
-#include <netinet/in.h>
-#endif
-
-#include "talk/base/logging.h"
-#include "talk/base/gunit.h"
-#include "talk/base/testclient.h"
-#include "talk/base/testutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-#include "talk/base/virtualsocketserver.h"
-
-using namespace talk_base;
-
-// Sends at a constant rate but with random packet sizes.
-struct Sender : public MessageHandler {
- Sender(Thread* th, AsyncSocket* s, uint32 rt)
- : thread(th), socket(new AsyncUDPSocket(s)),
- done(false), rate(rt), count(0) {
- last_send = talk_base::Time();
- thread->PostDelayed(NextDelay(), this, 1);
- }
-
- uint32 NextDelay() {
- uint32 size = (rand() % 4096) + 1;
- return 1000 * size / rate;
- }
-
- void OnMessage(Message* pmsg) {
- ASSERT_EQ(1u, pmsg->message_id);
-
- if (done)
- return;
-
- uint32 cur_time = talk_base::Time();
- uint32 delay = cur_time - last_send;
- uint32 size = rate * delay / 1000;
- size = std::min<uint32>(size, 4096);
- size = std::max<uint32>(size, sizeof(uint32));
-
- count += size;
- memcpy(dummy, &cur_time, sizeof(cur_time));
- socket->Send(dummy, size, options);
-
- last_send = cur_time;
- thread->PostDelayed(NextDelay(), this, 1);
- }
-
- Thread* thread;
- scoped_ptr<AsyncUDPSocket> socket;
- talk_base::PacketOptions options;
- bool done;
- uint32 rate; // bytes per second
- uint32 count;
- uint32 last_send;
- char dummy[4096];
-};
-
-struct Receiver : public MessageHandler, public sigslot::has_slots<> {
- Receiver(Thread* th, AsyncSocket* s, uint32 bw)
- : thread(th), socket(new AsyncUDPSocket(s)), bandwidth(bw), done(false),
- count(0), sec_count(0), sum(0), sum_sq(0), samples(0) {
- socket->SignalReadPacket.connect(this, &Receiver::OnReadPacket);
- thread->PostDelayed(1000, this, 1);
- }
-
- ~Receiver() {
- thread->Clear(this);
- }
-
- void OnReadPacket(AsyncPacketSocket* s, const char* data, size_t size,
- const SocketAddress& remote_addr,
- const PacketTime& packet_time) {
- ASSERT_EQ(socket.get(), s);
- ASSERT_GE(size, 4U);
-
- count += size;
- sec_count += size;
-
- uint32 send_time = *reinterpret_cast<const uint32*>(data);
- uint32 recv_time = talk_base::Time();
- uint32 delay = recv_time - send_time;
- sum += delay;
- sum_sq += delay * delay;
- samples += 1;
- }
-
- void OnMessage(Message* pmsg) {
- ASSERT_EQ(1u, pmsg->message_id);
-
- if (done)
- return;
-
- // It is always possible for us to receive more than expected because
- // packets can be further delayed in delivery.
- if (bandwidth > 0)
- ASSERT_TRUE(sec_count <= 5 * bandwidth / 4);
- sec_count = 0;
- thread->PostDelayed(1000, this, 1);
- }
-
- Thread* thread;
- scoped_ptr<AsyncUDPSocket> socket;
- uint32 bandwidth;
- bool done;
- size_t count;
- size_t sec_count;
- double sum;
- double sum_sq;
- uint32 samples;
-};
-
-class VirtualSocketServerTest : public testing::Test {
- public:
- VirtualSocketServerTest() : ss_(new VirtualSocketServer(NULL)),
- kIPv4AnyAddress(IPAddress(INADDR_ANY), 0),
- kIPv6AnyAddress(IPAddress(in6addr_any), 0) {
- }
-
- void CheckAddressIncrementalization(const SocketAddress& post,
- const SocketAddress& pre) {
- EXPECT_EQ(post.port(), pre.port() + 1);
- IPAddress post_ip = post.ipaddr();
- IPAddress pre_ip = pre.ipaddr();
- EXPECT_EQ(pre_ip.family(), post_ip.family());
- if (post_ip.family() == AF_INET) {
- in_addr pre_ipv4 = pre_ip.ipv4_address();
- in_addr post_ipv4 = post_ip.ipv4_address();
- int difference = ntohl(post_ipv4.s_addr) - ntohl(pre_ipv4.s_addr);
- EXPECT_EQ(1, difference);
- } else if (post_ip.family() == AF_INET6) {
- in6_addr post_ip6 = post_ip.ipv6_address();
- in6_addr pre_ip6 = pre_ip.ipv6_address();
- uint32* post_as_ints = reinterpret_cast<uint32*>(&post_ip6.s6_addr);
- uint32* pre_as_ints = reinterpret_cast<uint32*>(&pre_ip6.s6_addr);
- EXPECT_EQ(post_as_ints[3], pre_as_ints[3] + 1);
- }
- }
-
- void BasicTest(const SocketAddress& initial_addr) {
- AsyncSocket* socket = ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_DGRAM);
- socket->Bind(initial_addr);
- SocketAddress server_addr = socket->GetLocalAddress();
- // Make sure VSS didn't switch families on us.
- EXPECT_EQ(server_addr.family(), initial_addr.family());
-
- TestClient* client1 = new TestClient(new AsyncUDPSocket(socket));
- AsyncSocket* socket2 =
- ss_->CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
- TestClient* client2 = new TestClient(new AsyncUDPSocket(socket2));
-
- SocketAddress client2_addr;
- EXPECT_EQ(3, client2->SendTo("foo", 3, server_addr));
- EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &client2_addr));
-
- SocketAddress client1_addr;
- EXPECT_EQ(6, client1->SendTo("bizbaz", 6, client2_addr));
- EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &client1_addr));
- EXPECT_EQ(client1_addr, server_addr);
-
- SocketAddress empty = EmptySocketAddressWithFamily(initial_addr.family());
- for (int i = 0; i < 10; i++) {
- client2 = new TestClient(AsyncUDPSocket::Create(ss_, empty));
-
- SocketAddress next_client2_addr;
- EXPECT_EQ(3, client2->SendTo("foo", 3, server_addr));
- EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &next_client2_addr));
- CheckAddressIncrementalization(next_client2_addr, client2_addr);
- // EXPECT_EQ(next_client2_addr.port(), client2_addr.port() + 1);
-
- SocketAddress server_addr2;
- EXPECT_EQ(6, client1->SendTo("bizbaz", 6, next_client2_addr));
- EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &server_addr2));
- EXPECT_EQ(server_addr2, server_addr);
-
- client2_addr = next_client2_addr;
- }
- }
-
- // initial_addr should be made from either INADDR_ANY or in6addr_any.
- void ConnectTest(const SocketAddress& initial_addr) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
- const SocketAddress kEmptyAddr =
- EmptySocketAddressWithFamily(initial_addr.family());
-
- // Create client
- AsyncSocket* client = ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM);
- sink.Monitor(client);
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_TRUE(client->GetLocalAddress().IsNil());
-
- // Create server
- AsyncSocket* server = ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM);
- sink.Monitor(server);
- EXPECT_NE(0, server->Listen(5)); // Bind required
- EXPECT_EQ(0, server->Bind(initial_addr));
- EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
- EXPECT_EQ(0, server->Listen(5));
- EXPECT_EQ(server->GetState(), AsyncSocket::CS_CONNECTING);
-
- // No pending server connections
- EXPECT_FALSE(sink.Check(server, testing::SSE_READ));
- EXPECT_TRUE(NULL == server->Accept(&accept_addr));
- EXPECT_EQ(AF_UNSPEC, accept_addr.family());
-
- // Attempt connect to listening socket
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
- EXPECT_NE(client->GetLocalAddress(), kEmptyAddr); // Implicit Bind
- EXPECT_NE(AF_UNSPEC, client->GetLocalAddress().family()); // Implicit Bind
- EXPECT_NE(client->GetLocalAddress(), server->GetLocalAddress());
-
- // Client is connecting
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTING);
- EXPECT_FALSE(sink.Check(client, testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client, testing::SSE_CLOSE));
-
- ss_->ProcessMessagesUntilIdle();
-
- // Client still connecting
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTING);
- EXPECT_FALSE(sink.Check(client, testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client, testing::SSE_CLOSE));
-
- // Server has pending connection
- EXPECT_TRUE(sink.Check(server, testing::SSE_READ));
- Socket* accepted = server->Accept(&accept_addr);
- EXPECT_TRUE(NULL != accepted);
- EXPECT_NE(accept_addr, kEmptyAddr);
- EXPECT_EQ(accepted->GetRemoteAddress(), accept_addr);
-
- EXPECT_EQ(accepted->GetState(), AsyncSocket::CS_CONNECTED);
- EXPECT_EQ(accepted->GetLocalAddress(), server->GetLocalAddress());
- EXPECT_EQ(accepted->GetRemoteAddress(), client->GetLocalAddress());
-
- ss_->ProcessMessagesUntilIdle();
-
- // Client has connected
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTED);
- EXPECT_TRUE(sink.Check(client, testing::SSE_OPEN));
- EXPECT_FALSE(sink.Check(client, testing::SSE_CLOSE));
- EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
- EXPECT_EQ(client->GetRemoteAddress(), accepted->GetLocalAddress());
- }
-
- void ConnectToNonListenerTest(const SocketAddress& initial_addr) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
- const SocketAddress nil_addr;
- const SocketAddress empty_addr =
- EmptySocketAddressWithFamily(initial_addr.family());
-
- // Create client
- AsyncSocket* client = ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM);
- sink.Monitor(client);
-
- // Create server
- AsyncSocket* server = ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM);
- sink.Monitor(server);
- EXPECT_EQ(0, server->Bind(initial_addr));
- EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
- // Attempt connect to non-listening socket
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- ss_->ProcessMessagesUntilIdle();
-
- // No pending server connections
- EXPECT_FALSE(sink.Check(server, testing::SSE_READ));
- EXPECT_TRUE(NULL == server->Accept(&accept_addr));
- EXPECT_EQ(accept_addr, nil_addr);
-
- // Connection failed
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_FALSE(sink.Check(client, testing::SSE_OPEN));
- EXPECT_TRUE(sink.Check(client, testing::SSE_ERROR));
- EXPECT_EQ(client->GetRemoteAddress(), nil_addr);
- }
-
- void CloseDuringConnectTest(const SocketAddress& initial_addr) {
- testing::StreamSink sink;
- SocketAddress accept_addr;
- const SocketAddress empty_addr =
- EmptySocketAddressWithFamily(initial_addr.family());
-
- // Create client and server
- scoped_ptr<AsyncSocket> client(ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM));
- sink.Monitor(client.get());
- scoped_ptr<AsyncSocket> server(ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM));
- sink.Monitor(server.get());
-
- // Initiate connect
- EXPECT_EQ(0, server->Bind(initial_addr));
- EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
-
- EXPECT_EQ(0, server->Listen(5));
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- // Server close before socket enters accept queue
- EXPECT_FALSE(sink.Check(server.get(), testing::SSE_READ));
- server->Close();
-
- ss_->ProcessMessagesUntilIdle();
-
- // Result: connection failed
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_ERROR));
-
- server.reset(ss_->CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
- sink.Monitor(server.get());
-
- // Initiate connect
- EXPECT_EQ(0, server->Bind(initial_addr));
- EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
-
- EXPECT_EQ(0, server->Listen(5));
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- ss_->ProcessMessagesUntilIdle();
-
- // Server close while socket is in accept queue
- EXPECT_TRUE(sink.Check(server.get(), testing::SSE_READ));
- server->Close();
-
- ss_->ProcessMessagesUntilIdle();
-
- // Result: connection failed
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_TRUE(sink.Check(client.get(), testing::SSE_ERROR));
-
- // New server
- server.reset(ss_->CreateAsyncSocket(initial_addr.family(), SOCK_STREAM));
- sink.Monitor(server.get());
-
- // Initiate connect
- EXPECT_EQ(0, server->Bind(initial_addr));
- EXPECT_EQ(server->GetLocalAddress().family(), initial_addr.family());
-
- EXPECT_EQ(0, server->Listen(5));
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
-
- ss_->ProcessMessagesUntilIdle();
-
- // Server accepts connection
- EXPECT_TRUE(sink.Check(server.get(), testing::SSE_READ));
- scoped_ptr<AsyncSocket> accepted(server->Accept(&accept_addr));
- ASSERT_TRUE(NULL != accepted.get());
- sink.Monitor(accepted.get());
-
- // Client closes before connection complets
- EXPECT_EQ(accepted->GetState(), AsyncSocket::CS_CONNECTED);
-
- // Connected message has not been processed yet.
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CONNECTING);
- client->Close();
-
- ss_->ProcessMessagesUntilIdle();
-
- // Result: accepted socket closes
- EXPECT_EQ(accepted->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_TRUE(sink.Check(accepted.get(), testing::SSE_CLOSE));
- EXPECT_FALSE(sink.Check(client.get(), testing::SSE_CLOSE));
- }
-
- void CloseTest(const SocketAddress& initial_addr) {
- testing::StreamSink sink;
- const SocketAddress kEmptyAddr;
-
- // Create clients
- AsyncSocket* a = ss_->CreateAsyncSocket(initial_addr.family(), SOCK_STREAM);
- sink.Monitor(a);
- a->Bind(initial_addr);
- EXPECT_EQ(a->GetLocalAddress().family(), initial_addr.family());
-
-
- scoped_ptr<AsyncSocket> b(ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM));
- sink.Monitor(b.get());
- b->Bind(initial_addr);
- EXPECT_EQ(b->GetLocalAddress().family(), initial_addr.family());
-
- EXPECT_EQ(0, a->Connect(b->GetLocalAddress()));
- EXPECT_EQ(0, b->Connect(a->GetLocalAddress()));
-
- ss_->ProcessMessagesUntilIdle();
-
- EXPECT_TRUE(sink.Check(a, testing::SSE_OPEN));
- EXPECT_EQ(a->GetState(), AsyncSocket::CS_CONNECTED);
- EXPECT_EQ(a->GetRemoteAddress(), b->GetLocalAddress());
-
- EXPECT_TRUE(sink.Check(b.get(), testing::SSE_OPEN));
- EXPECT_EQ(b->GetState(), AsyncSocket::CS_CONNECTED);
- EXPECT_EQ(b->GetRemoteAddress(), a->GetLocalAddress());
-
- EXPECT_EQ(1, a->Send("a", 1));
- b->Close();
- EXPECT_EQ(1, a->Send("b", 1));
-
- ss_->ProcessMessagesUntilIdle();
-
- char buffer[10];
- EXPECT_FALSE(sink.Check(b.get(), testing::SSE_READ));
- EXPECT_EQ(-1, b->Recv(buffer, 10));
-
- EXPECT_TRUE(sink.Check(a, testing::SSE_CLOSE));
- EXPECT_EQ(a->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_EQ(a->GetRemoteAddress(), kEmptyAddr);
-
- // No signal for Closer
- EXPECT_FALSE(sink.Check(b.get(), testing::SSE_CLOSE));
- EXPECT_EQ(b->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_EQ(b->GetRemoteAddress(), kEmptyAddr);
- }
-
- void TcpSendTest(const SocketAddress& initial_addr) {
- testing::StreamSink sink;
- const SocketAddress kEmptyAddr;
-
- // Connect two sockets
- AsyncSocket* a = ss_->CreateAsyncSocket(initial_addr.family(), SOCK_STREAM);
- sink.Monitor(a);
- a->Bind(initial_addr);
- EXPECT_EQ(a->GetLocalAddress().family(), initial_addr.family());
-
- AsyncSocket* b = ss_->CreateAsyncSocket(initial_addr.family(), SOCK_STREAM);
- sink.Monitor(b);
- b->Bind(initial_addr);
- EXPECT_EQ(b->GetLocalAddress().family(), initial_addr.family());
-
- EXPECT_EQ(0, a->Connect(b->GetLocalAddress()));
- EXPECT_EQ(0, b->Connect(a->GetLocalAddress()));
-
- ss_->ProcessMessagesUntilIdle();
-
- const size_t kBufferSize = 2000;
- ss_->set_send_buffer_capacity(kBufferSize);
- ss_->set_recv_buffer_capacity(kBufferSize);
-
- const size_t kDataSize = 5000;
- char send_buffer[kDataSize], recv_buffer[kDataSize];
- for (size_t i = 0; i < kDataSize; ++i)
- send_buffer[i] = static_cast<char>(i % 256);
- memset(recv_buffer, 0, sizeof(recv_buffer));
- size_t send_pos = 0, recv_pos = 0;
-
- // Can't send more than send buffer in one write
- int result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
- EXPECT_EQ(static_cast<int>(kBufferSize), result);
- send_pos += result;
-
- ss_->ProcessMessagesUntilIdle();
- EXPECT_FALSE(sink.Check(a, testing::SSE_WRITE));
- EXPECT_TRUE(sink.Check(b, testing::SSE_READ));
-
- // Receive buffer is already filled, fill send buffer again
- result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
- EXPECT_EQ(static_cast<int>(kBufferSize), result);
- send_pos += result;
-
- ss_->ProcessMessagesUntilIdle();
- EXPECT_FALSE(sink.Check(a, testing::SSE_WRITE));
- EXPECT_FALSE(sink.Check(b, testing::SSE_READ));
-
- // No more room in send or receive buffer
- result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
- EXPECT_EQ(-1, result);
- EXPECT_TRUE(a->IsBlocking());
-
- // Read a subset of the data
- result = b->Recv(recv_buffer + recv_pos, 500);
- EXPECT_EQ(500, result);
- recv_pos += result;
-
- ss_->ProcessMessagesUntilIdle();
- EXPECT_TRUE(sink.Check(a, testing::SSE_WRITE));
- EXPECT_TRUE(sink.Check(b, testing::SSE_READ));
-
- // Room for more on the sending side
- result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
- EXPECT_EQ(500, result);
- send_pos += result;
-
- // Empty the recv buffer
- while (true) {
- result = b->Recv(recv_buffer + recv_pos, kDataSize - recv_pos);
- if (result < 0) {
- EXPECT_EQ(-1, result);
- EXPECT_TRUE(b->IsBlocking());
- break;
- }
- recv_pos += result;
- }
-
- ss_->ProcessMessagesUntilIdle();
- EXPECT_TRUE(sink.Check(b, testing::SSE_READ));
-
- // Continue to empty the recv buffer
- while (true) {
- result = b->Recv(recv_buffer + recv_pos, kDataSize - recv_pos);
- if (result < 0) {
- EXPECT_EQ(-1, result);
- EXPECT_TRUE(b->IsBlocking());
- break;
- }
- recv_pos += result;
- }
-
- // Send last of the data
- result = a->Send(send_buffer + send_pos, kDataSize - send_pos);
- EXPECT_EQ(500, result);
- send_pos += result;
-
- ss_->ProcessMessagesUntilIdle();
- EXPECT_TRUE(sink.Check(b, testing::SSE_READ));
-
- // Receive the last of the data
- while (true) {
- result = b->Recv(recv_buffer + recv_pos, kDataSize - recv_pos);
- if (result < 0) {
- EXPECT_EQ(-1, result);
- EXPECT_TRUE(b->IsBlocking());
- break;
- }
- recv_pos += result;
- }
-
- ss_->ProcessMessagesUntilIdle();
- EXPECT_FALSE(sink.Check(b, testing::SSE_READ));
-
- // The received data matches the sent data
- EXPECT_EQ(kDataSize, send_pos);
- EXPECT_EQ(kDataSize, recv_pos);
- EXPECT_EQ(0, memcmp(recv_buffer, send_buffer, kDataSize));
- }
-
- void TcpSendsPacketsInOrderTest(const SocketAddress& initial_addr) {
- const SocketAddress kEmptyAddr;
-
- // Connect two sockets
- AsyncSocket* a = ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM);
- AsyncSocket* b = ss_->CreateAsyncSocket(initial_addr.family(),
- SOCK_STREAM);
- a->Bind(initial_addr);
- EXPECT_EQ(a->GetLocalAddress().family(), initial_addr.family());
-
- b->Bind(initial_addr);
- EXPECT_EQ(b->GetLocalAddress().family(), initial_addr.family());
-
- EXPECT_EQ(0, a->Connect(b->GetLocalAddress()));
- EXPECT_EQ(0, b->Connect(a->GetLocalAddress()));
- ss_->ProcessMessagesUntilIdle();
-
- // First, deliver all packets in 0 ms.
- char buffer[2] = { 0, 0 };
- const char cNumPackets = 10;
- for (char i = 0; i < cNumPackets; ++i) {
- buffer[0] = '0' + i;
- EXPECT_EQ(1, a->Send(buffer, 1));
- }
-
- ss_->ProcessMessagesUntilIdle();
-
- for (char i = 0; i < cNumPackets; ++i) {
- EXPECT_EQ(1, b->Recv(buffer, sizeof(buffer)));
- EXPECT_EQ(static_cast<char>('0' + i), buffer[0]);
- }
-
- // Next, deliver packets at random intervals
- const uint32 mean = 50;
- const uint32 stddev = 50;
-
- ss_->set_delay_mean(mean);
- ss_->set_delay_stddev(stddev);
- ss_->UpdateDelayDistribution();
-
- for (char i = 0; i < cNumPackets; ++i) {
- buffer[0] = 'A' + i;
- EXPECT_EQ(1, a->Send(buffer, 1));
- }
-
- ss_->ProcessMessagesUntilIdle();
-
- for (char i = 0; i < cNumPackets; ++i) {
- EXPECT_EQ(1, b->Recv(buffer, sizeof(buffer)));
- EXPECT_EQ(static_cast<char>('A' + i), buffer[0]);
- }
- }
-
- void BandwidthTest(const SocketAddress& initial_addr) {
- AsyncSocket* send_socket =
- ss_->CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
- AsyncSocket* recv_socket =
- ss_->CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
- ASSERT_EQ(0, send_socket->Bind(initial_addr));
- ASSERT_EQ(0, recv_socket->Bind(initial_addr));
- EXPECT_EQ(send_socket->GetLocalAddress().family(), initial_addr.family());
- EXPECT_EQ(recv_socket->GetLocalAddress().family(), initial_addr.family());
- ASSERT_EQ(0, send_socket->Connect(recv_socket->GetLocalAddress()));
-
- uint32 bandwidth = 64 * 1024;
- ss_->set_bandwidth(bandwidth);
-
- Thread* pthMain = Thread::Current();
- Sender sender(pthMain, send_socket, 80 * 1024);
- Receiver receiver(pthMain, recv_socket, bandwidth);
-
- pthMain->ProcessMessages(5000);
- sender.done = true;
- pthMain->ProcessMessages(5000);
-
- ASSERT_TRUE(receiver.count >= 5 * 3 * bandwidth / 4);
- ASSERT_TRUE(receiver.count <= 6 * bandwidth); // queue could drain for 1s
-
- ss_->set_bandwidth(0);
- }
-
- void DelayTest(const SocketAddress& initial_addr) {
- time_t seed = ::time(NULL);
- LOG(LS_VERBOSE) << "seed = " << seed;
- srand(static_cast<unsigned int>(seed));
-
- const uint32 mean = 2000;
- const uint32 stddev = 500;
-
- ss_->set_delay_mean(mean);
- ss_->set_delay_stddev(stddev);
- ss_->UpdateDelayDistribution();
-
- AsyncSocket* send_socket =
- ss_->CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
- AsyncSocket* recv_socket =
- ss_->CreateAsyncSocket(initial_addr.family(), SOCK_DGRAM);
- ASSERT_EQ(0, send_socket->Bind(initial_addr));
- ASSERT_EQ(0, recv_socket->Bind(initial_addr));
- EXPECT_EQ(send_socket->GetLocalAddress().family(), initial_addr.family());
- EXPECT_EQ(recv_socket->GetLocalAddress().family(), initial_addr.family());
- ASSERT_EQ(0, send_socket->Connect(recv_socket->GetLocalAddress()));
-
- Thread* pthMain = Thread::Current();
- // Avg packet size is 2K, so at 200KB/s for 10s, we should see about
- // 1000 packets, which is necessary to get a good distribution.
- Sender sender(pthMain, send_socket, 100 * 2 * 1024);
- Receiver receiver(pthMain, recv_socket, 0);
-
- pthMain->ProcessMessages(10000);
- sender.done = receiver.done = true;
- ss_->ProcessMessagesUntilIdle();
-
- const double sample_mean = receiver.sum / receiver.samples;
- double num =
- receiver.samples * receiver.sum_sq - receiver.sum * receiver.sum;
- double den = receiver.samples * (receiver.samples - 1);
- const double sample_stddev = sqrt(num / den);
- LOG(LS_VERBOSE) << "mean=" << sample_mean << " stddev=" << sample_stddev;
-
- EXPECT_LE(500u, receiver.samples);
- // We initially used a 0.1 fudge factor, but on the build machine, we
- // have seen the value differ by as much as 0.13.
- EXPECT_NEAR(mean, sample_mean, 0.15 * mean);
- EXPECT_NEAR(stddev, sample_stddev, 0.15 * stddev);
-
- ss_->set_delay_mean(0);
- ss_->set_delay_stddev(0);
- ss_->UpdateDelayDistribution();
- }
-
- // Test cross-family communication between a client bound to client_addr and a
- // server bound to server_addr. shouldSucceed indicates if communication is
- // expected to work or not.
- void CrossFamilyConnectionTest(const SocketAddress& client_addr,
- const SocketAddress& server_addr,
- bool shouldSucceed) {
- testing::StreamSink sink;
- SocketAddress accept_address;
- const SocketAddress kEmptyAddr;
-
- // Client gets a IPv4 address
- AsyncSocket* client = ss_->CreateAsyncSocket(client_addr.family(),
- SOCK_STREAM);
- sink.Monitor(client);
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_EQ(client->GetLocalAddress(), kEmptyAddr);
- client->Bind(client_addr);
-
- // Server gets a non-mapped non-any IPv6 address.
- // IPv4 sockets should not be able to connect to this.
- AsyncSocket* server = ss_->CreateAsyncSocket(server_addr.family(),
- SOCK_STREAM);
- sink.Monitor(server);
- server->Bind(server_addr);
- server->Listen(5);
-
- if (shouldSucceed) {
- EXPECT_EQ(0, client->Connect(server->GetLocalAddress()));
- ss_->ProcessMessagesUntilIdle();
- EXPECT_TRUE(sink.Check(server, testing::SSE_READ));
- Socket* accepted = server->Accept(&accept_address);
- EXPECT_TRUE(NULL != accepted);
- EXPECT_NE(kEmptyAddr, accept_address);
- ss_->ProcessMessagesUntilIdle();
- EXPECT_TRUE(sink.Check(client, testing::SSE_OPEN));
- EXPECT_EQ(client->GetRemoteAddress(), server->GetLocalAddress());
- } else {
- // Check that the connection failed.
- EXPECT_EQ(-1, client->Connect(server->GetLocalAddress()));
- ss_->ProcessMessagesUntilIdle();
-
- EXPECT_FALSE(sink.Check(server, testing::SSE_READ));
- EXPECT_TRUE(NULL == server->Accept(&accept_address));
- EXPECT_EQ(accept_address, kEmptyAddr);
- EXPECT_EQ(client->GetState(), AsyncSocket::CS_CLOSED);
- EXPECT_FALSE(sink.Check(client, testing::SSE_OPEN));
- EXPECT_EQ(client->GetRemoteAddress(), kEmptyAddr);
- }
- }
-
- // Test cross-family datagram sending between a client bound to client_addr
- // and a server bound to server_addr. shouldSucceed indicates if sending is
- // expected to succed or not.
- void CrossFamilyDatagramTest(const SocketAddress& client_addr,
- const SocketAddress& server_addr,
- bool shouldSucceed) {
- AsyncSocket* socket = ss_->CreateAsyncSocket(SOCK_DGRAM);
- socket->Bind(server_addr);
- SocketAddress bound_server_addr = socket->GetLocalAddress();
- TestClient* client1 = new TestClient(new AsyncUDPSocket(socket));
-
- AsyncSocket* socket2 = ss_->CreateAsyncSocket(SOCK_DGRAM);
- socket2->Bind(client_addr);
- TestClient* client2 = new TestClient(new AsyncUDPSocket(socket2));
- SocketAddress client2_addr;
-
- if (shouldSucceed) {
- EXPECT_EQ(3, client2->SendTo("foo", 3, bound_server_addr));
- EXPECT_TRUE(client1->CheckNextPacket("foo", 3, &client2_addr));
- SocketAddress client1_addr;
- EXPECT_EQ(6, client1->SendTo("bizbaz", 6, client2_addr));
- EXPECT_TRUE(client2->CheckNextPacket("bizbaz", 6, &client1_addr));
- EXPECT_EQ(client1_addr, bound_server_addr);
- } else {
- EXPECT_EQ(-1, client2->SendTo("foo", 3, bound_server_addr));
- EXPECT_FALSE(client1->CheckNextPacket("foo", 3, 0));
- }
- }
-
- protected:
- virtual void SetUp() {
- Thread::Current()->set_socketserver(ss_);
- }
- virtual void TearDown() {
- Thread::Current()->set_socketserver(NULL);
- }
-
- VirtualSocketServer* ss_;
- const SocketAddress kIPv4AnyAddress;
- const SocketAddress kIPv6AnyAddress;
-};
-
-TEST_F(VirtualSocketServerTest, basic_v4) {
- SocketAddress ipv4_test_addr(IPAddress(INADDR_ANY), 5000);
- BasicTest(ipv4_test_addr);
-}
-
-TEST_F(VirtualSocketServerTest, basic_v6) {
- SocketAddress ipv6_test_addr(IPAddress(in6addr_any), 5000);
- BasicTest(ipv6_test_addr);
-}
-
-TEST_F(VirtualSocketServerTest, connect_v4) {
- ConnectTest(kIPv4AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, connect_v6) {
- ConnectTest(kIPv6AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, connect_to_non_listener_v4) {
- ConnectToNonListenerTest(kIPv4AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, connect_to_non_listener_v6) {
- ConnectToNonListenerTest(kIPv6AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, close_during_connect_v4) {
- CloseDuringConnectTest(kIPv4AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, close_during_connect_v6) {
- CloseDuringConnectTest(kIPv6AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, close_v4) {
- CloseTest(kIPv4AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, close_v6) {
- CloseTest(kIPv6AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, tcp_send_v4) {
- TcpSendTest(kIPv4AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, tcp_send_v6) {
- TcpSendTest(kIPv6AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, TcpSendsPacketsInOrder_v4) {
- TcpSendsPacketsInOrderTest(kIPv4AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, TcpSendsPacketsInOrder_v6) {
- TcpSendsPacketsInOrderTest(kIPv6AnyAddress);
-}
-
-TEST_F(VirtualSocketServerTest, bandwidth_v4) {
- SocketAddress ipv4_test_addr(IPAddress(INADDR_ANY), 1000);
- BandwidthTest(ipv4_test_addr);
-}
-
-TEST_F(VirtualSocketServerTest, bandwidth_v6) {
- SocketAddress ipv6_test_addr(IPAddress(in6addr_any), 1000);
- BandwidthTest(ipv6_test_addr);
-}
-
-TEST_F(VirtualSocketServerTest, delay_v4) {
- SocketAddress ipv4_test_addr(IPAddress(INADDR_ANY), 1000);
- DelayTest(ipv4_test_addr);
-}
-
-// See: https://code.google.com/p/webrtc/issues/detail?id=2409
-TEST_F(VirtualSocketServerTest, DISABLED_delay_v6) {
- SocketAddress ipv6_test_addr(IPAddress(in6addr_any), 1000);
- DelayTest(ipv6_test_addr);
-}
-
-// Works, receiving socket sees 127.0.0.2.
-TEST_F(VirtualSocketServerTest, CanConnectFromMappedIPv6ToIPv4Any) {
- CrossFamilyConnectionTest(SocketAddress("::ffff:127.0.0.2", 0),
- SocketAddress("0.0.0.0", 5000),
- true);
-}
-
-// Fails.
-TEST_F(VirtualSocketServerTest, CantConnectFromUnMappedIPv6ToIPv4Any) {
- CrossFamilyConnectionTest(SocketAddress("::2", 0),
- SocketAddress("0.0.0.0", 5000),
- false);
-}
-
-// Fails.
-TEST_F(VirtualSocketServerTest, CantConnectFromUnMappedIPv6ToMappedIPv6) {
- CrossFamilyConnectionTest(SocketAddress("::2", 0),
- SocketAddress("::ffff:127.0.0.1", 5000),
- false);
-}
-
-// Works. receiving socket sees ::ffff:127.0.0.2.
-TEST_F(VirtualSocketServerTest, CanConnectFromIPv4ToIPv6Any) {
- CrossFamilyConnectionTest(SocketAddress("127.0.0.2", 0),
- SocketAddress("::", 5000),
- true);
-}
-
-// Fails.
-TEST_F(VirtualSocketServerTest, CantConnectFromIPv4ToUnMappedIPv6) {
- CrossFamilyConnectionTest(SocketAddress("127.0.0.2", 0),
- SocketAddress("::1", 5000),
- false);
-}
-
-// Works. Receiving socket sees ::ffff:127.0.0.1.
-TEST_F(VirtualSocketServerTest, CanConnectFromIPv4ToMappedIPv6) {
- CrossFamilyConnectionTest(SocketAddress("127.0.0.1", 0),
- SocketAddress("::ffff:127.0.0.2", 5000),
- true);
-}
-
-// Works, receiving socket sees a result from GetNextIP.
-TEST_F(VirtualSocketServerTest, CanConnectFromUnboundIPv6ToIPv4Any) {
- CrossFamilyConnectionTest(SocketAddress("::", 0),
- SocketAddress("0.0.0.0", 5000),
- true);
-}
-
-// Works, receiving socket sees whatever GetNextIP gave the client.
-TEST_F(VirtualSocketServerTest, CanConnectFromUnboundIPv4ToIPv6Any) {
- CrossFamilyConnectionTest(SocketAddress("0.0.0.0", 0),
- SocketAddress("::", 5000),
- true);
-}
-
-TEST_F(VirtualSocketServerTest, CanSendDatagramFromUnboundIPv4ToIPv6Any) {
- CrossFamilyDatagramTest(SocketAddress("0.0.0.0", 0),
- SocketAddress("::", 5000),
- true);
-}
-
-TEST_F(VirtualSocketServerTest, CanSendDatagramFromMappedIPv6ToIPv4Any) {
- CrossFamilyDatagramTest(SocketAddress("::ffff:127.0.0.1", 0),
- SocketAddress("0.0.0.0", 5000),
- true);
-}
-
-TEST_F(VirtualSocketServerTest, CantSendDatagramFromUnMappedIPv6ToIPv4Any) {
- CrossFamilyDatagramTest(SocketAddress("::2", 0),
- SocketAddress("0.0.0.0", 5000),
- false);
-}
-
-TEST_F(VirtualSocketServerTest, CantSendDatagramFromUnMappedIPv6ToMappedIPv6) {
- CrossFamilyDatagramTest(SocketAddress("::2", 0),
- SocketAddress("::ffff:127.0.0.1", 5000),
- false);
-}
-
-TEST_F(VirtualSocketServerTest, CanSendDatagramFromIPv4ToIPv6Any) {
- CrossFamilyDatagramTest(SocketAddress("127.0.0.2", 0),
- SocketAddress("::", 5000),
- true);
-}
-
-TEST_F(VirtualSocketServerTest, CantSendDatagramFromIPv4ToUnMappedIPv6) {
- CrossFamilyDatagramTest(SocketAddress("127.0.0.2", 0),
- SocketAddress("::1", 5000),
- false);
-}
-
-TEST_F(VirtualSocketServerTest, CanSendDatagramFromIPv4ToMappedIPv6) {
- CrossFamilyDatagramTest(SocketAddress("127.0.0.1", 0),
- SocketAddress("::ffff:127.0.0.2", 5000),
- true);
-}
-
-TEST_F(VirtualSocketServerTest, CanSendDatagramFromUnboundIPv6ToIPv4Any) {
- CrossFamilyDatagramTest(SocketAddress("::", 0),
- SocketAddress("0.0.0.0", 5000),
- true);
-}
-
-TEST_F(VirtualSocketServerTest, CreatesStandardDistribution) {
- const uint32 kTestMean[] = { 10, 100, 333, 1000 };
- const double kTestDev[] = { 0.25, 0.1, 0.01 };
- // TODO: The current code only works for 1000 data points or more.
- const uint32 kTestSamples[] = { /*10, 100,*/ 1000 };
- for (size_t midx = 0; midx < ARRAY_SIZE(kTestMean); ++midx) {
- for (size_t didx = 0; didx < ARRAY_SIZE(kTestDev); ++didx) {
- for (size_t sidx = 0; sidx < ARRAY_SIZE(kTestSamples); ++sidx) {
- ASSERT_LT(0u, kTestSamples[sidx]);
- const uint32 kStdDev =
- static_cast<uint32>(kTestDev[didx] * kTestMean[midx]);
- VirtualSocketServer::Function* f =
- VirtualSocketServer::CreateDistribution(kTestMean[midx],
- kStdDev,
- kTestSamples[sidx]);
- ASSERT_TRUE(NULL != f);
- ASSERT_EQ(kTestSamples[sidx], f->size());
- double sum = 0;
- for (uint32 i = 0; i < f->size(); ++i) {
- sum += (*f)[i].second;
- }
- const double mean = sum / f->size();
- double sum_sq_dev = 0;
- for (uint32 i = 0; i < f->size(); ++i) {
- double dev = (*f)[i].second - mean;
- sum_sq_dev += dev * dev;
- }
- const double stddev = sqrt(sum_sq_dev / f->size());
- EXPECT_NEAR(kTestMean[midx], mean, 0.1 * kTestMean[midx])
- << "M=" << kTestMean[midx]
- << " SD=" << kStdDev
- << " N=" << kTestSamples[sidx];
- EXPECT_NEAR(kStdDev, stddev, 0.1 * kStdDev)
- << "M=" << kTestMean[midx]
- << " SD=" << kStdDev
- << " N=" << kTestSamples[sidx];
- delete f;
- }
- }
- }
-}
diff --git a/base/virtualsocketserver.cc b/base/virtualsocketserver.cc
deleted file mode 100644
index 6589ebb..0000000
--- a/base/virtualsocketserver.cc
+++ /dev/null
@@ -1,1118 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/virtualsocketserver.h"
-
-#include <errno.h>
-#include <math.h>
-
-#include <algorithm>
-#include <map>
-#include <vector>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/socketaddresspair.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
-
-namespace talk_base {
-#ifdef WIN32
-const in_addr kInitialNextIPv4 = { {0x01, 0, 0, 0} };
-#else
-// This value is entirely arbitrary, hence the lack of concern about endianness.
-const in_addr kInitialNextIPv4 = { 0x01000000 };
-#endif
-// Starts at ::2 so as to not cause confusion with ::1.
-const in6_addr kInitialNextIPv6 = { { {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2
- } } };
-
-const uint16 kFirstEphemeralPort = 49152;
-const uint16 kLastEphemeralPort = 65535;
-const uint16 kEphemeralPortCount = kLastEphemeralPort - kFirstEphemeralPort + 1;
-const uint32 kDefaultNetworkCapacity = 64 * 1024;
-const uint32 kDefaultTcpBufferSize = 32 * 1024;
-
-const uint32 UDP_HEADER_SIZE = 28; // IP + UDP headers
-const uint32 TCP_HEADER_SIZE = 40; // IP + TCP headers
-const uint32 TCP_MSS = 1400; // Maximum segment size
-
-// Note: The current algorithm doesn't work for sample sizes smaller than this.
-const int NUM_SAMPLES = 1000;
-
-enum {
- MSG_ID_PACKET,
- MSG_ID_CONNECT,
- MSG_ID_DISCONNECT,
-};
-
-// Packets are passed between sockets as messages. We copy the data just like
-// the kernel does.
-class Packet : public MessageData {
- public:
- Packet(const char* data, size_t size, const SocketAddress& from)
- : size_(size), consumed_(0), from_(from) {
- ASSERT(NULL != data);
- data_ = new char[size_];
- memcpy(data_, data, size_);
- }
-
- virtual ~Packet() {
- delete[] data_;
- }
-
- const char* data() const { return data_ + consumed_; }
- size_t size() const { return size_ - consumed_; }
- const SocketAddress& from() const { return from_; }
-
- // Remove the first size bytes from the data.
- void Consume(size_t size) {
- ASSERT(size + consumed_ < size_);
- consumed_ += size;
- }
-
- private:
- char* data_;
- size_t size_, consumed_;
- SocketAddress from_;
-};
-
-struct MessageAddress : public MessageData {
- explicit MessageAddress(const SocketAddress& a) : addr(a) { }
- SocketAddress addr;
-};
-
-// Implements the socket interface using the virtual network. Packets are
-// passed as messages using the message queue of the socket server.
-class VirtualSocket : public AsyncSocket, public MessageHandler {
- public:
- VirtualSocket(VirtualSocketServer* server, int family, int type, bool async)
- : server_(server), family_(family), type_(type), async_(async),
- state_(CS_CLOSED), error_(0), listen_queue_(NULL),
- write_enabled_(false),
- network_size_(0), recv_buffer_size_(0), bound_(false), was_any_(false) {
- ASSERT((type_ == SOCK_DGRAM) || (type_ == SOCK_STREAM));
- ASSERT(async_ || (type_ != SOCK_STREAM)); // We only support async streams
- }
-
- virtual ~VirtualSocket() {
- Close();
-
- for (RecvBuffer::iterator it = recv_buffer_.begin();
- it != recv_buffer_.end(); ++it) {
- delete *it;
- }
- }
-
- virtual SocketAddress GetLocalAddress() const {
- return local_addr_;
- }
-
- virtual SocketAddress GetRemoteAddress() const {
- return remote_addr_;
- }
-
- // Used by server sockets to set the local address without binding.
- void SetLocalAddress(const SocketAddress& addr) {
- local_addr_ = addr;
- }
-
- virtual int Bind(const SocketAddress& addr) {
- if (!local_addr_.IsNil()) {
- error_ = EINVAL;
- return -1;
- }
- local_addr_ = addr;
- int result = server_->Bind(this, &local_addr_);
- if (result != 0) {
- local_addr_.Clear();
- error_ = EADDRINUSE;
- } else {
- bound_ = true;
- was_any_ = addr.IsAnyIP();
- }
- return result;
- }
-
- virtual int Connect(const SocketAddress& addr) {
- return InitiateConnect(addr, true);
- }
-
- virtual int Close() {
- if (!local_addr_.IsNil() && bound_) {
- // Remove from the binding table.
- server_->Unbind(local_addr_, this);
- bound_ = false;
- }
-
- if (SOCK_STREAM == type_) {
- // Cancel pending sockets
- if (listen_queue_) {
- while (!listen_queue_->empty()) {
- SocketAddress addr = listen_queue_->front();
-
- // Disconnect listening socket.
- server_->Disconnect(server_->LookupBinding(addr));
- listen_queue_->pop_front();
- }
- delete listen_queue_;
- listen_queue_ = NULL;
- }
- // Disconnect stream sockets
- if (CS_CONNECTED == state_) {
- // Disconnect remote socket, check if it is a child of a server socket.
- VirtualSocket* socket =
- server_->LookupConnection(local_addr_, remote_addr_);
- if (!socket) {
- // Not a server socket child, then see if it is bound.
- // TODO: If this is indeed a server socket that has no
- // children this will cause the server socket to be
- // closed. This might lead to unexpected results, how to fix this?
- socket = server_->LookupBinding(remote_addr_);
- }
- server_->Disconnect(socket);
-
- // Remove mapping for both directions.
- server_->RemoveConnection(remote_addr_, local_addr_);
- server_->RemoveConnection(local_addr_, remote_addr_);
- }
- // Cancel potential connects
- MessageList msgs;
- if (server_->msg_queue_) {
- server_->msg_queue_->Clear(this, MSG_ID_CONNECT, &msgs);
- }
- for (MessageList::iterator it = msgs.begin(); it != msgs.end(); ++it) {
- ASSERT(NULL != it->pdata);
- MessageAddress* data = static_cast<MessageAddress*>(it->pdata);
-
- // Lookup remote side.
- VirtualSocket* socket = server_->LookupConnection(local_addr_,
- data->addr);
- if (socket) {
- // Server socket, remote side is a socket retreived by
- // accept. Accepted sockets are not bound so we will not
- // find it by looking in the bindings table.
- server_->Disconnect(socket);
- server_->RemoveConnection(local_addr_, data->addr);
- } else {
- server_->Disconnect(server_->LookupBinding(data->addr));
- }
- delete data;
- }
- // Clear incoming packets and disconnect messages
- if (server_->msg_queue_) {
- server_->msg_queue_->Clear(this);
- }
- }
-
- state_ = CS_CLOSED;
- local_addr_.Clear();
- remote_addr_.Clear();
- return 0;
- }
-
- virtual int Send(const void *pv, size_t cb) {
- if (CS_CONNECTED != state_) {
- error_ = ENOTCONN;
- return -1;
- }
- if (SOCK_DGRAM == type_) {
- return SendUdp(pv, cb, remote_addr_);
- } else {
- return SendTcp(pv, cb);
- }
- }
-
- virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr) {
- if (SOCK_DGRAM == type_) {
- return SendUdp(pv, cb, addr);
- } else {
- if (CS_CONNECTED != state_) {
- error_ = ENOTCONN;
- return -1;
- }
- return SendTcp(pv, cb);
- }
- }
-
- virtual int Recv(void *pv, size_t cb) {
- SocketAddress addr;
- return RecvFrom(pv, cb, &addr);
- }
-
- virtual int RecvFrom(void *pv, size_t cb, SocketAddress *paddr) {
- // If we don't have a packet, then either error or wait for one to arrive.
- if (recv_buffer_.empty()) {
- if (async_) {
- error_ = EAGAIN;
- return -1;
- }
- while (recv_buffer_.empty()) {
- Message msg;
- server_->msg_queue_->Get(&msg);
- server_->msg_queue_->Dispatch(&msg);
- }
- }
-
- // Return the packet at the front of the queue.
- Packet* packet = recv_buffer_.front();
- size_t data_read = _min(cb, packet->size());
- memcpy(pv, packet->data(), data_read);
- *paddr = packet->from();
-
- if (data_read < packet->size()) {
- packet->Consume(data_read);
- } else {
- recv_buffer_.pop_front();
- delete packet;
- }
-
- if (SOCK_STREAM == type_) {
- bool was_full = (recv_buffer_size_ == server_->recv_buffer_capacity_);
- recv_buffer_size_ -= data_read;
- if (was_full) {
- VirtualSocket* sender = server_->LookupBinding(remote_addr_);
- ASSERT(NULL != sender);
- server_->SendTcp(sender);
- }
- }
-
- return static_cast<int>(data_read);
- }
-
- virtual int Listen(int backlog) {
- ASSERT(SOCK_STREAM == type_);
- ASSERT(CS_CLOSED == state_);
- if (local_addr_.IsNil()) {
- error_ = EINVAL;
- return -1;
- }
- ASSERT(NULL == listen_queue_);
- listen_queue_ = new ListenQueue;
- state_ = CS_CONNECTING;
- return 0;
- }
-
- virtual VirtualSocket* Accept(SocketAddress *paddr) {
- if (NULL == listen_queue_) {
- error_ = EINVAL;
- return NULL;
- }
- while (!listen_queue_->empty()) {
- VirtualSocket* socket = new VirtualSocket(server_, AF_INET, type_,
- async_);
-
- // Set the new local address to the same as this server socket.
- socket->SetLocalAddress(local_addr_);
- // Sockets made from a socket that 'was Any' need to inherit that.
- socket->set_was_any(was_any_);
- SocketAddress remote_addr(listen_queue_->front());
- int result = socket->InitiateConnect(remote_addr, false);
- listen_queue_->pop_front();
- if (result != 0) {
- delete socket;
- continue;
- }
- socket->CompleteConnect(remote_addr, false);
- if (paddr) {
- *paddr = remote_addr;
- }
- return socket;
- }
- error_ = EWOULDBLOCK;
- return NULL;
- }
-
- virtual int GetError() const {
- return error_;
- }
-
- virtual void SetError(int error) {
- error_ = error;
- }
-
- virtual ConnState GetState() const {
- return state_;
- }
-
- virtual int GetOption(Option opt, int* value) {
- OptionsMap::const_iterator it = options_map_.find(opt);
- if (it == options_map_.end()) {
- return -1;
- }
- *value = it->second;
- return 0; // 0 is success to emulate getsockopt()
- }
-
- virtual int SetOption(Option opt, int value) {
- options_map_[opt] = value;
- return 0; // 0 is success to emulate setsockopt()
- }
-
- virtual int EstimateMTU(uint16* mtu) {
- if (CS_CONNECTED != state_)
- return ENOTCONN;
- else
- return 65536;
- }
-
- void OnMessage(Message *pmsg) {
- if (pmsg->message_id == MSG_ID_PACKET) {
- //ASSERT(!local_addr_.IsAny());
- ASSERT(NULL != pmsg->pdata);
- Packet* packet = static_cast<Packet*>(pmsg->pdata);
-
- recv_buffer_.push_back(packet);
-
- if (async_) {
- SignalReadEvent(this);
- }
- } else if (pmsg->message_id == MSG_ID_CONNECT) {
- ASSERT(NULL != pmsg->pdata);
- MessageAddress* data = static_cast<MessageAddress*>(pmsg->pdata);
- if (listen_queue_ != NULL) {
- listen_queue_->push_back(data->addr);
- if (async_) {
- SignalReadEvent(this);
- }
- } else if ((SOCK_STREAM == type_) && (CS_CONNECTING == state_)) {
- CompleteConnect(data->addr, true);
- } else {
- LOG(LS_VERBOSE) << "Socket at " << local_addr_ << " is not listening";
- server_->Disconnect(server_->LookupBinding(data->addr));
- }
- delete data;
- } else if (pmsg->message_id == MSG_ID_DISCONNECT) {
- ASSERT(SOCK_STREAM == type_);
- if (CS_CLOSED != state_) {
- int error = (CS_CONNECTING == state_) ? ECONNREFUSED : 0;
- state_ = CS_CLOSED;
- remote_addr_.Clear();
- if (async_) {
- SignalCloseEvent(this, error);
- }
- }
- } else {
- ASSERT(false);
- }
- }
-
- bool was_any() { return was_any_; }
- void set_was_any(bool was_any) { was_any_ = was_any; }
-
- private:
- struct NetworkEntry {
- size_t size;
- uint32 done_time;
- };
-
- typedef std::deque<SocketAddress> ListenQueue;
- typedef std::deque<NetworkEntry> NetworkQueue;
- typedef std::vector<char> SendBuffer;
- typedef std::list<Packet*> RecvBuffer;
- typedef std::map<Option, int> OptionsMap;
-
- int InitiateConnect(const SocketAddress& addr, bool use_delay) {
- if (!remote_addr_.IsNil()) {
- error_ = (CS_CONNECTED == state_) ? EISCONN : EINPROGRESS;
- return -1;
- }
- if (local_addr_.IsNil()) {
- // If there's no local address set, grab a random one in the correct AF.
- int result = 0;
- if (addr.ipaddr().family() == AF_INET) {
- result = Bind(SocketAddress("0.0.0.0", 0));
- } else if (addr.ipaddr().family() == AF_INET6) {
- result = Bind(SocketAddress("::", 0));
- }
- if (result != 0) {
- return result;
- }
- }
- if (type_ == SOCK_DGRAM) {
- remote_addr_ = addr;
- state_ = CS_CONNECTED;
- } else {
- int result = server_->Connect(this, addr, use_delay);
- if (result != 0) {
- error_ = EHOSTUNREACH;
- return -1;
- }
- state_ = CS_CONNECTING;
- }
- return 0;
- }
-
- void CompleteConnect(const SocketAddress& addr, bool notify) {
- ASSERT(CS_CONNECTING == state_);
- remote_addr_ = addr;
- state_ = CS_CONNECTED;
- server_->AddConnection(remote_addr_, local_addr_, this);
- if (async_ && notify) {
- SignalConnectEvent(this);
- }
- }
-
- int SendUdp(const void* pv, size_t cb, const SocketAddress& addr) {
- // If we have not been assigned a local port, then get one.
- if (local_addr_.IsNil()) {
- local_addr_ = EmptySocketAddressWithFamily(addr.ipaddr().family());
- int result = server_->Bind(this, &local_addr_);
- if (result != 0) {
- local_addr_.Clear();
- error_ = EADDRINUSE;
- return result;
- }
- }
-
- // Send the data in a message to the appropriate socket.
- return server_->SendUdp(this, static_cast<const char*>(pv), cb, addr);
- }
-
- int SendTcp(const void* pv, size_t cb) {
- size_t capacity = server_->send_buffer_capacity_ - send_buffer_.size();
- if (0 == capacity) {
- write_enabled_ = true;
- error_ = EWOULDBLOCK;
- return -1;
- }
- size_t consumed = _min(cb, capacity);
- const char* cpv = static_cast<const char*>(pv);
- send_buffer_.insert(send_buffer_.end(), cpv, cpv + consumed);
- server_->SendTcp(this);
- return static_cast<int>(consumed);
- }
-
- VirtualSocketServer* server_;
- int family_;
- int type_;
- bool async_;
- ConnState state_;
- int error_;
- SocketAddress local_addr_;
- SocketAddress remote_addr_;
-
- // Pending sockets which can be Accepted
- ListenQueue* listen_queue_;
-
- // Data which tcp has buffered for sending
- SendBuffer send_buffer_;
- bool write_enabled_;
-
- // Critical section to protect the recv_buffer and queue_
- CriticalSection crit_;
-
- // Network model that enforces bandwidth and capacity constraints
- NetworkQueue network_;
- size_t network_size_;
-
- // Data which has been received from the network
- RecvBuffer recv_buffer_;
- // The amount of data which is in flight or in recv_buffer_
- size_t recv_buffer_size_;
-
- // Is this socket bound?
- bool bound_;
-
- // When we bind a socket to Any, VSS's Bind gives it another address. For
- // dual-stack sockets, we want to distinguish between sockets that were
- // explicitly given a particular address and sockets that had one picked
- // for them by VSS.
- bool was_any_;
-
- // Store the options that are set
- OptionsMap options_map_;
-
- friend class VirtualSocketServer;
-};
-
-VirtualSocketServer::VirtualSocketServer(SocketServer* ss)
- : server_(ss), server_owned_(false), msg_queue_(NULL), stop_on_idle_(false),
- network_delay_(Time()), next_ipv4_(kInitialNextIPv4),
- next_ipv6_(kInitialNextIPv6), next_port_(kFirstEphemeralPort),
- bindings_(new AddressMap()), connections_(new ConnectionMap()),
- bandwidth_(0), network_capacity_(kDefaultNetworkCapacity),
- send_buffer_capacity_(kDefaultTcpBufferSize),
- recv_buffer_capacity_(kDefaultTcpBufferSize),
- delay_mean_(0), delay_stddev_(0), delay_samples_(NUM_SAMPLES),
- delay_dist_(NULL), drop_prob_(0.0) {
- if (!server_) {
- server_ = new PhysicalSocketServer();
- server_owned_ = true;
- }
- UpdateDelayDistribution();
-}
-
-VirtualSocketServer::~VirtualSocketServer() {
- delete bindings_;
- delete connections_;
- delete delay_dist_;
- if (server_owned_) {
- delete server_;
- }
-}
-
-IPAddress VirtualSocketServer::GetNextIP(int family) {
- if (family == AF_INET) {
- IPAddress next_ip(next_ipv4_);
- next_ipv4_.s_addr =
- HostToNetwork32(NetworkToHost32(next_ipv4_.s_addr) + 1);
- return next_ip;
- } else if (family == AF_INET6) {
- IPAddress next_ip(next_ipv6_);
- uint32* as_ints = reinterpret_cast<uint32*>(&next_ipv6_.s6_addr);
- as_ints[3] += 1;
- return next_ip;
- }
- return IPAddress();
-}
-
-uint16 VirtualSocketServer::GetNextPort() {
- uint16 port = next_port_;
- if (next_port_ < kLastEphemeralPort) {
- ++next_port_;
- } else {
- next_port_ = kFirstEphemeralPort;
- }
- return port;
-}
-
-Socket* VirtualSocketServer::CreateSocket(int type) {
- return CreateSocket(AF_INET, type);
-}
-
-Socket* VirtualSocketServer::CreateSocket(int family, int type) {
- return CreateSocketInternal(family, type);
-}
-
-AsyncSocket* VirtualSocketServer::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* VirtualSocketServer::CreateAsyncSocket(int family, int type) {
- return CreateSocketInternal(family, type);
-}
-
-VirtualSocket* VirtualSocketServer::CreateSocketInternal(int family, int type) {
- return new VirtualSocket(this, family, type, true);
-}
-
-void VirtualSocketServer::SetMessageQueue(MessageQueue* msg_queue) {
- msg_queue_ = msg_queue;
- if (msg_queue_) {
- msg_queue_->SignalQueueDestroyed.connect(this,
- &VirtualSocketServer::OnMessageQueueDestroyed);
- }
-}
-
-bool VirtualSocketServer::Wait(int cmsWait, bool process_io) {
- ASSERT(msg_queue_ == Thread::Current());
- if (stop_on_idle_ && Thread::Current()->empty()) {
- return false;
- }
- return socketserver()->Wait(cmsWait, process_io);
-}
-
-void VirtualSocketServer::WakeUp() {
- socketserver()->WakeUp();
-}
-
-bool VirtualSocketServer::ProcessMessagesUntilIdle() {
- ASSERT(msg_queue_ == Thread::Current());
- stop_on_idle_ = true;
- while (!msg_queue_->empty()) {
- Message msg;
- if (msg_queue_->Get(&msg, kForever)) {
- msg_queue_->Dispatch(&msg);
- }
- }
- stop_on_idle_ = false;
- return !msg_queue_->IsQuitting();
-}
-
-int VirtualSocketServer::Bind(VirtualSocket* socket,
- const SocketAddress& addr) {
- ASSERT(NULL != socket);
- // Address must be completely specified at this point
- ASSERT(!IPIsUnspec(addr.ipaddr()));
- ASSERT(addr.port() != 0);
-
- // Normalize the address (turns v6-mapped addresses into v4-addresses).
- SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
-
- AddressMap::value_type entry(normalized, socket);
- return bindings_->insert(entry).second ? 0 : -1;
-}
-
-int VirtualSocketServer::Bind(VirtualSocket* socket, SocketAddress* addr) {
- ASSERT(NULL != socket);
-
- if (IPIsAny(addr->ipaddr())) {
- addr->SetIP(GetNextIP(addr->ipaddr().family()));
- } else if (!IPIsUnspec(addr->ipaddr())) {
- addr->SetIP(addr->ipaddr().Normalized());
- } else {
- ASSERT(false);
- }
-
- if (addr->port() == 0) {
- for (int i = 0; i < kEphemeralPortCount; ++i) {
- addr->SetPort(GetNextPort());
- if (bindings_->find(*addr) == bindings_->end()) {
- break;
- }
- }
- }
-
- return Bind(socket, *addr);
-}
-
-VirtualSocket* VirtualSocketServer::LookupBinding(const SocketAddress& addr) {
- SocketAddress normalized(addr.ipaddr().Normalized(),
- addr.port());
- AddressMap::iterator it = bindings_->find(normalized);
- return (bindings_->end() != it) ? it->second : NULL;
-}
-
-int VirtualSocketServer::Unbind(const SocketAddress& addr,
- VirtualSocket* socket) {
- SocketAddress normalized(addr.ipaddr().Normalized(),
- addr.port());
- ASSERT((*bindings_)[normalized] == socket);
- bindings_->erase(bindings_->find(normalized));
- return 0;
-}
-
-void VirtualSocketServer::AddConnection(const SocketAddress& local,
- const SocketAddress& remote,
- VirtualSocket* remote_socket) {
- // Add this socket pair to our routing table. This will allow
- // multiple clients to connect to the same server address.
- SocketAddress local_normalized(local.ipaddr().Normalized(),
- local.port());
- SocketAddress remote_normalized(remote.ipaddr().Normalized(),
- remote.port());
- SocketAddressPair address_pair(local_normalized, remote_normalized);
- connections_->insert(std::pair<SocketAddressPair,
- VirtualSocket*>(address_pair, remote_socket));
-}
-
-VirtualSocket* VirtualSocketServer::LookupConnection(
- const SocketAddress& local,
- const SocketAddress& remote) {
- SocketAddress local_normalized(local.ipaddr().Normalized(),
- local.port());
- SocketAddress remote_normalized(remote.ipaddr().Normalized(),
- remote.port());
- SocketAddressPair address_pair(local_normalized, remote_normalized);
- ConnectionMap::iterator it = connections_->find(address_pair);
- return (connections_->end() != it) ? it->second : NULL;
-}
-
-void VirtualSocketServer::RemoveConnection(const SocketAddress& local,
- const SocketAddress& remote) {
- SocketAddress local_normalized(local.ipaddr().Normalized(),
- local.port());
- SocketAddress remote_normalized(remote.ipaddr().Normalized(),
- remote.port());
- SocketAddressPair address_pair(local_normalized, remote_normalized);
- connections_->erase(address_pair);
-}
-
-static double Random() {
- return static_cast<double>(rand()) / RAND_MAX;
-}
-
-int VirtualSocketServer::Connect(VirtualSocket* socket,
- const SocketAddress& remote_addr,
- bool use_delay) {
- uint32 delay = use_delay ? GetRandomTransitDelay() : 0;
- VirtualSocket* remote = LookupBinding(remote_addr);
- if (!CanInteractWith(socket, remote)) {
- LOG(LS_INFO) << "Address family mismatch between "
- << socket->GetLocalAddress() << " and " << remote_addr;
- return -1;
- }
- if (remote != NULL) {
- SocketAddress addr = socket->GetLocalAddress();
- msg_queue_->PostDelayed(delay, remote, MSG_ID_CONNECT,
- new MessageAddress(addr));
- } else {
- LOG(LS_INFO) << "No one listening at " << remote_addr;
- msg_queue_->PostDelayed(delay, socket, MSG_ID_DISCONNECT);
- }
- return 0;
-}
-
-bool VirtualSocketServer::Disconnect(VirtualSocket* socket) {
- if (socket) {
- // Remove the mapping.
- msg_queue_->Post(socket, MSG_ID_DISCONNECT);
- return true;
- }
- return false;
-}
-
-int VirtualSocketServer::SendUdp(VirtualSocket* socket,
- const char* data, size_t data_size,
- const SocketAddress& remote_addr) {
- // See if we want to drop this packet.
- if (Random() < drop_prob_) {
- LOG(LS_VERBOSE) << "Dropping packet: bad luck";
- return static_cast<int>(data_size);
- }
-
- VirtualSocket* recipient = LookupBinding(remote_addr);
- if (!recipient) {
- // Make a fake recipient for address family checking.
- scoped_ptr<VirtualSocket> dummy_socket(
- CreateSocketInternal(AF_INET, SOCK_DGRAM));
- dummy_socket->SetLocalAddress(remote_addr);
- if (!CanInteractWith(socket, dummy_socket.get())) {
- LOG(LS_VERBOSE) << "Incompatible address families: "
- << socket->GetLocalAddress() << " and " << remote_addr;
- return -1;
- }
- LOG(LS_VERBOSE) << "No one listening at " << remote_addr;
- return static_cast<int>(data_size);
- }
-
- if (!CanInteractWith(socket, recipient)) {
- LOG(LS_VERBOSE) << "Incompatible address families: "
- << socket->GetLocalAddress() << " and " << remote_addr;
- return -1;
- }
-
- CritScope cs(&socket->crit_);
-
- uint32 cur_time = Time();
- PurgeNetworkPackets(socket, cur_time);
-
- // Determine whether we have enough bandwidth to accept this packet. To do
- // this, we need to update the send queue. Once we know it's current size,
- // we know whether we can fit this packet.
- //
- // NOTE: There are better algorithms for maintaining such a queue (such as
- // "Derivative Random Drop"); however, this algorithm is a more accurate
- // simulation of what a normal network would do.
-
- size_t packet_size = data_size + UDP_HEADER_SIZE;
- if (socket->network_size_ + packet_size > network_capacity_) {
- LOG(LS_VERBOSE) << "Dropping packet: network capacity exceeded";
- return static_cast<int>(data_size);
- }
-
- AddPacketToNetwork(socket, recipient, cur_time, data, data_size,
- UDP_HEADER_SIZE, false);
-
- return static_cast<int>(data_size);
-}
-
-void VirtualSocketServer::SendTcp(VirtualSocket* socket) {
- // TCP can't send more data than will fill up the receiver's buffer.
- // We track the data that is in the buffer plus data in flight using the
- // recipient's recv_buffer_size_. Anything beyond that must be stored in the
- // sender's buffer. We will trigger the buffered data to be sent when data
- // is read from the recv_buffer.
-
- // Lookup the local/remote pair in the connections table.
- VirtualSocket* recipient = LookupConnection(socket->local_addr_,
- socket->remote_addr_);
- if (!recipient) {
- LOG(LS_VERBOSE) << "Sending data to no one.";
- return;
- }
-
- CritScope cs(&socket->crit_);
-
- uint32 cur_time = Time();
- PurgeNetworkPackets(socket, cur_time);
-
- while (true) {
- size_t available = recv_buffer_capacity_ - recipient->recv_buffer_size_;
- size_t max_data_size = _min<size_t>(available, TCP_MSS - TCP_HEADER_SIZE);
- size_t data_size = _min(socket->send_buffer_.size(), max_data_size);
- if (0 == data_size)
- break;
-
- AddPacketToNetwork(socket, recipient, cur_time, &socket->send_buffer_[0],
- data_size, TCP_HEADER_SIZE, true);
- recipient->recv_buffer_size_ += data_size;
-
- size_t new_buffer_size = socket->send_buffer_.size() - data_size;
- // Avoid undefined access beyond the last element of the vector.
- // This only happens when new_buffer_size is 0.
- if (data_size < socket->send_buffer_.size()) {
- // memmove is required for potentially overlapping source/destination.
- memmove(&socket->send_buffer_[0], &socket->send_buffer_[data_size],
- new_buffer_size);
- }
- socket->send_buffer_.resize(new_buffer_size);
- }
-
- if (socket->write_enabled_
- && (socket->send_buffer_.size() < send_buffer_capacity_)) {
- socket->write_enabled_ = false;
- socket->SignalWriteEvent(socket);
- }
-}
-
-void VirtualSocketServer::AddPacketToNetwork(VirtualSocket* sender,
- VirtualSocket* recipient,
- uint32 cur_time,
- const char* data,
- size_t data_size,
- size_t header_size,
- bool ordered) {
- VirtualSocket::NetworkEntry entry;
- entry.size = data_size + header_size;
-
- sender->network_size_ += entry.size;
- uint32 send_delay = SendDelay(static_cast<uint32>(sender->network_size_));
- entry.done_time = cur_time + send_delay;
- sender->network_.push_back(entry);
-
- // Find the delay for crossing the many virtual hops of the network.
- uint32 transit_delay = GetRandomTransitDelay();
-
- // Post the packet as a message to be delivered (on our own thread)
- Packet* p = new Packet(data, data_size, sender->local_addr_);
- uint32 ts = TimeAfter(send_delay + transit_delay);
- if (ordered) {
- // Ensure that new packets arrive after previous ones
- // TODO: consider ordering on a per-socket basis, since this
- // introduces artifical delay.
- ts = TimeMax(ts, network_delay_);
- }
- msg_queue_->PostAt(ts, recipient, MSG_ID_PACKET, p);
- network_delay_ = TimeMax(ts, network_delay_);
-}
-
-void VirtualSocketServer::PurgeNetworkPackets(VirtualSocket* socket,
- uint32 cur_time) {
- while (!socket->network_.empty() &&
- (socket->network_.front().done_time <= cur_time)) {
- ASSERT(socket->network_size_ >= socket->network_.front().size);
- socket->network_size_ -= socket->network_.front().size;
- socket->network_.pop_front();
- }
-}
-
-uint32 VirtualSocketServer::SendDelay(uint32 size) {
- if (bandwidth_ == 0)
- return 0;
- else
- return 1000 * size / bandwidth_;
-}
-
-#if 0
-void PrintFunction(std::vector<std::pair<double, double> >* f) {
- return;
- double sum = 0;
- for (uint32 i = 0; i < f->size(); ++i) {
- std::cout << (*f)[i].first << '\t' << (*f)[i].second << std::endl;
- sum += (*f)[i].second;
- }
- if (!f->empty()) {
- const double mean = sum / f->size();
- double sum_sq_dev = 0;
- for (uint32 i = 0; i < f->size(); ++i) {
- double dev = (*f)[i].second - mean;
- sum_sq_dev += dev * dev;
- }
- std::cout << "Mean = " << mean << " StdDev = "
- << sqrt(sum_sq_dev / f->size()) << std::endl;
- }
-}
-#endif // <unused>
-
-void VirtualSocketServer::UpdateDelayDistribution() {
- Function* dist = CreateDistribution(delay_mean_, delay_stddev_,
- delay_samples_);
- // We take a lock just to make sure we don't leak memory.
- {
- CritScope cs(&delay_crit_);
- delete delay_dist_;
- delay_dist_ = dist;
- }
-}
-
-static double PI = 4 * atan(1.0);
-
-static double Normal(double x, double mean, double stddev) {
- double a = (x - mean) * (x - mean) / (2 * stddev * stddev);
- return exp(-a) / (stddev * sqrt(2 * PI));
-}
-
-#if 0 // static unused gives a warning
-static double Pareto(double x, double min, double k) {
- if (x < min)
- return 0;
- else
- return k * std::pow(min, k) / std::pow(x, k+1);
-}
-#endif
-
-VirtualSocketServer::Function* VirtualSocketServer::CreateDistribution(
- uint32 mean, uint32 stddev, uint32 samples) {
- Function* f = new Function();
-
- if (0 == stddev) {
- f->push_back(Point(mean, 1.0));
- } else {
- double start = 0;
- if (mean >= 4 * static_cast<double>(stddev))
- start = mean - 4 * static_cast<double>(stddev);
- double end = mean + 4 * static_cast<double>(stddev);
-
- for (uint32 i = 0; i < samples; i++) {
- double x = start + (end - start) * i / (samples - 1);
- double y = Normal(x, mean, stddev);
- f->push_back(Point(x, y));
- }
- }
- return Resample(Invert(Accumulate(f)), 0, 1, samples);
-}
-
-uint32 VirtualSocketServer::GetRandomTransitDelay() {
- size_t index = rand() % delay_dist_->size();
- double delay = (*delay_dist_)[index].second;
- //LOG_F(LS_INFO) << "random[" << index << "] = " << delay;
- return static_cast<uint32>(delay);
-}
-
-struct FunctionDomainCmp {
- bool operator()(const VirtualSocketServer::Point& p1,
- const VirtualSocketServer::Point& p2) {
- return p1.first < p2.first;
- }
- bool operator()(double v1, const VirtualSocketServer::Point& p2) {
- return v1 < p2.first;
- }
- bool operator()(const VirtualSocketServer::Point& p1, double v2) {
- return p1.first < v2;
- }
-};
-
-VirtualSocketServer::Function* VirtualSocketServer::Accumulate(Function* f) {
- ASSERT(f->size() >= 1);
- double v = 0;
- for (Function::size_type i = 0; i < f->size() - 1; ++i) {
- double dx = (*f)[i + 1].first - (*f)[i].first;
- double avgy = ((*f)[i + 1].second + (*f)[i].second) / 2;
- (*f)[i].second = v;
- v = v + dx * avgy;
- }
- (*f)[f->size()-1].second = v;
- return f;
-}
-
-VirtualSocketServer::Function* VirtualSocketServer::Invert(Function* f) {
- for (Function::size_type i = 0; i < f->size(); ++i)
- std::swap((*f)[i].first, (*f)[i].second);
-
- std::sort(f->begin(), f->end(), FunctionDomainCmp());
- return f;
-}
-
-VirtualSocketServer::Function* VirtualSocketServer::Resample(
- Function* f, double x1, double x2, uint32 samples) {
- Function* g = new Function();
-
- for (size_t i = 0; i < samples; i++) {
- double x = x1 + (x2 - x1) * i / (samples - 1);
- double y = Evaluate(f, x);
- g->push_back(Point(x, y));
- }
-
- delete f;
- return g;
-}
-
-double VirtualSocketServer::Evaluate(Function* f, double x) {
- Function::iterator iter =
- std::lower_bound(f->begin(), f->end(), x, FunctionDomainCmp());
- if (iter == f->begin()) {
- return (*f)[0].second;
- } else if (iter == f->end()) {
- ASSERT(f->size() >= 1);
- return (*f)[f->size() - 1].second;
- } else if (iter->first == x) {
- return iter->second;
- } else {
- double x1 = (iter - 1)->first;
- double y1 = (iter - 1)->second;
- double x2 = iter->first;
- double y2 = iter->second;
- return y1 + (y2 - y1) * (x - x1) / (x2 - x1);
- }
-}
-
-bool VirtualSocketServer::CanInteractWith(VirtualSocket* local,
- VirtualSocket* remote) {
- if (!local || !remote) {
- return false;
- }
- IPAddress local_ip = local->GetLocalAddress().ipaddr();
- IPAddress remote_ip = remote->GetLocalAddress().ipaddr();
- IPAddress local_normalized = local_ip.Normalized();
- IPAddress remote_normalized = remote_ip.Normalized();
- // Check if the addresses are the same family after Normalization (turns
- // mapped IPv6 address into IPv4 addresses).
- // This will stop unmapped V6 addresses from talking to mapped V6 addresses.
- if (local_normalized.family() == remote_normalized.family()) {
- return true;
- }
-
- // If ip1 is IPv4 and ip2 is :: and ip2 is not IPV6_V6ONLY.
- int remote_v6_only = 0;
- remote->GetOption(Socket::OPT_IPV6_V6ONLY, &remote_v6_only);
- if (local_ip.family() == AF_INET && !remote_v6_only && IPIsAny(remote_ip)) {
- return true;
- }
- // Same check, backwards.
- int local_v6_only = 0;
- local->GetOption(Socket::OPT_IPV6_V6ONLY, &local_v6_only);
- if (remote_ip.family() == AF_INET && !local_v6_only && IPIsAny(local_ip)) {
- return true;
- }
-
- // Check to see if either socket was explicitly bound to IPv6-any.
- // These sockets can talk with anyone.
- if (local_ip.family() == AF_INET6 && local->was_any()) {
- return true;
- }
- if (remote_ip.family() == AF_INET6 && remote->was_any()) {
- return true;
- }
-
- return false;
-}
-
-} // namespace talk_base
diff --git a/base/virtualsocketserver.h b/base/virtualsocketserver.h
deleted file mode 100644
index 56e37a1..0000000
--- a/base/virtualsocketserver.h
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_VIRTUALSOCKETSERVER_H_
-#define TALK_BASE_VIRTUALSOCKETSERVER_H_
-
-#include <assert.h>
-
-#include <deque>
-#include <map>
-
-#include "talk/base/messagequeue.h"
-#include "talk/base/socketserver.h"
-
-namespace talk_base {
-
-class VirtualSocket;
-class SocketAddressPair;
-
-// Simulates a network in the same manner as a loopback interface. The
-// interface can create as many addresses as you want. All of the sockets
-// created by this network will be able to communicate with one another, unless
-// they are bound to addresses from incompatible families.
-class VirtualSocketServer : public SocketServer, public sigslot::has_slots<> {
- public:
- // TODO: Add "owned" parameter.
- // If "owned" is set, the supplied socketserver will be deleted later.
- explicit VirtualSocketServer(SocketServer* ss);
- virtual ~VirtualSocketServer();
-
- SocketServer* socketserver() { return server_; }
-
- // Limits the network bandwidth (maximum bytes per second). Zero means that
- // all sends occur instantly. Defaults to 0.
- uint32 bandwidth() const { return bandwidth_; }
- void set_bandwidth(uint32 bandwidth) { bandwidth_ = bandwidth; }
-
- // Limits the amount of data which can be in flight on the network without
- // packet loss (on a per sender basis). Defaults to 64 KB.
- uint32 network_capacity() const { return network_capacity_; }
- void set_network_capacity(uint32 capacity) {
- network_capacity_ = capacity;
- }
-
- // The amount of data which can be buffered by tcp on the sender's side
- uint32 send_buffer_capacity() const { return send_buffer_capacity_; }
- void set_send_buffer_capacity(uint32 capacity) {
- send_buffer_capacity_ = capacity;
- }
-
- // The amount of data which can be buffered by tcp on the receiver's side
- uint32 recv_buffer_capacity() const { return recv_buffer_capacity_; }
- void set_recv_buffer_capacity(uint32 capacity) {
- recv_buffer_capacity_ = capacity;
- }
-
- // Controls the (transit) delay for packets sent in the network. This does
- // not inclue the time required to sit in the send queue. Both of these
- // values are measured in milliseconds. Defaults to no delay.
- uint32 delay_mean() const { return delay_mean_; }
- uint32 delay_stddev() const { return delay_stddev_; }
- uint32 delay_samples() const { return delay_samples_; }
- void set_delay_mean(uint32 delay_mean) { delay_mean_ = delay_mean; }
- void set_delay_stddev(uint32 delay_stddev) {
- delay_stddev_ = delay_stddev;
- }
- void set_delay_samples(uint32 delay_samples) {
- delay_samples_ = delay_samples;
- }
-
- // If the (transit) delay parameters are modified, this method should be
- // called to recompute the new distribution.
- void UpdateDelayDistribution();
-
- // Controls the (uniform) probability that any sent packet is dropped. This
- // is separate from calculations to drop based on queue size.
- double drop_probability() { return drop_prob_; }
- void set_drop_probability(double drop_prob) {
- assert((0 <= drop_prob) && (drop_prob <= 1));
- drop_prob_ = drop_prob;
- }
-
- // SocketFactory:
- virtual Socket* CreateSocket(int type);
- virtual Socket* CreateSocket(int family, int type);
-
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- // SocketServer:
- virtual void SetMessageQueue(MessageQueue* queue);
- virtual bool Wait(int cms, bool process_io);
- virtual void WakeUp();
-
- typedef std::pair<double, double> Point;
- typedef std::vector<Point> Function;
-
- static Function* CreateDistribution(uint32 mean, uint32 stddev,
- uint32 samples);
-
- // Similar to Thread::ProcessMessages, but it only processes messages until
- // there are no immediate messages or pending network traffic. Returns false
- // if Thread::Stop() was called.
- bool ProcessMessagesUntilIdle();
-
- protected:
- // Returns a new IP not used before in this network.
- IPAddress GetNextIP(int family);
- uint16 GetNextPort();
-
- VirtualSocket* CreateSocketInternal(int family, int type);
-
- // Binds the given socket to addr, assigning and IP and Port if necessary
- int Bind(VirtualSocket* socket, SocketAddress* addr);
-
- // Binds the given socket to the given (fully-defined) address.
- int Bind(VirtualSocket* socket, const SocketAddress& addr);
-
- // Find the socket bound to the given address
- VirtualSocket* LookupBinding(const SocketAddress& addr);
-
- int Unbind(const SocketAddress& addr, VirtualSocket* socket);
-
- // Adds a mapping between this socket pair and the socket.
- void AddConnection(const SocketAddress& client,
- const SocketAddress& server,
- VirtualSocket* socket);
-
- // Find the socket pair corresponding to this server address.
- VirtualSocket* LookupConnection(const SocketAddress& client,
- const SocketAddress& server);
-
- void RemoveConnection(const SocketAddress& client,
- const SocketAddress& server);
-
- // Connects the given socket to the socket at the given address
- int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
- bool use_delay);
-
- // Sends a disconnect message to the socket at the given address
- bool Disconnect(VirtualSocket* socket);
-
- // Sends the given packet to the socket at the given address (if one exists).
- int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
- const SocketAddress& remote_addr);
-
- // Moves as much data as possible from the sender's buffer to the network
- void SendTcp(VirtualSocket* socket);
-
- // Places a packet on the network.
- void AddPacketToNetwork(VirtualSocket* socket, VirtualSocket* recipient,
- uint32 cur_time, const char* data, size_t data_size,
- size_t header_size, bool ordered);
-
- // Removes stale packets from the network
- void PurgeNetworkPackets(VirtualSocket* socket, uint32 cur_time);
-
- // Computes the number of milliseconds required to send a packet of this size.
- uint32 SendDelay(uint32 size);
-
- // Returns a random transit delay chosen from the appropriate distribution.
- uint32 GetRandomTransitDelay();
-
- // Basic operations on functions. Those that return a function also take
- // ownership of the function given (and hence, may modify or delete it).
- static Function* Accumulate(Function* f);
- static Function* Invert(Function* f);
- static Function* Resample(Function* f, double x1, double x2, uint32 samples);
- static double Evaluate(Function* f, double x);
-
- // NULL out our message queue if it goes away. Necessary in the case where
- // our lifetime is greater than that of the thread we are using, since we
- // try to send Close messages for all connected sockets when we shutdown.
- void OnMessageQueueDestroyed() { msg_queue_ = NULL; }
-
- // Determine if two sockets should be able to communicate.
- // We don't (currently) specify an address family for sockets; instead,
- // the currently bound address is used to infer the address family.
- // Any socket that is not explicitly bound to an IPv4 address is assumed to be
- // dual-stack capable.
- // This function tests if two addresses can communicate, as well as the
- // sockets to which they may be bound (the addresses may or may not yet be
- // bound to the sockets).
- // First the addresses are tested (after normalization):
- // If both have the same family, then communication is OK.
- // If only one is IPv4 then false, unless the other is bound to ::.
- // This applies even if the IPv4 address is 0.0.0.0.
- // The socket arguments are optional; the sockets are checked to see if they
- // were explicitly bound to IPv6-any ('::'), and if so communication is
- // permitted.
- // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
- static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
-
- private:
- friend class VirtualSocket;
-
- typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
- typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
-
- SocketServer* server_;
- bool server_owned_;
- MessageQueue* msg_queue_;
- bool stop_on_idle_;
- uint32 network_delay_;
- in_addr next_ipv4_;
- in6_addr next_ipv6_;
- uint16 next_port_;
- AddressMap* bindings_;
- ConnectionMap* connections_;
-
- uint32 bandwidth_;
- uint32 network_capacity_;
- uint32 send_buffer_capacity_;
- uint32 recv_buffer_capacity_;
- uint32 delay_mean_;
- uint32 delay_stddev_;
- uint32 delay_samples_;
- Function* delay_dist_;
- CriticalSection delay_crit_;
-
- double drop_prob_;
- DISALLOW_EVIL_CONSTRUCTORS(VirtualSocketServer);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_VIRTUALSOCKETSERVER_H_
diff --git a/base/win32.cc b/base/win32.cc
deleted file mode 100644
index a9fda8a..0000000
--- a/base/win32.cc
+++ /dev/null
@@ -1,473 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/win32.h"
-
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#include <algorithm>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-// Helper function declarations for inet_ntop/inet_pton.
-static const char* inet_ntop_v4(const void* src, char* dst, socklen_t size);
-static const char* inet_ntop_v6(const void* src, char* dst, socklen_t size);
-static int inet_pton_v4(const char* src, void* dst);
-static int inet_pton_v6(const char* src, void* dst);
-
-// Implementation of inet_ntop (create a printable representation of an
-// ip address). XP doesn't have its own inet_ntop, and
-// WSAAddressToString requires both IPv6 to be installed and for Winsock
-// to be initialized.
-const char* win32_inet_ntop(int af, const void *src,
- char* dst, socklen_t size) {
- if (!src || !dst) {
- return NULL;
- }
- switch (af) {
- case AF_INET: {
- return inet_ntop_v4(src, dst, size);
- }
- case AF_INET6: {
- return inet_ntop_v6(src, dst, size);
- }
- }
- return NULL;
-}
-
-// As above, but for inet_pton. Implements inet_pton for v4 and v6.
-// Note that our inet_ntop will output normal 'dotted' v4 addresses only.
-int win32_inet_pton(int af, const char* src, void* dst) {
- if (!src || !dst) {
- return 0;
- }
- if (af == AF_INET) {
- return inet_pton_v4(src, dst);
- } else if (af == AF_INET6) {
- return inet_pton_v6(src, dst);
- }
- return -1;
-}
-
-// Helper function for inet_ntop for IPv4 addresses.
-// Outputs "dotted-quad" decimal notation.
-const char* inet_ntop_v4(const void* src, char* dst, socklen_t size) {
- if (size < INET_ADDRSTRLEN) {
- return NULL;
- }
- const struct in_addr* as_in_addr =
- reinterpret_cast<const struct in_addr*>(src);
- talk_base::sprintfn(dst, size, "%d.%d.%d.%d",
- as_in_addr->S_un.S_un_b.s_b1,
- as_in_addr->S_un.S_un_b.s_b2,
- as_in_addr->S_un.S_un_b.s_b3,
- as_in_addr->S_un.S_un_b.s_b4);
- return dst;
-}
-
-// Helper function for inet_ntop for IPv6 addresses.
-const char* inet_ntop_v6(const void* src, char* dst, socklen_t size) {
- if (size < INET6_ADDRSTRLEN) {
- return NULL;
- }
- const uint16* as_shorts =
- reinterpret_cast<const uint16*>(src);
- int runpos[8];
- int current = 1;
- int max = 1;
- int maxpos = -1;
- int run_array_size = ARRAY_SIZE(runpos);
- // Run over the address marking runs of 0s.
- for (int i = 0; i < run_array_size; ++i) {
- if (as_shorts[i] == 0) {
- runpos[i] = current;
- if (current > max) {
- maxpos = i;
- max = current;
- }
- ++current;
- } else {
- runpos[i] = -1;
- current =1;
- }
- }
-
- if (max > 1) {
- int tmpmax = maxpos;
- // Run back through, setting -1 for all but the longest run.
- for (int i = run_array_size - 1; i >= 0; i--) {
- if (i > tmpmax) {
- runpos[i] = -1;
- } else if (runpos[i] == -1) {
- // We're less than maxpos, we hit a -1, so the 'good' run is done.
- // Setting tmpmax -1 means all remaining positions get set to -1.
- tmpmax = -1;
- }
- }
- }
-
- char* cursor = dst;
- // Print IPv4 compatible and IPv4 mapped addresses using the IPv4 helper.
- // These addresses have an initial run of either eight zero-bytes followed
- // by 0xFFFF, or an initial run of ten zero-bytes.
- if (runpos[0] == 1 && (maxpos == 5 ||
- (maxpos == 4 && as_shorts[5] == 0xFFFF))) {
- *cursor++ = ':';
- *cursor++ = ':';
- if (maxpos == 4) {
- cursor += talk_base::sprintfn(cursor, INET6_ADDRSTRLEN - 2, "ffff:");
- }
- const struct in_addr* as_v4 =
- reinterpret_cast<const struct in_addr*>(&(as_shorts[6]));
- inet_ntop_v4(as_v4, cursor,
- static_cast<socklen_t>(INET6_ADDRSTRLEN - (cursor - dst)));
- } else {
- for (int i = 0; i < run_array_size; ++i) {
- if (runpos[i] == -1) {
- cursor += talk_base::sprintfn(cursor,
- INET6_ADDRSTRLEN - (cursor - dst),
- "%x", NetworkToHost16(as_shorts[i]));
- if (i != 7 && runpos[i + 1] != 1) {
- *cursor++ = ':';
- }
- } else if (runpos[i] == 1) {
- // Entered the run; print the colons and skip the run.
- *cursor++ = ':';
- *cursor++ = ':';
- i += (max - 1);
- }
- }
- }
- return dst;
-}
-
-// Helper function for inet_pton for IPv4 addresses.
-// |src| points to a character string containing an IPv4 network address in
-// dotted-decimal format, "ddd.ddd.ddd.ddd", where ddd is a decimal number
-// of up to three digits in the range 0 to 255.
-// The address is converted and copied to dst,
-// which must be sizeof(struct in_addr) (4) bytes (32 bits) long.
-int inet_pton_v4(const char* src, void* dst) {
- const int kIpv4AddressSize = 4;
- int found = 0;
- const char* src_pos = src;
- unsigned char result[kIpv4AddressSize] = {0};
-
- while (*src_pos != '\0') {
- // strtol won't treat whitespace characters in the begining as an error,
- // so check to ensure this is started with digit before passing to strtol.
- if (!isdigit(*src_pos)) {
- return 0;
- }
- char* end_pos;
- long value = strtol(src_pos, &end_pos, 10);
- if (value < 0 || value > 255 || src_pos == end_pos) {
- return 0;
- }
- ++found;
- if (found > kIpv4AddressSize) {
- return 0;
- }
- result[found - 1] = static_cast<unsigned char>(value);
- src_pos = end_pos;
- if (*src_pos == '.') {
- // There's more.
- ++src_pos;
- } else if (*src_pos != '\0') {
- // If it's neither '.' nor '\0' then return fail.
- return 0;
- }
- }
- if (found != kIpv4AddressSize) {
- return 0;
- }
- memcpy(dst, result, sizeof(result));
- return 1;
-}
-
-// Helper function for inet_pton for IPv6 addresses.
-int inet_pton_v6(const char* src, void* dst) {
- // sscanf will pick any other invalid chars up, but it parses 0xnnnn as hex.
- // Check for literal x in the input string.
- const char* readcursor = src;
- char c = *readcursor++;
- while (c) {
- if (c == 'x') {
- return 0;
- }
- c = *readcursor++;
- }
- readcursor = src;
-
- struct in6_addr an_addr;
- memset(&an_addr, 0, sizeof(an_addr));
-
- uint16* addr_cursor = reinterpret_cast<uint16*>(&an_addr.s6_addr[0]);
- uint16* addr_end = reinterpret_cast<uint16*>(&an_addr.s6_addr[16]);
- bool seencompressed = false;
-
- // Addresses that start with "::" (i.e., a run of initial zeros) or
- // "::ffff:" can potentially be IPv4 mapped or compatibility addresses.
- // These have dotted-style IPv4 addresses on the end (e.g. "::192.168.7.1").
- if (*readcursor == ':' && *(readcursor+1) == ':' &&
- *(readcursor + 2) != 0) {
- // Check for periods, which we'll take as a sign of v4 addresses.
- const char* addrstart = readcursor + 2;
- if (talk_base::strchr(addrstart, ".")) {
- const char* colon = talk_base::strchr(addrstart, "::");
- if (colon) {
- uint16 a_short;
- int bytesread = 0;
- if (sscanf(addrstart, "%hx%n", &a_short, &bytesread) != 1 ||
- a_short != 0xFFFF || bytesread != 4) {
- // Colons + periods means has to be ::ffff:a.b.c.d. But it wasn't.
- return 0;
- } else {
- an_addr.s6_addr[10] = 0xFF;
- an_addr.s6_addr[11] = 0xFF;
- addrstart = colon + 1;
- }
- }
- struct in_addr v4;
- if (inet_pton_v4(addrstart, &v4.s_addr)) {
- memcpy(&an_addr.s6_addr[12], &v4, sizeof(v4));
- memcpy(dst, &an_addr, sizeof(an_addr));
- return 1;
- } else {
- // Invalid v4 address.
- return 0;
- }
- }
- }
-
- // For addresses without a trailing IPv4 component ('normal' IPv6 addresses).
- while (*readcursor != 0 && addr_cursor < addr_end) {
- if (*readcursor == ':') {
- if (*(readcursor + 1) == ':') {
- if (seencompressed) {
- // Can only have one compressed run of zeroes ("::") per address.
- return 0;
- }
- // Hit a compressed run. Count colons to figure out how much of the
- // address is skipped.
- readcursor += 2;
- const char* coloncounter = readcursor;
- int coloncount = 0;
- if (*coloncounter == 0) {
- // Special case - trailing ::.
- addr_cursor = addr_end;
- } else {
- while (*coloncounter) {
- if (*coloncounter == ':') {
- ++coloncount;
- }
- ++coloncounter;
- }
- // (coloncount + 1) is the number of shorts left in the address.
- addr_cursor = addr_end - (coloncount + 1);
- seencompressed = true;
- }
- } else {
- ++readcursor;
- }
- } else {
- uint16 word;
- int bytesread = 0;
- if (sscanf(readcursor, "%hx%n", &word, &bytesread) != 1) {
- return 0;
- } else {
- *addr_cursor = HostToNetwork16(word);
- ++addr_cursor;
- readcursor += bytesread;
- if (*readcursor != ':' && *readcursor != '\0') {
- return 0;
- }
- }
- }
- }
-
- if (*readcursor != '\0' || addr_cursor < addr_end) {
- // Catches addresses too short or too long.
- return 0;
- }
- memcpy(dst, &an_addr, sizeof(an_addr));
- return 1;
-}
-
-//
-// Unix time is in seconds relative to 1/1/1970. So we compute the windows
-// FILETIME of that time/date, then we add/subtract in appropriate units to
-// convert to/from unix time.
-// The units of FILETIME are 100ns intervals, so by multiplying by or dividing
-// by 10000000, we can convert to/from seconds.
-//
-// FileTime = UnixTime*10000000 + FileTime(1970)
-// UnixTime = (FileTime-FileTime(1970))/10000000
-//
-
-void FileTimeToUnixTime(const FILETIME& ft, time_t* ut) {
- ASSERT(NULL != ut);
-
- // FILETIME has an earlier date base than time_t (1/1/1970), so subtract off
- // the difference.
- SYSTEMTIME base_st;
- memset(&base_st, 0, sizeof(base_st));
- base_st.wDay = 1;
- base_st.wMonth = 1;
- base_st.wYear = 1970;
-
- FILETIME base_ft;
- SystemTimeToFileTime(&base_st, &base_ft);
-
- ULARGE_INTEGER base_ul, current_ul;
- memcpy(&base_ul, &base_ft, sizeof(FILETIME));
- memcpy(¤t_ul, &ft, sizeof(FILETIME));
-
- // Divide by big number to convert to seconds, then subtract out the 1970
- // base date value.
- const ULONGLONG RATIO = 10000000;
- *ut = static_cast<time_t>((current_ul.QuadPart - base_ul.QuadPart) / RATIO);
-}
-
-void UnixTimeToFileTime(const time_t& ut, FILETIME* ft) {
- ASSERT(NULL != ft);
-
- // FILETIME has an earlier date base than time_t (1/1/1970), so add in
- // the difference.
- SYSTEMTIME base_st;
- memset(&base_st, 0, sizeof(base_st));
- base_st.wDay = 1;
- base_st.wMonth = 1;
- base_st.wYear = 1970;
-
- FILETIME base_ft;
- SystemTimeToFileTime(&base_st, &base_ft);
-
- ULARGE_INTEGER base_ul;
- memcpy(&base_ul, &base_ft, sizeof(FILETIME));
-
- // Multiply by big number to convert to 100ns units, then add in the 1970
- // base date value.
- const ULONGLONG RATIO = 10000000;
- ULARGE_INTEGER current_ul;
- current_ul.QuadPart = base_ul.QuadPart + static_cast<int64>(ut) * RATIO;
- memcpy(ft, ¤t_ul, sizeof(FILETIME));
-}
-
-bool Utf8ToWindowsFilename(const std::string& utf8, std::wstring* filename) {
- // TODO: Integrate into fileutils.h
- // TODO: Handle wide and non-wide cases via TCHAR?
- // TODO: Skip \\?\ processing if the length is not > MAX_PATH?
- // TODO: Write unittests
-
- // Convert to Utf16
- int wlen = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
- static_cast<int>(utf8.length() + 1), NULL,
- 0);
- if (0 == wlen) {
- return false;
- }
- wchar_t* wfilename = STACK_ARRAY(wchar_t, wlen);
- if (0 == ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
- static_cast<int>(utf8.length() + 1),
- wfilename, wlen)) {
- return false;
- }
- // Replace forward slashes with backslashes
- std::replace(wfilename, wfilename + wlen, L'/', L'\\');
- // Convert to complete filename
- DWORD full_len = ::GetFullPathName(wfilename, 0, NULL, NULL);
- if (0 == full_len) {
- return false;
- }
- wchar_t* filepart = NULL;
- wchar_t* full_filename = STACK_ARRAY(wchar_t, full_len + 6);
- wchar_t* start = full_filename + 6;
- if (0 == ::GetFullPathName(wfilename, full_len, start, &filepart)) {
- return false;
- }
- // Add long-path prefix
- const wchar_t kLongPathPrefix[] = L"\\\\?\\UNC";
- if ((start[0] != L'\\') || (start[1] != L'\\')) {
- // Non-unc path: <pathname>
- // Becomes: \\?\<pathname>
- start -= 4;
- ASSERT(start >= full_filename);
- memcpy(start, kLongPathPrefix, 4 * sizeof(wchar_t));
- } else if (start[2] != L'?') {
- // Unc path: \\<server>\<pathname>
- // Becomes: \\?\UNC\<server>\<pathname>
- start -= 6;
- ASSERT(start >= full_filename);
- memcpy(start, kLongPathPrefix, 7 * sizeof(wchar_t));
- } else {
- // Already in long-path form.
- }
- filename->assign(start);
- return true;
-}
-
-bool GetOsVersion(int* major, int* minor, int* build) {
- OSVERSIONINFO info = {0};
- info.dwOSVersionInfoSize = sizeof(info);
- if (GetVersionEx(&info)) {
- if (major) *major = info.dwMajorVersion;
- if (minor) *minor = info.dwMinorVersion;
- if (build) *build = info.dwBuildNumber;
- return true;
- }
- return false;
-}
-
-bool GetCurrentProcessIntegrityLevel(int* level) {
- bool ret = false;
- HANDLE process = ::GetCurrentProcess(), token;
- if (OpenProcessToken(process, TOKEN_QUERY | TOKEN_QUERY_SOURCE, &token)) {
- DWORD size;
- if (!GetTokenInformation(token, TokenIntegrityLevel, NULL, 0, &size) &&
- GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
-
- char* buf = STACK_ARRAY(char, size);
- TOKEN_MANDATORY_LABEL* til =
- reinterpret_cast<TOKEN_MANDATORY_LABEL*>(buf);
- if (GetTokenInformation(token, TokenIntegrityLevel, til, size, &size)) {
-
- DWORD count = *GetSidSubAuthorityCount(til->Label.Sid);
- *level = *GetSidSubAuthority(til->Label.Sid, count - 1);
- ret = true;
- }
- }
- CloseHandle(token);
- }
- return ret;
-}
-} // namespace talk_base
diff --git a/base/win32.h b/base/win32.h
deleted file mode 100644
index 617d639..0000000
--- a/base/win32.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WIN32_H_
-#define TALK_BASE_WIN32_H_
-
-#ifdef WIN32
-
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN
-#endif
-
-// Make sure we don't get min/max macros
-#ifndef NOMINMAX
-#define NOMINMAX
-#endif
-
-#include <winsock2.h>
-#include <windows.h>
-
-#ifndef SECURITY_MANDATORY_LABEL_AUTHORITY
-// Add defines that we use if we are compiling against older sdks
-#define SECURITY_MANDATORY_MEDIUM_RID (0x00002000L)
-#define TokenIntegrityLevel static_cast<TOKEN_INFORMATION_CLASS>(0x19)
-typedef struct _TOKEN_MANDATORY_LABEL {
- SID_AND_ATTRIBUTES Label;
-} TOKEN_MANDATORY_LABEL, *PTOKEN_MANDATORY_LABEL;
-#endif // SECURITY_MANDATORY_LABEL_AUTHORITY
-
-#undef SetPort
-
-#include <string>
-
-#include "talk/base/stringutils.h"
-#include "talk/base/basictypes.h"
-
-namespace talk_base {
-
-const char* win32_inet_ntop(int af, const void *src, char* dst, socklen_t size);
-int win32_inet_pton(int af, const char* src, void *dst);
-
-///////////////////////////////////////////////////////////////////////////////
-
-inline std::wstring ToUtf16(const char* utf8, size_t len) {
- int len16 = ::MultiByteToWideChar(CP_UTF8, 0, utf8, static_cast<int>(len),
- NULL, 0);
- wchar_t* ws = STACK_ARRAY(wchar_t, len16);
- ::MultiByteToWideChar(CP_UTF8, 0, utf8, static_cast<int>(len), ws, len16);
- return std::wstring(ws, len16);
-}
-
-inline std::wstring ToUtf16(const std::string& str) {
- return ToUtf16(str.data(), str.length());
-}
-
-inline std::string ToUtf8(const wchar_t* wide, size_t len) {
- int len8 = ::WideCharToMultiByte(CP_UTF8, 0, wide, static_cast<int>(len),
- NULL, 0, NULL, NULL);
- char* ns = STACK_ARRAY(char, len8);
- ::WideCharToMultiByte(CP_UTF8, 0, wide, static_cast<int>(len), ns, len8,
- NULL, NULL);
- return std::string(ns, len8);
-}
-
-inline std::string ToUtf8(const wchar_t* wide) {
- return ToUtf8(wide, wcslen(wide));
-}
-
-inline std::string ToUtf8(const std::wstring& wstr) {
- return ToUtf8(wstr.data(), wstr.length());
-}
-
-// Convert FILETIME to time_t
-void FileTimeToUnixTime(const FILETIME& ft, time_t* ut);
-
-// Convert time_t to FILETIME
-void UnixTimeToFileTime(const time_t& ut, FILETIME * ft);
-
-// Convert a Utf8 path representation to a non-length-limited Unicode pathname.
-bool Utf8ToWindowsFilename(const std::string& utf8, std::wstring* filename);
-
-// Convert a FILETIME to a UInt64
-inline uint64 ToUInt64(const FILETIME& ft) {
- ULARGE_INTEGER r = {ft.dwLowDateTime, ft.dwHighDateTime};
- return r.QuadPart;
-}
-
-enum WindowsMajorVersions {
- kWindows2000 = 5,
- kWindowsVista = 6,
-};
-bool GetOsVersion(int* major, int* minor, int* build);
-
-inline bool IsWindowsVistaOrLater() {
- int major;
- return (GetOsVersion(&major, NULL, NULL) && major >= kWindowsVista);
-}
-
-inline bool IsWindowsXpOrLater() {
- int major, minor;
- return (GetOsVersion(&major, &minor, NULL) &&
- (major >= kWindowsVista ||
- (major == kWindows2000 && minor >= 1)));
-}
-
-// Determine the current integrity level of the process.
-bool GetCurrentProcessIntegrityLevel(int* level);
-
-inline bool IsCurrentProcessLowIntegrity() {
- int level;
- return (GetCurrentProcessIntegrityLevel(&level) &&
- level < SECURITY_MANDATORY_MEDIUM_RID);
-}
-
-bool AdjustCurrentProcessPrivilege(const TCHAR* privilege, bool to_enable);
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // WIN32
-#endif // TALK_BASE_WIN32_H_
diff --git a/base/win32_unittest.cc b/base/win32_unittest.cc
deleted file mode 100644
index 502de5b..0000000
--- a/base/win32_unittest.cc
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-
-#include "talk/base/gunit.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/win32.h"
-#include "talk/base/winping.h"
-
-#ifndef WIN32
-#error Only for Windows
-#endif
-
-namespace talk_base {
-
-class Win32Test : public testing::Test {
- public:
- Win32Test() {
- }
-};
-
-TEST_F(Win32Test, FileTimeToUInt64Test) {
- FILETIME ft;
- ft.dwHighDateTime = 0xBAADF00D;
- ft.dwLowDateTime = 0xFEED3456;
-
- uint64 expected = 0xBAADF00DFEED3456;
- EXPECT_EQ(expected, ToUInt64(ft));
-}
-
-TEST_F(Win32Test, WinPingTest) {
- WinPing ping;
- ASSERT_TRUE(ping.IsValid());
-
- // Test valid ping cases.
- WinPing::PingResult result = ping.Ping(IPAddress(INADDR_LOOPBACK), 20, 50, 1,
- false);
- ASSERT_EQ(WinPing::PING_SUCCESS, result);
- if (HasIPv6Enabled()) {
- WinPing::PingResult v6result = ping.Ping(IPAddress(in6addr_loopback), 20,
- 50, 1, false);
- ASSERT_EQ(WinPing::PING_SUCCESS, v6result);
- }
-
- // Test invalid parameter cases.
- ASSERT_EQ(WinPing::PING_INVALID_PARAMS, ping.Ping(
- IPAddress(INADDR_LOOPBACK), 0, 50, 1, false));
- ASSERT_EQ(WinPing::PING_INVALID_PARAMS, ping.Ping(
- IPAddress(INADDR_LOOPBACK), 20, 0, 1, false));
- ASSERT_EQ(WinPing::PING_INVALID_PARAMS, ping.Ping(
- IPAddress(INADDR_LOOPBACK), 20, 50, 0, false));
-}
-
-} // namespace talk_base
diff --git a/base/win32filesystem.cc b/base/win32filesystem.cc
deleted file mode 100644
index 5caeac2..0000000
--- a/base/win32filesystem.cc
+++ /dev/null
@@ -1,477 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/win32filesystem.h"
-
-#include "talk/base/win32.h"
-#include <shellapi.h>
-#include <shlobj.h>
-#include <tchar.h>
-
-#include "talk/base/fileutils.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringutils.h"
-
-// In several places in this file, we test the integrity level of the process
-// before calling GetLongPathName. We do this because calling GetLongPathName
-// when running under protected mode IE (a low integrity process) can result in
-// a virtualized path being returned, which is wrong if you only plan to read.
-// TODO: Waiting to hear back from IE team on whether this is the
-// best approach; IEIsProtectedModeProcess is another possible solution.
-
-namespace talk_base {
-
-bool Win32Filesystem::CreateFolder(const Pathname &pathname) {
- if (pathname.pathname().empty() || !pathname.filename().empty())
- return false;
-
- std::wstring path16;
- if (!Utf8ToWindowsFilename(pathname.pathname(), &path16))
- return false;
-
- DWORD res = ::GetFileAttributes(path16.c_str());
- if (res != INVALID_FILE_ATTRIBUTES) {
- // Something exists at this location, check if it is a directory
- return ((res & FILE_ATTRIBUTE_DIRECTORY) != 0);
- } else if ((GetLastError() != ERROR_FILE_NOT_FOUND)
- && (GetLastError() != ERROR_PATH_NOT_FOUND)) {
- // Unexpected error
- return false;
- }
-
- // Directory doesn't exist, look up one directory level
- if (!pathname.parent_folder().empty()) {
- Pathname parent(pathname);
- parent.SetFolder(pathname.parent_folder());
- if (!CreateFolder(parent)) {
- return false;
- }
- }
-
- return (::CreateDirectory(path16.c_str(), NULL) != 0);
-}
-
-FileStream *Win32Filesystem::OpenFile(const Pathname &filename,
- const std::string &mode) {
- FileStream *fs = new FileStream();
- if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
- delete fs;
- fs = NULL;
- }
- return fs;
-}
-
-bool Win32Filesystem::CreatePrivateFile(const Pathname &filename) {
- // To make the file private to the current user, we first must construct a
- // SECURITY_DESCRIPTOR specifying an ACL. This code is mostly based upon
- // http://msdn.microsoft.com/en-us/library/ms707085%28VS.85%29.aspx
-
- // Get the current process token.
- HANDLE process_token = INVALID_HANDLE_VALUE;
- if (!::OpenProcessToken(::GetCurrentProcess(),
- TOKEN_QUERY,
- &process_token)) {
- LOG_ERR(LS_ERROR) << "OpenProcessToken() failed";
- return false;
- }
-
- // Get the size of its TOKEN_USER structure. Return value is not checked
- // because we expect it to fail.
- DWORD token_user_size = 0;
- (void)::GetTokenInformation(process_token,
- TokenUser,
- NULL,
- 0,
- &token_user_size);
-
- // Get the TOKEN_USER structure.
- scoped_ptr<char[]> token_user_bytes(new char[token_user_size]);
- PTOKEN_USER token_user = reinterpret_cast<PTOKEN_USER>(
- token_user_bytes.get());
- memset(token_user, 0, token_user_size);
- BOOL success = ::GetTokenInformation(process_token,
- TokenUser,
- token_user,
- token_user_size,
- &token_user_size);
- // We're now done with this.
- ::CloseHandle(process_token);
- if (!success) {
- LOG_ERR(LS_ERROR) << "GetTokenInformation() failed";
- return false;
- }
-
- if (!IsValidSid(token_user->User.Sid)) {
- LOG_ERR(LS_ERROR) << "Current process has invalid user SID";
- return false;
- }
-
- // Compute size needed for an ACL that allows access to just this user.
- int acl_size = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) +
- GetLengthSid(token_user->User.Sid);
-
- // Allocate it.
- scoped_ptr<char[]> acl_bytes(new char[acl_size]);
- PACL acl = reinterpret_cast<PACL>(acl_bytes.get());
- memset(acl, 0, acl_size);
- if (!::InitializeAcl(acl, acl_size, ACL_REVISION)) {
- LOG_ERR(LS_ERROR) << "InitializeAcl() failed";
- return false;
- }
-
- // Allow access to only the current user.
- if (!::AddAccessAllowedAce(acl,
- ACL_REVISION,
- GENERIC_READ | GENERIC_WRITE | STANDARD_RIGHTS_ALL,
- token_user->User.Sid)) {
- LOG_ERR(LS_ERROR) << "AddAccessAllowedAce() failed";
- return false;
- }
-
- // Now make the security descriptor.
- SECURITY_DESCRIPTOR security_descriptor;
- if (!::InitializeSecurityDescriptor(&security_descriptor,
- SECURITY_DESCRIPTOR_REVISION)) {
- LOG_ERR(LS_ERROR) << "InitializeSecurityDescriptor() failed";
- return false;
- }
-
- // Put the ACL in it.
- if (!::SetSecurityDescriptorDacl(&security_descriptor,
- TRUE,
- acl,
- FALSE)) {
- LOG_ERR(LS_ERROR) << "SetSecurityDescriptorDacl() failed";
- return false;
- }
-
- // Finally create the file.
- SECURITY_ATTRIBUTES security_attributes;
- security_attributes.nLength = sizeof(security_attributes);
- security_attributes.lpSecurityDescriptor = &security_descriptor;
- security_attributes.bInheritHandle = FALSE;
- HANDLE handle = ::CreateFile(
- ToUtf16(filename.pathname()).c_str(),
- GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
- &security_attributes,
- CREATE_NEW,
- 0,
- NULL);
- if (INVALID_HANDLE_VALUE == handle) {
- LOG_ERR(LS_ERROR) << "CreateFile() failed";
- return false;
- }
- if (!::CloseHandle(handle)) {
- LOG_ERR(LS_ERROR) << "CloseFile() failed";
- // Continue.
- }
- return true;
-}
-
-bool Win32Filesystem::DeleteFile(const Pathname &filename) {
- LOG(LS_INFO) << "Deleting file " << filename.pathname();
- if (!IsFile(filename)) {
- ASSERT(IsFile(filename));
- return false;
- }
- return ::DeleteFile(ToUtf16(filename.pathname()).c_str()) != 0;
-}
-
-bool Win32Filesystem::DeleteEmptyFolder(const Pathname &folder) {
- LOG(LS_INFO) << "Deleting folder " << folder.pathname();
-
- std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
- return ::RemoveDirectory(ToUtf16(no_slash).c_str()) != 0;
-}
-
-bool Win32Filesystem::GetTemporaryFolder(Pathname &pathname, bool create,
- const std::string *append) {
- wchar_t buffer[MAX_PATH + 1];
- if (!::GetTempPath(ARRAY_SIZE(buffer), buffer))
- return false;
- if (!IsCurrentProcessLowIntegrity() &&
- !::GetLongPathName(buffer, buffer, ARRAY_SIZE(buffer)))
- return false;
- size_t len = strlen(buffer);
- if ((len > 0) && (buffer[len-1] != '\\')) {
- len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len, L"\\");
- }
- if (len >= ARRAY_SIZE(buffer) - 1)
- return false;
- pathname.clear();
- pathname.SetFolder(ToUtf8(buffer));
- if (append != NULL) {
- ASSERT(!append->empty());
- pathname.AppendFolder(*append);
- }
- return !create || CreateFolder(pathname);
-}
-
-std::string Win32Filesystem::TempFilename(const Pathname &dir,
- const std::string &prefix) {
- wchar_t filename[MAX_PATH];
- if (::GetTempFileName(ToUtf16(dir.pathname()).c_str(),
- ToUtf16(prefix).c_str(), 0, filename) != 0)
- return ToUtf8(filename);
- ASSERT(false);
- return "";
-}
-
-bool Win32Filesystem::MoveFile(const Pathname &old_path,
- const Pathname &new_path) {
- if (!IsFile(old_path)) {
- ASSERT(IsFile(old_path));
- return false;
- }
- LOG(LS_INFO) << "Moving " << old_path.pathname()
- << " to " << new_path.pathname();
- return ::MoveFile(ToUtf16(old_path.pathname()).c_str(),
- ToUtf16(new_path.pathname()).c_str()) != 0;
-}
-
-bool Win32Filesystem::MoveFolder(const Pathname &old_path,
- const Pathname &new_path) {
- if (!IsFolder(old_path)) {
- ASSERT(IsFolder(old_path));
- return false;
- }
- LOG(LS_INFO) << "Moving " << old_path.pathname()
- << " to " << new_path.pathname();
- if (::MoveFile(ToUtf16(old_path.pathname()).c_str(),
- ToUtf16(new_path.pathname()).c_str()) == 0) {
- if (::GetLastError() != ERROR_NOT_SAME_DEVICE) {
- LOG_GLE(LS_ERROR) << "Failed to move file";
- return false;
- }
- if (!CopyFolder(old_path, new_path))
- return false;
- if (!DeleteFolderAndContents(old_path))
- return false;
- }
- return true;
-}
-
-bool Win32Filesystem::IsFolder(const Pathname &path) {
- WIN32_FILE_ATTRIBUTE_DATA data = {0};
- if (0 == ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
- GetFileExInfoStandard, &data))
- return false;
- return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
- FILE_ATTRIBUTE_DIRECTORY;
-}
-
-bool Win32Filesystem::IsFile(const Pathname &path) {
- WIN32_FILE_ATTRIBUTE_DATA data = {0};
- if (0 == ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
- GetFileExInfoStandard, &data))
- return false;
- return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
-}
-
-bool Win32Filesystem::IsAbsent(const Pathname& path) {
- WIN32_FILE_ATTRIBUTE_DATA data = {0};
- if (0 != ::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
- GetFileExInfoStandard, &data))
- return false;
- DWORD err = ::GetLastError();
- return (ERROR_FILE_NOT_FOUND == err || ERROR_PATH_NOT_FOUND == err);
-}
-
-bool Win32Filesystem::CopyFile(const Pathname &old_path,
- const Pathname &new_path) {
- return ::CopyFile(ToUtf16(old_path.pathname()).c_str(),
- ToUtf16(new_path.pathname()).c_str(), TRUE) != 0;
-}
-
-bool Win32Filesystem::IsTemporaryPath(const Pathname& pathname) {
- TCHAR buffer[MAX_PATH + 1];
- if (!::GetTempPath(ARRAY_SIZE(buffer), buffer))
- return false;
- if (!IsCurrentProcessLowIntegrity() &&
- !::GetLongPathName(buffer, buffer, ARRAY_SIZE(buffer)))
- return false;
- return (::strnicmp(ToUtf16(pathname.pathname()).c_str(),
- buffer, strlen(buffer)) == 0);
-}
-
-bool Win32Filesystem::GetFileSize(const Pathname &pathname, size_t *size) {
- WIN32_FILE_ATTRIBUTE_DATA data = {0};
- if (::GetFileAttributesEx(ToUtf16(pathname.pathname()).c_str(),
- GetFileExInfoStandard, &data) == 0)
- return false;
- *size = data.nFileSizeLow;
- return true;
-}
-
-bool Win32Filesystem::GetFileTime(const Pathname& path, FileTimeType which,
- time_t* time) {
- WIN32_FILE_ATTRIBUTE_DATA data = {0};
- if (::GetFileAttributesEx(ToUtf16(path.pathname()).c_str(),
- GetFileExInfoStandard, &data) == 0)
- return false;
- switch (which) {
- case FTT_CREATED:
- FileTimeToUnixTime(data.ftCreationTime, time);
- break;
- case FTT_MODIFIED:
- FileTimeToUnixTime(data.ftLastWriteTime, time);
- break;
- case FTT_ACCESSED:
- FileTimeToUnixTime(data.ftLastAccessTime, time);
- break;
- default:
- return false;
- }
- return true;
-}
-
-bool Win32Filesystem::GetAppPathname(Pathname* path) {
- TCHAR buffer[MAX_PATH + 1];
- if (0 == ::GetModuleFileName(NULL, buffer, ARRAY_SIZE(buffer)))
- return false;
- path->SetPathname(ToUtf8(buffer));
- return true;
-}
-
-bool Win32Filesystem::GetAppDataFolder(Pathname* path, bool per_user) {
- ASSERT(!organization_name_.empty());
- ASSERT(!application_name_.empty());
- TCHAR buffer[MAX_PATH + 1];
- int csidl = per_user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA;
- if (!::SHGetSpecialFolderPath(NULL, buffer, csidl, TRUE))
- return false;
- if (!IsCurrentProcessLowIntegrity() &&
- !::GetLongPathName(buffer, buffer, ARRAY_SIZE(buffer)))
- return false;
- size_t len = strcatn(buffer, ARRAY_SIZE(buffer), __T("\\"));
- len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len,
- ToUtf16(organization_name_).c_str());
- if ((len > 0) && (buffer[len-1] != __T('\\'))) {
- len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len, __T("\\"));
- }
- len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len,
- ToUtf16(application_name_).c_str());
- if ((len > 0) && (buffer[len-1] != __T('\\'))) {
- len += strcpyn(buffer + len, ARRAY_SIZE(buffer) - len, __T("\\"));
- }
- if (len >= ARRAY_SIZE(buffer) - 1)
- return false;
- path->clear();
- path->SetFolder(ToUtf8(buffer));
- return CreateFolder(*path);
-}
-
-bool Win32Filesystem::GetAppTempFolder(Pathname* path) {
- if (!GetAppPathname(path))
- return false;
- std::string filename(path->filename());
- return GetTemporaryFolder(*path, true, &filename);
-}
-
-bool Win32Filesystem::GetDiskFreeSpace(const Pathname& path, int64 *freebytes) {
- if (!freebytes) {
- return false;
- }
- char drive[4];
- std::wstring drive16;
- const wchar_t* target_drive = NULL;
- if (path.GetDrive(drive, sizeof(drive))) {
- drive16 = ToUtf16(drive);
- target_drive = drive16.c_str();
- } else if (path.folder().substr(0, 2) == "\\\\") {
- // UNC path, fail.
- // TODO: Handle UNC paths.
- return false;
- } else {
- // The path is probably relative. GetDriveType and GetDiskFreeSpaceEx
- // use the current drive if NULL is passed as the drive name.
- // TODO: Add method to Pathname to determine if the path is relative.
- // TODO: Add method to Pathname to convert a path to absolute.
- }
- UINT driveType = ::GetDriveType(target_drive);
- if ( (driveType & DRIVE_REMOTE) || (driveType & DRIVE_UNKNOWN) ) {
- LOG(LS_VERBOSE) << " remove or unknown drive " << drive;
- return false;
- }
-
- int64 totalNumberOfBytes; // receives the number of bytes on disk
- int64 totalNumberOfFreeBytes; // receives the free bytes on disk
- // make sure things won't change in 64 bit machine
- // TODO replace with compile time assert
- ASSERT(sizeof(ULARGE_INTEGER) == sizeof(uint64)); //NOLINT
- if (::GetDiskFreeSpaceEx(target_drive,
- (PULARGE_INTEGER)freebytes,
- (PULARGE_INTEGER)&totalNumberOfBytes,
- (PULARGE_INTEGER)&totalNumberOfFreeBytes)) {
- return true;
- } else {
- LOG(LS_VERBOSE) << " GetDiskFreeSpaceEx returns error ";
- return false;
- }
-}
-
-Pathname Win32Filesystem::GetCurrentDirectory() {
- Pathname cwd;
- int path_len = 0;
- scoped_ptr<wchar_t[]> path;
- do {
- int needed = ::GetCurrentDirectory(path_len, path.get());
- if (needed == 0) {
- // Error.
- LOG_GLE(LS_ERROR) << "::GetCurrentDirectory() failed";
- return cwd; // returns empty pathname
- }
- if (needed <= path_len) {
- // It wrote successfully.
- break;
- }
- // Else need to re-alloc for "needed".
- path.reset(new wchar_t[needed]);
- path_len = needed;
- } while (true);
- cwd.SetFolder(ToUtf8(path.get()));
- return cwd;
-}
-
-// TODO: Consider overriding DeleteFolderAndContents for speed and potentially
-// better OS integration (recycle bin?)
-/*
- std::wstring temp_path16 = ToUtf16(temp_path.pathname());
- temp_path16.append(1, '*');
- temp_path16.append(1, '\0');
-
- SHFILEOPSTRUCT file_op = { 0 };
- file_op.wFunc = FO_DELETE;
- file_op.pFrom = temp_path16.c_str();
- file_op.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
- return (0 == SHFileOperation(&file_op));
-*/
-
-} // namespace talk_base
diff --git a/base/win32filesystem.h b/base/win32filesystem.h
deleted file mode 100644
index c17bdd9..0000000
--- a/base/win32filesystem.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2006, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef _TALK_BASE_WIN32FILESYSTEM_H__
-#define _TALK_BASE_WIN32FILESYSTEM_H__
-
-#include "fileutils.h"
-
-namespace talk_base {
-
-class Win32Filesystem : public FilesystemInterface {
- public:
- // Opens a file. Returns an open StreamInterface if function succeeds. Otherwise,
- // returns NULL.
- virtual FileStream *OpenFile(const Pathname &filename,
- const std::string &mode);
-
- // Atomically creates an empty file accessible only to the current user if one
- // does not already exist at the given path, otherwise fails.
- virtual bool CreatePrivateFile(const Pathname &filename);
-
- // This will attempt to delete the path located at filename.
- // If the path points to a folder, it will fail with VERIFY
- virtual bool DeleteFile(const Pathname &filename);
-
- // This will attempt to delete an empty folder. If the path does not point to
- // a folder, it fails with VERIFY. If the folder is not empty, it fails normally
- virtual bool DeleteEmptyFolder(const Pathname &folder);
-
- // Creates a directory. This will call itself recursively to create /foo/bar even if
- // /foo does not exist.
- // Returns TRUE if function succeeds
- virtual bool CreateFolder(const Pathname &pathname);
-
- // This moves a file from old_path to new_path. If the new path is on a
- // different volume than the old, it will attempt to copy and then delete
- // the folder
- // Returns true if the file is successfully moved
- virtual bool MoveFile(const Pathname &old_path, const Pathname &new_path);
-
- // Moves a folder from old_path to new_path. If the new path is on a different
- // volume from the old, it will attempt to Copy and then Delete the folder
- // Returns true if the folder is successfully moved
- virtual bool MoveFolder(const Pathname &old_path, const Pathname &new_path);
-
- // This copies a file from old_path to _new_path
- // Returns true if function succeeds
- virtual bool CopyFile(const Pathname &old_path, const Pathname &new_path);
-
- // Returns true if a pathname is a directory
- virtual bool IsFolder(const Pathname& pathname);
-
- // Returns true if a file exists at path
- virtual bool IsFile(const Pathname &path);
-
- // Returns true if pathname refers to no filesystem object, every parent
- // directory either exists, or is also absent.
- virtual bool IsAbsent(const Pathname& pathname);
-
- // Returns true if pathname represents a temporary location on the system.
- virtual bool IsTemporaryPath(const Pathname& pathname);
-
- // All of the following functions set pathname and return true if successful.
- // Returned paths always include a trailing backslash.
- // If create is true, the path will be recursively created.
- // If append is non-NULL, it will be appended (and possibly created).
-
- virtual std::string TempFilename(const Pathname &dir, const std::string &prefix);
-
- virtual bool GetFileSize(const Pathname& path, size_t* size);
- virtual bool GetFileTime(const Pathname& path, FileTimeType which,
- time_t* time);
-
- // A folder appropriate for storing temporary files (Contents are
- // automatically deleted when the program exists)
- virtual bool GetTemporaryFolder(Pathname &path, bool create,
- const std::string *append);
-
- // Returns the path to the running application.
- virtual bool GetAppPathname(Pathname* path);
-
- virtual bool GetAppDataFolder(Pathname* path, bool per_user);
-
- // Get a temporary folder that is unique to the current user and application.
- virtual bool GetAppTempFolder(Pathname* path);
-
- virtual bool GetDiskFreeSpace(const Pathname& path, int64 *freebytes);
-
- virtual Pathname GetCurrentDirectory();
-};
-
-} // namespace talk_base
-
-#endif // _WIN32FILESYSTEM_H__
diff --git a/base/win32regkey.cc b/base/win32regkey.cc
deleted file mode 100644
index 614f698..0000000
--- a/base/win32regkey.cc
+++ /dev/null
@@ -1,1119 +0,0 @@
-/*
- * libjingle
- * Copyright 2003-2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Registry configuration wrapers class implementation
-//
-// Change made by S. Ganesh - ganesh@google.com:
-// Use SHQueryValueEx instead of RegQueryValueEx throughout.
-// A call to the SHLWAPI function is essentially a call to the standard
-// function but with post-processing:
-// * to fix REG_SZ or REG_EXPAND_SZ data that is not properly null-terminated;
-// * to expand REG_EXPAND_SZ data.
-
-#include "talk/base/win32regkey.h"
-
-#include <shlwapi.h>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-
-namespace talk_base {
-
-RegKey::RegKey() {
- h_key_ = NULL;
-}
-
-RegKey::~RegKey() {
- Close();
-}
-
-HRESULT RegKey::Create(HKEY parent_key, const wchar_t* key_name) {
- return Create(parent_key,
- key_name,
- REG_NONE,
- REG_OPTION_NON_VOLATILE,
- KEY_ALL_ACCESS,
- NULL,
- NULL);
-}
-
-HRESULT RegKey::Open(HKEY parent_key, const wchar_t* key_name) {
- return Open(parent_key, key_name, KEY_ALL_ACCESS);
-}
-
-bool RegKey::HasValue(const TCHAR* value_name) const {
- return (ERROR_SUCCESS == ::RegQueryValueEx(h_key_, value_name, NULL,
- NULL, NULL, NULL));
-}
-
-HRESULT RegKey::SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD value) {
- ASSERT(full_key_name != NULL);
-
- return SetValueStaticHelper(full_key_name, value_name, REG_DWORD, &value);
-}
-
-HRESULT RegKey::SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD64 value) {
- ASSERT(full_key_name != NULL);
-
- return SetValueStaticHelper(full_key_name, value_name, REG_QWORD, &value);
-}
-
-HRESULT RegKey::SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- float value) {
- ASSERT(full_key_name != NULL);
-
- return SetValueStaticHelper(full_key_name, value_name,
- REG_BINARY, &value, sizeof(value));
-}
-
-HRESULT RegKey::SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- double value) {
- ASSERT(full_key_name != NULL);
-
- return SetValueStaticHelper(full_key_name, value_name,
- REG_BINARY, &value, sizeof(value));
-}
-
-HRESULT RegKey::SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- const TCHAR* value) {
- ASSERT(full_key_name != NULL);
- ASSERT(value != NULL);
-
- return SetValueStaticHelper(full_key_name, value_name,
- REG_SZ, const_cast<wchar_t*>(value));
-}
-
-HRESULT RegKey::SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- const uint8* value,
- DWORD byte_count) {
- ASSERT(full_key_name != NULL);
-
- return SetValueStaticHelper(full_key_name, value_name, REG_BINARY,
- const_cast<uint8*>(value), byte_count);
-}
-
-HRESULT RegKey::SetValueMultiSZ(const wchar_t* full_key_name,
- const wchar_t* value_name,
- const uint8* value,
- DWORD byte_count) {
- ASSERT(full_key_name != NULL);
-
- return SetValueStaticHelper(full_key_name, value_name, REG_MULTI_SZ,
- const_cast<uint8*>(value), byte_count);
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD* value) {
- ASSERT(full_key_name != NULL);
- ASSERT(value != NULL);
-
- return GetValueStaticHelper(full_key_name, value_name, REG_DWORD, value);
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD64* value) {
- ASSERT(full_key_name != NULL);
- ASSERT(value != NULL);
-
- return GetValueStaticHelper(full_key_name, value_name, REG_QWORD, value);
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- float* value) {
- ASSERT(value != NULL);
- ASSERT(full_key_name != NULL);
-
- DWORD byte_count = 0;
- scoped_ptr<byte[]> buffer;
- HRESULT hr = GetValueStaticHelper(full_key_name, value_name,
- REG_BINARY, buffer.accept(), &byte_count);
- if (SUCCEEDED(hr)) {
- ASSERT(byte_count == sizeof(*value));
- if (byte_count == sizeof(*value)) {
- *value = *reinterpret_cast<float*>(buffer.get());
- }
- }
- return hr;
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- double* value) {
- ASSERT(value != NULL);
- ASSERT(full_key_name != NULL);
-
- DWORD byte_count = 0;
- scoped_ptr<byte[]> buffer;
- HRESULT hr = GetValueStaticHelper(full_key_name, value_name,
- REG_BINARY, buffer.accept(), &byte_count);
- if (SUCCEEDED(hr)) {
- ASSERT(byte_count == sizeof(*value));
- if (byte_count == sizeof(*value)) {
- *value = *reinterpret_cast<double*>(buffer.get());
- }
- }
- return hr;
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- wchar_t** value) {
- ASSERT(full_key_name != NULL);
- ASSERT(value != NULL);
-
- return GetValueStaticHelper(full_key_name, value_name, REG_SZ, value);
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- std::wstring* value) {
- ASSERT(full_key_name != NULL);
- ASSERT(value != NULL);
-
- scoped_ptr<wchar_t[]> buffer;
- HRESULT hr = RegKey::GetValue(full_key_name, value_name, buffer.accept());
- if (SUCCEEDED(hr)) {
- value->assign(buffer.get());
- }
- return hr;
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- std::vector<std::wstring>* value) {
- ASSERT(full_key_name != NULL);
- ASSERT(value != NULL);
-
- return GetValueStaticHelper(full_key_name, value_name, REG_MULTI_SZ, value);
-}
-
-HRESULT RegKey::GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- uint8** value,
- DWORD* byte_count) {
- ASSERT(full_key_name != NULL);
- ASSERT(value != NULL);
- ASSERT(byte_count != NULL);
-
- return GetValueStaticHelper(full_key_name, value_name,
- REG_BINARY, value, byte_count);
-}
-
-HRESULT RegKey::DeleteSubKey(const wchar_t* key_name) {
- ASSERT(key_name != NULL);
- ASSERT(h_key_ != NULL);
-
- LONG res = ::RegDeleteKey(h_key_, key_name);
- HRESULT hr = HRESULT_FROM_WIN32(res);
- if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) ||
- hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) {
- hr = S_FALSE;
- }
- return hr;
-}
-
-HRESULT RegKey::DeleteValue(const wchar_t* value_name) {
- ASSERT(h_key_ != NULL);
-
- LONG res = ::RegDeleteValue(h_key_, value_name);
- HRESULT hr = HRESULT_FROM_WIN32(res);
- if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) ||
- hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) {
- hr = S_FALSE;
- }
- return hr;
-}
-
-HRESULT RegKey::Close() {
- HRESULT hr = S_OK;
- if (h_key_ != NULL) {
- LONG res = ::RegCloseKey(h_key_);
- hr = HRESULT_FROM_WIN32(res);
- h_key_ = NULL;
- }
- return hr;
-}
-
-HRESULT RegKey::Create(HKEY parent_key,
- const wchar_t* key_name,
- wchar_t* lpszClass,
- DWORD options,
- REGSAM sam_desired,
- LPSECURITY_ATTRIBUTES lpSecAttr,
- LPDWORD lpdwDisposition) {
- ASSERT(key_name != NULL);
- ASSERT(parent_key != NULL);
-
- DWORD dw = 0;
- HKEY h_key = NULL;
- LONG res = ::RegCreateKeyEx(parent_key, key_name, 0, lpszClass, options,
- sam_desired, lpSecAttr, &h_key, &dw);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (lpdwDisposition) {
- *lpdwDisposition = dw;
- }
-
- // we have to close the currently opened key
- // before replacing it with the new one
- if (hr == S_OK) {
- hr = Close();
- ASSERT(hr == S_OK);
- h_key_ = h_key;
- }
- return hr;
-}
-
-HRESULT RegKey::Open(HKEY parent_key,
- const wchar_t* key_name,
- REGSAM sam_desired) {
- ASSERT(key_name != NULL);
- ASSERT(parent_key != NULL);
-
- HKEY h_key = NULL;
- LONG res = ::RegOpenKeyEx(parent_key, key_name, 0, sam_desired, &h_key);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- // we have to close the currently opened key
- // before replacing it with the new one
- if (hr == S_OK) {
- // close the currently opened key if any
- hr = Close();
- ASSERT(hr == S_OK);
- h_key_ = h_key;
- }
- return hr;
-}
-
-// save the key and all of its subkeys and values to a file
-HRESULT RegKey::Save(const wchar_t* full_key_name, const wchar_t* file_name) {
- ASSERT(full_key_name != NULL);
- ASSERT(file_name != NULL);
-
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
- if (!h_key) {
- return E_FAIL;
- }
-
- RegKey key;
- HRESULT hr = key.Open(h_key, key_name.c_str(), KEY_READ);
- if (FAILED(hr)) {
- return hr;
- }
-
- AdjustCurrentProcessPrivilege(SE_BACKUP_NAME, true);
- LONG res = ::RegSaveKey(key.h_key_, file_name, NULL);
- AdjustCurrentProcessPrivilege(SE_BACKUP_NAME, false);
-
- return HRESULT_FROM_WIN32(res);
-}
-
-// restore the key and all of its subkeys and values which are saved into a file
-HRESULT RegKey::Restore(const wchar_t* full_key_name,
- const wchar_t* file_name) {
- ASSERT(full_key_name != NULL);
- ASSERT(file_name != NULL);
-
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
- if (!h_key) {
- return E_FAIL;
- }
-
- RegKey key;
- HRESULT hr = key.Open(h_key, key_name.c_str(), KEY_WRITE);
- if (FAILED(hr)) {
- return hr;
- }
-
- AdjustCurrentProcessPrivilege(SE_RESTORE_NAME, true);
- LONG res = ::RegRestoreKey(key.h_key_, file_name, REG_FORCE_RESTORE);
- AdjustCurrentProcessPrivilege(SE_RESTORE_NAME, false);
-
- return HRESULT_FROM_WIN32(res);
-}
-
-// check if the current key has the specified subkey
-bool RegKey::HasSubkey(const wchar_t* key_name) const {
- ASSERT(key_name != NULL);
-
- RegKey key;
- HRESULT hr = key.Open(h_key_, key_name, KEY_READ);
- key.Close();
- return hr == S_OK;
-}
-
-// static flush key
-HRESULT RegKey::FlushKey(const wchar_t* full_key_name) {
- ASSERT(full_key_name != NULL);
-
- HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
- // get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- if (h_key != NULL) {
- LONG res = ::RegFlushKey(h_key);
- hr = HRESULT_FROM_WIN32(res);
- }
- return hr;
-}
-
-// static SET helper
-HRESULT RegKey::SetValueStaticHelper(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD type,
- LPVOID value,
- DWORD byte_count) {
- ASSERT(full_key_name != NULL);
-
- HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
- // get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- if (h_key != NULL) {
- RegKey key;
- hr = key.Create(h_key, key_name.c_str());
- if (hr == S_OK) {
- switch (type) {
- case REG_DWORD:
- hr = key.SetValue(value_name, *(static_cast<DWORD*>(value)));
- break;
- case REG_QWORD:
- hr = key.SetValue(value_name, *(static_cast<DWORD64*>(value)));
- break;
- case REG_SZ:
- hr = key.SetValue(value_name, static_cast<const wchar_t*>(value));
- break;
- case REG_BINARY:
- hr = key.SetValue(value_name, static_cast<const uint8*>(value),
- byte_count);
- break;
- case REG_MULTI_SZ:
- hr = key.SetValue(value_name, static_cast<const uint8*>(value),
- byte_count, type);
- break;
- default:
- ASSERT(false);
- hr = HRESULT_FROM_WIN32(ERROR_DATATYPE_MISMATCH);
- break;
- }
- // close the key after writing
- HRESULT temp_hr = key.Close();
- if (hr == S_OK) {
- hr = temp_hr;
- }
- }
- }
- return hr;
-}
-
-// static GET helper
-HRESULT RegKey::GetValueStaticHelper(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD type,
- LPVOID value,
- DWORD* byte_count) {
- ASSERT(full_key_name != NULL);
-
- HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
- // get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- if (h_key != NULL) {
- RegKey key;
- hr = key.Open(h_key, key_name.c_str(), KEY_READ);
- if (hr == S_OK) {
- switch (type) {
- case REG_DWORD:
- hr = key.GetValue(value_name, reinterpret_cast<DWORD*>(value));
- break;
- case REG_QWORD:
- hr = key.GetValue(value_name, reinterpret_cast<DWORD64*>(value));
- break;
- case REG_SZ:
- hr = key.GetValue(value_name, reinterpret_cast<wchar_t**>(value));
- break;
- case REG_MULTI_SZ:
- hr = key.GetValue(value_name, reinterpret_cast<
- std::vector<std::wstring>*>(value));
- break;
- case REG_BINARY:
- hr = key.GetValue(value_name, reinterpret_cast<uint8**>(value),
- byte_count);
- break;
- default:
- ASSERT(false);
- hr = HRESULT_FROM_WIN32(ERROR_DATATYPE_MISMATCH);
- break;
- }
- // close the key after writing
- HRESULT temp_hr = key.Close();
- if (hr == S_OK) {
- hr = temp_hr;
- }
- }
- }
- return hr;
-}
-
-// GET helper
-HRESULT RegKey::GetValueHelper(const wchar_t* value_name,
- DWORD* type,
- uint8** value,
- DWORD* byte_count) const {
- ASSERT(byte_count != NULL);
- ASSERT(value != NULL);
- ASSERT(type != NULL);
-
- // init return buffer
- *value = NULL;
-
- // get the size of the return data buffer
- LONG res = ::SHQueryValueEx(h_key_, value_name, NULL, type, NULL, byte_count);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (hr == S_OK) {
- // if the value length is 0, nothing to do
- if (*byte_count != 0) {
- // allocate the buffer
- *value = new byte[*byte_count];
- ASSERT(*value != NULL);
-
- // make the call again to get the data
- res = ::SHQueryValueEx(h_key_, value_name, NULL,
- type, *value, byte_count);
- hr = HRESULT_FROM_WIN32(res);
- ASSERT(hr == S_OK);
- }
- }
- return hr;
-}
-
-// Int32 Get
-HRESULT RegKey::GetValue(const wchar_t* value_name, DWORD* value) const {
- ASSERT(value != NULL);
-
- DWORD type = 0;
- DWORD byte_count = sizeof(DWORD);
- LONG res = ::SHQueryValueEx(h_key_, value_name, NULL, &type,
- value, &byte_count);
- HRESULT hr = HRESULT_FROM_WIN32(res);
- ASSERT((hr != S_OK) || (type == REG_DWORD));
- ASSERT((hr != S_OK) || (byte_count == sizeof(DWORD)));
- return hr;
-}
-
-// Int64 Get
-HRESULT RegKey::GetValue(const wchar_t* value_name, DWORD64* value) const {
- ASSERT(value != NULL);
-
- DWORD type = 0;
- DWORD byte_count = sizeof(DWORD64);
- LONG res = ::SHQueryValueEx(h_key_, value_name, NULL, &type,
- value, &byte_count);
- HRESULT hr = HRESULT_FROM_WIN32(res);
- ASSERT((hr != S_OK) || (type == REG_QWORD));
- ASSERT((hr != S_OK) || (byte_count == sizeof(DWORD64)));
- return hr;
-}
-
-// String Get
-HRESULT RegKey::GetValue(const wchar_t* value_name, wchar_t** value) const {
- ASSERT(value != NULL);
-
- DWORD byte_count = 0;
- DWORD type = 0;
-
- // first get the size of the string buffer
- LONG res = ::SHQueryValueEx(h_key_, value_name, NULL,
- &type, NULL, &byte_count);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (hr == S_OK) {
- // allocate room for the string and a terminating \0
- *value = new wchar_t[(byte_count / sizeof(wchar_t)) + 1];
-
- if ((*value) != NULL) {
- if (byte_count != 0) {
- // make the call again
- res = ::SHQueryValueEx(h_key_, value_name, NULL, &type,
- *value, &byte_count);
- hr = HRESULT_FROM_WIN32(res);
- } else {
- (*value)[0] = L'\0';
- }
-
- ASSERT((hr != S_OK) || (type == REG_SZ) ||
- (type == REG_MULTI_SZ) || (type == REG_EXPAND_SZ));
- } else {
- hr = E_OUTOFMEMORY;
- }
- }
-
- return hr;
-}
-
-// get a string value
-HRESULT RegKey::GetValue(const wchar_t* value_name, std::wstring* value) const {
- ASSERT(value != NULL);
-
- DWORD byte_count = 0;
- DWORD type = 0;
-
- // first get the size of the string buffer
- LONG res = ::SHQueryValueEx(h_key_, value_name, NULL,
- &type, NULL, &byte_count);
- HRESULT hr = HRESULT_FROM_WIN32(res);
-
- if (hr == S_OK) {
- if (byte_count != 0) {
- // Allocate some memory and make the call again
- value->resize(byte_count / sizeof(wchar_t) + 1);
- res = ::SHQueryValueEx(h_key_, value_name, NULL, &type,
- &value->at(0), &byte_count);
- hr = HRESULT_FROM_WIN32(res);
- value->resize(wcslen(value->data()));
- } else {
- value->clear();
- }
-
- ASSERT((hr != S_OK) || (type == REG_SZ) ||
- (type == REG_MULTI_SZ) || (type == REG_EXPAND_SZ));
- }
-
- return hr;
-}
-
-// convert REG_MULTI_SZ bytes to string array
-HRESULT RegKey::MultiSZBytesToStringArray(const uint8* buffer,
- DWORD byte_count,
- std::vector<std::wstring>* value) {
- ASSERT(buffer != NULL);
- ASSERT(value != NULL);
-
- const wchar_t* data = reinterpret_cast<const wchar_t*>(buffer);
- DWORD data_len = byte_count / sizeof(wchar_t);
- value->clear();
- if (data_len > 1) {
- // must be terminated by two null characters
- if (data[data_len - 1] != 0 || data[data_len - 2] != 0) {
- return E_INVALIDARG;
- }
-
- // put null-terminated strings into arrays
- while (*data) {
- std::wstring str(data);
- value->push_back(str);
- data += str.length() + 1;
- }
- }
- return S_OK;
-}
-
-// get a std::vector<std::wstring> value from REG_MULTI_SZ type
-HRESULT RegKey::GetValue(const wchar_t* value_name,
- std::vector<std::wstring>* value) const {
- ASSERT(value != NULL);
-
- DWORD byte_count = 0;
- DWORD type = 0;
- uint8* buffer = 0;
-
- // first get the size of the buffer
- HRESULT hr = GetValueHelper(value_name, &type, &buffer, &byte_count);
- ASSERT((hr != S_OK) || (type == REG_MULTI_SZ));
-
- if (SUCCEEDED(hr)) {
- hr = MultiSZBytesToStringArray(buffer, byte_count, value);
- }
-
- return hr;
-}
-
-// Binary data Get
-HRESULT RegKey::GetValue(const wchar_t* value_name,
- uint8** value,
- DWORD* byte_count) const {
- ASSERT(byte_count != NULL);
- ASSERT(value != NULL);
-
- DWORD type = 0;
- HRESULT hr = GetValueHelper(value_name, &type, value, byte_count);
- ASSERT((hr != S_OK) || (type == REG_MULTI_SZ) || (type == REG_BINARY));
- return hr;
-}
-
-// Raw data get
-HRESULT RegKey::GetValue(const wchar_t* value_name,
- uint8** value,
- DWORD* byte_count,
- DWORD*type) const {
- ASSERT(type != NULL);
- ASSERT(byte_count != NULL);
- ASSERT(value != NULL);
-
- return GetValueHelper(value_name, type, value, byte_count);
-}
-
-// Int32 set
-HRESULT RegKey::SetValue(const wchar_t* value_name, DWORD value) const {
- ASSERT(h_key_ != NULL);
-
- LONG res = ::RegSetValueEx(h_key_, value_name, NULL, REG_DWORD,
- reinterpret_cast<const uint8*>(&value),
- sizeof(DWORD));
- return HRESULT_FROM_WIN32(res);
-}
-
-// Int64 set
-HRESULT RegKey::SetValue(const wchar_t* value_name, DWORD64 value) const {
- ASSERT(h_key_ != NULL);
-
- LONG res = ::RegSetValueEx(h_key_, value_name, NULL, REG_QWORD,
- reinterpret_cast<const uint8*>(&value),
- sizeof(DWORD64));
- return HRESULT_FROM_WIN32(res);
-}
-
-// String set
-HRESULT RegKey::SetValue(const wchar_t* value_name,
- const wchar_t* value) const {
- ASSERT(value != NULL);
- ASSERT(h_key_ != NULL);
-
- LONG res = ::RegSetValueEx(h_key_, value_name, NULL, REG_SZ,
- reinterpret_cast<const uint8*>(value),
- (lstrlen(value) + 1) * sizeof(wchar_t));
- return HRESULT_FROM_WIN32(res);
-}
-
-// Binary data set
-HRESULT RegKey::SetValue(const wchar_t* value_name,
- const uint8* value,
- DWORD byte_count) const {
- ASSERT(h_key_ != NULL);
-
- // special case - if 'value' is NULL make sure byte_count is zero
- if (value == NULL) {
- byte_count = 0;
- }
-
- LONG res = ::RegSetValueEx(h_key_, value_name, NULL,
- REG_BINARY, value, byte_count);
- return HRESULT_FROM_WIN32(res);
-}
-
-// Raw data set
-HRESULT RegKey::SetValue(const wchar_t* value_name,
- const uint8* value,
- DWORD byte_count,
- DWORD type) const {
- ASSERT(value != NULL);
- ASSERT(h_key_ != NULL);
-
- LONG res = ::RegSetValueEx(h_key_, value_name, NULL, type, value, byte_count);
- return HRESULT_FROM_WIN32(res);
-}
-
-bool RegKey::HasKey(const wchar_t* full_key_name) {
- ASSERT(full_key_name != NULL);
-
- // get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- if (h_key != NULL) {
- RegKey key;
- HRESULT hr = key.Open(h_key, key_name.c_str(), KEY_READ);
- key.Close();
- return S_OK == hr;
- }
- return false;
-}
-
-// static version of HasValue
-bool RegKey::HasValue(const wchar_t* full_key_name, const wchar_t* value_name) {
- ASSERT(full_key_name != NULL);
-
- bool has_value = false;
- // get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- if (h_key != NULL) {
- RegKey key;
- if (key.Open(h_key, key_name.c_str(), KEY_READ) == S_OK) {
- has_value = key.HasValue(value_name);
- key.Close();
- }
- }
- return has_value;
-}
-
-HRESULT RegKey::GetValueType(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD* value_type) {
- ASSERT(full_key_name != NULL);
- ASSERT(value_type != NULL);
-
- *value_type = REG_NONE;
-
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- RegKey key;
- HRESULT hr = key.Open(h_key, key_name.c_str(), KEY_READ);
- if (SUCCEEDED(hr)) {
- LONG res = ::SHQueryValueEx(key.h_key_, value_name, NULL, value_type,
- NULL, NULL);
- if (res != ERROR_SUCCESS) {
- hr = HRESULT_FROM_WIN32(res);
- }
- }
-
- return hr;
-}
-
-HRESULT RegKey::DeleteKey(const wchar_t* full_key_name) {
- ASSERT(full_key_name != NULL);
-
- return DeleteKey(full_key_name, true);
-}
-
-HRESULT RegKey::DeleteKey(const wchar_t* full_key_name, bool recursively) {
- ASSERT(full_key_name != NULL);
-
- // need to open the parent key first
- // get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- // get the parent key
- std::wstring parent_key(GetParentKeyInfo(&key_name));
-
- RegKey key;
- HRESULT hr = key.Open(h_key, parent_key.c_str());
-
- if (hr == S_OK) {
- hr = recursively ? key.RecurseDeleteSubKey(key_name.c_str())
- : key.DeleteSubKey(key_name.c_str());
- } else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) ||
- hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) {
- hr = S_FALSE;
- }
-
- key.Close();
- return hr;
-}
-
-HRESULT RegKey::DeleteValue(const wchar_t* full_key_name,
- const wchar_t* value_name) {
- ASSERT(full_key_name != NULL);
-
- HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
- // get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- if (h_key != NULL) {
- RegKey key;
- hr = key.Open(h_key, key_name.c_str());
- if (hr == S_OK) {
- hr = key.DeleteValue(value_name);
- key.Close();
- }
- }
- return hr;
-}
-
-HRESULT RegKey::RecurseDeleteSubKey(const wchar_t* key_name) {
- ASSERT(key_name != NULL);
-
- RegKey key;
- HRESULT hr = key.Open(h_key_, key_name);
-
- if (hr == S_OK) {
- // enumerate all subkeys of this key and recursivelly delete them
- FILETIME time = {0};
- wchar_t key_name_buf[kMaxKeyNameChars] = {0};
- DWORD key_name_buf_size = kMaxKeyNameChars;
- while (hr == S_OK &&
- ::RegEnumKeyEx(key.h_key_, 0, key_name_buf, &key_name_buf_size,
- NULL, NULL, NULL, &time) == ERROR_SUCCESS) {
- hr = key.RecurseDeleteSubKey(key_name_buf);
-
- // restore the buffer size
- key_name_buf_size = kMaxKeyNameChars;
- }
- // close the top key
- key.Close();
- }
-
- if (hr == S_OK) {
- // the key has no more children keys
- // delete the key and all of its values
- hr = DeleteSubKey(key_name);
- }
-
- return hr;
-}
-
-HKEY RegKey::GetRootKeyInfo(std::wstring* full_key_name) {
- ASSERT(full_key_name != NULL);
-
- HKEY h_key = NULL;
- // get the root HKEY
- size_t index = full_key_name->find(L'\\');
- std::wstring root_key;
-
- if (index == -1) {
- root_key = *full_key_name;
- *full_key_name = L"";
- } else {
- root_key = full_key_name->substr(0, index);
- *full_key_name = full_key_name->substr(index + 1,
- full_key_name->length() - index - 1);
- }
-
- for (std::wstring::iterator iter = root_key.begin();
- iter != root_key.end(); ++iter) {
- *iter = toupper(*iter);
- }
-
- if (!root_key.compare(L"HKLM") ||
- !root_key.compare(L"HKEY_LOCAL_MACHINE")) {
- h_key = HKEY_LOCAL_MACHINE;
- } else if (!root_key.compare(L"HKCU") ||
- !root_key.compare(L"HKEY_CURRENT_USER")) {
- h_key = HKEY_CURRENT_USER;
- } else if (!root_key.compare(L"HKU") ||
- !root_key.compare(L"HKEY_USERS")) {
- h_key = HKEY_USERS;
- } else if (!root_key.compare(L"HKCR") ||
- !root_key.compare(L"HKEY_CLASSES_ROOT")) {
- h_key = HKEY_CLASSES_ROOT;
- }
-
- return h_key;
-}
-
-
-// Returns true if this key name is 'safe' for deletion
-// (doesn't specify a key root)
-bool RegKey::SafeKeyNameForDeletion(const wchar_t* key_name) {
- ASSERT(key_name != NULL);
- std::wstring key(key_name);
-
- HKEY root_key = GetRootKeyInfo(&key);
-
- if (!root_key) {
- key = key_name;
- }
- if (key.empty()) {
- return false;
- }
- bool found_subkey = false, backslash_found = false;
- for (size_t i = 0 ; i < key.length() ; ++i) {
- if (key[i] == L'\\') {
- backslash_found = true;
- } else if (backslash_found) {
- found_subkey = true;
- break;
- }
- }
- return (root_key == HKEY_USERS) ? found_subkey : true;
-}
-
-std::wstring RegKey::GetParentKeyInfo(std::wstring* key_name) {
- ASSERT(key_name != NULL);
-
- // get the parent key
- size_t index = key_name->rfind(L'\\');
- std::wstring parent_key;
- if (index == -1) {
- parent_key = L"";
- } else {
- parent_key = key_name->substr(0, index);
- *key_name = key_name->substr(index + 1, key_name->length() - index - 1);
- }
-
- return parent_key;
-}
-
-// get the number of values for this key
-uint32 RegKey::GetValueCount() {
- DWORD num_values = 0;
-
- if (ERROR_SUCCESS != ::RegQueryInfoKey(
- h_key_, // key handle
- NULL, // buffer for class name
- NULL, // size of class string
- NULL, // reserved
- NULL, // number of subkeys
- NULL, // longest subkey size
- NULL, // longest class string
- &num_values, // number of values for this key
- NULL, // longest value name
- NULL, // longest value data
- NULL, // security descriptor
- NULL)) { // last write time
- ASSERT(false);
- }
- return num_values;
-}
-
-// Enumerators for the value_names for this key
-
-// Called to get the value name for the given value name index
-// Use GetValueCount() to get the total value_name count for this key
-// Returns failure if no key at the specified index
-HRESULT RegKey::GetValueNameAt(int index, std::wstring* value_name,
- DWORD* type) {
- ASSERT(value_name != NULL);
-
- LONG res = ERROR_SUCCESS;
- wchar_t value_name_buf[kMaxValueNameChars] = {0};
- DWORD value_name_buf_size = kMaxValueNameChars;
- res = ::RegEnumValue(h_key_, index, value_name_buf, &value_name_buf_size,
- NULL, type, NULL, NULL);
-
- if (res == ERROR_SUCCESS) {
- value_name->assign(value_name_buf);
- }
-
- return HRESULT_FROM_WIN32(res);
-}
-
-uint32 RegKey::GetSubkeyCount() {
- // number of values for key
- DWORD num_subkeys = 0;
-
- if (ERROR_SUCCESS != ::RegQueryInfoKey(
- h_key_, // key handle
- NULL, // buffer for class name
- NULL, // size of class string
- NULL, // reserved
- &num_subkeys, // number of subkeys
- NULL, // longest subkey size
- NULL, // longest class string
- NULL, // number of values for this key
- NULL, // longest value name
- NULL, // longest value data
- NULL, // security descriptor
- NULL)) { // last write time
- ASSERT(false);
- }
- return num_subkeys;
-}
-
-HRESULT RegKey::GetSubkeyNameAt(int index, std::wstring* key_name) {
- ASSERT(key_name != NULL);
-
- LONG res = ERROR_SUCCESS;
- wchar_t key_name_buf[kMaxKeyNameChars] = {0};
- DWORD key_name_buf_size = kMaxKeyNameChars;
-
- res = ::RegEnumKeyEx(h_key_, index, key_name_buf, &key_name_buf_size,
- NULL, NULL, NULL, NULL);
-
- if (res == ERROR_SUCCESS) {
- key_name->assign(key_name_buf);
- }
-
- return HRESULT_FROM_WIN32(res);
-}
-
-// Is the key empty: having no sub-keys and values
-bool RegKey::IsKeyEmpty(const wchar_t* full_key_name) {
- ASSERT(full_key_name != NULL);
-
- bool is_empty = true;
-
- // Get the root HKEY
- std::wstring key_name(full_key_name);
- HKEY h_key = GetRootKeyInfo(&key_name);
-
- // Open the key to check
- if (h_key != NULL) {
- RegKey key;
- HRESULT hr = key.Open(h_key, key_name.c_str(), KEY_READ);
- if (SUCCEEDED(hr)) {
- is_empty = key.GetSubkeyCount() == 0 && key.GetValueCount() == 0;
- key.Close();
- }
- }
-
- return is_empty;
-}
-
-bool AdjustCurrentProcessPrivilege(const TCHAR* privilege, bool to_enable) {
- ASSERT(privilege != NULL);
-
- bool ret = false;
- HANDLE token;
- if (::OpenProcessToken(::GetCurrentProcess(),
- TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
- LUID luid;
- memset(&luid, 0, sizeof(luid));
- if (::LookupPrivilegeValue(NULL, privilege, &luid)) {
- TOKEN_PRIVILEGES privs;
- privs.PrivilegeCount = 1;
- privs.Privileges[0].Luid = luid;
- privs.Privileges[0].Attributes = to_enable ? SE_PRIVILEGE_ENABLED : 0;
- if (::AdjustTokenPrivileges(token, FALSE, &privs, 0, NULL, 0)) {
- ret = true;
- } else {
- LOG_GLE(LS_ERROR) << "AdjustTokenPrivileges failed";
- }
- } else {
- LOG_GLE(LS_ERROR) << "LookupPrivilegeValue failed";
- }
- CloseHandle(token);
- } else {
- LOG_GLE(LS_ERROR) << "OpenProcessToken(GetCurrentProcess) failed";
- }
-
- return ret;
-}
-
-} // namespace talk_base
diff --git a/base/win32regkey.h b/base/win32regkey.h
deleted file mode 100644
index 9f01ce1..0000000
--- a/base/win32regkey.h
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- * libjingle
- * Copyright 2003-2007, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Registry configuration wrappers class
-//
-// Offers static functions for convenient
-// fast access for individual values
-//
-// Also provides a wrapper class for efficient
-// batch operations on values of a given registry key.
-//
-
-#ifndef TALK_BASE_WIN32REGKEY_H_
-#define TALK_BASE_WIN32REGKEY_H_
-
-#include <string>
-#include <vector>
-
-#include "talk/base/basictypes.h"
-#include "talk/base/win32.h"
-
-namespace talk_base {
-
-// maximum sizes registry key and value names
-const int kMaxKeyNameChars = 255 + 1;
-const int kMaxValueNameChars = 16383 + 1;
-
-class RegKey {
- public:
- // constructor
- RegKey();
-
- // destructor
- ~RegKey();
-
- // create a reg key
- HRESULT Create(HKEY parent_key, const wchar_t* key_name);
-
- HRESULT Create(HKEY parent_key,
- const wchar_t* key_name,
- wchar_t* reg_class,
- DWORD options,
- REGSAM sam_desired,
- LPSECURITY_ATTRIBUTES lp_sec_attr,
- LPDWORD lp_disposition);
-
- // open an existing reg key
- HRESULT Open(HKEY parent_key, const wchar_t* key_name);
-
- HRESULT Open(HKEY parent_key, const wchar_t* key_name, REGSAM sam_desired);
-
- // close this reg key
- HRESULT Close();
-
- // check if the key has a specified value
- bool HasValue(const wchar_t* value_name) const;
-
- // get the number of values for this key
- uint32 GetValueCount();
-
- // Called to get the value name for the given value name index
- // Use GetValueCount() to get the total value_name count for this key
- // Returns failure if no key at the specified index
- // If you modify the key while enumerating, the indexes will be out of order.
- // Since the index order is not guaranteed, you need to reset your counting
- // loop.
- // 'type' refers to REG_DWORD, REG_QWORD, etc..
- // 'type' can be NULL if not interested in the value type
- HRESULT GetValueNameAt(int index, std::wstring* value_name, DWORD* type);
-
- // check if the current key has the specified subkey
- bool HasSubkey(const wchar_t* key_name) const;
-
- // get the number of subkeys for this key
- uint32 GetSubkeyCount();
-
- // Called to get the key name for the given key index
- // Use GetSubkeyCount() to get the total count for this key
- // Returns failure if no key at the specified index
- // If you modify the key while enumerating, the indexes will be out of order.
- // Since the index order is not guaranteed, you need to reset your counting
- // loop.
- HRESULT GetSubkeyNameAt(int index, std::wstring* key_name);
-
- // SETTERS
-
- // set an int32 value - use when reading multiple values from a key
- HRESULT SetValue(const wchar_t* value_name, DWORD value) const;
-
- // set an int64 value
- HRESULT SetValue(const wchar_t* value_name, DWORD64 value) const;
-
- // set a string value
- HRESULT SetValue(const wchar_t* value_name, const wchar_t* value) const;
-
- // set binary data
- HRESULT SetValue(const wchar_t* value_name,
- const uint8* value,
- DWORD byte_count) const;
-
- // set raw data, including type
- HRESULT SetValue(const wchar_t* value_name,
- const uint8* value,
- DWORD byte_count,
- DWORD type) const;
-
- // GETTERS
-
- // get an int32 value
- HRESULT GetValue(const wchar_t* value_name, DWORD* value) const;
-
- // get an int64 value
- HRESULT GetValue(const wchar_t* value_name, DWORD64* value) const;
-
- // get a string value - the caller must free the return buffer
- HRESULT GetValue(const wchar_t* value_name, wchar_t** value) const;
-
- // get a string value
- HRESULT GetValue(const wchar_t* value_name, std::wstring* value) const;
-
- // get a std::vector<std::wstring> value from REG_MULTI_SZ type
- HRESULT GetValue(const wchar_t* value_name,
- std::vector<std::wstring>* value) const;
-
- // get binary data - the caller must free the return buffer
- HRESULT GetValue(const wchar_t* value_name,
- uint8** value,
- DWORD* byte_count) const;
-
- // get raw data, including type - the caller must free the return buffer
- HRESULT GetValue(const wchar_t* value_name,
- uint8** value,
- DWORD* byte_count,
- DWORD* type) const;
-
- // STATIC VERSIONS
-
- // flush
- static HRESULT FlushKey(const wchar_t* full_key_name);
-
- // check if a key exists
- static bool HasKey(const wchar_t* full_key_name);
-
- // check if the key has a specified value
- static bool HasValue(const wchar_t* full_key_name, const wchar_t* value_name);
-
- // SETTERS
-
- // STATIC int32 set
- static HRESULT SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD value);
-
- // STATIC int64 set
- static HRESULT SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD64 value);
-
- // STATIC float set
- static HRESULT SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- float value);
-
- // STATIC double set
- static HRESULT SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- double value);
-
- // STATIC string set
- static HRESULT SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- const wchar_t* value);
-
- // STATIC binary data set
- static HRESULT SetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- const uint8* value,
- DWORD byte_count);
-
- // STATIC multi-string set
- static HRESULT SetValueMultiSZ(const wchar_t* full_key_name,
- const TCHAR* value_name,
- const uint8* value,
- DWORD byte_count);
-
- // GETTERS
-
- // STATIC int32 get
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD* value);
-
- // STATIC int64 get
- //
- // Note: if you are using time64 you should
- // likely use GetLimitedTimeValue (util.h) instead of this method.
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD64* value);
-
- // STATIC float get
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- float* value);
-
- // STATIC double get
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- double* value);
-
- // STATIC string get
- // Note: the caller must free the return buffer for wchar_t* version
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- wchar_t** value);
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- std::wstring* value);
-
- // STATIC REG_MULTI_SZ get
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- std::vector<std::wstring>* value);
-
- // STATIC get binary data - the caller must free the return buffer
- static HRESULT GetValue(const wchar_t* full_key_name,
- const wchar_t* value_name,
- uint8** value,
- DWORD* byte_count);
-
- // Get type of a registry value
- static HRESULT GetValueType(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD* value_type);
-
- // delete a subkey of the current key (with no subkeys)
- HRESULT DeleteSubKey(const wchar_t* key_name);
-
- // recursively delete a sub key of the current key (and all its subkeys)
- HRESULT RecurseDeleteSubKey(const wchar_t* key_name);
-
- // STATIC version of delete key - handles nested keys also
- // delete a key and all its sub-keys recursively
- // Returns S_FALSE if key didn't exist, S_OK if deletion was successful,
- // and failure otherwise.
- static HRESULT DeleteKey(const wchar_t* full_key_name);
-
- // STATIC version of delete key
- // delete a key recursively or non-recursively
- // Returns S_FALSE if key didn't exist, S_OK if deletion was successful,
- // and failure otherwise.
- static HRESULT DeleteKey(const wchar_t* full_key_name, bool recursive);
-
- // delete the specified value
- HRESULT DeleteValue(const wchar_t* value_name);
-
- // STATIC version of delete value
- // Returns S_FALSE if key didn't exist, S_OK if deletion was successful,
- // and failure otherwise.
- static HRESULT DeleteValue(const wchar_t* full_key_name,
- const wchar_t* value_name);
-
- // Peek inside (use a RegKey as a smart wrapper around a registry handle)
- HKEY key() { return h_key_; }
-
- // helper function to get the HKEY and the root key from a string
- // modifies the argument in place and returns the key name
- // e.g. HKLM\\Software\\Google\... returns HKLM, "Software\\Google\..."
- // Necessary for the static versions that use the full name of the reg key
- static HKEY GetRootKeyInfo(std::wstring* full_key_name);
-
- // Returns true if this key name is 'safe' for deletion (doesn't specify a key
- // root)
- static bool SafeKeyNameForDeletion(const wchar_t* key_name);
-
- // save the key and all of its subkeys and values to a file
- static HRESULT Save(const wchar_t* full_key_name, const wchar_t* file_name);
-
- // restore the key and all of its subkeys and values which are saved into a
- // file
- static HRESULT Restore(const wchar_t* full_key_name,
- const wchar_t* file_name);
-
- // Is the key empty: having no sub-keys and values
- static bool IsKeyEmpty(const wchar_t* full_key_name);
-
- private:
-
- // helper function to get any value from the registry
- // used when the size of the data is unknown
- HRESULT GetValueHelper(const wchar_t* value_name,
- DWORD* type, uint8** value,
- DWORD* byte_count) const;
-
- // helper function to get the parent key name and the subkey from a string
- // modifies the argument in place and returns the key name
- // Necessary for the static versions that use the full name of the reg key
- static std::wstring GetParentKeyInfo(std::wstring* key_name);
-
- // common SET Helper for the static case
- static HRESULT SetValueStaticHelper(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD type,
- LPVOID value,
- DWORD byte_count = 0);
-
- // common GET Helper for the static case
- static HRESULT GetValueStaticHelper(const wchar_t* full_key_name,
- const wchar_t* value_name,
- DWORD type,
- LPVOID value,
- DWORD* byte_count = NULL);
-
- // convert REG_MULTI_SZ bytes to string array
- static HRESULT MultiSZBytesToStringArray(const uint8* buffer,
- DWORD byte_count,
- std::vector<std::wstring>* value);
-
- // the HKEY for the current key
- HKEY h_key_;
-
- // for unittest
- friend void RegKeyHelperFunctionsTest();
-
- DISALLOW_EVIL_CONSTRUCTORS(RegKey);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WIN32REGKEY_H_
diff --git a/base/win32regkey_unittest.cc b/base/win32regkey_unittest.cc
deleted file mode 100644
index 1dd8fe4..0000000
--- a/base/win32regkey_unittest.cc
+++ /dev/null
@@ -1,607 +0,0 @@
-/*
- * libjingle
- * Copyright 2003-2008, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Unittest for registry access API
-
-#include "talk/base/gunit.h"
-#include "talk/base/common.h"
-#include "talk/base/win32regkey.h"
-
-namespace talk_base {
-
-#ifndef EXPECT_SUCCEEDED
-#define EXPECT_SUCCEEDED(x) EXPECT_TRUE(SUCCEEDED(x))
-#endif
-
-#ifndef EXPECT_FAILED
-#define EXPECT_FAILED(x) EXPECT_TRUE(FAILED(x))
-#endif
-
-#define kBaseKey L"Software\\Google\\__TEST"
-#define kSubkeyName L"subkey_test"
-
-const wchar_t kRkey1[] = kBaseKey;
-const wchar_t kRkey1SubkeyName[] = kSubkeyName;
-const wchar_t kRkey1Subkey[] = kBaseKey L"\\" kSubkeyName;
-const wchar_t kFullRkey1[] = L"HKCU\\" kBaseKey;
-const wchar_t kFullRkey1Subkey[] = L"HKCU\\" kBaseKey L"\\" kSubkeyName;
-
-const wchar_t kValNameInt[] = L"Int32 Value";
-const DWORD kIntVal = 20;
-const DWORD kIntVal2 = 30;
-
-const wchar_t kValNameInt64[] = L"Int64 Value";
-const DWORD64 kIntVal64 = 119600064000000000uI64;
-
-const wchar_t kValNameFloat[] = L"Float Value";
-const float kFloatVal = 12.3456789f;
-
-const wchar_t kValNameDouble[] = L"Double Value";
-const double kDoubleVal = 98.7654321;
-
-const wchar_t kValNameStr[] = L"Str Value";
-const wchar_t kStrVal[] = L"Some string data 1";
-const wchar_t kStrVal2[] = L"Some string data 2";
-
-const wchar_t kValNameBinary[] = L"Binary Value";
-const char kBinaryVal[] = "Some binary data abcdefghi 1";
-const char kBinaryVal2[] = "Some binary data abcdefghi 2";
-
-const wchar_t kValNameMultiStr[] = L"MultiStr Value";
-const wchar_t kMultiSZ[] = L"abc\0def\0P12345\0";
-const wchar_t kEmptyMultiSZ[] = L"";
-const wchar_t kInvalidMultiSZ[] = {L'6', L'7', L'8'};
-
-// friend function of RegKey
-void RegKeyHelperFunctionsTest() {
- // Try out some dud values
- std::wstring temp_key = L"";
- EXPECT_TRUE(RegKey::GetRootKeyInfo(&temp_key) == NULL);
- EXPECT_STREQ(temp_key.c_str(), L"");
-
- temp_key = L"a";
- EXPECT_TRUE(RegKey::GetRootKeyInfo(&temp_key) == NULL);
- EXPECT_STREQ(temp_key.c_str(), L"");
-
- // The basics
- temp_key = L"HKLM\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_LOCAL_MACHINE);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"HKEY_LOCAL_MACHINE\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_LOCAL_MACHINE);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"HKCU\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CURRENT_USER);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"HKEY_CURRENT_USER\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CURRENT_USER);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"HKU\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_USERS);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"HKEY_USERS\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_USERS);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"HKCR\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"HKEY_CLASSES_ROOT\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- // Make sure it is case insensitive
- temp_key = L"hkcr\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"hkey_CLASSES_ROOT\\a";
- EXPECT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT);
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- //
- // Test RegKey::GetParentKeyInfo
- //
-
- // dud cases
- temp_key = L"";
- EXPECT_STREQ(RegKey::GetParentKeyInfo(&temp_key).c_str(), L"");
- EXPECT_STREQ(temp_key.c_str(), L"");
-
- temp_key = L"a";
- EXPECT_STREQ(RegKey::GetParentKeyInfo(&temp_key).c_str(), L"");
- EXPECT_STREQ(temp_key.c_str(), L"a");
-
- temp_key = L"a\\b";
- EXPECT_STREQ(RegKey::GetParentKeyInfo(&temp_key).c_str(), L"a");
- EXPECT_STREQ(temp_key.c_str(), L"b");
-
- temp_key = L"\\b";
- EXPECT_STREQ(RegKey::GetParentKeyInfo(&temp_key).c_str(), L"");
- EXPECT_STREQ(temp_key.c_str(), L"b");
-
- // Some regular cases
- temp_key = L"HKEY_CLASSES_ROOT\\moon";
- EXPECT_STREQ(RegKey::GetParentKeyInfo(&temp_key).c_str(),
- L"HKEY_CLASSES_ROOT");
- EXPECT_STREQ(temp_key.c_str(), L"moon");
-
- temp_key = L"HKEY_CLASSES_ROOT\\moon\\doggy";
- EXPECT_STREQ(RegKey::GetParentKeyInfo(&temp_key).c_str(),
- L"HKEY_CLASSES_ROOT\\moon");
- EXPECT_STREQ(temp_key.c_str(), L"doggy");
-
- //
- // Test MultiSZBytesToStringArray
- //
-
- std::vector<std::wstring> result;
- EXPECT_SUCCEEDED(RegKey::MultiSZBytesToStringArray(
- reinterpret_cast<const uint8*>(kMultiSZ), sizeof(kMultiSZ), &result));
- EXPECT_EQ(result.size(), 3);
- EXPECT_STREQ(result[0].c_str(), L"abc");
- EXPECT_STREQ(result[1].c_str(), L"def");
- EXPECT_STREQ(result[2].c_str(), L"P12345");
-
- EXPECT_SUCCEEDED(RegKey::MultiSZBytesToStringArray(
- reinterpret_cast<const uint8*>(kEmptyMultiSZ),
- sizeof(kEmptyMultiSZ), &result));
- EXPECT_EQ(result.size(), 0);
- EXPECT_FALSE(SUCCEEDED(RegKey::MultiSZBytesToStringArray(
- reinterpret_cast<const uint8*>(kInvalidMultiSZ),
- sizeof(kInvalidMultiSZ), &result)));
-}
-
-TEST(RegKeyTest, RegKeyHelperFunctionsTest) {
- RegKeyHelperFunctionsTest();
-}
-
-TEST(RegKeyTest, RegKeyNonStaticFunctionsTest) {
- DWORD int_val = 0;
- DWORD64 int64_val = 0;
- wchar_t* str_val = NULL;
- uint8* binary_val = NULL;
- DWORD uint8_count = 0;
-
- // Just in case...
- // make sure the no test key residue is left from previous aborted runs
- RegKey::DeleteKey(kFullRkey1);
-
- // initial state
- RegKey r_key;
- EXPECT_TRUE(r_key.key() == NULL);
-
- // create a reg key
- EXPECT_SUCCEEDED(r_key.Create(HKEY_CURRENT_USER, kRkey1));
-
- // do the create twice - it should return the already created one
- EXPECT_SUCCEEDED(r_key.Create(HKEY_CURRENT_USER, kRkey1));
-
- // now do an open - should work just fine
- EXPECT_SUCCEEDED(r_key.Open(HKEY_CURRENT_USER, kRkey1));
-
- // get an in-existent value
- EXPECT_EQ(r_key.GetValue(kValNameInt, &int_val),
- HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
-
- // set and get some values
-
- // set an INT 32
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameInt, kIntVal));
-
- // check that the value exists
- EXPECT_TRUE(r_key.HasValue(kValNameInt));
-
- // read it back
- EXPECT_SUCCEEDED(r_key.GetValue(kValNameInt, &int_val));
- EXPECT_EQ(int_val, kIntVal);
-
- // set it again!
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameInt, kIntVal2));
-
- // read it again
- EXPECT_SUCCEEDED(r_key.GetValue(kValNameInt, &int_val));
- EXPECT_EQ(int_val, kIntVal2);
-
- // delete the value
- EXPECT_SUCCEEDED(r_key.DeleteValue(kValNameInt));
-
- // check that the value is gone
- EXPECT_FALSE(r_key.HasValue(kValNameInt));
-
- // set an INT 64
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameInt64, kIntVal64));
-
- // check that the value exists
- EXPECT_TRUE(r_key.HasValue(kValNameInt64));
-
- // read it back
- EXPECT_SUCCEEDED(r_key.GetValue(kValNameInt64, &int64_val));
- EXPECT_EQ(int64_val, kIntVal64);
-
- // delete the value
- EXPECT_SUCCEEDED(r_key.DeleteValue(kValNameInt64));
-
- // check that the value is gone
- EXPECT_FALSE(r_key.HasValue(kValNameInt64));
-
- // set a string
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameStr, kStrVal));
-
- // check that the value exists
- EXPECT_TRUE(r_key.HasValue(kValNameStr));
-
- // read it back
- EXPECT_SUCCEEDED(r_key.GetValue(kValNameStr, &str_val));
- EXPECT_TRUE(lstrcmp(str_val, kStrVal) == 0);
- delete[] str_val;
-
- // set it again
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameStr, kStrVal2));
-
- // read it again
- EXPECT_SUCCEEDED(r_key.GetValue(kValNameStr, &str_val));
- EXPECT_TRUE(lstrcmp(str_val, kStrVal2) == 0);
- delete[] str_val;
-
- // delete the value
- EXPECT_SUCCEEDED(r_key.DeleteValue(kValNameStr));
-
- // check that the value is gone
- EXPECT_FALSE(r_key.HasValue(kValNameInt));
-
- // set a binary value
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameBinary,
- reinterpret_cast<const uint8*>(kBinaryVal), sizeof(kBinaryVal) - 1));
-
- // check that the value exists
- EXPECT_TRUE(r_key.HasValue(kValNameBinary));
-
- // read it back
- EXPECT_SUCCEEDED(r_key.GetValue(kValNameBinary, &binary_val, &uint8_count));
- EXPECT_TRUE(memcmp(binary_val, kBinaryVal, sizeof(kBinaryVal) - 1) == 0);
- delete[] binary_val;
-
- // set it again
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameBinary,
- reinterpret_cast<const uint8*>(kBinaryVal2), sizeof(kBinaryVal) - 1));
-
- // read it again
- EXPECT_SUCCEEDED(r_key.GetValue(kValNameBinary, &binary_val, &uint8_count));
- EXPECT_TRUE(memcmp(binary_val, kBinaryVal2, sizeof(kBinaryVal2) - 1) == 0);
- delete[] binary_val;
-
- // delete the value
- EXPECT_SUCCEEDED(r_key.DeleteValue(kValNameBinary));
-
- // check that the value is gone
- EXPECT_FALSE(r_key.HasValue(kValNameBinary));
-
- // set some values and check the total count
-
- // set an INT 32
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameInt, kIntVal));
-
- // set an INT 64
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameInt64, kIntVal64));
-
- // set a string
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameStr, kStrVal));
-
- // set a binary value
- EXPECT_SUCCEEDED(r_key.SetValue(kValNameBinary,
- reinterpret_cast<const uint8*>(kBinaryVal), sizeof(kBinaryVal) - 1));
-
- // get the value count
- uint32 value_count = r_key.GetValueCount();
- EXPECT_EQ(value_count, 4);
-
- // check the value names
- std::wstring value_name;
- DWORD type = 0;
-
- EXPECT_SUCCEEDED(r_key.GetValueNameAt(0, &value_name, &type));
- EXPECT_STREQ(value_name.c_str(), kValNameInt);
- EXPECT_EQ(type, REG_DWORD);
-
- EXPECT_SUCCEEDED(r_key.GetValueNameAt(1, &value_name, &type));
- EXPECT_STREQ(value_name.c_str(), kValNameInt64);
- EXPECT_EQ(type, REG_QWORD);
-
- EXPECT_SUCCEEDED(r_key.GetValueNameAt(2, &value_name, &type));
- EXPECT_STREQ(value_name.c_str(), kValNameStr);
- EXPECT_EQ(type, REG_SZ);
-
- EXPECT_SUCCEEDED(r_key.GetValueNameAt(3, &value_name, &type));
- EXPECT_STREQ(value_name.c_str(), kValNameBinary);
- EXPECT_EQ(type, REG_BINARY);
-
- // check that there are no more values
- EXPECT_FAILED(r_key.GetValueNameAt(4, &value_name, &type));
-
- uint32 subkey_count = r_key.GetSubkeyCount();
- EXPECT_EQ(subkey_count, 0);
-
- // now create a subkey and make sure we can get the name
- RegKey temp_key;
- EXPECT_SUCCEEDED(temp_key.Create(HKEY_CURRENT_USER, kRkey1Subkey));
-
- // check the subkey exists
- EXPECT_TRUE(r_key.HasSubkey(kRkey1SubkeyName));
-
- // check the name
- EXPECT_EQ(r_key.GetSubkeyCount(), 1);
-
- std::wstring subkey_name;
- EXPECT_SUCCEEDED(r_key.GetSubkeyNameAt(0, &subkey_name));
- EXPECT_STREQ(subkey_name.c_str(), kRkey1SubkeyName);
-
- // delete the key
- EXPECT_SUCCEEDED(r_key.DeleteSubKey(kRkey1));
-
- // close this key
- EXPECT_SUCCEEDED(r_key.Close());
-
- // whack the whole key
- EXPECT_SUCCEEDED(RegKey::DeleteKey(kFullRkey1));
-}
-
-TEST(RegKeyTest, RegKeyStaticFunctionsTest) {
- DWORD int_val = 0;
- DWORD64 int64_val = 0;
- float float_val = 0;
- double double_val = 0;
- wchar_t* str_val = NULL;
- std::wstring wstr_val;
- uint8* binary_val = NULL;
- DWORD uint8_count = 0;
-
- // Just in case...
- // make sure the no test key residue is left from previous aborted runs
- RegKey::DeleteKey(kFullRkey1);
-
- // get an in-existent value from an un-existent key
- EXPECT_EQ(RegKey::GetValue(kFullRkey1, kValNameInt, &int_val),
- HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
-
- // set int32
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameInt, kIntVal));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameInt));
-
- // get an in-existent value from an existent key
- EXPECT_EQ(RegKey::GetValue(kFullRkey1, L"bogus", &int_val),
- HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameInt, &int_val));
- EXPECT_EQ(int_val, kIntVal);
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameInt));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameInt));
-
- // set int64
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameInt64, kIntVal64));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameInt64));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameInt64, &int64_val));
- EXPECT_EQ(int64_val, kIntVal64);
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameInt64));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameInt64));
-
- // set float
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameFloat, kFloatVal));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameFloat));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameFloat, &float_val));
- EXPECT_EQ(float_val, kFloatVal);
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameFloat));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameFloat));
- EXPECT_FAILED(RegKey::GetValue(kFullRkey1, kValNameFloat, &float_val));
-
- // set double
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameDouble, kDoubleVal));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameDouble));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameDouble, &double_val));
- EXPECT_EQ(double_val, kDoubleVal);
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameDouble));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameDouble));
- EXPECT_FAILED(RegKey::GetValue(kFullRkey1, kValNameDouble, &double_val));
-
- // set string
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameStr, kStrVal));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameStr));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameStr, &str_val));
- EXPECT_TRUE(lstrcmp(str_val, kStrVal) == 0);
- delete[] str_val;
-
- // read it back in std::wstring
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameStr, &wstr_val));
- EXPECT_STREQ(wstr_val.c_str(), kStrVal);
-
- // get an in-existent value from an existent key
- EXPECT_EQ(RegKey::GetValue(kFullRkey1, L"bogus", &str_val),
- HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameStr));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameStr));
-
- // set binary
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameBinary,
- reinterpret_cast<const uint8*>(kBinaryVal), sizeof(kBinaryVal)-1));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameBinary));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameBinary,
- &binary_val, &uint8_count));
- EXPECT_TRUE(memcmp(binary_val, kBinaryVal, sizeof(kBinaryVal)-1) == 0);
- delete[] binary_val;
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameBinary));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameBinary));
-
- // special case - set a binary value with length 0
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameBinary,
- reinterpret_cast<const uint8*>(kBinaryVal), 0));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameBinary));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameBinary,
- &binary_val, &uint8_count));
- EXPECT_EQ(uint8_count, 0);
- EXPECT_TRUE(binary_val == NULL);
- delete[] binary_val;
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameBinary));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameBinary));
-
- // special case - set a NULL binary value
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1, kValNameBinary, NULL, 100));
-
- // check that the value exists
- EXPECT_TRUE(RegKey::HasValue(kFullRkey1, kValNameBinary));
-
- // read it back
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameBinary,
- &binary_val, &uint8_count));
- EXPECT_EQ(uint8_count, 0);
- EXPECT_TRUE(binary_val == NULL);
- delete[] binary_val;
-
- // delete the value
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1, kValNameBinary));
-
- // check that the value is gone
- EXPECT_FALSE(RegKey::HasValue(kFullRkey1, kValNameBinary));
-
- // test read/write REG_MULTI_SZ value
- std::vector<std::wstring> result;
- EXPECT_SUCCEEDED(RegKey::SetValueMultiSZ(kFullRkey1, kValNameMultiStr,
- reinterpret_cast<const uint8*>(kMultiSZ), sizeof(kMultiSZ)));
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameMultiStr, &result));
- EXPECT_EQ(result.size(), 3);
- EXPECT_STREQ(result[0].c_str(), L"abc");
- EXPECT_STREQ(result[1].c_str(), L"def");
- EXPECT_STREQ(result[2].c_str(), L"P12345");
- EXPECT_SUCCEEDED(RegKey::SetValueMultiSZ(kFullRkey1, kValNameMultiStr,
- reinterpret_cast<const uint8*>(kEmptyMultiSZ), sizeof(kEmptyMultiSZ)));
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameMultiStr, &result));
- EXPECT_EQ(result.size(), 0);
- // writing REG_MULTI_SZ value will automatically add ending null characters
- EXPECT_SUCCEEDED(RegKey::SetValueMultiSZ(kFullRkey1, kValNameMultiStr,
- reinterpret_cast<const uint8*>(kInvalidMultiSZ), sizeof(kInvalidMultiSZ)));
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1, kValNameMultiStr, &result));
- EXPECT_EQ(result.size(), 1);
- EXPECT_STREQ(result[0].c_str(), L"678");
-
- // Run the following test only in dev machine
- // This is because the build machine might not have admin privilege
-#ifdef IS_PRIVATE_BUILD
- // get a temp file name
- wchar_t temp_path[MAX_PATH] = {0};
- EXPECT_LT(::GetTempPath(ARRAY_SIZE(temp_path), temp_path),
- static_cast<DWORD>(ARRAY_SIZE(temp_path)));
- wchar_t temp_file[MAX_PATH] = {0};
- EXPECT_NE(::GetTempFileName(temp_path, L"rkut_",
- ::GetTickCount(), temp_file), 0);
-
- // test save
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1Subkey, kValNameInt, kIntVal));
- EXPECT_SUCCEEDED(RegKey::SetValue(kFullRkey1Subkey, kValNameInt64, kIntVal64));
- EXPECT_SUCCEEDED(RegKey::Save(kFullRkey1Subkey, temp_file));
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1Subkey, kValNameInt));
- EXPECT_SUCCEEDED(RegKey::DeleteValue(kFullRkey1Subkey, kValNameInt64));
-
- // test restore
- EXPECT_SUCCEEDED(RegKey::Restore(kFullRkey1Subkey, temp_file));
- int_val = 0;
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1Subkey, kValNameInt, &int_val));
- EXPECT_EQ(int_val, kIntVal);
- int64_val = 0;
- EXPECT_SUCCEEDED(RegKey::GetValue(kFullRkey1Subkey,
- kValNameInt64,
- &int64_val));
- EXPECT_EQ(int64_val, kIntVal64);
-
- // delete the temp file
- EXPECT_EQ(TRUE, ::DeleteFile(temp_file));
-#endif
-
- // whack the whole key
- EXPECT_SUCCEEDED(RegKey::DeleteKey(kFullRkey1));
-}
-
-} // namespace talk_base
diff --git a/base/win32securityerrors.cc b/base/win32securityerrors.cc
deleted file mode 100644
index 50f4f66..0000000
--- a/base/win32securityerrors.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/win32.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-
-extern const ConstantLabel SECURITY_ERRORS[];
-
-const ConstantLabel SECURITY_ERRORS[] = {
- KLABEL(SEC_I_COMPLETE_AND_CONTINUE),
- KLABEL(SEC_I_COMPLETE_NEEDED),
- KLABEL(SEC_I_CONTEXT_EXPIRED),
- KLABEL(SEC_I_CONTINUE_NEEDED),
- KLABEL(SEC_I_INCOMPLETE_CREDENTIALS),
- KLABEL(SEC_I_RENEGOTIATE),
- KLABEL(SEC_E_CERT_EXPIRED),
- KLABEL(SEC_E_INCOMPLETE_MESSAGE),
- KLABEL(SEC_E_INSUFFICIENT_MEMORY),
- KLABEL(SEC_E_INTERNAL_ERROR),
- KLABEL(SEC_E_INVALID_HANDLE),
- KLABEL(SEC_E_INVALID_TOKEN),
- KLABEL(SEC_E_LOGON_DENIED),
- KLABEL(SEC_E_NO_AUTHENTICATING_AUTHORITY),
- KLABEL(SEC_E_NO_CREDENTIALS),
- KLABEL(SEC_E_NOT_OWNER),
- KLABEL(SEC_E_OK),
- KLABEL(SEC_E_SECPKG_NOT_FOUND),
- KLABEL(SEC_E_TARGET_UNKNOWN),
- KLABEL(SEC_E_UNKNOWN_CREDENTIALS),
- KLABEL(SEC_E_UNSUPPORTED_FUNCTION),
- KLABEL(SEC_E_UNTRUSTED_ROOT),
- KLABEL(SEC_E_WRONG_PRINCIPAL),
- LASTLABEL
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/win32socketinit.cc b/base/win32socketinit.cc
deleted file mode 100644
index f6ac666..0000000
--- a/base/win32socketinit.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/win32socketinit.h"
-
-#include "talk/base/win32.h"
-
-namespace talk_base {
-
-// Please don't remove this function.
-void EnsureWinsockInit() {
- // The default implementation uses a global initializer, so WSAStartup
- // happens at module load time. Thus we don't need to do anything here.
- // The hook is provided so that a client that statically links with
- // libjingle can override it, to provide its own initialization.
-}
-
-#ifdef WIN32
-class WinsockInitializer {
- public:
- WinsockInitializer() {
- WSADATA wsaData;
- WORD wVersionRequested = MAKEWORD(1, 0);
- err_ = WSAStartup(wVersionRequested, &wsaData);
- }
- ~WinsockInitializer() {
- if (!err_)
- WSACleanup();
- }
- int error() {
- return err_;
- }
- private:
- int err_;
-};
-WinsockInitializer g_winsockinit;
-#endif
-
-} // namespace talk_base
diff --git a/base/win32socketinit.h b/base/win32socketinit.h
deleted file mode 100644
index f56b7ff..0000000
--- a/base/win32socketinit.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WIN32SOCKETINIT_H_
-#define TALK_BASE_WIN32SOCKETINIT_H_
-
-namespace talk_base {
-
-void EnsureWinsockInit();
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WIN32SOCKETINIT_H_
diff --git a/base/win32socketserver.cc b/base/win32socketserver.cc
deleted file mode 100644
index 9566669..0000000
--- a/base/win32socketserver.cc
+++ /dev/null
@@ -1,867 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/win32socketserver.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/winping.h"
-#include "talk/base/win32window.h"
-#include <ws2tcpip.h> // NOLINT
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// Win32Socket
-///////////////////////////////////////////////////////////////////////////////
-
-// TODO: Move this to a common place where PhysicalSocketServer can
-// share it.
-// Standard MTUs
-static const uint16 PACKET_MAXIMUMS[] = {
- 65535, // Theoretical maximum, Hyperchannel
- 32000, // Nothing
- 17914, // 16Mb IBM Token Ring
- 8166, // IEEE 802.4
- // 4464 // IEEE 802.5 (4Mb max)
- 4352, // FDDI
- // 2048, // Wideband Network
- 2002, // IEEE 802.5 (4Mb recommended)
- // 1536, // Expermental Ethernet Networks
- // 1500, // Ethernet, Point-to-Point (default)
- 1492, // IEEE 802.3
- 1006, // SLIP, ARPANET
- // 576, // X.25 Networks
- // 544, // DEC IP Portal
- // 512, // NETBIOS
- 508, // IEEE 802/Source-Rt Bridge, ARCNET
- 296, // Point-to-Point (low delay)
- 68, // Official minimum
- 0, // End of list marker
-};
-
-static const int IP_HEADER_SIZE = 20u;
-static const int ICMP_HEADER_SIZE = 8u;
-static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
-
-// TODO: Enable for production builds also? Use FormatMessage?
-#ifdef _DEBUG
-LPCSTR WSAErrorToString(int error, LPCSTR *description_result) {
- LPCSTR string = "Unspecified";
- LPCSTR description = "Unspecified description";
- switch (error) {
- case ERROR_SUCCESS:
- string = "SUCCESS";
- description = "Operation succeeded";
- break;
- case WSAEWOULDBLOCK:
- string = "WSAEWOULDBLOCK";
- description = "Using a non-blocking socket, will notify later";
- break;
- case WSAEACCES:
- string = "WSAEACCES";
- description = "Access denied, or sharing violation";
- break;
- case WSAEADDRNOTAVAIL:
- string = "WSAEADDRNOTAVAIL";
- description = "Address is not valid in this context";
- break;
- case WSAENETDOWN:
- string = "WSAENETDOWN";
- description = "Network is down";
- break;
- case WSAENETUNREACH:
- string = "WSAENETUNREACH";
- description = "Network is up, but unreachable";
- break;
- case WSAENETRESET:
- string = "WSANETRESET";
- description = "Connection has been reset due to keep-alive activity";
- break;
- case WSAECONNABORTED:
- string = "WSAECONNABORTED";
- description = "Aborted by host";
- break;
- case WSAECONNRESET:
- string = "WSAECONNRESET";
- description = "Connection reset by host";
- break;
- case WSAETIMEDOUT:
- string = "WSAETIMEDOUT";
- description = "Timed out, host failed to respond";
- break;
- case WSAECONNREFUSED:
- string = "WSAECONNREFUSED";
- description = "Host actively refused connection";
- break;
- case WSAEHOSTDOWN:
- string = "WSAEHOSTDOWN";
- description = "Host is down";
- break;
- case WSAEHOSTUNREACH:
- string = "WSAEHOSTUNREACH";
- description = "Host is unreachable";
- break;
- case WSAHOST_NOT_FOUND:
- string = "WSAHOST_NOT_FOUND";
- description = "No such host is known";
- break;
- }
- if (description_result) {
- *description_result = description;
- }
- return string;
-}
-
-void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {
- LPCSTR description_string;
- LPCSTR error_string = WSAErrorToString(error, &description_string);
- LOG(LS_INFO) << context << " = " << error
- << " (" << error_string << ":" << description_string << ") ["
- << address.ToString() << "]";
-}
-#else
-void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {}
-#endif
-
-/////////////////////////////////////////////////////////////////////////////
-// Win32Socket::EventSink
-/////////////////////////////////////////////////////////////////////////////
-
-#define WM_SOCKETNOTIFY (WM_USER + 50)
-#define WM_DNSNOTIFY (WM_USER + 51)
-
-struct Win32Socket::DnsLookup {
- HANDLE handle;
- uint16 port;
- char buffer[MAXGETHOSTSTRUCT];
-};
-
-class Win32Socket::EventSink : public Win32Window {
- public:
- explicit EventSink(Win32Socket * parent) : parent_(parent) { }
-
- void Dispose();
-
- virtual bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
- LRESULT& result);
- virtual void OnNcDestroy();
-
- private:
- bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
- bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result);
-
- Win32Socket * parent_;
-};
-
-void Win32Socket::EventSink::Dispose() {
- parent_ = NULL;
- if (::IsWindow(handle())) {
- ::DestroyWindow(handle());
- } else {
- delete this;
- }
-}
-
-bool Win32Socket::EventSink::OnMessage(UINT uMsg, WPARAM wParam,
- LPARAM lParam, LRESULT& result) {
- switch (uMsg) {
- case WM_SOCKETNOTIFY:
- case WM_TIMER:
- return OnSocketNotify(uMsg, wParam, lParam, result);
- case WM_DNSNOTIFY:
- return OnDnsNotify(wParam, lParam, result);
- }
- return false;
-}
-
-bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg, WPARAM wParam,
- LPARAM lParam, LRESULT& result) {
- result = 0;
-
- int wsa_event = WSAGETSELECTEVENT(lParam);
- int wsa_error = WSAGETSELECTERROR(lParam);
-
- // Treat connect timeouts as close notifications
- if (uMsg == WM_TIMER) {
- wsa_event = FD_CLOSE;
- wsa_error = WSAETIMEDOUT;
- }
-
- if (parent_)
- parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error);
- return true;
-}
-
-bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam, LPARAM lParam,
- LRESULT& result) {
- result = 0;
-
- int error = WSAGETASYNCERROR(lParam);
- if (parent_)
- parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error);
- return true;
-}
-
-void Win32Socket::EventSink::OnNcDestroy() {
- if (parent_) {
- LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink"
- " hasn't yet been disposed.";
- } else {
- delete this;
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////
-// Win32Socket
-/////////////////////////////////////////////////////////////////////////////
-
-Win32Socket::Win32Socket()
- : socket_(INVALID_SOCKET), error_(0), state_(CS_CLOSED), connect_time_(0),
- closing_(false), close_error_(0), sink_(NULL), dns_(NULL) {
-}
-
-Win32Socket::~Win32Socket() {
- Close();
-}
-
-bool Win32Socket::CreateT(int family, int type) {
- Close();
- int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP;
- socket_ = ::WSASocket(family, type, proto, NULL, NULL, 0);
- if (socket_ == INVALID_SOCKET) {
- UpdateLastError();
- return false;
- }
- if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) {
- return false;
- }
- return true;
-}
-
-int Win32Socket::Attach(SOCKET s) {
- ASSERT(socket_ == INVALID_SOCKET);
- if (socket_ != INVALID_SOCKET)
- return SOCKET_ERROR;
-
- ASSERT(s != INVALID_SOCKET);
- if (s == INVALID_SOCKET)
- return SOCKET_ERROR;
-
- socket_ = s;
- state_ = CS_CONNECTED;
-
- if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE))
- return SOCKET_ERROR;
-
- return 0;
-}
-
-void Win32Socket::SetTimeout(int ms) {
- if (sink_)
- ::SetTimer(sink_->handle(), 1, ms, 0);
-}
-
-SocketAddress Win32Socket::GetLocalAddress() const {
- sockaddr_storage addr = {0};
- socklen_t addrlen = sizeof(addr);
- int result = ::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr),
- &addrlen);
- SocketAddress address;
- if (result >= 0) {
- SocketAddressFromSockAddrStorage(addr, &address);
- } else {
- LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
- << socket_;
- }
- return address;
-}
-
-SocketAddress Win32Socket::GetRemoteAddress() const {
- sockaddr_storage addr = {0};
- socklen_t addrlen = sizeof(addr);
- int result = ::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr),
- &addrlen);
- SocketAddress address;
- if (result >= 0) {
- SocketAddressFromSockAddrStorage(addr, &address);
- } else {
- LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
- << socket_;
- }
- return address;
-}
-
-int Win32Socket::Bind(const SocketAddress& addr) {
- ASSERT(socket_ != INVALID_SOCKET);
- if (socket_ == INVALID_SOCKET)
- return SOCKET_ERROR;
-
- sockaddr_storage saddr;
- size_t len = addr.ToSockAddrStorage(&saddr);
- int err = ::bind(socket_,
- reinterpret_cast<sockaddr*>(&saddr),
- static_cast<int>(len));
- UpdateLastError();
- return err;
-}
-
-int Win32Socket::Connect(const SocketAddress& addr) {
- if (state_ != CS_CLOSED) {
- SetError(EALREADY);
- return SOCKET_ERROR;
- }
-
- if (!addr.IsUnresolvedIP()) {
- return DoConnect(addr);
- }
-
- LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")";
- DnsLookup * dns = new DnsLookup;
- if (!sink_) {
- // Explicitly create the sink ourselves here; we can't rely on SetAsync
- // because we don't have a socket_ yet.
- CreateSink();
- }
- // TODO: Replace with IPv6 compatible lookup.
- dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY,
- addr.hostname().c_str(), dns->buffer,
- sizeof(dns->buffer));
-
- if (!dns->handle) {
- LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError();
- delete dns;
- UpdateLastError();
- Close();
- return SOCKET_ERROR;
- }
-
- dns->port = addr.port();
- dns_ = dns;
- state_ = CS_CONNECTING;
- return 0;
-}
-
-int Win32Socket::DoConnect(const SocketAddress& addr) {
- if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) {
- return SOCKET_ERROR;
- }
- if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) {
- return SOCKET_ERROR;
- }
-
- sockaddr_storage saddr = {0};
- size_t len = addr.ToSockAddrStorage(&saddr);
- connect_time_ = Time();
- int result = connect(socket_,
- reinterpret_cast<SOCKADDR*>(&saddr),
- static_cast<int>(len));
- if (result != SOCKET_ERROR) {
- state_ = CS_CONNECTED;
- } else {
- int code = WSAGetLastError();
- if (code == WSAEWOULDBLOCK) {
- state_ = CS_CONNECTING;
- } else {
- ReportWSAError("WSAAsync:connect", code, addr);
- error_ = code;
- Close();
- return SOCKET_ERROR;
- }
- }
- addr_ = addr;
-
- return 0;
-}
-
-int Win32Socket::GetError() const {
- return error_;
-}
-
-void Win32Socket::SetError(int error) {
- error_ = error;
-}
-
-Socket::ConnState Win32Socket::GetState() const {
- return state_;
-}
-
-int Win32Socket::GetOption(Option opt, int* value) {
- int slevel;
- int sopt;
- if (TranslateOption(opt, &slevel, &sopt) == -1)
- return -1;
-
- char* p = reinterpret_cast<char*>(value);
- int optlen = sizeof(value);
- return ::getsockopt(socket_, slevel, sopt, p, &optlen);
-}
-
-int Win32Socket::SetOption(Option opt, int value) {
- int slevel;
- int sopt;
- if (TranslateOption(opt, &slevel, &sopt) == -1)
- return -1;
-
- const char* p = reinterpret_cast<const char*>(&value);
- return ::setsockopt(socket_, slevel, sopt, p, sizeof(value));
-}
-
-int Win32Socket::Send(const void* buffer, size_t length) {
- int sent = ::send(socket_,
- reinterpret_cast<const char*>(buffer),
- static_cast<int>(length),
- 0);
- UpdateLastError();
- return sent;
-}
-
-int Win32Socket::SendTo(const void* buffer, size_t length,
- const SocketAddress& addr) {
- sockaddr_storage saddr;
- size_t addr_len = addr.ToSockAddrStorage(&saddr);
- int sent = ::sendto(socket_, reinterpret_cast<const char*>(buffer),
- static_cast<int>(length), 0,
- reinterpret_cast<sockaddr*>(&saddr),
- static_cast<int>(addr_len));
- UpdateLastError();
- return sent;
-}
-
-int Win32Socket::Recv(void* buffer, size_t length) {
- int received = ::recv(socket_, static_cast<char*>(buffer),
- static_cast<int>(length), 0);
- UpdateLastError();
- if (closing_ && received <= static_cast<int>(length))
- PostClosed();
- return received;
-}
-
-int Win32Socket::RecvFrom(void* buffer, size_t length,
- SocketAddress* out_addr) {
- sockaddr_storage saddr;
- socklen_t addr_len = sizeof(saddr);
- int received = ::recvfrom(socket_, static_cast<char*>(buffer),
- static_cast<int>(length), 0,
- reinterpret_cast<sockaddr*>(&saddr), &addr_len);
- UpdateLastError();
- if (received != SOCKET_ERROR)
- SocketAddressFromSockAddrStorage(saddr, out_addr);
- if (closing_ && received <= static_cast<int>(length))
- PostClosed();
- return received;
-}
-
-int Win32Socket::Listen(int backlog) {
- int err = ::listen(socket_, backlog);
- if (!SetAsync(FD_ACCEPT))
- return SOCKET_ERROR;
-
- UpdateLastError();
- if (err == 0)
- state_ = CS_CONNECTING;
- return err;
-}
-
-Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) {
- sockaddr_storage saddr;
- socklen_t addr_len = sizeof(saddr);
- SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
- UpdateLastError();
- if (s == INVALID_SOCKET)
- return NULL;
- if (out_addr)
- SocketAddressFromSockAddrStorage(saddr, out_addr);
- Win32Socket* socket = new Win32Socket;
- if (0 == socket->Attach(s))
- return socket;
- delete socket;
- return NULL;
-}
-
-int Win32Socket::Close() {
- int err = 0;
- if (socket_ != INVALID_SOCKET) {
- err = ::closesocket(socket_);
- socket_ = INVALID_SOCKET;
- closing_ = false;
- close_error_ = 0;
- UpdateLastError();
- }
- if (dns_) {
- WSACancelAsyncRequest(dns_->handle);
- delete dns_;
- dns_ = NULL;
- }
- if (sink_) {
- sink_->Dispose();
- sink_ = NULL;
- }
- addr_.Clear();
- state_ = CS_CLOSED;
- return err;
-}
-
-int Win32Socket::EstimateMTU(uint16* mtu) {
- SocketAddress addr = GetRemoteAddress();
- if (addr.IsAny()) {
- error_ = ENOTCONN;
- return -1;
- }
-
- WinPing ping;
- if (!ping.IsValid()) {
- error_ = EINVAL; // can't think of a better error ID
- return -1;
- }
-
- for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
- int32 size = PACKET_MAXIMUMS[level] - IP_HEADER_SIZE - ICMP_HEADER_SIZE;
- WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
- ICMP_PING_TIMEOUT_MILLIS, 1, false);
- if (result == WinPing::PING_FAIL) {
- error_ = EINVAL; // can't think of a better error ID
- return -1;
- }
- if (result != WinPing::PING_TOO_LARGE) {
- *mtu = PACKET_MAXIMUMS[level];
- return 0;
- }
- }
-
- ASSERT(false);
- return 0;
-}
-
-void Win32Socket::CreateSink() {
- ASSERT(NULL == sink_);
-
- // Create window
- sink_ = new EventSink(this);
- sink_->Create(NULL, L"EventSink", 0, 0, 0, 0, 10, 10);
-}
-
-bool Win32Socket::SetAsync(int events) {
- if (NULL == sink_) {
- CreateSink();
- ASSERT(NULL != sink_);
- }
-
- // start the async select
- if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events)
- == SOCKET_ERROR) {
- UpdateLastError();
- Close();
- return false;
- }
-
- return true;
-}
-
-bool Win32Socket::HandleClosed(int close_error) {
- // WM_CLOSE will be received before all data has been read, so we need to
- // hold on to it until the read buffer has been drained.
- char ch;
- closing_ = true;
- close_error_ = close_error;
- return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0);
-}
-
-void Win32Socket::PostClosed() {
- // If we see that the buffer is indeed drained, then send the close.
- closing_ = false;
- ::PostMessage(sink_->handle(), WM_SOCKETNOTIFY,
- socket_, WSAMAKESELECTREPLY(FD_CLOSE, close_error_));
-}
-
-void Win32Socket::UpdateLastError() {
- error_ = WSAGetLastError();
-}
-
-int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) {
- switch (opt) {
- case OPT_DONTFRAGMENT:
- *slevel = IPPROTO_IP;
- *sopt = IP_DONTFRAGMENT;
- break;
- case OPT_RCVBUF:
- *slevel = SOL_SOCKET;
- *sopt = SO_RCVBUF;
- break;
- case OPT_SNDBUF:
- *slevel = SOL_SOCKET;
- *sopt = SO_SNDBUF;
- break;
- case OPT_NODELAY:
- *slevel = IPPROTO_TCP;
- *sopt = TCP_NODELAY;
- break;
- case OPT_DSCP:
- LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
- return -1;
- default:
- ASSERT(false);
- return -1;
- }
- return 0;
-}
-
-void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) {
- // Ignore events if we're already closed.
- if (socket != socket_)
- return;
-
- error_ = error;
- switch (event) {
- case FD_CONNECT:
- if (error != ERROR_SUCCESS) {
- ReportWSAError("WSAAsync:connect notify", error, addr_);
-#ifdef _DEBUG
- int32 duration = TimeSince(connect_time_);
- LOG(LS_INFO) << "WSAAsync:connect error (" << duration
- << " ms), faking close";
-#endif
- state_ = CS_CLOSED;
- // If you get an error connecting, close doesn't really do anything
- // and it certainly doesn't send back any close notification, but
- // we really only maintain a few states, so it is easiest to get
- // back into a known state by pretending that a close happened, even
- // though the connect event never did occur.
- SignalCloseEvent(this, error);
- } else {
-#ifdef _DEBUG
- int32 duration = TimeSince(connect_time_);
- LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)";
-#endif
- state_ = CS_CONNECTED;
- SignalConnectEvent(this);
- }
- break;
-
- case FD_ACCEPT:
- case FD_READ:
- if (error != ERROR_SUCCESS) {
- ReportWSAError("WSAAsync:read notify", error, addr_);
- } else {
- SignalReadEvent(this);
- }
- break;
-
- case FD_WRITE:
- if (error != ERROR_SUCCESS) {
- ReportWSAError("WSAAsync:write notify", error, addr_);
- } else {
- SignalWriteEvent(this);
- }
- break;
-
- case FD_CLOSE:
- if (HandleClosed(error)) {
- ReportWSAError("WSAAsync:close notify", error, addr_);
- state_ = CS_CLOSED;
- SignalCloseEvent(this, error);
- }
- break;
- }
-}
-
-void Win32Socket::OnDnsNotify(HANDLE task, int error) {
- if (!dns_ || dns_->handle != task)
- return;
-
- uint32 ip = 0;
- if (error == 0) {
- hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer);
- uint32 net_ip = *reinterpret_cast<uint32*>(pHost->h_addr_list[0]);
- ip = NetworkToHost32(net_ip);
- }
-
- LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString()
- << ", " << error << ")";
-
- if (error == 0) {
- SocketAddress address(ip, dns_->port);
- error = DoConnect(address);
- } else {
- Close();
- }
-
- if (error) {
- error_ = error;
- SignalCloseEvent(this, error_);
- } else {
- delete dns_;
- dns_ = NULL;
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// Win32SocketServer
-// Provides cricket base services on top of a win32 gui thread
-///////////////////////////////////////////////////////////////////////////////
-
-static UINT s_wm_wakeup_id = 0;
-const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window";
-
-Win32SocketServer::Win32SocketServer(MessageQueue* message_queue)
- : message_queue_(message_queue),
- wnd_(this),
- posted_(false),
- hdlg_(NULL) {
- if (s_wm_wakeup_id == 0)
- s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP");
- if (!wnd_.Create(NULL, kWindowName, 0, 0, 0, 0, 0, 0)) {
- LOG_GLE(LS_ERROR) << "Failed to create message window.";
- }
-}
-
-Win32SocketServer::~Win32SocketServer() {
- if (wnd_.handle() != NULL) {
- KillTimer(wnd_.handle(), 1);
- wnd_.Destroy();
- }
-}
-
-Socket* Win32SocketServer::CreateSocket(int type) {
- return CreateSocket(AF_INET, type);
-}
-
-Socket* Win32SocketServer::CreateSocket(int family, int type) {
- return CreateAsyncSocket(family, type);
-}
-
-AsyncSocket* Win32SocketServer::CreateAsyncSocket(int type) {
- return CreateAsyncSocket(AF_INET, type);
-}
-
-AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) {
- Win32Socket* socket = new Win32Socket;
- if (socket->CreateT(family, type)) {
- return socket;
- }
- delete socket;
- return NULL;
-}
-
-void Win32SocketServer::SetMessageQueue(MessageQueue* queue) {
- message_queue_ = queue;
-}
-
-bool Win32SocketServer::Wait(int cms, bool process_io) {
- BOOL b;
- if (process_io) {
- // Spin the Win32 message pump at least once, and as long as requested.
- // This is the Thread::ProcessMessages case.
- uint32 start = Time();
- do {
- MSG msg;
- SetTimer(wnd_.handle(), 0, cms, NULL);
- // Get the next available message. If we have a modeless dialog, give
- // give the message to IsDialogMessage, which will return true if it
- // was a message for the dialog that it handled internally.
- // Otherwise, dispatch as usual via Translate/DispatchMessage.
- b = GetMessage(&msg, NULL, 0, 0);
- if (b == -1) {
- LOG_GLE(LS_ERROR) << "GetMessage failed.";
- return false;
- } else if(b) {
- if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- }
- KillTimer(wnd_.handle(), 0);
- } while (b && TimeSince(start) < cms);
- } else if (cms != 0) {
- // Sit and wait forever for a WakeUp. This is the Thread::Send case.
- ASSERT(cms == -1);
- MSG msg;
- b = GetMessage(&msg, NULL, s_wm_wakeup_id, s_wm_wakeup_id);
- {
- CritScope scope(&cs_);
- posted_ = false;
- }
- } else {
- // No-op (cms == 0 && !process_io). This is the Pump case.
- b = TRUE;
- }
- return (b != FALSE);
-}
-
-void Win32SocketServer::WakeUp() {
- if (wnd_.handle()) {
- // Set the "message pending" flag, if not already set.
- {
- CritScope scope(&cs_);
- if (posted_)
- return;
- posted_ = true;
- }
-
- PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0);
- }
-}
-
-void Win32SocketServer::Pump() {
- // Clear the "message pending" flag.
- {
- CritScope scope(&cs_);
- posted_ = false;
- }
-
- // Dispatch all the messages that are currently in our queue. If new messages
- // are posted during the dispatch, they will be handled in the next Pump.
- // We use max(1, ...) to make sure we try to dispatch at least once, since
- // this allow us to process "sent" messages, not included in the size() count.
- Message msg;
- for (size_t max_messages_to_process = _max<size_t>(1, message_queue_->size());
- max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false);
- --max_messages_to_process) {
- message_queue_->Dispatch(&msg);
- }
-
- // Anything remaining?
- int delay = message_queue_->GetDelay();
- if (delay == -1) {
- KillTimer(wnd_.handle(), 1);
- } else {
- SetTimer(wnd_.handle(), 1, delay, NULL);
- }
-}
-
-bool Win32SocketServer::MessageWindow::OnMessage(UINT wm, WPARAM wp,
- LPARAM lp, LRESULT& lr) {
- bool handled = false;
- if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) {
- ss_->Pump();
- lr = 0;
- handled = true;
- }
- return handled;
-}
-
-} // namespace talk_base
diff --git a/base/win32socketserver.h b/base/win32socketserver.h
deleted file mode 100644
index 3459879..0000000
--- a/base/win32socketserver.h
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WIN32SOCKETSERVER_H_
-#define TALK_BASE_WIN32SOCKETSERVER_H_
-
-#ifdef WIN32
-#include "talk/base/asyncsocket.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/socketserver.h"
-#include "talk/base/socketfactory.h"
-#include "talk/base/socket.h"
-#include "talk/base/thread.h"
-#include "talk/base/win32window.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// Win32Socket
-///////////////////////////////////////////////////////////////////////////////
-
-class Win32Socket : public AsyncSocket {
- public:
- Win32Socket();
- virtual ~Win32Socket();
-
- bool CreateT(int family, int type);
-
- int Attach(SOCKET s);
- void SetTimeout(int ms);
-
- // AsyncSocket Interface
- virtual SocketAddress GetLocalAddress() const;
- virtual SocketAddress GetRemoteAddress() const;
- virtual int Bind(const SocketAddress& addr);
- virtual int Connect(const SocketAddress& addr);
- virtual int Send(const void *buffer, size_t length);
- virtual int SendTo(const void *buffer, size_t length, const SocketAddress& addr);
- virtual int Recv(void *buffer, size_t length);
- virtual int RecvFrom(void *buffer, size_t length, SocketAddress *out_addr);
- virtual int Listen(int backlog);
- virtual Win32Socket *Accept(SocketAddress *out_addr);
- virtual int Close();
- virtual int GetError() const;
- virtual void SetError(int error);
- virtual ConnState GetState() const;
- virtual int EstimateMTU(uint16* mtu);
- virtual int GetOption(Option opt, int* value);
- virtual int SetOption(Option opt, int value);
-
- private:
- void CreateSink();
- bool SetAsync(int events);
- int DoConnect(const SocketAddress& addr);
- bool HandleClosed(int close_error);
- void PostClosed();
- void UpdateLastError();
- static int TranslateOption(Option opt, int* slevel, int* sopt);
-
- void OnSocketNotify(SOCKET socket, int event, int error);
- void OnDnsNotify(HANDLE task, int error);
-
- SOCKET socket_;
- int error_;
- ConnState state_;
- SocketAddress addr_; // address that we connected to (see DoConnect)
- uint32 connect_time_;
- bool closing_;
- int close_error_;
-
- class EventSink;
- friend class EventSink;
- EventSink * sink_;
-
- struct DnsLookup;
- DnsLookup * dns_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Win32SocketServer
-///////////////////////////////////////////////////////////////////////////////
-
-class Win32SocketServer : public SocketServer {
- public:
- explicit Win32SocketServer(MessageQueue* message_queue);
- virtual ~Win32SocketServer();
-
- void set_modeless_dialog(HWND hdlg) {
- hdlg_ = hdlg;
- }
-
- // SocketServer Interface
- virtual Socket* CreateSocket(int type);
- virtual Socket* CreateSocket(int family, int type);
-
- virtual AsyncSocket* CreateAsyncSocket(int type);
- virtual AsyncSocket* CreateAsyncSocket(int family, int type);
-
- virtual void SetMessageQueue(MessageQueue* queue);
- virtual bool Wait(int cms, bool process_io);
- virtual void WakeUp();
-
- void Pump();
-
- HWND handle() { return wnd_.handle(); }
-
- private:
- class MessageWindow : public Win32Window {
- public:
- explicit MessageWindow(Win32SocketServer* ss) : ss_(ss) {}
- private:
- virtual bool OnMessage(UINT msg, WPARAM wp, LPARAM lp, LRESULT& result);
- Win32SocketServer* ss_;
- };
-
- static const TCHAR kWindowName[];
- MessageQueue *message_queue_;
- MessageWindow wnd_;
- CriticalSection cs_;
- bool posted_;
- HWND hdlg_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Win32Thread. Automatically pumps Windows messages.
-///////////////////////////////////////////////////////////////////////////////
-
-class Win32Thread : public Thread {
- public:
- Win32Thread() : ss_(this), id_(0) {
- set_socketserver(&ss_);
- }
- virtual ~Win32Thread() {
- Stop();
- set_socketserver(NULL);
- }
- virtual void Run() {
- id_ = GetCurrentThreadId();
- Thread::Run();
- id_ = 0;
- }
- virtual void Quit() {
- PostThreadMessage(id_, WM_QUIT, 0, 0);
- }
- private:
- Win32SocketServer ss_;
- DWORD id_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // WIN32
-
-#endif // TALK_BASE_WIN32SOCKETSERVER_H_
diff --git a/base/win32socketserver_unittest.cc b/base/win32socketserver_unittest.cc
deleted file mode 100644
index f78a444..0000000
--- a/base/win32socketserver_unittest.cc
+++ /dev/null
@@ -1,151 +0,0 @@
-// Copyright 2009 Google Inc. All Rights Reserved.
-
-
-#include "talk/base/gunit.h"
-#include "talk/base/socket_unittest.h"
-#include "talk/base/thread.h"
-#include "talk/base/win32socketserver.h"
-
-namespace talk_base {
-
-// Test that Win32SocketServer::Wait works as expected.
-TEST(Win32SocketServerTest, TestWait) {
- Win32SocketServer server(NULL);
- uint32 start = Time();
- server.Wait(1000, true);
- EXPECT_GE(TimeSince(start), 1000);
-}
-
-// Test that Win32Socket::Pump does not touch general Windows messages.
-TEST(Win32SocketServerTest, TestPump) {
- Win32SocketServer server(NULL);
- SocketServerScope scope(&server);
- EXPECT_EQ(TRUE, PostMessage(NULL, WM_USER, 999, 0));
- server.Pump();
- MSG msg;
- EXPECT_EQ(TRUE, PeekMessage(&msg, NULL, WM_USER, 0, PM_REMOVE));
- EXPECT_EQ(WM_USER, msg.message);
- EXPECT_EQ(999, msg.wParam);
-}
-
-// Test that Win32Socket passes all the generic Socket tests.
-class Win32SocketTest : public SocketTest {
- protected:
- Win32SocketTest() : server_(NULL), scope_(&server_) {}
- Win32SocketServer server_;
- SocketServerScope scope_;
-};
-
-TEST_F(Win32SocketTest, TestConnectIPv4) {
- SocketTest::TestConnectIPv4();
-}
-
-TEST_F(Win32SocketTest, TestConnectIPv6) {
- SocketTest::TestConnectIPv6();
-}
-
-TEST_F(Win32SocketTest, TestConnectWithDnsLookupIPv4) {
- SocketTest::TestConnectWithDnsLookupIPv4();
-}
-
-TEST_F(Win32SocketTest, TestConnectWithDnsLookupIPv6) {
- SocketTest::TestConnectWithDnsLookupIPv6();
-}
-
-TEST_F(Win32SocketTest, TestConnectFailIPv4) {
- SocketTest::TestConnectFailIPv4();
-}
-
-TEST_F(Win32SocketTest, TestConnectFailIPv6) {
- SocketTest::TestConnectFailIPv6();
-}
-
-TEST_F(Win32SocketTest, TestConnectWithDnsLookupFailIPv4) {
- SocketTest::TestConnectWithDnsLookupFailIPv4();
-}
-
-TEST_F(Win32SocketTest, TestConnectWithDnsLookupFailIPv6) {
- SocketTest::TestConnectWithDnsLookupFailIPv6();
-}
-
-TEST_F(Win32SocketTest, TestConnectWithClosedSocketIPv4) {
- SocketTest::TestConnectWithClosedSocketIPv4();
-}
-
-TEST_F(Win32SocketTest, TestConnectWithClosedSocketIPv6) {
- SocketTest::TestConnectWithClosedSocketIPv6();
-}
-
-TEST_F(Win32SocketTest, TestConnectWhileNotClosedIPv4) {
- SocketTest::TestConnectWhileNotClosedIPv4();
-}
-
-TEST_F(Win32SocketTest, TestConnectWhileNotClosedIPv6) {
- SocketTest::TestConnectWhileNotClosedIPv6();
-}
-
-TEST_F(Win32SocketTest, TestServerCloseDuringConnectIPv4) {
- SocketTest::TestServerCloseDuringConnectIPv4();
-}
-
-TEST_F(Win32SocketTest, TestServerCloseDuringConnectIPv6) {
- SocketTest::TestServerCloseDuringConnectIPv6();
-}
-
-TEST_F(Win32SocketTest, TestClientCloseDuringConnectIPv4) {
- SocketTest::TestClientCloseDuringConnectIPv4();
-}
-
-TEST_F(Win32SocketTest, TestClientCloseDuringConnectIPv6) {
- SocketTest::TestClientCloseDuringConnectIPv6();
-}
-
-TEST_F(Win32SocketTest, TestServerCloseIPv4) {
- SocketTest::TestServerCloseIPv4();
-}
-
-TEST_F(Win32SocketTest, TestServerCloseIPv6) {
- SocketTest::TestServerCloseIPv6();
-}
-
-TEST_F(Win32SocketTest, TestCloseInClosedCallbackIPv4) {
- SocketTest::TestCloseInClosedCallbackIPv4();
-}
-
-TEST_F(Win32SocketTest, TestCloseInClosedCallbackIPv6) {
- SocketTest::TestCloseInClosedCallbackIPv6();
-}
-
-TEST_F(Win32SocketTest, TestSocketServerWaitIPv4) {
- SocketTest::TestSocketServerWaitIPv4();
-}
-
-TEST_F(Win32SocketTest, TestSocketServerWaitIPv6) {
- SocketTest::TestSocketServerWaitIPv6();
-}
-
-TEST_F(Win32SocketTest, TestTcpIPv4) {
- SocketTest::TestTcpIPv4();
-}
-
-TEST_F(Win32SocketTest, TestTcpIPv6) {
- SocketTest::TestTcpIPv6();
-}
-
-TEST_F(Win32SocketTest, TestUdpIPv4) {
- SocketTest::TestUdpIPv4();
-}
-
-TEST_F(Win32SocketTest, TestUdpIPv6) {
- SocketTest::TestUdpIPv6();
-}
-
-TEST_F(Win32SocketTest, TestGetSetOptionsIPv4) {
- SocketTest::TestGetSetOptionsIPv4();
-}
-
-TEST_F(Win32SocketTest, TestGetSetOptionsIPv6) {
- SocketTest::TestGetSetOptionsIPv6();
-}
-
-} // namespace talk_base
diff --git a/base/win32toolhelp.h b/base/win32toolhelp.h
deleted file mode 100644
index 64a191a..0000000
--- a/base/win32toolhelp.h
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved.
-
-
-#ifndef TALK_BASE_WIN32TOOLHELP_H_
-#define TALK_BASE_WIN32TOOLHELP_H_
-
-#ifndef WIN32
-#error WIN32 Only
-#endif
-
-#include "talk/base/win32.h"
-
-// Should be included first, but that causes redefinitions.
-#include <tlhelp32.h>
-
-#include "talk/base/constructormagic.h"
-
-namespace talk_base {
-
-// The toolhelp api used to enumerate processes and their modules
-// on Windows is very repetetive and clunky to use. This little
-// template wraps it to make it a little more programmer friendly.
-//
-// Traits: Traits type that adapts the enumerator to the corresponding
-// win32 toolhelp api. Each traits class need to:
-// - define the type of the enumerated data as a public symbol Type
-//
-// - implement bool First(HANDLE, T*) normally calls a
-// Xxxx32First method in the toolhelp API. Ex Process32First(...)
-//
-// - implement bool Next(HANDLE, T*) normally calls a
-// Xxxx32Next method in the toolhelp API. Ex Process32Next(...)
-//
-// - implement bool CloseHandle(HANDLE)
-//
-template<typename Traits>
-class ToolhelpEnumeratorBase {
- public:
- ToolhelpEnumeratorBase(HANDLE snapshot)
- : snapshot_(snapshot), broken_(false), first_(true) {
-
- // Clear out the Traits::Type structure instance.
- Zero(¤t_);
- }
-
- virtual ~ToolhelpEnumeratorBase() {
- Close();
- }
-
- // Moves forward to the next object using the First and Next
- // pointers. If either First or Next ever indicates an failure
- // all subsequent calls to this method will fail; the enumerator
- // object is considered broken.
- bool Next() {
- if (!Valid()) {
- return false;
- }
-
- // Move the iteration forward.
- current_.dwSize = sizeof(typename Traits::Type);
- bool incr_ok = false;
- if (first_) {
- incr_ok = Traits::First(snapshot_, ¤t_);
- first_ = false;
- } else {
- incr_ok = Traits::Next(snapshot_, ¤t_);
- }
-
- if (!incr_ok) {
- Zero(¤t_);
- broken_ = true;
- }
-
- return incr_ok;
- }
-
- const typename Traits::Type& current() const {
- return current_;
- }
-
- void Close() {
- if (snapshot_ != INVALID_HANDLE_VALUE) {
- Traits::CloseHandle(snapshot_);
- snapshot_ = INVALID_HANDLE_VALUE;
- }
- }
-
- private:
- // Checks the state of the snapshot handle.
- bool Valid() {
- return snapshot_ != INVALID_HANDLE_VALUE && !broken_;
- }
-
- static void Zero(typename Traits::Type* buff) {
- ZeroMemory(buff, sizeof(typename Traits::Type));
- }
-
- HANDLE snapshot_;
- typename Traits::Type current_;
- bool broken_;
- bool first_;
-};
-
-class ToolhelpTraits {
- public:
- static HANDLE CreateSnapshot(uint32 flags, uint32 process_id) {
- return CreateToolhelp32Snapshot(flags, process_id);
- }
-
- static bool CloseHandle(HANDLE handle) {
- return ::CloseHandle(handle) == TRUE;
- }
-};
-
-class ToolhelpProcessTraits : public ToolhelpTraits {
- public:
- typedef PROCESSENTRY32 Type;
-
- static bool First(HANDLE handle, Type* t) {
- return ::Process32First(handle, t) == TRUE;
- }
-
- static bool Next(HANDLE handle, Type* t) {
- return ::Process32Next(handle, t) == TRUE;
- }
-};
-
-class ProcessEnumerator : public ToolhelpEnumeratorBase<ToolhelpProcessTraits> {
- public:
- ProcessEnumerator()
- : ToolhelpEnumeratorBase(
- ToolhelpProcessTraits::CreateSnapshot(TH32CS_SNAPPROCESS, 0)) {
- }
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(ProcessEnumerator);
-};
-
-class ToolhelpModuleTraits : public ToolhelpTraits {
- public:
- typedef MODULEENTRY32 Type;
-
- static bool First(HANDLE handle, Type* t) {
- return ::Module32First(handle, t) == TRUE;
- }
-
- static bool Next(HANDLE handle, Type* t) {
- return ::Module32Next(handle, t) == TRUE;
- }
-};
-
-class ModuleEnumerator : public ToolhelpEnumeratorBase<ToolhelpModuleTraits> {
- public:
- explicit ModuleEnumerator(uint32 process_id)
- : ToolhelpEnumeratorBase(
- ToolhelpModuleTraits::CreateSnapshot(TH32CS_SNAPMODULE,
- process_id)) {
- }
-
- private:
- DISALLOW_EVIL_CONSTRUCTORS(ModuleEnumerator);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WIN32TOOLHELP_H_
diff --git a/base/win32toolhelp_unittest.cc b/base/win32toolhelp_unittest.cc
deleted file mode 100644
index e740345..0000000
--- a/base/win32toolhelp_unittest.cc
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/win32toolhelp.h"
-
-namespace talk_base {
-
-typedef struct {
- // Required to match the toolhelp api struct 'design'.
- DWORD dwSize;
- int a;
- uint32 b;
-} TestData;
-
-class Win32ToolhelpTest : public testing::Test {
- public:
- Win32ToolhelpTest() {
- }
-
- HANDLE AsHandle() {
- return reinterpret_cast<HANDLE>(this);
- }
-
- static Win32ToolhelpTest* AsFixture(HANDLE handle) {
- return reinterpret_cast<Win32ToolhelpTest*>(handle);
- }
-
- static bool First(HANDLE handle, TestData* d) {
- Win32ToolhelpTest* tst = Win32ToolhelpTest::AsFixture(handle);
- // This method should be called only once for every test.
- // If it is called more than once it return false which
- // should break the test.
- EXPECT_EQ(0, tst->first_called_); // Just to be safe.
- if (tst->first_called_ > 0) {
- return false;
- }
-
- *d = kTestData[0];
- tst->index_ = 1;
- ++(tst->first_called_);
- return true;
- }
-
- static bool Next(HANDLE handle, TestData* d) {
- Win32ToolhelpTest* tst = Win32ToolhelpTest::AsFixture(handle);
- ++(tst->next_called_);
-
- if (tst->index_ >= kTestDataSize) {
- return FALSE;
- }
-
- *d = kTestData[tst->index_];
- ++(tst->index_);
- return true;
- }
-
- static bool Fail(HANDLE handle, TestData* d) {
- Win32ToolhelpTest* tst = Win32ToolhelpTest::AsFixture(handle);
- ++(tst->fail_called_);
- return false;
- }
-
- static bool CloseHandle(HANDLE handle) {
- Win32ToolhelpTest* tst = Win32ToolhelpTest::AsFixture(handle);
- ++(tst->close_handle_called_);
- return true;
- }
-
- protected:
- virtual void SetUp() {
- fail_called_ = 0;
- first_called_ = 0;
- next_called_ = 0;
- close_handle_called_ = 0;
- index_ = 0;
- }
-
- static bool AllZero(const TestData& data) {
- return data.dwSize == 0 && data.a == 0 && data.b == 0;
- }
-
- static bool Equals(const TestData& expected, const TestData& actual) {
- return expected.dwSize == actual.dwSize
- && expected.a == actual.a
- && expected.b == actual.b;
- }
-
- bool CheckCallCounters(int first, int next, int fail, int close) {
- bool match = first_called_ == first && next_called_ == next
- && fail_called_ == fail && close_handle_called_ == close;
-
- if (!match) {
- LOG(LS_ERROR) << "Expected: ("
- << first << ", "
- << next << ", "
- << fail << ", "
- << close << ")";
-
- LOG(LS_ERROR) << "Actual: ("
- << first_called_ << ", "
- << next_called_ << ", "
- << fail_called_ << ", "
- << close_handle_called_ << ")";
- }
- return match;
- }
-
- static const int kTestDataSize = 3;
- static const TestData kTestData[];
- int index_;
- int first_called_;
- int fail_called_;
- int next_called_;
- int close_handle_called_;
-};
-
-const TestData Win32ToolhelpTest::kTestData[] = {
- {1, 1, 1}, {2, 2, 2}, {3, 3, 3}
-};
-
-
-class TestTraits {
- public:
- typedef TestData Type;
-
- static bool First(HANDLE handle, Type* t) {
- return Win32ToolhelpTest::First(handle, t);
- }
-
- static bool Next(HANDLE handle, Type* t) {
- return Win32ToolhelpTest::Next(handle, t);
- }
-
- static bool CloseHandle(HANDLE handle) {
- return Win32ToolhelpTest::CloseHandle(handle);
- }
-};
-
-class BadFirstTraits {
- public:
- typedef TestData Type;
-
- static bool First(HANDLE handle, Type* t) {
- return Win32ToolhelpTest::Fail(handle, t);
- }
-
- static bool Next(HANDLE handle, Type* t) {
- // This should never be called.
- ADD_FAILURE();
- return false;
- }
-
- static bool CloseHandle(HANDLE handle) {
- return Win32ToolhelpTest::CloseHandle(handle);
- }
-};
-
-class BadNextTraits {
- public:
- typedef TestData Type;
-
- static bool First(HANDLE handle, Type* t) {
- return Win32ToolhelpTest::First(handle, t);
- }
-
- static bool Next(HANDLE handle, Type* t) {
- return Win32ToolhelpTest::Fail(handle, t);
- }
-
- static bool CloseHandle(HANDLE handle) {
- return Win32ToolhelpTest::CloseHandle(handle);
- }
-};
-
-// The toolhelp in normally inherited but most of
-// these tests only excercise the methods from the
-// traits therefore I use a typedef to make the
-// test code easier to read.
-typedef talk_base::ToolhelpEnumeratorBase<TestTraits> EnumeratorForTest;
-
-TEST_F(Win32ToolhelpTest, TestNextWithInvalidCtorHandle) {
- EnumeratorForTest t(INVALID_HANDLE_VALUE);
-
- EXPECT_FALSE(t.Next());
- EXPECT_TRUE(CheckCallCounters(0, 0, 0, 0));
-}
-
-// Tests that Next() returns false if the first-pointer
-// function fails.
-TEST_F(Win32ToolhelpTest, TestNextFirstFails) {
- typedef talk_base::ToolhelpEnumeratorBase<BadFirstTraits> BadEnumerator;
- talk_base::scoped_ptr<BadEnumerator> t(new BadEnumerator(AsHandle()));
-
- // If next ever fails it shall always fail.
- EXPECT_FALSE(t->Next());
- EXPECT_FALSE(t->Next());
- EXPECT_FALSE(t->Next());
- t.reset();
- EXPECT_TRUE(CheckCallCounters(0, 0, 1, 1));
-}
-
-// Tests that Next() returns false if the next-pointer
-// function fails.
-TEST_F(Win32ToolhelpTest, TestNextNextFails) {
- typedef talk_base::ToolhelpEnumeratorBase<BadNextTraits> BadEnumerator;
- talk_base::scoped_ptr<BadEnumerator> t(new BadEnumerator(AsHandle()));
-
- // If next ever fails it shall always fail. No more calls
- // shall be dispatched to Next(...).
- EXPECT_TRUE(t->Next());
- EXPECT_FALSE(t->Next());
- EXPECT_FALSE(t->Next());
- t.reset();
- EXPECT_TRUE(CheckCallCounters(1, 0, 1, 1));
-}
-
-
-// Tests that current returns an object is all zero's
-// if Next() hasn't been called.
-TEST_F(Win32ToolhelpTest, TestCurrentNextNotCalled) {
- talk_base::scoped_ptr<EnumeratorForTest> t(new EnumeratorForTest(AsHandle()));
- EXPECT_TRUE(AllZero(t->current()));
- t.reset();
- EXPECT_TRUE(CheckCallCounters(0, 0, 0, 1));
-}
-
-// Tests the simple everything works path through the code.
-TEST_F(Win32ToolhelpTest, TestCurrentNextCalled) {
- talk_base::scoped_ptr<EnumeratorForTest> t(new EnumeratorForTest(AsHandle()));
-
- EXPECT_TRUE(t->Next());
- EXPECT_TRUE(Equals(t->current(), kTestData[0]));
- EXPECT_TRUE(t->Next());
- EXPECT_TRUE(Equals(t->current(), kTestData[1]));
- EXPECT_TRUE(t->Next());
- EXPECT_TRUE(Equals(t->current(), kTestData[2]));
- EXPECT_FALSE(t->Next());
- t.reset();
- EXPECT_TRUE(CheckCallCounters(1, 3, 0, 1));
-}
-
-TEST_F(Win32ToolhelpTest, TestCurrentProcess) {
- WCHAR buf[MAX_PATH];
- GetModuleFileName(NULL, buf, ARRAY_SIZE(buf));
- std::wstring name = ToUtf16(Pathname(ToUtf8(buf)).filename());
-
- talk_base::ProcessEnumerator processes;
- bool found = false;
- while (processes.Next()) {
- if (!name.compare(processes.current().szExeFile)) {
- found = true;
- break;
- }
- }
- EXPECT_TRUE(found);
-
- talk_base::ModuleEnumerator modules(processes.current().th32ProcessID);
- found = false;
- while (modules.Next()) {
- if (!name.compare(modules.current().szModule)) {
- found = true;
- break;
- }
- }
- EXPECT_TRUE(found);
-}
-
-} // namespace talk_base
diff --git a/base/win32window.cc b/base/win32window.cc
deleted file mode 100644
index b11c349..0000000
--- a/base/win32window.cc
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/win32window.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// Win32Window
-///////////////////////////////////////////////////////////////////////////////
-
-static const wchar_t kWindowBaseClassName[] = L"WindowBaseClass";
-HINSTANCE Win32Window::instance_ = NULL;
-ATOM Win32Window::window_class_ = 0;
-
-Win32Window::Win32Window() : wnd_(NULL) {
-}
-
-Win32Window::~Win32Window() {
- ASSERT(NULL == wnd_);
-}
-
-bool Win32Window::Create(HWND parent, const wchar_t* title, DWORD style,
- DWORD exstyle, int x, int y, int cx, int cy) {
- if (wnd_) {
- // Window already exists.
- return false;
- }
-
- if (!window_class_) {
- if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
- GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
- reinterpret_cast<LPCWSTR>(&Win32Window::WndProc),
- &instance_)) {
- LOG_GLE(LS_ERROR) << "GetModuleHandleEx failed";
- return false;
- }
-
- // Class not registered, register it.
- WNDCLASSEX wcex;
- memset(&wcex, 0, sizeof(wcex));
- wcex.cbSize = sizeof(wcex);
- wcex.hInstance = instance_;
- wcex.lpfnWndProc = &Win32Window::WndProc;
- wcex.lpszClassName = kWindowBaseClassName;
- window_class_ = ::RegisterClassEx(&wcex);
- if (!window_class_) {
- LOG_GLE(LS_ERROR) << "RegisterClassEx failed";
- return false;
- }
- }
- wnd_ = ::CreateWindowEx(exstyle, kWindowBaseClassName, title, style,
- x, y, cx, cy, parent, NULL, instance_, this);
- return (NULL != wnd_);
-}
-
-void Win32Window::Destroy() {
- VERIFY(::DestroyWindow(wnd_) != FALSE);
-}
-
-void Win32Window::Shutdown() {
- if (window_class_) {
- ::UnregisterClass(MAKEINTATOM(window_class_), instance_);
- window_class_ = 0;
- }
-}
-
-bool Win32Window::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
- LRESULT& result) {
- switch (uMsg) {
- case WM_CLOSE:
- if (!OnClose()) {
- result = 0;
- return true;
- }
- break;
- }
- return false;
-}
-
-LRESULT Win32Window::WndProc(HWND hwnd, UINT uMsg,
- WPARAM wParam, LPARAM lParam) {
- Win32Window* that = reinterpret_cast<Win32Window*>(
- ::GetWindowLongPtr(hwnd, GWLP_USERDATA));
- if (!that && (WM_CREATE == uMsg)) {
- CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lParam);
- that = static_cast<Win32Window*>(cs->lpCreateParams);
- that->wnd_ = hwnd;
- ::SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
- }
- if (that) {
- LRESULT result;
- bool handled = that->OnMessage(uMsg, wParam, lParam, result);
- if (WM_DESTROY == uMsg) {
- for (HWND child = ::GetWindow(hwnd, GW_CHILD); child;
- child = ::GetWindow(child, GW_HWNDNEXT)) {
- LOG(LS_INFO) << "Child window: " << static_cast<void*>(child);
- }
- }
- if (WM_NCDESTROY == uMsg) {
- ::SetWindowLongPtr(hwnd, GWLP_USERDATA, NULL);
- that->wnd_ = NULL;
- that->OnNcDestroy();
- }
- if (handled) {
- return result;
- }
- }
- return ::DefWindowProc(hwnd, uMsg, wParam, lParam);
-}
-
-} // namespace talk_base
diff --git a/base/win32window.h b/base/win32window.h
deleted file mode 100644
index 37f3696..0000000
--- a/base/win32window.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WIN32WINDOW_H_
-#define TALK_BASE_WIN32WINDOW_H_
-
-#ifdef WIN32
-
-#include "talk/base/win32.h"
-
-namespace talk_base {
-
-///////////////////////////////////////////////////////////////////////////////
-// Win32Window
-///////////////////////////////////////////////////////////////////////////////
-
-class Win32Window {
- public:
- Win32Window();
- virtual ~Win32Window();
-
- HWND handle() const { return wnd_; }
-
- bool Create(HWND parent, const wchar_t* title, DWORD style, DWORD exstyle,
- int x, int y, int cx, int cy);
- void Destroy();
-
- // Call this when your DLL unloads.
- static void Shutdown();
-
- protected:
- virtual bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
- LRESULT& result);
-
- virtual bool OnClose() { return true; }
- virtual void OnNcDestroy() { }
-
- private:
- static LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam,
- LPARAM lParam);
-
- HWND wnd_;
- static HINSTANCE instance_;
- static ATOM window_class_;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // WIN32
-
-#endif // TALK_BASE_WIN32WINDOW_H_
diff --git a/base/win32window_unittest.cc b/base/win32window_unittest.cc
deleted file mode 100644
index 96173b7..0000000
--- a/base/win32window_unittest.cc
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * libjingle
- * Copyright 2009, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/common.h"
-#include "talk/base/win32window.h"
-#include "talk/base/logging.h"
-
-static LRESULT kDummyResult = 0x1234ABCD;
-
-class TestWindow : public talk_base::Win32Window {
- public:
- TestWindow() : destroyed_(false) { memset(&msg_, 0, sizeof(msg_)); }
- const MSG& msg() const { return msg_; }
- bool destroyed() const { return destroyed_; }
-
- virtual bool OnMessage(UINT uMsg, WPARAM wParam,
- LPARAM lParam, LRESULT& result) {
- msg_.message = uMsg;
- msg_.wParam = wParam;
- msg_.lParam = lParam;
- result = kDummyResult;
- return true;
- }
- virtual void OnNcDestroy() {
- destroyed_ = true;
- }
-
- private:
- MSG msg_;
- bool destroyed_;
-};
-
-TEST(Win32WindowTest, Basics) {
- TestWindow wnd;
- EXPECT_TRUE(wnd.handle() == NULL);
- EXPECT_FALSE(wnd.destroyed());
- EXPECT_TRUE(wnd.Create(0, L"Test", 0, 0, 0, 0, 100, 100));
- EXPECT_TRUE(wnd.handle() != NULL);
- EXPECT_EQ(kDummyResult, ::SendMessage(wnd.handle(), WM_USER, 1, 2));
- EXPECT_EQ(WM_USER, wnd.msg().message);
- EXPECT_EQ(1, wnd.msg().wParam);
- EXPECT_EQ(2, wnd.msg().lParam);
- wnd.Destroy();
- EXPECT_TRUE(wnd.handle() == NULL);
- EXPECT_TRUE(wnd.destroyed());
-}
-
-TEST(Win32WindowTest, MultipleWindows) {
- TestWindow wnd1, wnd2;
- EXPECT_TRUE(wnd1.Create(0, L"Test", 0, 0, 0, 0, 100, 100));
- EXPECT_TRUE(wnd2.Create(0, L"Test", 0, 0, 0, 0, 100, 100));
- EXPECT_TRUE(wnd1.handle() != NULL);
- EXPECT_TRUE(wnd2.handle() != NULL);
- wnd1.Destroy();
- wnd2.Destroy();
- EXPECT_TRUE(wnd2.handle() == NULL);
- EXPECT_TRUE(wnd1.handle() == NULL);
-}
diff --git a/base/win32windowpicker.cc b/base/win32windowpicker.cc
deleted file mode 100644
index d996c0e..0000000
--- a/base/win32windowpicker.cc
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved
-
-
-#include "talk/base/win32windowpicker.h"
-
-#include <string>
-#include <vector>
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-
-namespace talk_base {
-
-namespace {
-
-// Window class names that we want to filter out.
-const char kProgramManagerClass[] = "Progman";
-const char kButtonClass[] = "Button";
-
-} // namespace
-
-BOOL CALLBACK Win32WindowPicker::EnumProc(HWND hwnd, LPARAM l_param) {
- WindowDescriptionList* descriptions =
- reinterpret_cast<WindowDescriptionList*>(l_param);
-
- // Skip windows that are invisible, minimized, have no title, or are owned,
- // unless they have the app window style set. Except for minimized windows,
- // this is what Alt-Tab does.
- // TODO: Figure out how to grab a thumbnail of a minimized window and
- // include them in the list.
- int len = GetWindowTextLength(hwnd);
- HWND owner = GetWindow(hwnd, GW_OWNER);
- LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);
- if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||
- (owner && !(exstyle & WS_EX_APPWINDOW))) {
- // TODO: Investigate if windows without title still could be
- // interesting to share. We could use the name of the process as title:
- //
- // GetWindowThreadProcessId()
- // OpenProcess()
- // QueryFullProcessImageName()
- return TRUE;
- }
-
- // Skip the Program Manager window and the Start button.
- TCHAR class_name_w[500];
- ::GetClassName(hwnd, class_name_w, 500);
- std::string class_name = ToUtf8(class_name_w);
- if (class_name == kProgramManagerClass || class_name == kButtonClass) {
- // We don't want the Program Manager window nor the Start button.
- return TRUE;
- }
-
- TCHAR window_title[500];
- GetWindowText(hwnd, window_title, ARRAY_SIZE(window_title));
- std::string title = ToUtf8(window_title);
-
- WindowId id(hwnd);
- WindowDescription desc(id, title);
- descriptions->push_back(desc);
- return TRUE;
-}
-
-BOOL CALLBACK Win32WindowPicker::MonitorEnumProc(HMONITOR h_monitor,
- HDC hdc_monitor,
- LPRECT lprc_monitor,
- LPARAM l_param) {
- DesktopDescriptionList* desktop_desc =
- reinterpret_cast<DesktopDescriptionList*>(l_param);
-
- DesktopId id(h_monitor, static_cast<int>(desktop_desc->size()));
- // TODO: Figure out an appropriate desktop title.
- DesktopDescription desc(id, "");
-
- // Determine whether it's the primary monitor.
- MONITORINFO monitor_info = {0};
- monitor_info.cbSize = sizeof(monitor_info);
- bool primary = (GetMonitorInfo(h_monitor, &monitor_info) &&
- (monitor_info.dwFlags & MONITORINFOF_PRIMARY) != 0);
- desc.set_primary(primary);
-
- desktop_desc->push_back(desc);
- return TRUE;
-}
-
-Win32WindowPicker::Win32WindowPicker() {
-}
-
-bool Win32WindowPicker::Init() {
- return true;
-}
-// TODO: Consider changing enumeration to clear() descriptions
-// before append().
-bool Win32WindowPicker::GetWindowList(WindowDescriptionList* descriptions) {
- LPARAM desc = reinterpret_cast<LPARAM>(descriptions);
- return EnumWindows(Win32WindowPicker::EnumProc, desc) != FALSE;
-}
-
-bool Win32WindowPicker::GetDesktopList(DesktopDescriptionList* descriptions) {
- // Create a fresh WindowDescriptionList so that we can use desktop_desc.size()
- // in MonitorEnumProc to compute the desktop index.
- DesktopDescriptionList desktop_desc;
- HDC hdc = GetDC(NULL);
- bool success = false;
- if (EnumDisplayMonitors(hdc, NULL, Win32WindowPicker::MonitorEnumProc,
- reinterpret_cast<LPARAM>(&desktop_desc)) != FALSE) {
- // Append the desktop descriptions to the end of the returned descriptions.
- descriptions->insert(descriptions->end(), desktop_desc.begin(),
- desktop_desc.end());
- success = true;
- }
- ReleaseDC(NULL, hdc);
- return success;
-}
-
-bool Win32WindowPicker::GetDesktopDimensions(const DesktopId& id,
- int* width,
- int* height) {
- MONITORINFOEX monitor_info;
- monitor_info.cbSize = sizeof(MONITORINFOEX);
- if (!GetMonitorInfo(id.id(), &monitor_info)) {
- return false;
- }
- *width = monitor_info.rcMonitor.right - monitor_info.rcMonitor.left;
- *height = monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top;
- return true;
-}
-
-bool Win32WindowPicker::IsVisible(const WindowId& id) {
- return (::IsWindow(id.id()) != FALSE && ::IsWindowVisible(id.id()) != FALSE);
-}
-
-bool Win32WindowPicker::MoveToFront(const WindowId& id) {
- return SetForegroundWindow(id.id()) != FALSE;
-}
-
-} // namespace talk_base
diff --git a/base/win32windowpicker.h b/base/win32windowpicker.h
deleted file mode 100644
index 5e8fc6a..0000000
--- a/base/win32windowpicker.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved
-
-
-#ifndef TALK_BASE_WIN32WINDOWPICKER_H_
-#define TALK_BASE_WIN32WINDOWPICKER_H_
-
-#include "talk/base/win32.h"
-#include "talk/base/windowpicker.h"
-
-namespace talk_base {
-
-class Win32WindowPicker : public WindowPicker {
- public:
- Win32WindowPicker();
- virtual bool Init();
- virtual bool IsVisible(const WindowId& id);
- virtual bool MoveToFront(const WindowId& id);
- virtual bool GetWindowList(WindowDescriptionList* descriptions);
- virtual bool GetDesktopList(DesktopDescriptionList* descriptions);
- virtual bool GetDesktopDimensions(const DesktopId& id, int* width,
- int* height);
-
- protected:
- static BOOL CALLBACK EnumProc(HWND hwnd, LPARAM l_param);
- static BOOL CALLBACK MonitorEnumProc(HMONITOR h_monitor,
- HDC hdc_monitor,
- LPRECT lprc_monitor,
- LPARAM l_param);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WIN32WINDOWPICKER_H_
diff --git a/base/win32windowpicker_unittest.cc b/base/win32windowpicker_unittest.cc
deleted file mode 100644
index b418fd7..0000000
--- a/base/win32windowpicker_unittest.cc
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved
-
-
-#include "talk/base/gunit.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/win32window.h"
-#include "talk/base/win32windowpicker.h"
-#include "talk/base/windowpicker.h"
-
-#ifndef WIN32
-#error Only for Windows
-#endif
-
-namespace talk_base {
-
-static const TCHAR* kVisibleWindowTitle = L"Visible Window";
-static const TCHAR* kInvisibleWindowTitle = L"Invisible Window";
-
-class Win32WindowPickerForTest : public Win32WindowPicker {
- public:
- Win32WindowPickerForTest() {
- EXPECT_TRUE(visible_window_.Create(NULL, kVisibleWindowTitle, WS_VISIBLE,
- 0, 0, 0, 0, 0));
- EXPECT_TRUE(invisible_window_.Create(NULL, kInvisibleWindowTitle, 0,
- 0, 0, 0, 0, 0));
- }
-
- ~Win32WindowPickerForTest() {
- visible_window_.Destroy();
- invisible_window_.Destroy();
- }
-
- virtual bool GetWindowList(WindowDescriptionList* descriptions) {
- if (!Win32WindowPicker::EnumProc(visible_window_.handle(),
- reinterpret_cast<LPARAM>(descriptions))) {
- return false;
- }
- if (!Win32WindowPicker::EnumProc(invisible_window_.handle(),
- reinterpret_cast<LPARAM>(descriptions))) {
- return false;
- }
- return true;
- }
-
- Win32Window* visible_window() {
- return &visible_window_;
- }
-
- Win32Window* invisible_window() {
- return &invisible_window_;
- }
-
- private:
- Win32Window visible_window_;
- Win32Window invisible_window_;
-};
-
-TEST(Win32WindowPickerTest, TestGetWindowList) {
- Win32WindowPickerForTest window_picker;
- WindowDescriptionList descriptions;
- EXPECT_TRUE(window_picker.GetWindowList(&descriptions));
- EXPECT_EQ(1, descriptions.size());
- WindowDescription desc = descriptions.front();
- EXPECT_EQ(window_picker.visible_window()->handle(), desc.id().id());
- TCHAR window_title[500];
- GetWindowText(window_picker.visible_window()->handle(), window_title,
- ARRAY_SIZE(window_title));
- EXPECT_EQ(0, wcscmp(window_title, kVisibleWindowTitle));
-}
-
-TEST(Win32WindowPickerTest, TestIsVisible) {
- Win32WindowPickerForTest window_picker;
- HWND visible_id = window_picker.visible_window()->handle();
- HWND invisible_id = window_picker.invisible_window()->handle();
- EXPECT_TRUE(window_picker.IsVisible(WindowId(visible_id)));
- EXPECT_FALSE(window_picker.IsVisible(WindowId(invisible_id)));
-}
-
-TEST(Win32WindowPickerTest, TestMoveToFront) {
- Win32WindowPickerForTest window_picker;
- HWND visible_id = window_picker.visible_window()->handle();
- HWND invisible_id = window_picker.invisible_window()->handle();
-
- // There are a number of condition where SetForegroundWindow might
- // fail depending on the state of the calling process. To be on the
- // safe side we doesn't expect MoveToFront to return true, just test
- // that we don't crash.
- window_picker.MoveToFront(WindowId(visible_id));
- window_picker.MoveToFront(WindowId(invisible_id));
-}
-
-} // namespace talk_base
diff --git a/base/window.h b/base/window.h
deleted file mode 100644
index ad9467a..0000000
--- a/base/window.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WINDOW_H_
-#define TALK_BASE_WINDOW_H_
-
-#include "talk/base/stringencode.h"
-
-// Define platform specific window types.
-#if defined(LINUX)
-typedef unsigned long Window; // Avoid include <X11/Xlib.h>.
-#elif defined(WIN32)
-// We commonly include win32.h in talk/base so just include it here.
-#include "talk/base/win32.h" // Include HWND, HMONITOR.
-#elif defined(OSX)
-typedef unsigned int CGWindowID;
-typedef unsigned int CGDirectDisplayID;
-#endif
-
-namespace talk_base {
-
-class WindowId {
- public:
- // Define WindowT for each platform.
-#if defined(LINUX)
- typedef Window WindowT;
-#elif defined(WIN32)
- typedef HWND WindowT;
-#elif defined(OSX)
- typedef CGWindowID WindowT;
-#else
- typedef unsigned int WindowT;
-#endif
-
- static WindowId Cast(uint64 id) {
-#if defined(WIN32)
- return WindowId(reinterpret_cast<WindowId::WindowT>(id));
-#else
- return WindowId(static_cast<WindowId::WindowT>(id));
-#endif
- }
-
- static uint64 Format(const WindowT& id) {
-#if defined(WIN32)
- return static_cast<uint64>(reinterpret_cast<uintptr_t>(id));
-#else
- return static_cast<uint64>(id);
-#endif
- }
-
- WindowId() : id_(0) {}
- WindowId(const WindowT& id) : id_(id) {} // NOLINT
- const WindowT& id() const { return id_; }
- bool IsValid() const { return id_ != 0; }
- bool Equals(const WindowId& other) const {
- return id_ == other.id();
- }
-
- private:
- WindowT id_;
-};
-
-class DesktopId {
- public:
- // Define DesktopT for each platform.
-#if defined(LINUX)
- typedef Window DesktopT;
-#elif defined(WIN32)
- typedef HMONITOR DesktopT;
-#elif defined(OSX)
- typedef CGDirectDisplayID DesktopT;
-#else
- typedef unsigned int DesktopT;
-#endif
-
- static DesktopId Cast(int id, int index) {
-#if defined(WIN32)
- return DesktopId(reinterpret_cast<DesktopId::DesktopT>(id), index);
-#else
- return DesktopId(static_cast<DesktopId::DesktopT>(id), index);
-#endif
- }
-
- DesktopId() : id_(0), index_(-1) {}
- DesktopId(const DesktopT& id, int index) // NOLINT
- : id_(id), index_(index) {
- }
- const DesktopT& id() const { return id_; }
- int index() const { return index_; }
- bool IsValid() const { return index_ != -1; }
- bool Equals(const DesktopId& other) const {
- return id_ == other.id() && index_ == other.index();
- }
-
- private:
- // Id is the platform specific desktop identifier.
- DesktopT id_;
- // Index is the desktop index as enumerated by each platform.
- // Desktop capturer typically takes the index instead of id.
- int index_;
-};
-
-// Window event types.
-enum WindowEvent {
- WE_RESIZE = 0,
- WE_CLOSE = 1,
- WE_MINIMIZE = 2,
- WE_RESTORE = 3,
-};
-
-inline std::string ToString(const WindowId& window) {
- return ToString(window.id());
-}
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WINDOW_H_
diff --git a/base/windowpicker.h b/base/windowpicker.h
deleted file mode 100644
index e948d4c..0000000
--- a/base/windowpicker.h
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved
-
-// thorcarpenter@google.com (Thor Carpenter)
-
-#ifndef TALK_BASE_WINDOWPICKER_H_
-#define TALK_BASE_WINDOWPICKER_H_
-
-#include <string>
-#include <vector>
-
-#include "talk/base/window.h"
-
-namespace talk_base {
-
-class WindowDescription {
- public:
- WindowDescription() : id_() {}
- WindowDescription(const WindowId& id, const std::string& title)
- : id_(id), title_(title) {
- }
- const WindowId& id() const { return id_; }
- void set_id(const WindowId& id) { id_ = id; }
- const std::string& title() const { return title_; }
- void set_title(const std::string& title) { title_ = title; }
-
- private:
- WindowId id_;
- std::string title_;
-};
-
-class DesktopDescription {
- public:
- DesktopDescription() : id_() {}
- DesktopDescription(const DesktopId& id, const std::string& title)
- : id_(id), title_(title), primary_(false) {
- }
- const DesktopId& id() const { return id_; }
- void set_id(const DesktopId& id) { id_ = id; }
- const std::string& title() const { return title_; }
- void set_title(const std::string& title) { title_ = title; }
- // Indicates whether it is the primary desktop in the system.
- bool primary() const { return primary_; }
- void set_primary(bool primary) { primary_ = primary; }
-
- private:
- DesktopId id_;
- std::string title_;
- bool primary_;
-};
-
-typedef std::vector<WindowDescription> WindowDescriptionList;
-typedef std::vector<DesktopDescription> DesktopDescriptionList;
-
-class WindowPicker {
- public:
- virtual ~WindowPicker() {}
- virtual bool Init() = 0;
-
- // TODO: Move this two methods to window.h when we no longer need to load
- // CoreGraphics dynamically.
- virtual bool IsVisible(const WindowId& id) = 0;
- virtual bool MoveToFront(const WindowId& id) = 0;
-
- // Gets a list of window description and appends to descriptions.
- // Returns true if successful.
- virtual bool GetWindowList(WindowDescriptionList* descriptions) = 0;
- // Gets a list of desktop descriptions and appends to descriptions.
- // Returns true if successful.
- virtual bool GetDesktopList(DesktopDescriptionList* descriptions) = 0;
- // Gets the width and height of a desktop.
- // Returns true if successful.
- virtual bool GetDesktopDimensions(const DesktopId& id, int* width,
- int* height) = 0;
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WINDOWPICKER_H_
diff --git a/base/windowpicker_unittest.cc b/base/windowpicker_unittest.cc
deleted file mode 100644
index 436854a..0000000
--- a/base/windowpicker_unittest.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-#include "talk/base/gunit.h"
-#include "talk/base/testutils.h"
-#include "talk/base/window.h"
-#include "talk/base/windowpicker.h"
-#include "talk/base/windowpickerfactory.h"
-
-#ifdef OSX
-# define DISABLE_ON_MAC(name) DISABLED_ ## name
-#else
-# define DISABLE_ON_MAC(name) name
-#endif
-
-TEST(WindowPickerTest, GetWindowList) {
- MAYBE_SKIP_SCREENCAST_TEST();
- if (!talk_base::WindowPickerFactory::IsSupported()) {
- LOG(LS_INFO) << "skipping test: window capturing is not supported with "
- << "current configuration.";
- }
- talk_base::scoped_ptr<talk_base::WindowPicker> picker(
- talk_base::WindowPickerFactory::CreateWindowPicker());
- EXPECT_TRUE(picker->Init());
- talk_base::WindowDescriptionList descriptions;
- EXPECT_TRUE(picker->GetWindowList(&descriptions));
-}
-
-// TODO(hughv) Investigate why this fails on pulse but not locally after
-// upgrading to XCode 4.5. The failure is GetDesktopList returning FALSE.
-TEST(WindowPickerTest, DISABLE_ON_MAC(GetDesktopList)) {
- MAYBE_SKIP_SCREENCAST_TEST();
- if (!talk_base::WindowPickerFactory::IsSupported()) {
- LOG(LS_INFO) << "skipping test: window capturing is not supported with "
- << "current configuration.";
- }
- talk_base::scoped_ptr<talk_base::WindowPicker> picker(
- talk_base::WindowPickerFactory::CreateWindowPicker());
- EXPECT_TRUE(picker->Init());
- talk_base::DesktopDescriptionList descriptions;
- EXPECT_TRUE(picker->GetDesktopList(&descriptions));
- if (descriptions.size() > 0) {
- int width = 0;
- int height = 0;
- EXPECT_TRUE(picker->GetDesktopDimensions(descriptions[0].id(), &width,
- &height));
- EXPECT_GT(width, 0);
- EXPECT_GT(height, 0);
-
- // Test |IsPrimaryDesktop|. Only one desktop should be a primary.
- bool found_primary = false;
- for (talk_base::DesktopDescriptionList::iterator it = descriptions.begin();
- it != descriptions.end(); ++it) {
- if (it->primary()) {
- EXPECT_FALSE(found_primary);
- found_primary = true;
- }
- }
- EXPECT_TRUE(found_primary);
- }
-}
diff --git a/base/windowpickerfactory.h b/base/windowpickerfactory.h
deleted file mode 100644
index e9ba6c4..0000000
--- a/base/windowpickerfactory.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * libjingle
- * Copyright 2010 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WINDOWPICKERFACTORY_H_
-#define TALK_BASE_WINDOWPICKERFACTORY_H_
-
-#if defined(WIN32)
-#include "talk/base/win32windowpicker.h"
-#elif defined(OSX)
-#include "talk/base/macutils.h"
-#include "talk/base/macwindowpicker.h"
-#elif defined(LINUX)
-#include "talk/base/linuxwindowpicker.h"
-#endif
-
-#include "talk/base/windowpicker.h"
-
-namespace talk_base {
-
-class WindowPickerFactory {
- public:
- virtual ~WindowPickerFactory() {}
-
- // Instance method for dependency injection.
- virtual WindowPicker* Create() {
- return CreateWindowPicker();
- }
-
- static WindowPicker* CreateWindowPicker() {
-#if defined(WIN32)
- return new Win32WindowPicker();
-#elif defined(OSX)
- return new MacWindowPicker();
-#elif defined(LINUX) && defined(HAVE_X11)
- return new LinuxWindowPicker();
-#else
- return NULL;
-#endif
- }
-
- static bool IsSupported() {
-#ifdef OSX
- return GetOSVersionName() >= kMacOSLeopard;
-#else
- return true;
-#endif
- }
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WINDOWPICKERFACTORY_H_
diff --git a/base/winfirewall.cc b/base/winfirewall.cc
deleted file mode 100644
index e87ee5a..0000000
--- a/base/winfirewall.cc
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/winfirewall.h"
-
-#include "talk/base/win32.h"
-
-#include <comdef.h>
-#include <netfw.h>
-
-#define RELEASE(lpUnk) do { \
- if ((lpUnk) != NULL) { \
- (lpUnk)->Release(); \
- (lpUnk) = NULL; \
- } \
-} while (0)
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// WinFirewall
-//////////////////////////////////////////////////////////////////////
-
-WinFirewall::WinFirewall() : mgr_(NULL), policy_(NULL), profile_(NULL) {
-}
-
-WinFirewall::~WinFirewall() {
- Shutdown();
-}
-
-bool WinFirewall::Initialize(HRESULT* result) {
- if (mgr_) {
- if (result) {
- *result = S_OK;
- }
- return true;
- }
-
- HRESULT hr = CoCreateInstance(__uuidof(NetFwMgr),
- 0, CLSCTX_INPROC_SERVER,
- __uuidof(INetFwMgr),
- reinterpret_cast<void **>(&mgr_));
- if (SUCCEEDED(hr) && (mgr_ != NULL))
- hr = mgr_->get_LocalPolicy(&policy_);
- if (SUCCEEDED(hr) && (policy_ != NULL))
- hr = policy_->get_CurrentProfile(&profile_);
-
- if (result)
- *result = hr;
- return SUCCEEDED(hr) && (profile_ != NULL);
-}
-
-void WinFirewall::Shutdown() {
- RELEASE(profile_);
- RELEASE(policy_);
- RELEASE(mgr_);
-}
-
-bool WinFirewall::Enabled() const {
- if (!profile_)
- return false;
-
- VARIANT_BOOL fwEnabled = VARIANT_FALSE;
- profile_->get_FirewallEnabled(&fwEnabled);
- return (fwEnabled != VARIANT_FALSE);
-}
-
-bool WinFirewall::QueryAuthorized(const char* filename, bool* authorized)
- const {
- return QueryAuthorizedW(ToUtf16(filename).c_str(), authorized);
-}
-
-bool WinFirewall::QueryAuthorizedW(const wchar_t* filename, bool* authorized)
- const {
- *authorized = false;
- bool success = false;
-
- if (!profile_)
- return false;
-
- _bstr_t bfilename = filename;
-
- INetFwAuthorizedApplications* apps = NULL;
- HRESULT hr = profile_->get_AuthorizedApplications(&apps);
- if (SUCCEEDED(hr) && (apps != NULL)) {
- INetFwAuthorizedApplication* app = NULL;
- hr = apps->Item(bfilename, &app);
- if (SUCCEEDED(hr) && (app != NULL)) {
- VARIANT_BOOL fwEnabled = VARIANT_FALSE;
- hr = app->get_Enabled(&fwEnabled);
- app->Release();
-
- if (SUCCEEDED(hr)) {
- success = true;
- *authorized = (fwEnabled != VARIANT_FALSE);
- }
- } else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) {
- // No entry in list of authorized apps
- success = true;
- } else {
- // Unexpected error
- }
- apps->Release();
- }
-
- return success;
-}
-
-bool WinFirewall::AddApplication(const char* filename,
- const char* friendly_name,
- bool authorized,
- HRESULT* result) {
- return AddApplicationW(ToUtf16(filename).c_str(),
- ToUtf16(friendly_name).c_str(), authorized, result);
-}
-
-bool WinFirewall::AddApplicationW(const wchar_t* filename,
- const wchar_t* friendly_name,
- bool authorized,
- HRESULT* result) {
- INetFwAuthorizedApplications* apps = NULL;
- HRESULT hr = profile_->get_AuthorizedApplications(&apps);
- if (SUCCEEDED(hr) && (apps != NULL)) {
- INetFwAuthorizedApplication* app = NULL;
- hr = CoCreateInstance(__uuidof(NetFwAuthorizedApplication),
- 0, CLSCTX_INPROC_SERVER,
- __uuidof(INetFwAuthorizedApplication),
- reinterpret_cast<void **>(&app));
- if (SUCCEEDED(hr) && (app != NULL)) {
- _bstr_t bstr = filename;
- hr = app->put_ProcessImageFileName(bstr);
- bstr = friendly_name;
- if (SUCCEEDED(hr))
- hr = app->put_Name(bstr);
- if (SUCCEEDED(hr))
- hr = app->put_Enabled(authorized ? VARIANT_TRUE : VARIANT_FALSE);
- if (SUCCEEDED(hr))
- hr = apps->Add(app);
- app->Release();
- }
- apps->Release();
- }
- if (result)
- *result = hr;
- return SUCCEEDED(hr);
-}
-
-} // namespace talk_base
diff --git a/base/winfirewall.h b/base/winfirewall.h
deleted file mode 100644
index 11d687e..0000000
--- a/base/winfirewall.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WINFIREWALL_H_
-#define TALK_BASE_WINFIREWALL_H_
-
-#ifndef _HRESULT_DEFINED
-#define _HRESULT_DEFINED
-typedef long HRESULT; // Can't forward declare typedef, but don't need all win
-#endif // !_HRESULT_DEFINED
-
-struct INetFwMgr;
-struct INetFwPolicy;
-struct INetFwProfile;
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// WinFirewall
-//////////////////////////////////////////////////////////////////////
-
-class WinFirewall {
- public:
- WinFirewall();
- ~WinFirewall();
-
- bool Initialize(HRESULT* result);
- void Shutdown();
-
- bool Enabled() const;
- bool QueryAuthorized(const char* filename, bool* authorized) const;
- bool QueryAuthorizedW(const wchar_t* filename, bool* authorized) const;
-
- bool AddApplication(const char* filename, const char* friendly_name,
- bool authorized, HRESULT* result);
- bool AddApplicationW(const wchar_t* filename, const wchar_t* friendly_name,
- bool authorized, HRESULT* result);
-
- private:
- INetFwMgr* mgr_;
- INetFwPolicy* policy_;
- INetFwProfile* profile_;
-};
-
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WINFIREWALL_H_
diff --git a/base/winfirewall_unittest.cc b/base/winfirewall_unittest.cc
deleted file mode 100644
index 9987716..0000000
--- a/base/winfirewall_unittest.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/base/winfirewall.h"
-
-#include <objbase.h>
-
-namespace talk_base {
-
-TEST(WinFirewallTest, ReadStatus) {
- ::CoInitialize(NULL);
- WinFirewall fw;
- HRESULT hr;
- bool authorized;
-
- EXPECT_FALSE(fw.QueryAuthorized("bogus.exe", &authorized));
- EXPECT_TRUE(fw.Initialize(&hr));
- EXPECT_EQ(S_OK, hr);
-
- EXPECT_TRUE(fw.QueryAuthorized("bogus.exe", &authorized));
-
- // Unless we mock out INetFwMgr we can't really have an expectation either way
- // about whether we're authorized. It will depend on the settings of the
- // machine running the test. Same goes for AddApplication.
-
- fw.Shutdown();
- EXPECT_FALSE(fw.QueryAuthorized("bogus.exe", &authorized));
-
- ::CoUninitialize();
-}
-
-} // namespace talk_base
diff --git a/base/winping.cc b/base/winping.cc
deleted file mode 100644
index fd25a23..0000000
--- a/base/winping.cc
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/winping.h"
-
-#include <assert.h>
-#include <Iphlpapi.h>
-
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/ipaddress.h"
-#include "talk/base/logging.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/socketaddress.h"
-
-namespace talk_base {
-
-//////////////////////////////////////////////////////////////////////
-// Found in IPExport.h
-//////////////////////////////////////////////////////////////////////
-
-typedef struct icmp_echo_reply {
- ULONG Address; // Replying address
- ULONG Status; // Reply IP_STATUS
- ULONG RoundTripTime; // RTT in milliseconds
- USHORT DataSize; // Reply data size in bytes
- USHORT Reserved; // Reserved for system use
- PVOID Data; // Pointer to the reply data
- struct ip_option_information Options; // Reply options
-} ICMP_ECHO_REPLY, * PICMP_ECHO_REPLY;
-
-typedef struct icmpv6_echo_reply_lh {
- sockaddr_in6 Address;
- ULONG Status;
- unsigned int RoundTripTime;
-} ICMPV6_ECHO_REPLY, *PICMPV6_ECHO_REPLY;
-
-//
-// IP_STATUS codes returned from IP APIs
-//
-
-#define IP_STATUS_BASE 11000
-
-#define IP_SUCCESS 0
-#define IP_BUF_TOO_SMALL (IP_STATUS_BASE + 1)
-#define IP_DEST_NET_UNREACHABLE (IP_STATUS_BASE + 2)
-#define IP_DEST_HOST_UNREACHABLE (IP_STATUS_BASE + 3)
-#define IP_DEST_PROT_UNREACHABLE (IP_STATUS_BASE + 4)
-#define IP_DEST_PORT_UNREACHABLE (IP_STATUS_BASE + 5)
-#define IP_NO_RESOURCES (IP_STATUS_BASE + 6)
-#define IP_BAD_OPTION (IP_STATUS_BASE + 7)
-#define IP_HW_ERROR (IP_STATUS_BASE + 8)
-#define IP_PACKET_TOO_BIG (IP_STATUS_BASE + 9)
-#define IP_REQ_TIMED_OUT (IP_STATUS_BASE + 10)
-#define IP_BAD_REQ (IP_STATUS_BASE + 11)
-#define IP_BAD_ROUTE (IP_STATUS_BASE + 12)
-#define IP_TTL_EXPIRED_TRANSIT (IP_STATUS_BASE + 13)
-#define IP_TTL_EXPIRED_REASSEM (IP_STATUS_BASE + 14)
-#define IP_PARAM_PROBLEM (IP_STATUS_BASE + 15)
-#define IP_SOURCE_QUENCH (IP_STATUS_BASE + 16)
-#define IP_OPTION_TOO_BIG (IP_STATUS_BASE + 17)
-#define IP_BAD_DESTINATION (IP_STATUS_BASE + 18)
-
-#define IP_ADDR_DELETED (IP_STATUS_BASE + 19)
-#define IP_SPEC_MTU_CHANGE (IP_STATUS_BASE + 20)
-#define IP_MTU_CHANGE (IP_STATUS_BASE + 21)
-#define IP_UNLOAD (IP_STATUS_BASE + 22)
-#define IP_ADDR_ADDED (IP_STATUS_BASE + 23)
-#define IP_MEDIA_CONNECT (IP_STATUS_BASE + 24)
-#define IP_MEDIA_DISCONNECT (IP_STATUS_BASE + 25)
-#define IP_BIND_ADAPTER (IP_STATUS_BASE + 26)
-#define IP_UNBIND_ADAPTER (IP_STATUS_BASE + 27)
-#define IP_DEVICE_DOES_NOT_EXIST (IP_STATUS_BASE + 28)
-#define IP_DUPLICATE_ADDRESS (IP_STATUS_BASE + 29)
-#define IP_INTERFACE_METRIC_CHANGE (IP_STATUS_BASE + 30)
-#define IP_RECONFIG_SECFLTR (IP_STATUS_BASE + 31)
-#define IP_NEGOTIATING_IPSEC (IP_STATUS_BASE + 32)
-#define IP_INTERFACE_WOL_CAPABILITY_CHANGE (IP_STATUS_BASE + 33)
-#define IP_DUPLICATE_IPADD (IP_STATUS_BASE + 34)
-
-#define IP_GENERAL_FAILURE (IP_STATUS_BASE + 50)
-#define MAX_IP_STATUS IP_GENERAL_FAILURE
-#define IP_PENDING (IP_STATUS_BASE + 255)
-
-//
-// Values used in the IP header Flags field.
-//
-#define IP_FLAG_DF 0x2 // Don't fragment this packet.
-
-//
-// Supported IP Option Types.
-//
-// These types define the options which may be used in the OptionsData field
-// of the ip_option_information structure. See RFC 791 for a complete
-// description of each.
-//
-#define IP_OPT_EOL 0 // End of list option
-#define IP_OPT_NOP 1 // No operation
-#define IP_OPT_SECURITY 0x82 // Security option
-#define IP_OPT_LSRR 0x83 // Loose source route
-#define IP_OPT_SSRR 0x89 // Strict source route
-#define IP_OPT_RR 0x7 // Record route
-#define IP_OPT_TS 0x44 // Timestamp
-#define IP_OPT_SID 0x88 // Stream ID (obsolete)
-#define IP_OPT_ROUTER_ALERT 0x94 // Router Alert Option
-
-#define MAX_OPT_SIZE 40 // Maximum length of IP options in bytes
-
-//////////////////////////////////////////////////////////////////////
-// Global Constants and Types
-//////////////////////////////////////////////////////////////////////
-
-const char * const ICMP_DLL_NAME = "Iphlpapi.dll";
-const char * const ICMP_CREATE_FUNC = "IcmpCreateFile";
-const char * const ICMP_CLOSE_FUNC = "IcmpCloseHandle";
-const char * const ICMP_SEND_FUNC = "IcmpSendEcho";
-const char * const ICMP6_CREATE_FUNC = "Icmp6CreateFile";
-const char * const ICMP6_CLOSE_FUNC = "Icmp6CloseHandle";
-const char * const ICMP6_SEND_FUNC = "Icmp6SendEcho2";
-
-inline uint32 ReplySize(uint32 data_size, int family) {
- if (family == AF_INET) {
- // A ping error message is 8 bytes long, so make sure we allow for at least
- // 8 bytes of reply data.
- return sizeof(ICMP_ECHO_REPLY) + talk_base::_max<uint32>(8, data_size);
- } else if (family == AF_INET6) {
- // Per MSDN, Send6IcmpEcho2 needs at least one ICMPV6_ECHO_REPLY,
- // 8 bytes for ICMP header, _and_ an IO_BLOCK_STATUS (2 pointers),
- // in addition to the data size.
- return sizeof(ICMPV6_ECHO_REPLY) + data_size + 8 + (2 * sizeof(DWORD*));
- } else {
- return 0;
- }
-}
-
-//////////////////////////////////////////////////////////////////////
-// WinPing
-//////////////////////////////////////////////////////////////////////
-
-WinPing::WinPing()
- : dll_(0), hping_(INVALID_HANDLE_VALUE), create_(0), close_(0), send_(0),
- create6_(0), send6_(0), data_(0), dlen_(0), reply_(0),
- rlen_(0), valid_(false) {
-
- dll_ = LoadLibraryA(ICMP_DLL_NAME);
- if (!dll_) {
- LOG(LERROR) << "LoadLibrary: " << GetLastError();
- return;
- }
-
- create_ = (PIcmpCreateFile) GetProcAddress(dll_, ICMP_CREATE_FUNC);
- close_ = (PIcmpCloseHandle) GetProcAddress(dll_, ICMP_CLOSE_FUNC);
- send_ = (PIcmpSendEcho) GetProcAddress(dll_, ICMP_SEND_FUNC);
- if (!create_ || !close_ || !send_) {
- LOG(LERROR) << "GetProcAddress(ICMP_*): " << GetLastError();
- return;
- }
- hping_ = create_();
- if (hping_ == INVALID_HANDLE_VALUE) {
- LOG(LERROR) << "IcmpCreateFile: " << GetLastError();
- return;
- }
-
- if (HasIPv6Enabled()) {
- create6_ = (PIcmp6CreateFile) GetProcAddress(dll_, ICMP6_CREATE_FUNC);
- send6_ = (PIcmp6SendEcho2) GetProcAddress(dll_, ICMP6_SEND_FUNC);
- if (!create6_ || !send6_) {
- LOG(LERROR) << "GetProcAddress(ICMP6_*): " << GetLastError();
- return;
- }
- hping6_ = create6_();
- if (hping6_ == INVALID_HANDLE_VALUE) {
- LOG(LERROR) << "Icmp6CreateFile: " << GetLastError();
- }
- }
-
- dlen_ = 0;
- rlen_ = ReplySize(dlen_, AF_INET);
- data_ = new char[dlen_];
- reply_ = new char[rlen_];
-
- valid_ = true;
-}
-
-WinPing::~WinPing() {
- if ((hping_ != INVALID_HANDLE_VALUE) && close_) {
- if (!close_(hping_))
- LOG(WARNING) << "IcmpCloseHandle: " << GetLastError();
- }
- if ((hping6_ != INVALID_HANDLE_VALUE) && close_) {
- if (!close_(hping6_)) {
- LOG(WARNING) << "Icmp6CloseHandle: " << GetLastError();
- }
- }
-
- if (dll_)
- FreeLibrary(dll_);
-
- delete[] data_;
- delete[] reply_;
-}
-
-WinPing::PingResult WinPing::Ping(
- IPAddress ip, uint32 data_size, uint32 timeout, uint8 ttl,
- bool allow_fragments) {
-
- if (data_size == 0 || timeout == 0 || ttl == 0) {
- LOG(LERROR) << "IcmpSendEcho: data_size/timeout/ttl is 0.";
- return PING_INVALID_PARAMS;
- }
-
- assert(IsValid());
-
- IP_OPTION_INFORMATION ipopt;
- memset(&ipopt, 0, sizeof(ipopt));
- if (!allow_fragments)
- ipopt.Flags |= IP_FLAG_DF;
- ipopt.Ttl = ttl;
-
- uint32 reply_size = ReplySize(data_size, ip.family());
-
- if (data_size > dlen_) {
- delete [] data_;
- dlen_ = data_size;
- data_ = new char[dlen_];
- memset(data_, 'z', dlen_);
- }
-
- if (reply_size > rlen_) {
- delete [] reply_;
- rlen_ = reply_size;
- reply_ = new char[rlen_];
- }
- DWORD result = 0;
- if (ip.family() == AF_INET) {
- result = send_(hping_, ip.ipv4_address().S_un.S_addr,
- data_, uint16(data_size), &ipopt,
- reply_, reply_size, timeout);
- } else if (ip.family() == AF_INET6) {
- sockaddr_in6 src = {0};
- sockaddr_in6 dst = {0};
- src.sin6_family = AF_INET6;
- dst.sin6_family = AF_INET6;
- dst.sin6_addr = ip.ipv6_address();
- result = send6_(hping6_, NULL, NULL, NULL,
- &src, &dst,
- data_, int16(data_size), &ipopt,
- reply_, reply_size, timeout);
- }
- if (result == 0) {
- DWORD error = GetLastError();
- if (error == IP_PACKET_TOO_BIG)
- return PING_TOO_LARGE;
- if (error == IP_REQ_TIMED_OUT)
- return PING_TIMEOUT;
- LOG(LERROR) << "IcmpSendEcho(" << ip.ToSensitiveString()
- << ", " << data_size << "): " << error;
- return PING_FAIL;
- }
-
- return PING_SUCCESS;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Microsoft Documenation
-//////////////////////////////////////////////////////////////////////
-//
-// Routine Name:
-//
-// IcmpCreateFile
-//
-// Routine Description:
-//
-// Opens a handle on which ICMP Echo Requests can be issued.
-//
-// Arguments:
-//
-// None.
-//
-// Return Value:
-//
-// An open file handle or INVALID_HANDLE_VALUE. Extended error information
-// is available by calling GetLastError().
-//
-//////////////////////////////////////////////////////////////////////
-//
-// Routine Name:
-//
-// IcmpCloseHandle
-//
-// Routine Description:
-//
-// Closes a handle opened by ICMPOpenFile.
-//
-// Arguments:
-//
-// IcmpHandle - The handle to close.
-//
-// Return Value:
-//
-// TRUE if the handle was closed successfully, otherwise FALSE. Extended
-// error information is available by calling GetLastError().
-//
-//////////////////////////////////////////////////////////////////////
-//
-// Routine Name:
-//
-// IcmpSendEcho
-//
-// Routine Description:
-//
-// Sends an ICMP Echo request and returns any replies. The
-// call returns when the timeout has expired or the reply buffer
-// is filled.
-//
-// Arguments:
-//
-// IcmpHandle - An open handle returned by ICMPCreateFile.
-//
-// DestinationAddress - The destination of the echo request.
-//
-// RequestData - A buffer containing the data to send in the
-// request.
-//
-// RequestSize - The number of bytes in the request data buffer.
-//
-// RequestOptions - Pointer to the IP header options for the request.
-// May be NULL.
-//
-// ReplyBuffer - A buffer to hold any replies to the request.
-// On return, the buffer will contain an array of
-// ICMP_ECHO_REPLY structures followed by the
-// options and data for the replies. The buffer
-// should be large enough to hold at least one
-// ICMP_ECHO_REPLY structure plus
-// MAX(RequestSize, 8) bytes of data since an ICMP
-// error message contains 8 bytes of data.
-//
-// ReplySize - The size in bytes of the reply buffer.
-//
-// Timeout - The time in milliseconds to wait for replies.
-//
-// Return Value:
-//
-// Returns the number of ICMP_ECHO_REPLY structures stored in ReplyBuffer.
-// The status of each reply is contained in the structure. If the return
-// value is zero, extended error information is available via
-// GetLastError().
-//
-//////////////////////////////////////////////////////////////////////
-
-} // namespace talk_base
diff --git a/base/winping.h b/base/winping.h
deleted file mode 100644
index 34b5bbd..0000000
--- a/base/winping.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2005, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WINPING_H__
-#define TALK_BASE_WINPING_H__
-
-#ifdef WIN32
-
-#include "talk/base/win32.h"
-#include "talk/base/basictypes.h"
-#include "talk/base/IPAddress.h"
-
-namespace talk_base {
-
-// This class wraps a Win32 API for doing ICMP pinging. This API, unlike the
-// the normal socket APIs (as implemented on Win9x), will return an error if
-// an ICMP packet with the dont-fragment bit set is too large. This means this
-// class can be used to detect the MTU to a given address.
-
-typedef struct ip_option_information {
- UCHAR Ttl; // Time To Live
- UCHAR Tos; // Type Of Service
- UCHAR Flags; // IP header flags
- UCHAR OptionsSize; // Size in bytes of options data
- PUCHAR OptionsData; // Pointer to options data
-} IP_OPTION_INFORMATION, * PIP_OPTION_INFORMATION;
-
-typedef HANDLE (WINAPI *PIcmpCreateFile)();
-
-typedef BOOL (WINAPI *PIcmpCloseHandle)(HANDLE icmp_handle);
-
-typedef HANDLE (WINAPI *PIcmp6CreateFile)();
-
-typedef BOOL (WINAPI *PIcmp6CloseHandle)(HANDLE icmp_handle);
-
-typedef DWORD (WINAPI *PIcmpSendEcho)(
- HANDLE IcmpHandle,
- ULONG DestinationAddress,
- LPVOID RequestData,
- WORD RequestSize,
- PIP_OPTION_INFORMATION RequestOptions,
- LPVOID ReplyBuffer,
- DWORD ReplySize,
- DWORD Timeout);
-
-typedef DWORD (WINAPI *PIcmp6SendEcho2)(
- HANDLE IcmpHandle,
- HANDLE Event,
- FARPROC ApcRoutine,
- PVOID ApcContext,
- struct sockaddr_in6 *SourceAddress,
- struct sockaddr_in6 *DestinationAddress,
- LPVOID RequestData,
- WORD RequestSize,
- PIP_OPTION_INFORMATION RequestOptions,
- LPVOID ReplyBuffer,
- DWORD ReplySize,
- DWORD Timeout
-);
-
-class WinPing {
-public:
- WinPing();
- ~WinPing();
-
- // Determines whether the class was initialized correctly.
- bool IsValid() { return valid_; }
-
- // Attempts to send a ping with the given parameters.
- enum PingResult { PING_FAIL, PING_INVALID_PARAMS,
- PING_TOO_LARGE, PING_TIMEOUT, PING_SUCCESS };
- PingResult Ping(
- IPAddress ip, uint32 data_size, uint32 timeout_millis, uint8 ttl,
- bool allow_fragments);
-
-private:
- HMODULE dll_;
- HANDLE hping_;
- HANDLE hping6_;
- PIcmpCreateFile create_;
- PIcmpCloseHandle close_;
- PIcmpSendEcho send_;
- PIcmp6CreateFile create6_;
- PIcmp6SendEcho2 send6_;
- char* data_;
- uint32 dlen_;
- char* reply_;
- uint32 rlen_;
- bool valid_;
-};
-
-} // namespace talk_base
-
-#endif // WIN32
-
-#endif // TALK_BASE_WINPING_H__
diff --git a/base/worker.cc b/base/worker.cc
deleted file mode 100644
index 28fcc9f..0000000
--- a/base/worker.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/worker.h"
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
-
-namespace talk_base {
-
-enum {
- MSG_HAVEWORK = 0,
-};
-
-Worker::Worker() : worker_thread_(NULL) {}
-
-Worker::~Worker() {
- // We need to already be stopped before being destroyed. We cannot call
- // StopWork() from here because the subclass's data has already been
- // destructed, so OnStop() cannot be called.
- ASSERT(!worker_thread_);
-}
-
-bool Worker::StartWork() {
- talk_base::Thread *me = talk_base::Thread::Current();
- if (worker_thread_) {
- if (worker_thread_ == me) {
- // Already working on this thread, so nothing to do.
- return true;
- } else {
- LOG(LS_ERROR) << "Automatically switching threads is not supported";
- ASSERT(false);
- return false;
- }
- }
- worker_thread_ = me;
- OnStart();
- return true;
-}
-
-bool Worker::StopWork() {
- if (!worker_thread_) {
- // Already not working, so nothing to do.
- return true;
- } else if (worker_thread_ != talk_base::Thread::Current()) {
- LOG(LS_ERROR) << "Stopping from a different thread is not supported";
- ASSERT(false);
- return false;
- }
- OnStop();
- worker_thread_->Clear(this, MSG_HAVEWORK);
- worker_thread_ = NULL;
- return true;
-}
-
-void Worker::HaveWork() {
- ASSERT(worker_thread_ != NULL);
- worker_thread_->Post(this, MSG_HAVEWORK);
-}
-
-void Worker::OnMessage(talk_base::Message *msg) {
- ASSERT(msg->message_id == MSG_HAVEWORK);
- ASSERT(worker_thread_ == talk_base::Thread::Current());
- OnHaveWork();
-}
-
-} // namespace talk_base
diff --git a/base/worker.h b/base/worker.h
deleted file mode 100644
index 582fe1b..0000000
--- a/base/worker.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_BASE_WORKER_H_
-#define TALK_BASE_WORKER_H_
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/messagehandler.h"
-
-namespace talk_base {
-
-class Thread;
-
-// A worker is an object that performs some specific long-lived task in an
-// event-driven manner.
-// The only method that should be considered thread-safe is HaveWork(), which
-// allows you to signal the availability of work from any thread. All other
-// methods are thread-hostile. Specifically:
-// StartWork()/StopWork() should not be called concurrently with themselves or
-// each other, and it is an error to call them while the worker is running on
-// a different thread.
-// The destructor may not be called if the worker is currently running
-// (regardless of the thread), but you can call StopWork() in a subclass's
-// destructor.
-class Worker : private MessageHandler {
- public:
- Worker();
-
- // Destroys this Worker, but it must have already been stopped via StopWork().
- virtual ~Worker();
-
- // Attaches the worker to the current thread and begins processing work if not
- // already doing so.
- bool StartWork();
- // Stops processing work if currently doing so and detaches from the current
- // thread.
- bool StopWork();
-
- protected:
- // Signal that work is available to be done. May only be called within the
- // lifetime of a OnStart()/OnStop() pair.
- void HaveWork();
-
- // These must be implemented by a subclass.
- // Called on the worker thread to start working.
- virtual void OnStart() = 0;
- // Called on the worker thread when work has been signalled via HaveWork().
- virtual void OnHaveWork() = 0;
- // Called on the worker thread to stop working. Upon return, any pending
- // OnHaveWork() calls are cancelled.
- virtual void OnStop() = 0;
-
- private:
- // Inherited from MessageHandler.
- virtual void OnMessage(Message *msg);
-
- // The thread that is currently doing the work.
- Thread *worker_thread_;
-
- DISALLOW_COPY_AND_ASSIGN(Worker);
-};
-
-} // namespace talk_base
-
-#endif // TALK_BASE_WORKER_H_
diff --git a/build/common.gypi b/build/common.gypi
index 8261c20..7ee4224 100644
--- a/build/common.gypi
+++ b/build/common.gypi
@@ -31,6 +31,7 @@
'variables': {
'webrtc_root%': '<(DEPTH)/webrtc',
# TODO(ronghuawu): Chromium build will need a different libjingle_root.
+ 'libjingle_tests_additional_deps%': [],
'libjingle_root%': '<(DEPTH)',
# TODO(ronghuawu): For now, disable the Chrome plugins, which causes a
# flood of chromium-style warnings.
@@ -64,14 +65,10 @@
'FEATURE_ENABLE_SSL',
'FEATURE_ENABLE_VOICEMAIL',
'FEATURE_ENABLE_PSTN',
- # TODO(eric): enable HAVE_NSS_SSL_H and SSL_USE_NSS once they are ready.
- # 'HAVE_NSS_SSL_H=1',
+ 'HAVE_SCTP',
'HAVE_SRTP',
'HAVE_WEBRTC_VIDEO',
'HAVE_WEBRTC_VOICE',
- # 'SSL_USE_NSS',
- # TODO(ronghuawu): Remove this once libjingle is updated to use the new
- # webrtc.
'USE_WEBRTC_DEV_BRANCH',
],
'conditions': [
@@ -82,6 +79,7 @@
['OS=="linux"', {
'defines': [
'LINUX',
+ 'WEBRTC_LINUX',
],
'conditions': [
['clang==1', {
@@ -93,6 +91,7 @@
# LateBindingSymbolTable::TableInfo from
# latebindingsymboltable.cc.def and remove below flag.
'-Wno-address-of-array-temporary',
+ '-Wthread-safety',
],
}],
],
@@ -100,15 +99,25 @@
['OS=="mac"', {
'defines': [
'OSX',
+ 'WEBRTC_MAC',
+ ],
+ }],
+ ['OS=="win"', {
+ 'defines': [
+ 'WEBRTC_WIN',
+ ],
+ 'msvs_disabled_warnings': [
+ # https://code.google.com/p/chromium/issues/detail?id=372451#c20
+ # Warning 4702 ("Unreachable code") should be re-enabled once
+ # users are updated to VS2013 Update 2.
+ 4702,
],
}],
['OS=="ios"', {
'defines': [
'IOS',
- ],
- }, {
- 'defines': [
- 'HAVE_SCTP',
+ 'WEBRTC_MAC',
+ 'WEBRTC_IOS',
],
}],
['OS=="ios" or (OS=="mac" and target_arch!="ia32")', {
@@ -130,42 +139,12 @@
'defines': [
'HASH_NAMESPACE=__gnu_cxx',
'POSIX',
+ 'WEBRTC_POSIX',
'DISABLE_DYNAMIC_CAST',
# The POSIX standard says we have to define this.
'_REENTRANT',
],
}],
- # TODO(jiayl): collapse the following 5 defines into 2, one for NSS and
- # one for OPENSSL, and update the relevant code.
- ['use_openssl==1', {
- 'defines': [
- 'SSL_USE_OPENSSL',
- 'HAVE_OPENSSL_SSL_H',
- ],
- 'dependencies': [
- '<(DEPTH)/third_party/openssl/openssl.gyp:openssl',
- ],
- }, {
- 'defines': [
- 'SSL_USE_NSS',
- 'HAVE_NSS_SSL_H',
- 'SSL_USE_NSS_RNG',
- ],
- 'conditions': [
- ['os_posix == 1 and OS != "mac" and OS != "ios" and OS != "android"', {
- 'dependencies': [
- '<(DEPTH)/build/linux/system.gyp:ssl',
- ],
- }],
- ['OS == "mac" or OS == "ios" or OS == "win"', {
- 'dependencies': [
- '<(DEPTH)/net/third_party/nss/ssl.gyp:libssl',
- '<(DEPTH)/third_party/nss/nss.gyp:nspr',
- '<(DEPTH)/third_party/nss/nss.gyp:nss',
- ],
- }],
- ],
- }],
],
}, # target_defaults
}
diff --git a/examples/OWNERS b/examples/OWNERS
new file mode 100644
index 0000000..f489e6b
--- /dev/null
+++ b/examples/OWNERS
@@ -0,0 +1,2 @@
+glaznev@webrtc.org
+tkchin@webrtc.org
diff --git a/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java b/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java
index ef97cda..468ce22 100644
--- a/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java
+++ b/examples/android/src/org/appspot/apprtc/AppRTCDemoActivity.java
@@ -77,7 +77,6 @@
public class AppRTCDemoActivity extends Activity
implements AppRTCClient.IceServersObserver {
private static final String TAG = "AppRTCDemoActivity";
- private static boolean factoryStaticInitialized;
private PeerConnectionFactory factory;
private VideoSource videoSource;
private boolean videoSourceStopped;
@@ -133,13 +132,6 @@
hudView.setVisibility(View.INVISIBLE);
addContentView(hudView, hudLayout);
- if (!factoryStaticInitialized) {
- abortUnless(PeerConnectionFactory.initializeAndroidGlobals(
- this, true, true),
- "Failed to initializeAndroidGlobals");
- factoryStaticInitialized = true;
- }
-
AudioManager audioManager =
((AudioManager) getSystemService(AUDIO_SERVICE));
// TODO(fischman): figure out how to do this Right(tm) and remove the
@@ -200,19 +192,49 @@
private void updateHUD(StatsReport[] reports) {
StringBuilder builder = new StringBuilder();
for (StatsReport report : reports) {
- if (!report.id.equals("bweforvideo")) {
+ // bweforvideo to show statistics for video Bandwidth Estimation,
+ // which is global per-session.
+ if (report.id.equals("bweforvideo")) {
+ for (StatsReport.Value value : report.values) {
+ String name = value.name.replace("goog", "")
+ .replace("Available", "").replace("Bandwidth", "")
+ .replace("Bitrate", "").replace("Enc", "");
+
+ builder.append(name).append("=").append(value.value)
+ .append(" ");
+ }
+ builder.append("\n");
+ } else if (report.type.equals("googCandidatePair")) {
+ String activeConnectionStats = getActiveConnectionStats(report);
+ if (activeConnectionStats == null) {
+ continue;
+ }
+ builder.append(activeConnectionStats);
+ } else {
continue;
}
- for (StatsReport.Value value : report.values) {
- String name = value.name.replace("goog", "").replace("Available", "")
- .replace("Bandwidth", "").replace("Bitrate", "").replace("Enc", "");
- builder.append(name).append("=").append(value.value).append(" ");
- }
builder.append("\n");
}
hudView.setText(builder.toString() + hudView.getText());
}
+ // Return the active connection stats else return null
+ private String getActiveConnectionStats(StatsReport report) {
+ StringBuilder activeConnectionbuilder = new StringBuilder();
+ // googCandidatePair to show information about the active
+ // connection.
+ for (StatsReport.Value value : report.values) {
+ if (value.name.equals("googActiveConnection")
+ && value.value.equals("false")) {
+ return null;
+ }
+ String name = value.name.replace("goog", "");
+ activeConnectionbuilder.append(name).append("=")
+ .append(value.value).append("\n");
+ }
+ return activeConnectionbuilder.toString();
+ }
+
@Override
public void onPause() {
super.onPause();
@@ -252,6 +274,9 @@
@Override
public void onIceServers(List<PeerConnection.IceServer> iceServers) {
+ abortUnless(PeerConnectionFactory.initializeAndroidGlobals(
+ this, true, true, VideoRendererGui.getEGLContext()),
+ "Failed to initializeAndroidGlobals");
factory = new PeerConnectionFactory();
MediaConstraints pcConstraints = appRtcClient.pcConstraints();
diff --git a/examples/call/call_main.cc b/examples/call/call_main.cc
index 33d5385..cb309dc 100644
--- a/examples/call/call_main.cc
+++ b/examples/call/call_main.cc
@@ -33,15 +33,11 @@
#include <iostream>
#include <vector>
-#include "talk/base/flags.h"
-#include "talk/base/logging.h"
+#include "webrtc/base/flags.h"
+#include "webrtc/base/logging.h"
#ifdef OSX
-#include "talk/base/maccocoasocketserver.h"
+#include "webrtc/base/maccocoasocketserver.h"
#endif
-#include "talk/base/pathutils.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/stream.h"
-#include "talk/base/win32socketserver.h"
#include "talk/examples/call/callclient.h"
#include "talk/examples/call/console.h"
#include "talk/examples/call/mediaenginefactory.h"
@@ -52,6 +48,10 @@
#include "talk/xmpp/xmppclientsettings.h"
#include "talk/xmpp/xmpppump.h"
#include "talk/xmpp/xmppsocket.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/win32socketserver.h"
class DebugLog : public sigslot::has_slots<> {
public:
@@ -257,9 +257,9 @@
"Enable roster messages printed in console.");
// parse options
- FlagList::SetFlagsFromCommandLine(&argc, argv, true);
+ rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
if (FLAG_help) {
- FlagList::Print(NULL, false);
+ rtc::FlagList::Print(NULL, false);
return 0;
}
@@ -283,19 +283,19 @@
bool render = FLAG_render;
std::string data_channel = FLAG_datachannel;
bool multisession_enabled = FLAG_multisession;
- talk_base::SSLIdentity* ssl_identity = NULL;
+ rtc::SSLIdentity* ssl_identity = NULL;
bool show_roster_messages = FLAG_roster;
// Set up debugging.
if (debug) {
- talk_base::LogMessage::LogToDebug(talk_base::LS_VERBOSE);
+ rtc::LogMessage::LogToDebug(rtc::LS_VERBOSE);
}
if (!log.empty()) {
- talk_base::StreamInterface* stream =
- talk_base::Filesystem::OpenFile(log, "a");
+ rtc::StreamInterface* stream =
+ rtc::Filesystem::OpenFile(log, "a");
if (stream) {
- talk_base::LogMessage::LogToStream(stream, talk_base::LS_VERBOSE);
+ rtc::LogMessage::LogToStream(stream, rtc::LS_VERBOSE);
} else {
Print(("Cannot open debug log " + log + "\n").c_str());
return 1;
@@ -307,12 +307,12 @@
}
// Set up the crypto subsystem.
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
// Parse username and password, if present.
buzz::Jid jid;
std::string username;
- talk_base::InsecureCryptStringImpl pass;
+ rtc::InsecureCryptStringImpl pass;
if (argc > 1) {
username = argv[1];
if (argc > 2) {
@@ -364,7 +364,7 @@
xcs.set_use_tls(buzz::TLS_DISABLED);
xcs.set_test_server_domain("google.com");
}
- xcs.set_pass(talk_base::CryptString(pass));
+ xcs.set_pass(rtc::CryptString(pass));
if (!oauth_token.empty()) {
xcs.set_auth_token(buzz::AUTH_MECHANISM_OAUTH2, oauth_token);
}
@@ -381,7 +381,7 @@
port = atoi(server.substr(colon + 1).c_str());
}
- xcs.set_server(talk_base::SocketAddress(host, port));
+ xcs.set_server(rtc::SocketAddress(host, port));
// Decide on the signaling and crypto settings.
cricket::SignalingProtocol signaling_protocol = cricket::PROTOCOL_HYBRID;
@@ -428,7 +428,7 @@
return 1;
}
if (dtls_policy != cricket::SEC_DISABLED) {
- ssl_identity = talk_base::SSLIdentity::Generate(jid.Str());
+ ssl_identity = rtc::SSLIdentity::Generate(jid.Str());
if (!ssl_identity) {
Print("Failed to generate identity for DTLS.\n");
return 1;
@@ -441,13 +441,13 @@
#if WIN32
// Need to pump messages on our main thread on Windows.
- talk_base::Win32Thread w32_thread;
- talk_base::ThreadManager::Instance()->SetCurrentThread(&w32_thread);
+ rtc::Win32Thread w32_thread;
+ rtc::ThreadManager::Instance()->SetCurrentThread(&w32_thread);
#endif
- talk_base::Thread* main_thread = talk_base::Thread::Current();
+ rtc::Thread* main_thread = rtc::Thread::Current();
#ifdef OSX
- talk_base::MacCocoaSocketServer ss;
- talk_base::SocketServerScope ss_scope(&ss);
+ rtc::MacCocoaSocketServer ss;
+ rtc::SocketServerScope ss_scope(&ss);
#endif
buzz::XmppPump pump;
diff --git a/examples/call/call_unittest.cc b/examples/call/call_unittest.cc
index d95f1dd..cc2878f 100644
--- a/examples/call/call_unittest.cc
+++ b/examples/call/call_unittest.cc
@@ -27,11 +27,11 @@
// Main function for all unit tests in talk/examples/call
-#include "talk/base/logging.h"
#include "testing/base/public/gunit.h"
+#include "webrtc/base/logging.h"
int main(int argc, char **argv) {
- talk_base::LogMessage::LogToDebug(talk_base::LogMessage::NO_LOGGING);
+ rtc::LogMessage::LogToDebug(rtc::LogMessage::NO_LOGGING);
testing::ParseGUnitFlags(&argc, argv);
return RUN_ALL_TESTS();
}
diff --git a/examples/call/callclient.cc b/examples/call/callclient.cc
index 849455e..b31e24a 100644
--- a/examples/call/callclient.cc
+++ b/examples/call/callclient.cc
@@ -29,14 +29,6 @@
#include <string>
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/network.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/windowpickerfactory.h"
#include "talk/examples/call/console.h"
#include "talk/examples/call/friendinvitesendtask.h"
#include "talk/examples/call/muc.h"
@@ -47,6 +39,14 @@
#include "talk/media/base/mediaengine.h"
#include "talk/media/base/rtpdataengine.h"
#include "talk/media/base/screencastid.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/windowpickerfactory.h"
#ifdef HAVE_SCTP
#include "talk/media/sctp/sctpdataengine.h"
#endif
@@ -62,8 +62,8 @@
#include "talk/xmpp/hangoutpubsubclient.h"
#include "talk/xmpp/mucroomconfigtask.h"
#include "talk/xmpp/mucroomlookuptask.h"
-#include "talk/xmpp/presenceouttask.h"
#include "talk/xmpp/pingtask.h"
+#include "talk/xmpp/presenceouttask.h"
namespace {
@@ -94,7 +94,7 @@
int GetInt(const std::vector<std::string>& words, size_t index, int def) {
int val;
- if (words.size() > index && talk_base::FromString(words[index], &val)) {
+ if (words.size() > index && rtc::FromString(words[index], &val)) {
return val;
} else {
return def;
@@ -251,7 +251,7 @@
console_->PrintLine("Can't screencast twice. Unscreencast first.");
} else {
std::string streamid = "screencast";
- screencast_ssrc_ = talk_base::CreateRandomId();
+ screencast_ssrc_ = rtc::CreateRandomId();
int fps = GetInt(words, 1, 5); // Default to 5 fps.
cricket::ScreencastId screencastid;
@@ -478,7 +478,7 @@
}
void CallClient::InitMedia() {
- worker_thread_ = new talk_base::Thread();
+ worker_thread_ = new rtc::Thread();
// The worker thread must be started here since initialization of
// the ChannelManager will generate messages that need to be
// dispatched by it.
@@ -486,13 +486,15 @@
// TODO: It looks like we are leaking many objects. E.g.
// |network_manager_| is never deleted.
- network_manager_ = new talk_base::BasicNetworkManager();
+ network_manager_ = new rtc::BasicNetworkManager();
// TODO: Decide if the relay address should be specified here.
- talk_base::SocketAddress stun_addr("stun.l.google.com", 19302);
+ rtc::SocketAddress stun_addr("stun.l.google.com", 19302);
+ cricket::ServerAddresses stun_servers;
+ stun_servers.insert(stun_addr);
port_allocator_ = new cricket::BasicPortAllocator(
- network_manager_, stun_addr, talk_base::SocketAddress(),
- talk_base::SocketAddress(), talk_base::SocketAddress());
+ network_manager_, stun_servers, rtc::SocketAddress(),
+ rtc::SocketAddress(), rtc::SocketAddress());
if (portallocator_flags_ != 0) {
port_allocator_->set_flags(portallocator_flags_);
@@ -683,7 +685,7 @@
void CallClient::StartXmppPing() {
buzz::PingTask* ping = new buzz::PingTask(
- xmpp_client_, talk_base::Thread::Current(),
+ xmpp_client_, rtc::Thread::Current(),
kPingPeriodMillis, kPingTimeoutMillis);
ping->SignalTimeout.connect(this, &CallClient::OnPingTimeout);
ping->Start();
@@ -739,7 +741,7 @@
void CallClient::SendChat(const std::string& to, const std::string msg) {
buzz::XmlElement* stanza = new buzz::XmlElement(buzz::QN_MESSAGE);
stanza->AddAttr(buzz::QN_TO, to);
- stanza->AddAttr(buzz::QN_ID, talk_base::CreateRandomString(16));
+ stanza->AddAttr(buzz::QN_ID, rtc::CreateRandomString(16));
stanza->AddAttr(buzz::QN_TYPE, "chat");
buzz::XmlElement* body = new buzz::XmlElement(buzz::QN_BODY);
body->SetBodyText(msg);
@@ -779,7 +781,7 @@
cricket::SendDataParams params;
params.ssrc = stream.first_ssrc();
- talk_base::Buffer payload(text.data(), text.length());
+ rtc::Buffer payload(text.data(), text.length());
cricket::SendDataResult result;
bool sent = call_->SendData(session, params, payload, &result);
if (!sent) {
@@ -854,7 +856,7 @@
void CallClient::OnDataReceived(cricket::Call*,
const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload) {
+ const rtc::Buffer& payload) {
// TODO(mylesj): Support receiving data on sessions other than the first.
cricket::Session* session = GetFirstSession();
if (!session)
@@ -887,10 +889,8 @@
AddSession(call_->InitiateSession(jid, media_client_->jid(), options));
}
media_client_->SetFocus(call_);
- if (call_->has_video() && render_) {
- if (!options.is_muc) {
- call_->SetLocalRenderer(local_renderer_);
- }
+ if (call_->has_video() && render_ && !options.is_muc) {
+ // TODO(pthatcher): Hookup local_render_ to the local capturer.
}
if (options.is_muc) {
const std::string& nick = mucs_[jid]->local_jid().resource();
@@ -1084,7 +1084,7 @@
call_->AcceptSession(session, options);
media_client_->SetFocus(call_);
if (call_->has_video() && render_) {
- call_->SetLocalRenderer(local_renderer_);
+ // TODO(pthatcher): Hookup local_render_ to the local capturer.
RenderAllStreams(call_, session, true);
}
SetupAcceptedCall();
@@ -1104,7 +1104,7 @@
}
void CallClient::Quit() {
- talk_base::Thread::Current()->Quit();
+ rtc::Thread::Current()->Quit();
}
void CallClient::SetNick(const std::string& muc_nick) {
@@ -1283,8 +1283,9 @@
return;
}
- if (!status.available()) {
- // Remove them from the room.
+ if (status.available()) {
+ muc->members()[status.jid().resource()] = status;
+ } else {
muc->members().erase(status.jid().resource());
}
}
@@ -1562,7 +1563,7 @@
}
}
- talk_base::sprintfn(guid_room,
+ rtc::sprintfn(guid_room,
ARRAY_SIZE(guid_room),
"private-chat-%s@%s",
guid,
@@ -1572,19 +1573,19 @@
bool CallClient::SelectFirstDesktopScreencastId(
cricket::ScreencastId* screencastid) {
- if (!talk_base::WindowPickerFactory::IsSupported()) {
+ if (!rtc::WindowPickerFactory::IsSupported()) {
LOG(LS_WARNING) << "Window picker not suported on this OS.";
return false;
}
- talk_base::WindowPicker* picker =
- talk_base::WindowPickerFactory::CreateWindowPicker();
+ rtc::WindowPicker* picker =
+ rtc::WindowPickerFactory::CreateWindowPicker();
if (!picker) {
LOG(LS_WARNING) << "Could not create a window picker.";
return false;
}
- talk_base::DesktopDescriptionList desktops;
+ rtc::DesktopDescriptionList desktops;
if (!picker->GetDesktopList(&desktops) || desktops.empty()) {
LOG(LS_WARNING) << "Could not get a list of desktops.";
return false;
diff --git a/examples/call/callclient.h b/examples/call/callclient.h
index 39a5b11..50c584b 100644
--- a/examples/call/callclient.h
+++ b/examples/call/callclient.h
@@ -32,8 +32,6 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslidentity.h"
#include "talk/examples/call/console.h"
#include "talk/media/base/mediachannel.h"
#include "talk/p2p/base/session.h"
@@ -42,6 +40,8 @@
#include "talk/xmpp/hangoutpubsubclient.h"
#include "talk/xmpp/presencestatus.h"
#include "talk/xmpp/xmppclient.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sslidentity.h"
namespace buzz {
class PresencePushTask;
@@ -62,10 +62,10 @@
struct MucRoomInfo;
} // namespace buzz
-namespace talk_base {
+namespace rtc {
class Thread;
class NetworkManager;
-} // namespace talk_base
+} // namespace rtc
namespace cricket {
class PortAllocator;
@@ -166,7 +166,7 @@
sdes_policy_ = sdes_policy;
dtls_policy_ = dtls_policy;
}
- void SetSslIdentity(talk_base::SSLIdentity* identity) {
+ void SetSslIdentity(rtc::SSLIdentity* identity) {
ssl_identity_.reset(identity);
}
@@ -242,7 +242,7 @@
const buzz::XmlElement* stanza);
void OnDataReceived(cricket::Call*,
const cricket::ReceiveDataParams& params,
- const talk_base::Buffer& payload);
+ const rtc::Buffer& payload);
buzz::Jid GenerateRandomMucJid();
// Depending on |enable|, render (or don't) all the streams in |session|.
@@ -303,8 +303,8 @@
Console *console_;
buzz::XmppClient* xmpp_client_;
- talk_base::Thread* worker_thread_;
- talk_base::NetworkManager* network_manager_;
+ rtc::Thread* worker_thread_;
+ rtc::NetworkManager* network_manager_;
cricket::PortAllocator* port_allocator_;
cricket::SessionManager* session_manager_;
cricket::SessionManagerTask* session_manager_task_;
@@ -343,7 +343,7 @@
cricket::TransportProtocol transport_protocol_;
cricket::SecurePolicy sdes_policy_;
cricket::SecurePolicy dtls_policy_;
- talk_base::scoped_ptr<talk_base::SSLIdentity> ssl_identity_;
+ rtc::scoped_ptr<rtc::SSLIdentity> ssl_identity_;
std::string last_sent_to_;
bool show_roster_messages_;
diff --git a/examples/call/callclient_unittest.cc b/examples/call/callclient_unittest.cc
index b0e9d89..d11580e 100644
--- a/examples/call/callclient_unittest.cc
+++ b/examples/call/callclient_unittest.cc
@@ -27,11 +27,11 @@
// Unit tests for CallClient
-#include "talk/base/gunit.h"
#include "talk/examples/call/callclient.h"
#include "talk/media/base/filemediaengine.h"
#include "talk/media/base/mediaengine.h"
#include "talk/xmpp/xmppthread.h"
+#include "webrtc/base/gunit.h"
TEST(CallClientTest, CreateCallClientWithDefaultMediaEngine) {
buzz::XmppPump pump;
diff --git a/examples/call/console.cc b/examples/call/console.cc
index 647601e..a0da2af 100644
--- a/examples/call/console.cc
+++ b/examples/call/console.cc
@@ -35,17 +35,17 @@
#include <unistd.h>
#endif // POSIX
-#include "talk/base/logging.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/stringutils.h"
-#include "talk/examples/call/console.h"
#include "talk/examples/call/callclient.h"
+#include "talk/examples/call/console.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/stringutils.h"
#ifdef POSIX
static void DoNothing(int unused) {}
#endif
-Console::Console(talk_base::Thread *thread, CallClient *client) :
+Console::Console(rtc::Thread *thread, CallClient *client) :
client_(client),
client_thread_(thread),
stopped_(false) {}
@@ -64,7 +64,7 @@
LOG(LS_WARNING) << "Already started";
return;
}
- console_thread_.reset(new talk_base::Thread());
+ console_thread_.reset(new rtc::Thread());
console_thread_->Start();
console_thread_->Post(this, MSG_START);
}
@@ -140,11 +140,11 @@
char input_buffer[128];
while (fgets(input_buffer, sizeof(input_buffer), stdin) != NULL) {
client_thread_->Post(this, MSG_INPUT,
- new talk_base::TypedMessageData<std::string>(input_buffer));
+ new rtc::TypedMessageData<std::string>(input_buffer));
}
}
-void Console::OnMessage(talk_base::Message *msg) {
+void Console::OnMessage(rtc::Message *msg) {
switch (msg->message_id) {
case MSG_START:
#ifdef POSIX
@@ -161,8 +161,8 @@
RunConsole();
break;
case MSG_INPUT:
- talk_base::TypedMessageData<std::string> *data =
- static_cast<talk_base::TypedMessageData<std::string>*>(msg->pdata);
+ rtc::TypedMessageData<std::string> *data =
+ static_cast<rtc::TypedMessageData<std::string>*>(msg->pdata);
client_->ParseLine(data->data());
break;
}
diff --git a/examples/call/console.h b/examples/call/console.h
index f0f36e3..abcae99 100644
--- a/examples/call/console.h
+++ b/examples/call/console.h
@@ -30,15 +30,15 @@
#include <stdio.h>
-#include "talk/base/thread.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/scoped_ptr.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread.h"
class CallClient;
-class Console : public talk_base::MessageHandler {
+class Console : public rtc::MessageHandler {
public:
- Console(talk_base::Thread *thread, CallClient *client);
+ Console(rtc::Thread *thread, CallClient *client);
~Console();
// Starts reading lines from the console and giving them to the CallClient.
@@ -46,7 +46,7 @@
// Stops reading lines. Cannot be restarted.
void Stop();
- virtual void OnMessage(talk_base::Message *msg);
+ virtual void OnMessage(rtc::Message *msg);
void PrintLine(const char* format, ...);
@@ -62,8 +62,8 @@
void ParseLine(std::string &str);
CallClient *client_;
- talk_base::Thread *client_thread_;
- talk_base::scoped_ptr<talk_base::Thread> console_thread_;
+ rtc::Thread *client_thread_;
+ rtc::scoped_ptr<rtc::Thread> console_thread_;
bool stopped_;
};
diff --git a/examples/call/friendinvitesendtask.cc b/examples/call/friendinvitesendtask.cc
index cdb0b2c..dae1006 100644
--- a/examples/call/friendinvitesendtask.cc
+++ b/examples/call/friendinvitesendtask.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/xmpp/constants.h"
#include "talk/examples/call/friendinvitesendtask.h"
+#include "talk/xmpp/constants.h"
namespace buzz {
diff --git a/examples/call/mediaenginefactory.cc b/examples/call/mediaenginefactory.cc
index 983345d..dd62bf8 100644
--- a/examples/call/mediaenginefactory.cc
+++ b/examples/call/mediaenginefactory.cc
@@ -27,10 +27,10 @@
#include "talk/examples/call/mediaenginefactory.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/filemediaengine.h"
#include "talk/media/base/mediaengine.h"
+#include "webrtc/base/stringutils.h"
std::vector<cricket::AudioCodec> RequiredAudioCodecs() {
std::vector<cricket::AudioCodec> audio_codecs;
diff --git a/examples/call/mucinviterecvtask.cc b/examples/call/mucinviterecvtask.cc
index 061db74..e32456f 100644
--- a/examples/call/mucinviterecvtask.cc
+++ b/examples/call/mucinviterecvtask.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/xmpp/constants.h"
#include "talk/examples/call/mucinviterecvtask.h"
+#include "talk/xmpp/constants.h"
namespace buzz {
diff --git a/examples/call/mucinviterecvtask.h b/examples/call/mucinviterecvtask.h
index 24f05e0..ddfd6be 100644
--- a/examples/call/mucinviterecvtask.h
+++ b/examples/call/mucinviterecvtask.h
@@ -30,9 +30,9 @@
#include <vector>
-#include "talk/base/sigslot.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
+#include "webrtc/base/sigslot.h"
namespace buzz {
diff --git a/examples/call/mucinvitesendtask.h b/examples/call/mucinvitesendtask.h
index 2429b31..3ae74c1 100644
--- a/examples/call/mucinvitesendtask.h
+++ b/examples/call/mucinvitesendtask.h
@@ -28,9 +28,9 @@
#ifndef _MUCINVITESENDTASK_H_
#define _MUCINVITESENDTASK_H_
+#include "talk/examples/call/muc.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
-#include "talk/examples/call/muc.h"
namespace buzz {
diff --git a/examples/call/presencepushtask.cc b/examples/call/presencepushtask.cc
index af02b1f..b598eb6 100644
--- a/examples/call/presencepushtask.cc
+++ b/examples/call/presencepushtask.cc
@@ -27,9 +27,9 @@
#include "talk/examples/call/presencepushtask.h"
-#include "talk/base/stringencode.h"
#include "talk/examples/call/muc.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/stringencode.h"
@@ -153,7 +153,7 @@
const XmlElement * priority = stanza->FirstNamed(QN_PRIORITY);
if (priority != NULL) {
int pri;
- if (talk_base::FromString(priority->BodyText(), &pri)) {
+ if (rtc::FromString(priority->BodyText(), &pri)) {
s->set_priority(pri);
}
}
diff --git a/examples/call/presencepushtask.h b/examples/call/presencepushtask.h
index 9cd1b42..c13a4f5 100644
--- a/examples/call/presencepushtask.h
+++ b/examples/call/presencepushtask.h
@@ -30,11 +30,11 @@
#include <vector>
+#include "talk/examples/call/callclient.h"
+#include "talk/xmpp/presencestatus.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
-#include "talk/xmpp/presencestatus.h"
-#include "talk/base/sigslot.h"
-#include "talk/examples/call/callclient.h"
+#include "webrtc/base/sigslot.h"
namespace buzz {
diff --git a/examples/login/login_main.cc b/examples/login/login_main.cc
index 5c5d1d7..bfe12af 100644
--- a/examples/login/login_main.cc
+++ b/examples/login/login_main.cc
@@ -29,11 +29,11 @@
#include <iostream>
-#include "talk/base/thread.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/xmppclientsettings.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmppthread.h"
+#include "webrtc/base/thread.h"
int main(int argc, char **argv) {
std::cout << "OAuth Access Token: ";
@@ -54,7 +54,7 @@
xcs.set_use_tls(buzz::TLS_DISABLED);
xcs.set_auth_token(buzz::AUTH_MECHANISM_OAUTH2,
auth_token.c_str());
- xcs.set_server(talk_base::SocketAddress("talk.google.com", 5222));
+ xcs.set_server(rtc::SocketAddress("talk.google.com", 5222));
thread.Login(xcs);
// Use main thread for console input
diff --git a/examples/objc/AppRTCDemo/ios/APPRTCViewController.m b/examples/objc/AppRTCDemo/ios/APPRTCViewController.m
index a4a0bd3..8042762 100644
--- a/examples/objc/AppRTCDemo/ios/APPRTCViewController.m
+++ b/examples/objc/AppRTCDemo/ios/APPRTCViewController.m
@@ -63,6 +63,18 @@
- (void)viewDidLoad {
[super viewDidLoad];
+
+ self.remoteVideoView =
+ [[RTCEAGLVideoView alloc] initWithFrame:self.blackView.bounds];
+ self.remoteVideoView.delegate = self;
+ self.remoteVideoView.transform = CGAffineTransformMakeScale(-1, 1);
+ [self.blackView addSubview:self.remoteVideoView];
+
+ self.localVideoView =
+ [[RTCEAGLVideoView alloc] initWithFrame:self.blackView.bounds];
+ self.localVideoView.delegate = self;
+ [self.blackView addSubview:self.localVideoView];
+
self.statusBarOrientation =
[UIApplication sharedApplication].statusBarOrientation;
self.roomInput.delegate = self;
@@ -181,25 +193,13 @@
self.instructionsView.hidden = NO;
self.logView.hidden = YES;
self.logView.text = nil;
+ self.localVideoView.videoTrack = nil;
+ self.remoteVideoView.videoTrack = nil;
self.blackView.hidden = YES;
- [self.remoteVideoView removeFromSuperview];
- self.remoteVideoView = nil;
- [self.localVideoView removeFromSuperview];
- self.localVideoView = nil;
}
- (void)setupCaptureSession {
self.blackView.hidden = NO;
- self.remoteVideoView =
- [[RTCEAGLVideoView alloc] initWithFrame:self.blackView.bounds];
- self.remoteVideoView.delegate = self;
- self.remoteVideoView.transform = CGAffineTransformMakeScale(-1, 1);
- [self.blackView addSubview:self.remoteVideoView];
-
- self.localVideoView =
- [[RTCEAGLVideoView alloc] initWithFrame:self.blackView.bounds];
- self.localVideoView.delegate = self;
- [self.blackView addSubview:self.localVideoView];
[self updateVideoViewLayout];
}
diff --git a/examples/objc/AppRTCDemo/ios/AppRTCDemo-Prefix.pch b/examples/objc/AppRTCDemo/ios/AppRTCDemo-Prefix.pch
index 3ac2c3b..cf7719c 100644
--- a/examples/objc/AppRTCDemo/ios/AppRTCDemo-Prefix.pch
+++ b/examples/objc/AppRTCDemo/ios/AppRTCDemo-Prefix.pch
@@ -36,5 +36,5 @@
#warning "This project uses features only available in iOS SDK 6.0 and later."
#endif
-#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
+#import <UIKit/UIKit.h>
diff --git a/examples/peerconnection/client/conductor.cc b/examples/peerconnection/client/conductor.cc
index bbab3d0..f49aee6 100644
--- a/examples/peerconnection/client/conductor.cc
+++ b/examples/peerconnection/client/conductor.cc
@@ -30,11 +30,11 @@
#include <utility>
#include "talk/app/webrtc/videosourceinterface.h"
-#include "talk/base/common.h"
-#include "talk/base/json.h"
-#include "talk/base/logging.h"
#include "talk/examples/peerconnection/client/defaults.h"
#include "talk/media/devices/devicemanager.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/json.h"
+#include "webrtc/base/logging.h"
// Names used for a IceCandidate JSON object.
const char kCandidateSdpMidName[] = "sdpMid";
@@ -50,7 +50,7 @@
public:
static DummySetSessionDescriptionObserver* Create() {
return
- new talk_base::RefCountedObject<DummySetSessionDescriptionObserver>();
+ new rtc::RefCountedObject<DummySetSessionDescriptionObserver>();
}
virtual void OnSuccess() {
LOG(INFO) << __FUNCTION__;
@@ -272,7 +272,7 @@
LOG(WARNING) << "Can't parse received message.";
return;
}
- talk_base::scoped_ptr<webrtc::IceCandidateInterface> candidate(
+ rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(
webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp));
if (!candidate.get()) {
LOG(WARNING) << "Can't parse received candidate message.";
@@ -332,7 +332,7 @@
}
cricket::VideoCapturer* Conductor::OpenVideoCaptureDevice() {
- talk_base::scoped_ptr<cricket::DeviceManagerInterface> dev_manager(
+ rtc::scoped_ptr<cricket::DeviceManagerInterface> dev_manager(
cricket::DeviceManagerFactory::Create());
if (!dev_manager->Init()) {
LOG(LS_ERROR) << "Can't create device manager";
@@ -357,18 +357,18 @@
if (active_streams_.find(kStreamLabel) != active_streams_.end())
return; // Already added.
- talk_base::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
+ rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
peer_connection_factory_->CreateAudioTrack(
kAudioLabel, peer_connection_factory_->CreateAudioSource(NULL)));
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> video_track(
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
peer_connection_factory_->CreateVideoTrack(
kVideoLabel,
peer_connection_factory_->CreateVideoSource(OpenVideoCaptureDevice(),
NULL)));
main_wnd_->StartLocalRenderer(video_track);
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> stream =
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
peer_connection_factory_->CreateLocalMediaStream(kStreamLabel);
stream->AddTrack(audio_track);
@@ -377,7 +377,7 @@
LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
}
typedef std::pair<std::string,
- talk_base::scoped_refptr<webrtc::MediaStreamInterface> >
+ rtc::scoped_refptr<webrtc::MediaStreamInterface> >
MediaStreamPair;
active_streams_.insert(MediaStreamPair(stream->label(), stream));
main_wnd_->SwitchToStreamingUI();
diff --git a/examples/peerconnection/client/conductor.h b/examples/peerconnection/client/conductor.h
index f9fb393..0aff531 100644
--- a/examples/peerconnection/client/conductor.h
+++ b/examples/peerconnection/client/conductor.h
@@ -34,11 +34,11 @@
#include <set>
#include <string>
-#include "talk/examples/peerconnection/client/main_wnd.h"
-#include "talk/examples/peerconnection/client/peer_connection_client.h"
#include "talk/app/webrtc/mediastreaminterface.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
-#include "talk/base/scoped_ptr.h"
+#include "talk/examples/peerconnection/client/main_wnd.h"
+#include "talk/examples/peerconnection/client/peer_connection_client.h"
+#include "webrtc/base/scoped_ptr.h"
namespace webrtc {
class VideoCaptureModule;
@@ -130,13 +130,13 @@
void SendMessage(const std::string& json_object);
int peer_id_;
- talk_base::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
- talk_base::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
+ rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
+ rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
peer_connection_factory_;
PeerConnectionClient* client_;
MainWindow* main_wnd_;
std::deque<std::string*> pending_messages_;
- std::map<std::string, talk_base::scoped_refptr<webrtc::MediaStreamInterface> >
+ std::map<std::string, rtc::scoped_refptr<webrtc::MediaStreamInterface> >
active_streams_;
std::string server_;
};
diff --git a/examples/peerconnection/client/defaults.cc b/examples/peerconnection/client/defaults.cc
index 40f3dd1..15252c6 100644
--- a/examples/peerconnection/client/defaults.cc
+++ b/examples/peerconnection/client/defaults.cc
@@ -36,7 +36,7 @@
#include <unistd.h>
#endif
-#include "talk/base/common.h"
+#include "webrtc/base/common.h"
const char kAudioLabel[] = "audio_label";
const char kVideoLabel[] = "video_label";
diff --git a/examples/peerconnection/client/defaults.h b/examples/peerconnection/client/defaults.h
index f646149..5834f34 100644
--- a/examples/peerconnection/client/defaults.h
+++ b/examples/peerconnection/client/defaults.h
@@ -31,7 +31,7 @@
#include <string>
-#include "talk/base/basictypes.h"
+#include "webrtc/base/basictypes.h"
extern const char kAudioLabel[];
extern const char kVideoLabel[];
diff --git a/examples/peerconnection/client/flagdefs.h b/examples/peerconnection/client/flagdefs.h
index c135bbb..3d3edca 100644
--- a/examples/peerconnection/client/flagdefs.h
+++ b/examples/peerconnection/client/flagdefs.h
@@ -29,7 +29,7 @@
#define TALK_EXAMPLES_PEERCONNECTION_CLIENT_FLAGDEFS_H_
#pragma once
-#include "talk/base/flags.h"
+#include "webrtc/base/flags.h"
extern const uint16 kDefaultServerPort; // From defaults.[h|cc]
diff --git a/examples/peerconnection/client/linux/main.cc b/examples/peerconnection/client/linux/main.cc
index 4ef81cd..67fd33d 100644
--- a/examples/peerconnection/client/linux/main.cc
+++ b/examples/peerconnection/client/linux/main.cc
@@ -32,12 +32,12 @@
#include "talk/examples/peerconnection/client/linux/main_wnd.h"
#include "talk/examples/peerconnection/client/peer_connection_client.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/thread.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/thread.h"
-class CustomSocketServer : public talk_base::PhysicalSocketServer {
+class CustomSocketServer : public rtc::PhysicalSocketServer {
public:
- CustomSocketServer(talk_base::Thread* thread, GtkMainWnd* wnd)
+ CustomSocketServer(rtc::Thread* thread, GtkMainWnd* wnd)
: thread_(thread), wnd_(wnd), conductor_(NULL), client_(NULL) {}
virtual ~CustomSocketServer() {}
@@ -58,12 +58,12 @@
client_ != NULL && !client_->is_connected()) {
thread_->Quit();
}
- return talk_base::PhysicalSocketServer::Wait(0/*cms == -1 ? 1 : cms*/,
+ return rtc::PhysicalSocketServer::Wait(0/*cms == -1 ? 1 : cms*/,
process_io);
}
protected:
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
GtkMainWnd* wnd_;
Conductor* conductor_;
PeerConnectionClient* client_;
@@ -74,9 +74,9 @@
g_type_init();
g_thread_init(NULL);
- FlagList::SetFlagsFromCommandLine(&argc, argv, true);
+ rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
if (FLAG_help) {
- FlagList::Print(NULL, false);
+ rtc::FlagList::Print(NULL, false);
return 0;
}
@@ -90,16 +90,16 @@
GtkMainWnd wnd(FLAG_server, FLAG_port, FLAG_autoconnect, FLAG_autocall);
wnd.Create();
- talk_base::AutoThread auto_thread;
- talk_base::Thread* thread = talk_base::Thread::Current();
+ rtc::AutoThread auto_thread;
+ rtc::Thread* thread = rtc::Thread::Current();
CustomSocketServer socket_server(thread, &wnd);
thread->set_socketserver(&socket_server);
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
// Must be constructed after we set the socketserver.
PeerConnectionClient client;
- talk_base::scoped_refptr<Conductor> conductor(
- new talk_base::RefCountedObject<Conductor>(&client, &wnd));
+ rtc::scoped_refptr<Conductor> conductor(
+ new rtc::RefCountedObject<Conductor>(&client, &wnd));
socket_server.set_client(&client);
socket_server.set_conductor(conductor);
@@ -113,7 +113,7 @@
//while (gtk_events_pending()) {
// gtk_main_iteration();
//}
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
return 0;
}
diff --git a/examples/peerconnection/client/linux/main_wnd.cc b/examples/peerconnection/client/linux/main_wnd.cc
index 0a2e1f6..55f3649 100644
--- a/examples/peerconnection/client/linux/main_wnd.cc
+++ b/examples/peerconnection/client/linux/main_wnd.cc
@@ -33,11 +33,11 @@
#include <stddef.h>
#include "talk/examples/peerconnection/client/defaults.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringutils.h"
-using talk_base::sprintfn;
+using rtc::sprintfn;
namespace {
diff --git a/examples/peerconnection/client/linux/main_wnd.h b/examples/peerconnection/client/linux/main_wnd.h
index 5a44640..6e45333 100644
--- a/examples/peerconnection/client/linux/main_wnd.h
+++ b/examples/peerconnection/client/linux/main_wnd.h
@@ -110,11 +110,11 @@
}
protected:
- talk_base::scoped_ptr<uint8[]> image_;
+ rtc::scoped_ptr<uint8[]> image_;
int width_;
int height_;
GtkMainWnd* main_wnd_;
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> rendered_track_;
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> rendered_track_;
};
protected:
@@ -129,9 +129,9 @@
std::string port_;
bool autoconnect_;
bool autocall_;
- talk_base::scoped_ptr<VideoRenderer> local_renderer_;
- talk_base::scoped_ptr<VideoRenderer> remote_renderer_;
- talk_base::scoped_ptr<uint8> draw_buffer_;
+ rtc::scoped_ptr<VideoRenderer> local_renderer_;
+ rtc::scoped_ptr<VideoRenderer> remote_renderer_;
+ rtc::scoped_ptr<uint8> draw_buffer_;
int draw_buffer_size_;
};
diff --git a/examples/peerconnection/client/main.cc b/examples/peerconnection/client/main.cc
index e68c78e..34fadfa 100644
--- a/examples/peerconnection/client/main.cc
+++ b/examples/peerconnection/client/main.cc
@@ -26,29 +26,47 @@
*/
#include "talk/examples/peerconnection/client/conductor.h"
+#include "talk/examples/peerconnection/client/flagdefs.h"
#include "talk/examples/peerconnection/client/main_wnd.h"
#include "talk/examples/peerconnection/client/peer_connection_client.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/win32socketinit.h"
-#include "talk/base/win32socketserver.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/win32socketinit.h"
+#include "webrtc/base/win32socketserver.h"
int PASCAL wWinMain(HINSTANCE instance, HINSTANCE prev_instance,
wchar_t* cmd_line, int cmd_show) {
- talk_base::EnsureWinsockInit();
- talk_base::Win32Thread w32_thread;
- talk_base::ThreadManager::Instance()->SetCurrentThread(&w32_thread);
+ rtc::EnsureWinsockInit();
+ rtc::Win32Thread w32_thread;
+ rtc::ThreadManager::Instance()->SetCurrentThread(&w32_thread);
- MainWnd wnd;
+ rtc::WindowsCommandLineArguments win_args;
+ int argc = win_args.argc();
+ char **argv = win_args.argv();
+
+ rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
+ if (FLAG_help) {
+ rtc::FlagList::Print(NULL, false);
+ return 0;
+ }
+
+ // Abort if the user specifies a port that is outside the allowed
+ // range [1, 65535].
+ if ((FLAG_port < 1) || (FLAG_port > 65535)) {
+ printf("Error: %i is not a valid port.\n", FLAG_port);
+ return -1;
+ }
+
+ MainWnd wnd(FLAG_server, FLAG_port, FLAG_autoconnect, FLAG_autocall);
if (!wnd.Create()) {
ASSERT(false);
return -1;
}
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
PeerConnectionClient client;
- talk_base::scoped_refptr<Conductor> conductor(
- new talk_base::RefCountedObject<Conductor>(&client, &wnd));
+ rtc::scoped_refptr<Conductor> conductor(
+ new rtc::RefCountedObject<Conductor>(&client, &wnd));
// Main loop.
MSG msg;
@@ -70,6 +88,6 @@
}
}
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
return 0;
}
diff --git a/examples/peerconnection/client/main_wnd.cc b/examples/peerconnection/client/main_wnd.cc
index 6211e99..05c73ec 100644
--- a/examples/peerconnection/client/main_wnd.cc
+++ b/examples/peerconnection/client/main_wnd.cc
@@ -29,13 +29,15 @@
#include <math.h>
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
#include "talk/examples/peerconnection/client/defaults.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
ATOM MainWnd::wnd_class_ = 0;
const wchar_t MainWnd::kClassName[] = L"WebRTC_MainWnd";
+using rtc::sprintfn;
+
namespace {
const char kConnecting[] = "Connecting... ";
@@ -79,10 +81,15 @@
} // namespace
-MainWnd::MainWnd()
+MainWnd::MainWnd(const char* server, int port, bool auto_connect,
+ bool auto_call)
: ui_(CONNECT_TO_SERVER), wnd_(NULL), edit1_(NULL), edit2_(NULL),
label1_(NULL), label2_(NULL), button_(NULL), listbox_(NULL),
- destroyed_(false), callback_(NULL), nested_msg_(NULL) {
+ destroyed_(false), callback_(NULL), nested_msg_(NULL),
+ server_(server), auto_connect_(auto_connect), auto_call_(auto_call) {
+ char buffer[10] = {0};
+ sprintfn(buffer, sizeof(buffer), "%i", port);
+ port_ = buffer;
}
MainWnd::~MainWnd() {
@@ -158,6 +165,9 @@
ui_ = CONNECT_TO_SERVER;
LayoutConnectUI(true);
::SetFocus(edit1_);
+
+ if (auto_connect_)
+ ::PostMessage(button_, BM_CLICK, 0, 0);
}
void MainWnd::SwitchToPeerList(const Peers& peers) {
@@ -173,6 +183,19 @@
ui_ = LIST_PEERS;
LayoutPeerListUI(true);
::SetFocus(listbox_);
+
+ if (auto_call_ && peers.begin() != peers.end()) {
+ // Get the number of items in the list
+ LRESULT count = ::SendMessage(listbox_, LB_GETCOUNT, 0, 0);
+ if (count != LB_ERR) {
+ // Select the last item in the list
+ LRESULT selection = ::SendMessage(listbox_, LB_SETCURSEL , count - 1, 0);
+ if (selection != LB_ERR)
+ ::PostMessage(wnd_, WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(listbox_),
+ LBN_DBLCLK),
+ reinterpret_cast<LPARAM>(listbox_));
+ }
+ }
}
void MainWnd::SwitchToStreamingUI() {
@@ -465,8 +488,8 @@
CreateChildWindow(&listbox_, LISTBOX_ID, L"ListBox",
LBS_HASSTRINGS | LBS_NOTIFY, WS_EX_CLIENTEDGE);
- ::SetWindowTextA(edit1_, GetDefaultServerName().c_str());
- ::SetWindowTextA(edit2_, "8888");
+ ::SetWindowTextA(edit1_, server_.c_str());
+ ::SetWindowTextA(edit2_, port_.c_str());
}
void MainWnd::LayoutConnectUI(bool show) {
diff --git a/examples/peerconnection/client/main_wnd.h b/examples/peerconnection/client/main_wnd.h
index 6d2bf3e..08bdabb 100644
--- a/examples/peerconnection/client/main_wnd.h
+++ b/examples/peerconnection/client/main_wnd.h
@@ -33,12 +33,12 @@
#include <string>
#include "talk/app/webrtc/mediastreaminterface.h"
-#include "talk/base/win32.h"
#include "talk/examples/peerconnection/client/peer_connection_client.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/base/videoframe.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/win32.h"
class MainWndCallback {
public:
@@ -93,7 +93,7 @@
UI_THREAD_CALLBACK = WM_APP + 1,
};
- MainWnd();
+ MainWnd(const char* server, int port, bool auto_connect, bool auto_call);
~MainWnd();
bool Create();
@@ -147,9 +147,9 @@
HWND wnd_;
BITMAPINFO bmi_;
- talk_base::scoped_ptr<uint8[]> image_;
+ rtc::scoped_ptr<uint8[]> image_;
CRITICAL_SECTION buffer_lock_;
- talk_base::scoped_refptr<webrtc::VideoTrackInterface> rendered_track_;
+ rtc::scoped_refptr<webrtc::VideoTrackInterface> rendered_track_;
};
// A little helper class to make sure we always to proper locking and
@@ -192,8 +192,8 @@
void HandleTabbing();
private:
- talk_base::scoped_ptr<VideoRenderer> local_renderer_;
- talk_base::scoped_ptr<VideoRenderer> remote_renderer_;
+ rtc::scoped_ptr<VideoRenderer> local_renderer_;
+ rtc::scoped_ptr<VideoRenderer> remote_renderer_;
UI ui_;
HWND wnd_;
DWORD ui_thread_id_;
@@ -207,6 +207,10 @@
void* nested_msg_;
MainWndCallback* callback_;
static ATOM wnd_class_;
+ std::string server_;
+ std::string port_;
+ bool auto_connect_;
+ bool auto_call_;
};
#endif // WIN32
diff --git a/examples/peerconnection/client/peer_connection_client.cc b/examples/peerconnection/client/peer_connection_client.cc
index 9cdaedc..3aaea41 100644
--- a/examples/peerconnection/client/peer_connection_client.cc
+++ b/examples/peerconnection/client/peer_connection_client.cc
@@ -28,16 +28,16 @@
#include "talk/examples/peerconnection/client/peer_connection_client.h"
#include "talk/examples/peerconnection/client/defaults.h"
-#include "talk/base/common.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/nethelpers.h"
+#include "webrtc/base/stringutils.h"
#ifdef WIN32
-#include "talk/base/win32socketserver.h"
+#include "webrtc/base/win32socketserver.h"
#endif
-using talk_base::sprintfn;
+using rtc::sprintfn;
namespace {
@@ -46,13 +46,13 @@
// Delay between server connection retries, in milliseconds
const int kReconnectDelay = 2000;
-talk_base::AsyncSocket* CreateClientSocket(int family) {
+rtc::AsyncSocket* CreateClientSocket(int family) {
#ifdef WIN32
- talk_base::Win32Socket* sock = new talk_base::Win32Socket();
+ rtc::Win32Socket* sock = new rtc::Win32Socket();
sock->CreateT(family, SOCK_STREAM);
return sock;
#elif defined(POSIX)
- talk_base::Thread* thread = talk_base::Thread::Current();
+ rtc::Thread* thread = rtc::Thread::Current();
ASSERT(thread != NULL);
return thread->socketserver()->CreateAsyncSocket(family, SOCK_STREAM);
#else
@@ -133,7 +133,7 @@
if (server_address_.IsUnresolved()) {
state_ = RESOLVING;
- resolver_ = new talk_base::AsyncResolver();
+ resolver_ = new rtc::AsyncResolver();
resolver_->SignalDone.connect(this, &PeerConnectionClient::OnResolveResult);
resolver_->Start(server_address_);
} else {
@@ -142,7 +142,7 @@
}
void PeerConnectionClient::OnResolveResult(
- talk_base::AsyncResolverInterface* resolver) {
+ rtc::AsyncResolverInterface* resolver) {
if (resolver_->GetError() != 0) {
callback_->OnServerConnectionFailure();
resolver_->Destroy(false);
@@ -176,7 +176,7 @@
return false;
ASSERT(is_connected());
- ASSERT(control_socket_->GetState() == talk_base::Socket::CS_CLOSED);
+ ASSERT(control_socket_->GetState() == rtc::Socket::CS_CLOSED);
if (!is_connected() || peer_id == -1)
return false;
@@ -198,17 +198,17 @@
bool PeerConnectionClient::IsSendingMessage() {
return state_ == CONNECTED &&
- control_socket_->GetState() != talk_base::Socket::CS_CLOSED;
+ control_socket_->GetState() != rtc::Socket::CS_CLOSED;
}
bool PeerConnectionClient::SignOut() {
if (state_ == NOT_CONNECTED || state_ == SIGNING_OUT)
return true;
- if (hanging_get_->GetState() != talk_base::Socket::CS_CLOSED)
+ if (hanging_get_->GetState() != rtc::Socket::CS_CLOSED)
hanging_get_->Close();
- if (control_socket_->GetState() == talk_base::Socket::CS_CLOSED) {
+ if (control_socket_->GetState() == rtc::Socket::CS_CLOSED) {
state_ = SIGNING_OUT;
if (my_id_ != -1) {
@@ -242,7 +242,7 @@
}
bool PeerConnectionClient::ConnectControlSocket() {
- ASSERT(control_socket_->GetState() == talk_base::Socket::CS_CLOSED);
+ ASSERT(control_socket_->GetState() == rtc::Socket::CS_CLOSED);
int err = control_socket_->Connect(server_address_);
if (err == SOCKET_ERROR) {
Close();
@@ -251,22 +251,22 @@
return true;
}
-void PeerConnectionClient::OnConnect(talk_base::AsyncSocket* socket) {
+void PeerConnectionClient::OnConnect(rtc::AsyncSocket* socket) {
ASSERT(!onconnect_data_.empty());
size_t sent = socket->Send(onconnect_data_.c_str(), onconnect_data_.length());
ASSERT(sent == onconnect_data_.length());
- UNUSED(sent);
+ RTC_UNUSED(sent);
onconnect_data_.clear();
}
-void PeerConnectionClient::OnHangingGetConnect(talk_base::AsyncSocket* socket) {
+void PeerConnectionClient::OnHangingGetConnect(rtc::AsyncSocket* socket) {
char buffer[1024];
sprintfn(buffer, sizeof(buffer),
"GET /wait?peer_id=%i HTTP/1.0\r\n\r\n", my_id_);
int len = static_cast<int>(strlen(buffer));
int sent = socket->Send(buffer, len);
ASSERT(sent == len);
- UNUSED2(sent, len);
+ RTC_UNUSED2(sent, len);
}
void PeerConnectionClient::OnMessageFromPeer(int peer_id,
@@ -308,7 +308,7 @@
return false;
}
-bool PeerConnectionClient::ReadIntoBuffer(talk_base::AsyncSocket* socket,
+bool PeerConnectionClient::ReadIntoBuffer(rtc::AsyncSocket* socket,
std::string* data,
size_t* content_length) {
char buffer[0xffff];
@@ -346,7 +346,7 @@
return ret;
}
-void PeerConnectionClient::OnRead(talk_base::AsyncSocket* socket) {
+void PeerConnectionClient::OnRead(rtc::AsyncSocket* socket) {
size_t content_length = 0;
if (ReadIntoBuffer(socket, &control_data_, &content_length)) {
size_t peer_id = 0, eoh = 0;
@@ -390,14 +390,14 @@
control_data_.clear();
if (state_ == SIGNING_IN) {
- ASSERT(hanging_get_->GetState() == talk_base::Socket::CS_CLOSED);
+ ASSERT(hanging_get_->GetState() == rtc::Socket::CS_CLOSED);
state_ = CONNECTED;
hanging_get_->Connect(server_address_);
}
}
}
-void PeerConnectionClient::OnHangingGetRead(talk_base::AsyncSocket* socket) {
+void PeerConnectionClient::OnHangingGetRead(rtc::AsyncSocket* socket) {
LOG(INFO) << __FUNCTION__;
size_t content_length = 0;
if (ReadIntoBuffer(socket, ¬ification_data_, &content_length)) {
@@ -434,7 +434,7 @@
notification_data_.clear();
}
- if (hanging_get_->GetState() == talk_base::Socket::CS_CLOSED &&
+ if (hanging_get_->GetState() == rtc::Socket::CS_CLOSED &&
state_ == CONNECTED) {
hanging_get_->Connect(server_address_);
}
@@ -496,7 +496,7 @@
return true;
}
-void PeerConnectionClient::OnClose(talk_base::AsyncSocket* socket, int err) {
+void PeerConnectionClient::OnClose(rtc::AsyncSocket* socket, int err) {
LOG(INFO) << __FUNCTION__;
socket->Close();
@@ -517,7 +517,7 @@
} else {
if (socket == control_socket_.get()) {
LOG(WARNING) << "Connection refused; retrying in 2 seconds";
- talk_base::Thread::Current()->PostDelayed(kReconnectDelay, this, 0);
+ rtc::Thread::Current()->PostDelayed(kReconnectDelay, this, 0);
} else {
Close();
callback_->OnDisconnected();
@@ -525,7 +525,7 @@
}
}
-void PeerConnectionClient::OnMessage(talk_base::Message* msg) {
+void PeerConnectionClient::OnMessage(rtc::Message* msg) {
// ignore msg; there is currently only one supported message ("retry")
DoConnect();
}
diff --git a/examples/peerconnection/client/peer_connection_client.h b/examples/peerconnection/client/peer_connection_client.h
index 43fee34..7b897a5 100644
--- a/examples/peerconnection/client/peer_connection_client.h
+++ b/examples/peerconnection/client/peer_connection_client.h
@@ -32,11 +32,11 @@
#include <map>
#include <string>
-#include "talk/base/nethelpers.h"
-#include "talk/base/signalthread.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
+#include "webrtc/base/nethelpers.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/signalthread.h"
+#include "webrtc/base/sigslot.h"
typedef std::map<int, std::string> Peers;
@@ -54,7 +54,7 @@
};
class PeerConnectionClient : public sigslot::has_slots<>,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
enum State {
NOT_CONNECTED,
@@ -84,15 +84,15 @@
bool SignOut();
// implements the MessageHandler interface
- void OnMessage(talk_base::Message* msg);
+ void OnMessage(rtc::Message* msg);
protected:
void DoConnect();
void Close();
void InitSocketSignals();
bool ConnectControlSocket();
- void OnConnect(talk_base::AsyncSocket* socket);
- void OnHangingGetConnect(talk_base::AsyncSocket* socket);
+ void OnConnect(rtc::AsyncSocket* socket);
+ void OnHangingGetConnect(rtc::AsyncSocket* socket);
void OnMessageFromPeer(int peer_id, const std::string& message);
// Quick and dirty support for parsing HTTP header values.
@@ -103,12 +103,12 @@
const char* header_pattern, std::string* value);
// Returns true if the whole response has been read.
- bool ReadIntoBuffer(talk_base::AsyncSocket* socket, std::string* data,
+ bool ReadIntoBuffer(rtc::AsyncSocket* socket, std::string* data,
size_t* content_length);
- void OnRead(talk_base::AsyncSocket* socket);
+ void OnRead(rtc::AsyncSocket* socket);
- void OnHangingGetRead(talk_base::AsyncSocket* socket);
+ void OnHangingGetRead(rtc::AsyncSocket* socket);
// Parses a single line entry in the form "<name>,<id>,<connected>"
bool ParseEntry(const std::string& entry, std::string* name, int* id,
@@ -119,15 +119,15 @@
bool ParseServerResponse(const std::string& response, size_t content_length,
size_t* peer_id, size_t* eoh);
- void OnClose(talk_base::AsyncSocket* socket, int err);
+ void OnClose(rtc::AsyncSocket* socket, int err);
- void OnResolveResult(talk_base::AsyncResolverInterface* resolver);
+ void OnResolveResult(rtc::AsyncResolverInterface* resolver);
PeerConnectionClientObserver* callback_;
- talk_base::SocketAddress server_address_;
- talk_base::AsyncResolver* resolver_;
- talk_base::scoped_ptr<talk_base::AsyncSocket> control_socket_;
- talk_base::scoped_ptr<talk_base::AsyncSocket> hanging_get_;
+ rtc::SocketAddress server_address_;
+ rtc::AsyncResolver* resolver_;
+ rtc::scoped_ptr<rtc::AsyncSocket> control_socket_;
+ rtc::scoped_ptr<rtc::AsyncSocket> hanging_get_;
std::string onconnect_data_;
std::string control_data_;
std::string notification_data_;
diff --git a/examples/peerconnection/server/main.cc b/examples/peerconnection/server/main.cc
index 40ede93..1bdbfdc 100644
--- a/examples/peerconnection/server/main.cc
+++ b/examples/peerconnection/server/main.cc
@@ -31,10 +31,10 @@
#include <vector>
-#include "talk/base/flags.h"
#include "talk/examples/peerconnection/server/data_socket.h"
#include "talk/examples/peerconnection/server/peer_channel.h"
#include "talk/examples/peerconnection/server/utils.h"
+#include "webrtc/base/flags.h"
DEFINE_bool(help, false, "Prints this message");
DEFINE_int(port, 8888, "The port on which to listen.");
@@ -67,9 +67,9 @@
}
int main(int argc, char** argv) {
- FlagList::SetFlagsFromCommandLine(&argc, argv, true);
+ rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
if (FLAG_help) {
- FlagList::Print(NULL, false);
+ rtc::FlagList::Print(NULL, false);
return 0;
}
diff --git a/examples/peerconnection/server/peer_channel.cc b/examples/peerconnection/server/peer_channel.cc
index 2603465..15e7acb 100644
--- a/examples/peerconnection/server/peer_channel.cc
+++ b/examples/peerconnection/server/peer_channel.cc
@@ -59,6 +59,8 @@
kMessage,
};
+const size_t kMaxNameLength = 512;
+
//
// ChannelMember
//
@@ -72,8 +74,11 @@
assert(socket->method() == DataSocket::GET);
assert(socket->PathEquals("/sign_in"));
name_ = socket->request_arguments(); // TODO: urldecode
- if (!name_.length())
+ if (name_.empty())
name_ = "peer_" + int2str(id_);
+ else if (name_.length() > kMaxNameLength)
+ name_.resize(kMaxNameLength);
+
std::replace(name_.begin(), name_.end(), ',', '_');
}
@@ -100,8 +105,9 @@
return true;
}
-// Returns a string in the form "name,id\n".
+// Returns a string in the form "name,id,connected\n".
std::string ChannelMember::GetEntry() const {
+ assert(name_.length() <= kMaxNameLength);
char entry[1024] = {0};
sprintf(entry, "%s,%i,%i\n", name_.c_str(), id_, connected_); // NOLINT
return entry;
@@ -169,7 +175,6 @@
}
}
-
//
// PeerChannel
//
diff --git a/examples/peerconnection/server/utils.h b/examples/peerconnection/server/utils.h
index d05a2c3..5320d5a 100644
--- a/examples/peerconnection/server/utils.h
+++ b/examples/peerconnection/server/utils.h
@@ -29,18 +29,7 @@
#define TALK_EXAMPLES_PEERCONNECTION_SERVER_UTILS_H_
#pragma once
-#ifndef assert
-#ifndef WIN32
#include <assert.h>
-#else
-#ifndef NDEBUG
-#define assert(expr) ((void)((expr) ? true : __debugbreak()))
-#else
-#define assert(expr) ((void)0)
-#endif // NDEBUG
-#endif // WIN32
-#endif // assert
-
#include <string>
#ifndef ARRAYSIZE
diff --git a/examples/relayserver/relayserver_main.cc b/examples/relayserver/relayserver_main.cc
index 11e8a5b..1a4ab78 100644
--- a/examples/relayserver/relayserver_main.cc
+++ b/examples/relayserver/relayserver_main.cc
@@ -27,9 +27,9 @@
#include <iostream> // NOLINT
-#include "talk/base/thread.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/p2p/base/relayserver.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread.h"
int main(int argc, char **argv) {
if (argc != 3) {
@@ -38,30 +38,30 @@
return 1;
}
- talk_base::SocketAddress int_addr;
+ rtc::SocketAddress int_addr;
if (!int_addr.FromString(argv[1])) {
std::cerr << "Unable to parse IP address: " << argv[1];
return 1;
}
- talk_base::SocketAddress ext_addr;
+ rtc::SocketAddress ext_addr;
if (!ext_addr.FromString(argv[2])) {
std::cerr << "Unable to parse IP address: " << argv[2];
return 1;
}
- talk_base::Thread *pthMain = talk_base::Thread::Current();
+ rtc::Thread *pthMain = rtc::Thread::Current();
- talk_base::scoped_ptr<talk_base::AsyncUDPSocket> int_socket(
- talk_base::AsyncUDPSocket::Create(pthMain->socketserver(), int_addr));
+ rtc::scoped_ptr<rtc::AsyncUDPSocket> int_socket(
+ rtc::AsyncUDPSocket::Create(pthMain->socketserver(), int_addr));
if (!int_socket) {
std::cerr << "Failed to create a UDP socket bound at"
<< int_addr.ToString() << std::endl;
return 1;
}
- talk_base::scoped_ptr<talk_base::AsyncUDPSocket> ext_socket(
- talk_base::AsyncUDPSocket::Create(pthMain->socketserver(), ext_addr));
+ rtc::scoped_ptr<rtc::AsyncUDPSocket> ext_socket(
+ rtc::AsyncUDPSocket::Create(pthMain->socketserver(), ext_addr));
if (!ext_socket) {
std::cerr << "Failed to create a UDP socket bound at"
<< ext_addr.ToString() << std::endl;
diff --git a/examples/stunserver/stunserver_main.cc b/examples/stunserver/stunserver_main.cc
index 4467944..f800f31 100644
--- a/examples/stunserver/stunserver_main.cc
+++ b/examples/stunserver/stunserver_main.cc
@@ -31,8 +31,8 @@
#include <iostream>
-#include "talk/base/thread.h"
#include "talk/p2p/base/stunserver.h"
+#include "webrtc/base/thread.h"
using namespace cricket;
@@ -42,16 +42,16 @@
return 1;
}
- talk_base::SocketAddress server_addr;
+ rtc::SocketAddress server_addr;
if (!server_addr.FromString(argv[1])) {
std::cerr << "Unable to parse IP address: " << argv[1];
return 1;
}
- talk_base::Thread *pthMain = talk_base::Thread::Current();
+ rtc::Thread *pthMain = rtc::Thread::Current();
- talk_base::AsyncUDPSocket* server_socket =
- talk_base::AsyncUDPSocket::Create(pthMain->socketserver(), server_addr);
+ rtc::AsyncUDPSocket* server_socket =
+ rtc::AsyncUDPSocket::Create(pthMain->socketserver(), server_addr);
if (!server_socket) {
std::cerr << "Failed to create a UDP socket" << std::endl;
return 1;
diff --git a/examples/turnserver/turnserver_main.cc b/examples/turnserver/turnserver_main.cc
index d40fede..607b8cf 100644
--- a/examples/turnserver/turnserver_main.cc
+++ b/examples/turnserver/turnserver_main.cc
@@ -27,12 +27,12 @@
#include <iostream> // NOLINT
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/optionsfile.h"
-#include "talk/base/thread.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/turnserver.h"
+#include "webrtc/base/asyncudpsocket.h"
+#include "webrtc/base/optionsfile.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/thread.h"
static const char kSoftware[] = "libjingle TurnServer";
@@ -49,13 +49,13 @@
bool ret = file_.GetStringValue(username, &hex);
if (ret) {
char buf[32];
- size_t len = talk_base::hex_decode(buf, sizeof(buf), hex);
+ size_t len = rtc::hex_decode(buf, sizeof(buf), hex);
*key = std::string(buf, len);
}
return ret;
}
private:
- talk_base::OptionsFile file_;
+ rtc::OptionsFile file_;
};
int main(int argc, char **argv) {
@@ -65,21 +65,21 @@
return 1;
}
- talk_base::SocketAddress int_addr;
+ rtc::SocketAddress int_addr;
if (!int_addr.FromString(argv[1])) {
std::cerr << "Unable to parse IP address: " << argv[1] << std::endl;
return 1;
}
- talk_base::IPAddress ext_addr;
+ rtc::IPAddress ext_addr;
if (!IPFromString(argv[2], &ext_addr)) {
std::cerr << "Unable to parse IP address: " << argv[2] << std::endl;
return 1;
}
- talk_base::Thread* main = talk_base::Thread::Current();
- talk_base::AsyncUDPSocket* int_socket =
- talk_base::AsyncUDPSocket::Create(main->socketserver(), int_addr);
+ rtc::Thread* main = rtc::Thread::Current();
+ rtc::AsyncUDPSocket* int_socket =
+ rtc::AsyncUDPSocket::Create(main->socketserver(), int_addr);
if (!int_socket) {
std::cerr << "Failed to create a UDP socket bound at"
<< int_addr.ToString() << std::endl;
@@ -92,8 +92,8 @@
server.set_software(kSoftware);
server.set_auth_hook(&auth);
server.AddInternalSocket(int_socket, cricket::PROTO_UDP);
- server.SetExternalSocketFactory(new talk_base::BasicPacketSocketFactory(),
- talk_base::SocketAddress(ext_addr, 0));
+ server.SetExternalSocketFactory(new rtc::BasicPacketSocketFactory(),
+ rtc::SocketAddress(ext_addr, 0));
std::cout << "Listening internally at " << int_addr.ToString() << std::endl;
diff --git a/libjingle.gyp b/libjingle.gyp
index 2182561..335a788 100755
--- a/libjingle.gyp
+++ b/libjingle.gyp
@@ -110,6 +110,7 @@
'android_java_files': [
'app/webrtc/java/android/org/webrtc/VideoRendererGui.java',
'app/webrtc/java/src/org/webrtc/MediaCodecVideoEncoder.java',
+ 'app/webrtc/java/src/org/webrtc/MediaCodecVideoDecoder.java',
'<(webrtc_modules_dir)/audio_device/android/java/src/org/webrtc/voiceengine/AudioManagerAndroid.java',
'<(webrtc_modules_dir)/video_capture/android/java/src/org/webrtc/videoengine/VideoCaptureAndroid.java',
'<(webrtc_modules_dir)/video_capture/android/java/src/org/webrtc/videoengine/VideoCaptureDeviceInfoAndroid.java',
@@ -302,230 +303,13 @@
'dependencies': [
'<(DEPTH)/third_party/expat/expat.gyp:expat',
'<(DEPTH)/third_party/jsoncpp/jsoncpp.gyp:jsoncpp',
+ '<(webrtc_root)/base/base.gyp:rtc_base',
],
'export_dependent_settings': [
'<(DEPTH)/third_party/expat/expat.gyp:expat',
'<(DEPTH)/third_party/jsoncpp/jsoncpp.gyp:jsoncpp',
],
'sources': [
- 'base/asyncfile.cc',
- 'base/asyncfile.h',
- 'base/asynchttprequest.cc',
- 'base/asynchttprequest.h',
- 'base/asyncinvoker.cc',
- 'base/asyncinvoker.h',
- 'base/asyncpacketsocket.h',
- 'base/asyncresolverinterface.h',
- 'base/asyncsocket.cc',
- 'base/asyncsocket.h',
- 'base/asynctcpsocket.cc',
- 'base/asynctcpsocket.h',
- 'base/asyncudpsocket.cc',
- 'base/asyncudpsocket.h',
- 'base/atomicops.h',
- 'base/autodetectproxy.cc',
- 'base/autodetectproxy.h',
- 'base/bandwidthsmoother.cc',
- 'base/bandwidthsmoother.h',
- 'base/base64.cc',
- 'base/base64.h',
- 'base/basicdefs.h',
- 'base/basictypes.h',
- 'base/bind.h',
- 'base/buffer.h',
- 'base/bytebuffer.cc',
- 'base/bytebuffer.h',
- 'base/byteorder.h',
- 'base/callback.h',
- 'base/checks.cc',
- 'base/checks.h',
- 'base/common.cc',
- 'base/common.h',
- 'base/constructormagic.h',
- 'base/cpumonitor.cc',
- 'base/cpumonitor.h',
- 'base/crc32.cc',
- 'base/crc32.h',
- 'base/criticalsection.h',
- 'base/cryptstring.h',
- 'base/diskcache.cc',
- 'base/diskcache.h',
- 'base/event.cc',
- 'base/event.h',
- 'base/filelock.cc',
- 'base/filelock.h',
- 'base/fileutils.cc',
- 'base/fileutils.h',
- 'base/fileutils_mock.h',
- 'base/firewallsocketserver.cc',
- 'base/firewallsocketserver.h',
- 'base/flags.cc',
- 'base/flags.h',
- 'base/gunit_prod.h',
- 'base/helpers.cc',
- 'base/helpers.h',
- 'base/httpbase.cc',
- 'base/httpbase.h',
- 'base/httpclient.cc',
- 'base/httpclient.h',
- 'base/httpcommon-inl.h',
- 'base/httpcommon.cc',
- 'base/httpcommon.h',
- 'base/httprequest.cc',
- 'base/httprequest.h',
- 'base/httpserver.cc',
- 'base/httpserver.h',
- 'base/ifaddrs-android.cc',
- 'base/ifaddrs-android.h',
- 'base/ipaddress.cc',
- 'base/ipaddress.h',
- 'base/json.cc',
- 'base/json.h',
- 'base/linked_ptr.h',
- 'base/linuxfdwalk.h',
- 'base/logging.cc',
- 'base/logging.h',
- 'base/maccocoathreadhelper.h',
- 'base/maccocoathreadhelper.mm',
- 'base/mathutils.h',
- 'base/md5.cc',
- 'base/md5.h',
- 'base/md5digest.h',
- 'base/messagedigest.cc',
- 'base/messagedigest.h',
- 'base/messagehandler.cc',
- 'base/messagehandler.h',
- 'base/messagequeue.cc',
- 'base/messagequeue.h',
- 'base/multipart.cc',
- 'base/multipart.h',
- 'base/natserver.cc',
- 'base/natserver.h',
- 'base/natsocketfactory.cc',
- 'base/natsocketfactory.h',
- 'base/nattypes.cc',
- 'base/nattypes.h',
- 'base/nethelpers.cc',
- 'base/nethelpers.h',
- 'base/network.cc',
- 'base/network.h',
- 'base/nssidentity.cc',
- 'base/nssidentity.h',
- 'base/nssstreamadapter.cc',
- 'base/nssstreamadapter.h',
- 'base/nullsocketserver.h',
- 'base/optionsfile.cc',
- 'base/optionsfile.h',
- 'base/pathutils.cc',
- 'base/pathutils.h',
- 'base/physicalsocketserver.cc',
- 'base/physicalsocketserver.h',
- 'base/profiler.cc',
- 'base/profiler.h',
- 'base/proxydetect.cc',
- 'base/proxydetect.h',
- 'base/proxyinfo.cc',
- 'base/proxyinfo.h',
- 'base/proxyserver.cc',
- 'base/proxyserver.h',
- 'base/ratelimiter.cc',
- 'base/ratelimiter.h',
- 'base/ratetracker.cc',
- 'base/ratetracker.h',
- 'base/refcount.h',
- 'base/referencecountedsingletonfactory.h',
- 'base/rollingaccumulator.h',
- 'base/scoped_autorelease_pool.h',
- 'base/scoped_ptr.h',
- 'base/scoped_ref_ptr.h',
- 'base/scopedptrcollection.h',
- 'base/sec_buffer.h',
- 'base/sha1.cc',
- 'base/sha1.h',
- 'base/sha1digest.h',
- 'base/sharedexclusivelock.cc',
- 'base/sharedexclusivelock.h',
- 'base/signalthread.cc',
- 'base/signalthread.h',
- 'base/sigslot.h',
- 'base/sigslotrepeater.h',
- 'base/socket.h',
- 'base/socketadapters.cc',
- 'base/socketadapters.h',
- 'base/socketaddress.cc',
- 'base/socketaddress.h',
- 'base/socketaddresspair.cc',
- 'base/socketaddresspair.h',
- 'base/socketfactory.h',
- 'base/socketpool.cc',
- 'base/socketpool.h',
- 'base/socketserver.h',
- 'base/socketstream.cc',
- 'base/socketstream.h',
- 'base/ssladapter.cc',
- 'base/ssladapter.h',
- 'base/sslconfig.h',
- 'base/sslfingerprint.cc',
- 'base/sslfingerprint.h',
- 'base/sslidentity.cc',
- 'base/sslidentity.h',
- 'base/sslroots.h',
- 'base/sslsocketfactory.cc',
- 'base/sslsocketfactory.h',
- 'base/sslstreamadapter.cc',
- 'base/sslstreamadapter.h',
- 'base/sslstreamadapterhelper.cc',
- 'base/sslstreamadapterhelper.h',
- 'base/stream.cc',
- 'base/stream.h',
- 'base/stringdigest.h',
- 'base/stringencode.cc',
- 'base/stringencode.h',
- 'base/stringutils.cc',
- 'base/stringutils.h',
- 'base/systeminfo.cc',
- 'base/systeminfo.h',
- 'base/task.cc',
- 'base/task.h',
- 'base/taskparent.cc',
- 'base/taskparent.h',
- 'base/taskrunner.cc',
- 'base/taskrunner.h',
- 'base/testclient.cc',
- 'base/testclient.h',
- 'base/thread.cc',
- 'base/thread.h',
- 'base/timeutils.cc',
- 'base/timeutils.h',
- 'base/timing.cc',
- 'base/timing.h',
- 'base/transformadapter.cc',
- 'base/transformadapter.h',
- 'base/urlencode.cc',
- 'base/urlencode.h',
- 'base/versionparsing.cc',
- 'base/versionparsing.h',
- 'base/virtualsocketserver.cc',
- 'base/virtualsocketserver.h',
- 'base/window.h',
- 'base/windowpicker.h',
- 'base/windowpickerfactory.h',
- 'base/worker.cc',
- 'base/worker.h',
- 'xmllite/qname.cc',
- 'xmllite/qname.h',
- 'xmllite/xmlbuilder.cc',
- 'xmllite/xmlbuilder.h',
- 'xmllite/xmlconstants.cc',
- 'xmllite/xmlconstants.h',
- 'xmllite/xmlelement.cc',
- 'xmllite/xmlelement.h',
- 'xmllite/xmlnsstack.cc',
- 'xmllite/xmlnsstack.h',
- 'xmllite/xmlparser.cc',
- 'xmllite/xmlparser.h',
- 'xmllite/xmlprinter.cc',
- 'xmllite/xmlprinter.h',
'xmpp/asyncsocket.h',
'xmpp/chatroommodule.h',
'xmpp/chatroommoduleimpl.cc',
@@ -600,227 +384,8 @@
'xmpp/xmppthread.cc',
'xmpp/xmppthread.h',
],
- 'conditions': [
- ['OS=="android"', {
- 'sources': [
- 'base/ifaddrs-android.cc',
- ],
- 'link_settings': {
- 'libraries': [
- '-llog',
- '-lGLESv2',
- ],
- },
- }],
- ['OS=="linux" or OS=="android"', {
- 'sources': [
- 'base/linux.cc',
- 'base/linux.h',
- ],
- }],
- ['OS=="linux"', {
- 'sources': [
- 'base/dbus.cc',
- 'base/dbus.h',
- 'base/libdbusglibsymboltable.cc',
- 'base/libdbusglibsymboltable.h',
- 'base/linuxfdwalk.c',
- 'base/linuxwindowpicker.cc',
- 'base/linuxwindowpicker.h',
- ],
- 'link_settings': {
- 'libraries': [
- '-lcrypto',
- '-ldl',
- '-lrt',
- '-lXext',
- '-lX11',
- '-lXcomposite',
- '-lXrender',
- '<!@(<(pkg-config) --libs-only-l nss | sed -e "s/-lssl3//")',
- ],
- },
- 'cflags': [
- '<!@(<(pkg-config) --cflags nss)',
- ],
- 'ldflags': [
- '<!@(<(pkg-config) --libs-only-L --libs-only-other nss)',
- ],
- }],
- ['OS=="mac"', {
- 'sources': [
- 'base/macasyncsocket.cc',
- 'base/macasyncsocket.h',
- 'base/maccocoasocketserver.h',
- 'base/maccocoasocketserver.mm',
- 'base/macconversion.cc',
- 'base/macconversion.h',
- 'base/macsocketserver.cc',
- 'base/macsocketserver.h',
- 'base/macutils.cc',
- 'base/macutils.h',
- 'base/macwindowpicker.cc',
- 'base/macwindowpicker.h',
- 'base/scoped_autorelease_pool.mm',
- ],
- 'link_settings': {
- 'libraries': [
- '$(SDKROOT)/usr/lib/libcrypto.dylib',
- '$(SDKROOT)/usr/lib/libssl.dylib',
- ],
- },
- 'all_dependent_settings': {
- 'link_settings': {
- 'xcode_settings': {
- 'OTHER_LDFLAGS': [
- '-framework Cocoa',
- '-framework Foundation',
- '-framework IOKit',
- '-framework Security',
- '-framework SystemConfiguration',
- ],
- },
- },
- },
- 'conditions': [
- ['target_arch=="ia32"', {
- 'all_dependent_settings': {
- 'link_settings': {
- 'xcode_settings': {
- 'OTHER_LDFLAGS': [
- '-framework Carbon',
- ],
- },
- },
- },
- }],
- ],
- }],
- ['OS=="ios"', {
- 'sources': [
- 'base/iosfilesystem.mm',
- 'base/scoped_autorelease_pool.mm',
- ],
- 'dependencies': [
- '<(DEPTH)/net/third_party/nss/ssl.gyp:libssl',
- ],
- 'all_dependent_settings': {
- 'xcode_settings': {
- 'OTHER_LDFLAGS': [
- '-framework Foundation',
- '-framework Security',
- '-framework SystemConfiguration',
- '-framework UIKit',
- ],
- },
- },
- }],
- ['OS=="win"', {
- 'sources': [
- 'base/diskcache_win32.cc',
- 'base/diskcache_win32.h',
- 'base/schanneladapter.cc',
- 'base/schanneladapter.h',
- 'base/win32.cc',
- 'base/win32.h',
- 'base/win32filesystem.cc',
- 'base/win32filesystem.h',
- 'base/win32regkey.cc',
- 'base/win32regkey.h',
- 'base/win32securityerrors.cc',
- 'base/win32socketinit.cc',
- 'base/win32socketinit.h',
- 'base/win32socketserver.cc',
- 'base/win32socketserver.h',
- 'base/win32window.cc',
- 'base/win32window.h',
- 'base/win32windowpicker.cc',
- 'base/win32windowpicker.h',
- 'base/winfirewall.cc',
- 'base/winfirewall.h',
- 'base/winping.cc',
- 'base/winping.h',
- ],
- 'link_settings': {
- 'libraries': [
- '-lcrypt32.lib',
- '-liphlpapi.lib',
- '-lsecur32.lib',
- ],
- },
- # Suppress warnings about WIN32_LEAN_AND_MEAN.
- 'msvs_disabled_warnings': [4005],
- }],
- ['os_posix==1', {
- 'sources': [
- 'base/latebindingsymboltable.cc',
- 'base/latebindingsymboltable.h',
- 'base/posix.cc',
- 'base/posix.h',
- 'base/unixfilesystem.cc',
- 'base/unixfilesystem.h',
- ],
- 'conditions': [
- ['OS!="ios"', {
- 'sources': [
- 'base/openssl.h',
- 'base/openssladapter.cc',
- 'base/openssladapter.h',
- 'base/openssldigest.cc',
- 'base/openssldigest.h',
- 'base/opensslidentity.cc',
- 'base/opensslidentity.h',
- 'base/opensslstreamadapter.cc',
- 'base/opensslstreamadapter.h',
- ],
- }],
- ],
- }],
- ], # conditions
}, # target libjingle
{
- 'target_name': 'libjingle_sound',
- 'type': 'static_library',
- 'dependencies': [
- 'libjingle',
- ],
- 'sources': [
- 'sound/automaticallychosensoundsystem.h',
- 'sound/nullsoundsystem.cc',
- 'sound/nullsoundsystem.h',
- 'sound/nullsoundsystemfactory.cc',
- 'sound/nullsoundsystemfactory.h',
- 'sound/platformsoundsystem.cc',
- 'sound/platformsoundsystem.h',
- 'sound/platformsoundsystemfactory.cc',
- 'sound/platformsoundsystemfactory.h',
- 'sound/sounddevicelocator.h',
- 'sound/soundinputstreaminterface.h',
- 'sound/soundoutputstreaminterface.h',
- 'sound/soundsystemfactory.h',
- 'sound/soundsysteminterface.cc',
- 'sound/soundsysteminterface.h',
- 'sound/soundsystemproxy.cc',
- 'sound/soundsystemproxy.h',
- ],
- 'conditions': [
- ['OS=="linux"', {
- 'sources': [
- 'sound/alsasoundsystem.cc',
- 'sound/alsasoundsystem.h',
- 'sound/alsasymboltable.cc',
- 'sound/alsasymboltable.h',
- 'sound/linuxsoundsystem.cc',
- 'sound/linuxsoundsystem.h',
- 'sound/pulseaudiosoundsystem.cc',
- 'sound/pulseaudiosoundsystem.h',
- 'sound/pulseaudiosymboltable.cc',
- 'sound/pulseaudiosymboltable.h',
- ],
- }],
- ],
- }, # target libjingle_sound
- {
'target_name': 'libjingle_media',
'type': 'static_library',
'include_dirs': [
@@ -831,14 +396,14 @@
'dependencies': [
'<(DEPTH)/third_party/libyuv/libyuv.gyp:libyuv',
'<(DEPTH)/third_party/usrsctp/usrsctp.gyp:usrsctplib',
- '<(webrtc_root)/modules/modules.gyp:video_capture_module',
'<(webrtc_root)/modules/modules.gyp:video_render_module',
'<(webrtc_root)/webrtc.gyp:webrtc',
'<(webrtc_root)/voice_engine/voice_engine.gyp:voice_engine',
+ '<(webrtc_root)/sound/sound.gyp:rtc_sound',
'<(webrtc_root)/system_wrappers/source/system_wrappers.gyp:system_wrappers',
'<(webrtc_root)/system_wrappers/source/system_wrappers.gyp:field_trial_default',
+ '<(webrtc_root)/libjingle/xmllite/xmllite.gyp:rtc_xmllite',
'libjingle',
- 'libjingle_sound',
],
'direct_dependent_settings': {
'include_dirs': [
@@ -859,17 +424,15 @@
'media/base/cpuid.cc',
'media/base/cpuid.h',
'media/base/cryptoparams.h',
+ 'media/base/device.h',
+ 'media/base/fakescreencapturerfactory.h',
'media/base/filemediaengine.cc',
'media/base/filemediaengine.h',
'media/base/hybriddataengine.h',
- 'media/base/hybridvideoengine.cc',
- 'media/base/hybridvideoengine.h',
'media/base/mediachannel.h',
'media/base/mediacommon.h',
'media/base/mediaengine.cc',
'media/base/mediaengine.h',
- 'media/base/mutedvideocapturer.cc',
- 'media/base/mutedvideocapturer.h',
'media/base/rtpdataengine.cc',
'media/base/rtpdataengine.h',
'media/base/rtpdump.cc',
@@ -883,10 +446,12 @@
'media/base/videoadapter.h',
'media/base/videocapturer.cc',
'media/base/videocapturer.h',
+ 'media/base/videocapturerfactory.h',
'media/base/videocommon.cc',
'media/base/videocommon.h',
'media/base/videoframe.cc',
'media/base/videoframe.h',
+ 'media/base/videoframefactory.h',
'media/base/videoprocessor.h',
'media/base/videorenderer.h',
'media/base/voiceprocessor.h',
@@ -908,11 +473,14 @@
'media/webrtc/webrtcexport.h',
'media/webrtc/webrtcmediaengine.cc',
'media/webrtc/webrtcmediaengine.h',
+ 'media/webrtc/webrtcmediaengine.cc',
'media/webrtc/webrtcpassthroughrender.cc',
'media/webrtc/webrtcpassthroughrender.h',
'media/webrtc/webrtctexturevideoframe.cc',
'media/webrtc/webrtctexturevideoframe.h',
'media/webrtc/webrtcvideocapturer.cc',
+ 'media/webrtc/webrtcvideocapturerfactory.h',
+ 'media/webrtc/webrtcvideocapturerfactory.cc',
'media/webrtc/webrtcvideocapturer.h',
'media/webrtc/webrtcvideodecoderfactory.h',
'media/webrtc/webrtcvideoencoderfactory.h',
@@ -922,12 +490,25 @@
'media/webrtc/webrtcvideoengine2.h',
'media/webrtc/webrtcvideoframe.cc',
'media/webrtc/webrtcvideoframe.h',
+ 'media/webrtc/webrtcvideoframefactory.cc',
+ 'media/webrtc/webrtcvideoframefactory.h',
'media/webrtc/webrtcvie.h',
'media/webrtc/webrtcvoe.h',
'media/webrtc/webrtcvoiceengine.cc',
'media/webrtc/webrtcvoiceengine.h',
],
'conditions': [
+ ['build_with_chromium==1', {
+ 'dependencies': [
+ '<(webrtc_root)/modules/modules.gyp:video_capture_module_impl',
+ '<(webrtc_root)/modules/modules.gyp:video_render_module_impl',
+ ],
+ }, {
+ 'dependencies': [
+ '<(webrtc_root)/modules/modules.gyp:video_capture_module_internal_impl',
+ '<(webrtc_root)/modules/modules.gyp:video_render_module_internal_impl',
+ ],
+ }],
['OS=="linux"', {
'sources': [
'media/devices/gtkvideorenderer.cc',
@@ -1003,6 +584,7 @@
'link_settings': {
'xcode_settings': {
'OTHER_LDFLAGS': [
+ '-weak_framework AVFoundation',
'-framework Cocoa',
'-framework CoreAudio',
'-framework CoreVideo',
@@ -1021,13 +603,6 @@
# libjpeg which pulls in libyuv which currently disabled.
'../third_party/libyuv/include',
],
- 'dependencies!': [
- '<(DEPTH)/third_party/usrsctp/usrsctp.gyp:usrsctplib',
- ],
- 'sources!': [
- 'media/sctp/sctpdataengine.cc',
- 'media/sctp/sctpdataengine.h',
- ],
}],
['OS=="android"', {
'sources': [
diff --git a/libjingle_examples.gyp b/libjingle_examples.gyp
index f69c5dc..3e31f50 100755
--- a/libjingle_examples.gyp
+++ b/libjingle_examples.gyp
@@ -172,6 +172,7 @@
'dependencies': [
'<(DEPTH)/third_party/jsoncpp/jsoncpp.gyp:jsoncpp',
'libjingle.gyp:libjingle_peerconnection',
+ '<@(libjingle_tests_additional_deps)',
],
'conditions': [
# TODO(ronghuawu): Move these files to a win/ directory then they
diff --git a/libjingle_tests.gyp b/libjingle_tests.gyp
index 016f0a5..44adec3 100755
--- a/libjingle_tests.gyp
+++ b/libjingle_tests.gyp
@@ -29,57 +29,25 @@
'includes': ['build/common.gypi'],
'targets': [
{
- # TODO(ronghuawu): Use gtest.gyp from chromium.
- 'target_name': 'gunit',
- 'type': 'static_library',
- 'sources': [
- '<(DEPTH)/testing/gtest/src/gtest-all.cc',
- ],
- 'include_dirs': [
- '<(DEPTH)/testing/gtest/include',
- '<(DEPTH)/testing/gtest',
- ],
- 'defines': ['_VARIADIC_MAX=10'],
- 'direct_dependent_settings': {
- 'defines': [
- '_VARIADIC_MAX=10',
- ],
- 'include_dirs': [
- '<(DEPTH)/testing/gtest/include',
- ],
- },
- 'conditions': [
- ['OS=="android"', {
- 'include_dirs': [
- '<(android_ndk_include)',
- ]
- }],
- ],
- }, # target gunit
- {
'target_name': 'libjingle_unittest_main',
'type': 'static_library',
'dependencies': [
'<(DEPTH)/third_party/libyuv/libyuv.gyp:libyuv',
- 'gunit',
+ '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils',
+ '<@(libjingle_tests_additional_deps)',
],
'direct_dependent_settings': {
'include_dirs': [
'<(DEPTH)/third_party/libyuv/include',
+ '<(DEPTH)/testing/gtest/include',
+ '<(DEPTH)/testing/gtest',
],
},
+ 'include_dirs': [
+ '<(DEPTH)/testing/gtest/include',
+ '<(DEPTH)/testing/gtest',
+ ],
'sources': [
- 'base/unittest_main.cc',
- # Also use this as a convenient dumping ground for misc files that are
- # included by multiple targets below.
- 'base/fakecpumonitor.h',
- 'base/fakenetwork.h',
- 'base/fakesslidentity.h',
- 'base/faketaskrunner.h',
- 'base/gunit.h',
- 'base/testbase64.h',
- 'base/testechoserver.h',
- 'base/win32toolhelp.h',
'media/base/fakecapturemanager.h',
'media/base/fakemediaengine.h',
'media/base/fakemediaprocessor.h',
@@ -106,79 +74,13 @@
'type': 'executable',
'includes': [ 'build/ios_tests.gypi', ],
'dependencies': [
- 'gunit',
+ '<(webrtc_root)/base/base.gyp:rtc_base',
+ '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils',
+ '<(webrtc_root)/libjingle/xmllite/xmllite.gyp:rtc_xmllite',
'libjingle.gyp:libjingle',
'libjingle_unittest_main',
],
'sources': [
- 'base/asynchttprequest_unittest.cc',
- 'base/atomicops_unittest.cc',
- 'base/autodetectproxy_unittest.cc',
- 'base/bandwidthsmoother_unittest.cc',
- 'base/base64_unittest.cc',
- 'base/basictypes_unittest.cc',
- 'base/bind_unittest.cc',
- 'base/buffer_unittest.cc',
- 'base/bytebuffer_unittest.cc',
- 'base/byteorder_unittest.cc',
- 'base/callback_unittest.cc',
- 'base/cpumonitor_unittest.cc',
- 'base/crc32_unittest.cc',
- 'base/criticalsection_unittest.cc',
- 'base/event_unittest.cc',
- 'base/filelock_unittest.cc',
- 'base/fileutils_unittest.cc',
- 'base/helpers_unittest.cc',
- 'base/httpbase_unittest.cc',
- 'base/httpcommon_unittest.cc',
- 'base/httpserver_unittest.cc',
- 'base/ipaddress_unittest.cc',
- 'base/logging_unittest.cc',
- 'base/md5digest_unittest.cc',
- 'base/messagedigest_unittest.cc',
- 'base/messagequeue_unittest.cc',
- 'base/multipart_unittest.cc',
- 'base/nat_unittest.cc',
- 'base/network_unittest.cc',
- 'base/nullsocketserver_unittest.cc',
- 'base/optionsfile_unittest.cc',
- 'base/pathutils_unittest.cc',
- 'base/physicalsocketserver_unittest.cc',
- 'base/profiler_unittest.cc',
- 'base/proxy_unittest.cc',
- 'base/proxydetect_unittest.cc',
- 'base/ratelimiter_unittest.cc',
- 'base/ratetracker_unittest.cc',
- 'base/referencecountedsingletonfactory_unittest.cc',
- 'base/rollingaccumulator_unittest.cc',
- 'base/scopedptrcollection_unittest.cc',
- 'base/sha1digest_unittest.cc',
- 'base/sharedexclusivelock_unittest.cc',
- 'base/signalthread_unittest.cc',
- 'base/sigslot_unittest.cc',
- 'base/socket_unittest.cc',
- 'base/socket_unittest.h',
- 'base/socketaddress_unittest.cc',
- 'base/stream_unittest.cc',
- 'base/stringencode_unittest.cc',
- 'base/stringutils_unittest.cc',
- # TODO(ronghuawu): Reenable this test.
- # 'base/systeminfo_unittest.cc',
- 'base/task_unittest.cc',
- 'base/testclient_unittest.cc',
- 'base/thread_unittest.cc',
- 'base/timeutils_unittest.cc',
- 'base/urlencode_unittest.cc',
- 'base/versionparsing_unittest.cc',
- 'base/virtualsocket_unittest.cc',
- # TODO(ronghuawu): Reenable this test.
- # 'base/windowpicker_unittest.cc',
- 'xmllite/qname_unittest.cc',
- 'xmllite/xmlbuilder_unittest.cc',
- 'xmllite/xmlelement_unittest.cc',
- 'xmllite/xmlnsstack_unittest.cc',
- 'xmllite/xmlparser_unittest.cc',
- 'xmllite/xmlprinter_unittest.cc',
'xmpp/fakexmppclient.h',
'xmpp/hangoutpubsubclient_unittest.cc',
'xmpp/jid_unittest.cc',
@@ -195,66 +97,12 @@
'xmpp/xmpplogintask_unittest.cc',
'xmpp/xmppstanzaparser_unittest.cc',
], # sources
- 'conditions': [
- ['OS=="linux"', {
- 'sources': [
- 'base/latebindingsymboltable_unittest.cc',
- # TODO(ronghuawu): Reenable this test.
- # 'base/linux_unittest.cc',
- 'base/linuxfdwalk_unittest.cc',
- ],
- }],
- ['OS=="win"', {
- 'sources': [
- 'base/win32_unittest.cc',
- 'base/win32regkey_unittest.cc',
- 'base/win32socketserver_unittest.cc',
- 'base/win32toolhelp_unittest.cc',
- 'base/win32window_unittest.cc',
- 'base/win32windowpicker_unittest.cc',
- 'base/winfirewall_unittest.cc',
- ],
- 'sources!': [
- # TODO(ronghuawu): Fix TestUdpReadyToSendIPv6 on windows bot
- # then reenable these tests.
- 'base/physicalsocketserver_unittest.cc',
- 'base/socket_unittest.cc',
- 'base/win32socketserver_unittest.cc',
- 'base/win32windowpicker_unittest.cc',
- ],
- }],
- ['OS=="mac"', {
- 'sources': [
- 'base/macsocketserver_unittest.cc',
- 'base/macutils_unittest.cc',
- 'base/macwindowpicker_unittest.cc',
- ],
- }],
- ['os_posix==1', {
- 'sources': [
- 'base/sslidentity_unittest.cc',
- 'base/sslstreamadapter_unittest.cc',
- ],
- }],
- ], # conditions
}, # target libjingle_unittest
{
- 'target_name': 'libjingle_sound_unittest',
- 'type': 'executable',
- 'dependencies': [
- 'gunit',
- 'libjingle.gyp:libjingle_sound',
- 'libjingle_unittest_main',
- ],
- 'sources': [
- 'sound/automaticallychosensoundsystem_unittest.cc',
- ],
- }, # target libjingle_sound_unittest
- {
'target_name': 'libjingle_media_unittest',
'type': 'executable',
'dependencies': [
- 'gunit',
+ '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils',
'libjingle.gyp:libjingle_media',
'libjingle_unittest_main',
],
@@ -280,8 +128,10 @@
'media/base/rtpdataengine_unittest.cc',
'media/base/rtpdump_unittest.cc',
'media/base/rtputils_unittest.cc',
+ 'media/base/streamparams_unittest.cc',
'media/base/testutils.cc',
'media/base/testutils.h',
+ 'media/base/videoadapter_unittest.cc',
'media/base/videocapturer_unittest.cc',
'media/base/videocommon_unittest.cc',
'media/base/videoengine_unittest.h',
@@ -290,9 +140,8 @@
'media/sctp/sctpdataengine_unittest.cc',
'media/webrtc/webrtcpassthroughrender_unittest.cc',
'media/webrtc/webrtcvideocapturer_unittest.cc',
- # Omitted because depends on non-open-source testdata files.
- # 'media/base/videoframe_unittest.h',
- # 'media/webrtc/webrtcvideoframe_unittest.cc',
+ 'media/base/videoframe_unittest.h',
+ 'media/webrtc/webrtcvideoframe_unittest.cc',
# Disabled because some tests fail.
# TODO(ronghuawu): Reenable these tests.
@@ -304,6 +153,11 @@
],
'conditions': [
['OS=="win"', {
+ 'dependencies': [
+ '<(DEPTH)/net/third_party/nss/ssl.gyp:libssl',
+ '<(DEPTH)/third_party/nss/nss.gyp:nspr',
+ '<(DEPTH)/third_party/nss/nss.gyp:nss',
+ ],
'msvs_settings': {
'VCLinkerTool': {
'AdditionalDependencies': [
@@ -327,7 +181,7 @@
'type': 'executable',
'dependencies': [
'<(DEPTH)/third_party/libsrtp/libsrtp.gyp:libsrtp',
- 'gunit',
+ '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils',
'libjingle.gyp:libjingle',
'libjingle.gyp:libjingle_p2p',
'libjingle_unittest_main',
@@ -354,6 +208,7 @@
'p2p/base/testturnserver.h',
'p2p/base/transport_unittest.cc',
'p2p/base/transportdescriptionfactory_unittest.cc',
+ 'p2p/base/turnport_unittest.cc',
'p2p/client/connectivitychecker_unittest.cc',
'p2p/client/fakeportallocator.h',
'p2p/client/portallocator_unittest.cc',
@@ -385,7 +240,7 @@
'type': 'executable',
'dependencies': [
'<(DEPTH)/testing/gmock.gyp:gmock',
- 'gunit',
+ '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils',
'libjingle.gyp:libjingle',
'libjingle.gyp:libjingle_p2p',
'libjingle.gyp:libjingle_peerconnection',
@@ -518,7 +373,7 @@
'type': 'executable',
'includes': [ 'build/ios_tests.gypi', ],
'dependencies': [
- 'gunit',
+ '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils',
'libjingle.gyp:libjingle_peerconnection_objc',
],
'sources': [
@@ -618,20 +473,6 @@
],
},
{
- 'target_name': 'libjingle_sound_unittest_run',
- 'type': 'none',
- 'dependencies': [
- 'libjingle_sound_unittest',
- ],
- 'includes': [
- 'build/isolate.gypi',
- 'libjingle_sound_unittest.isolate',
- ],
- 'sources': [
- 'libjingle_sound_unittest.isolate',
- ],
- },
- {
'target_name': 'libjingle_unittest_run',
'type': 'none',
'dependencies': [
diff --git a/media/base/capturemanager.cc b/media/base/capturemanager.cc
index 85bfa54..06f4b83 100644
--- a/media/base/capturemanager.cc
+++ b/media/base/capturemanager.cc
@@ -29,10 +29,10 @@
#include <algorithm>
-#include "talk/base/logging.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videoprocessor.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -64,7 +64,7 @@
explicit VideoCapturerState(CaptureRenderAdapter* adapter);
- talk_base::scoped_ptr<CaptureRenderAdapter> adapter_;
+ rtc::scoped_ptr<CaptureRenderAdapter> adapter_;
int start_count_;
CaptureFormats capture_formats_;
diff --git a/media/base/capturemanager.h b/media/base/capturemanager.h
index 5226e7b..16e8091 100644
--- a/media/base/capturemanager.h
+++ b/media/base/capturemanager.h
@@ -46,9 +46,9 @@
#include <map>
#include <vector>
-#include "talk/base/sigslotrepeater.h"
#include "talk/media/base/capturerenderadapter.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/sigslotrepeater.h"
namespace cricket {
diff --git a/media/base/capturemanager_unittest.cc b/media/base/capturemanager_unittest.cc
index 8025e56..1bdf0f8 100644
--- a/media/base/capturemanager_unittest.cc
+++ b/media/base/capturemanager_unittest.cc
@@ -27,11 +27,11 @@
#include "talk/media/base/capturemanager.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
#include "talk/media/base/fakemediaprocessor.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/base/fakevideorenderer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
const int kMsCallbackWait = 50;
diff --git a/media/base/capturerenderadapter.cc b/media/base/capturerenderadapter.cc
index a281e66..826909d 100644
--- a/media/base/capturerenderadapter.cc
+++ b/media/base/capturerenderadapter.cc
@@ -27,10 +27,10 @@
#include "talk/media/base/capturerenderadapter.h"
-#include "talk/base/logging.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videoprocessor.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -66,7 +66,7 @@
if (!video_renderer) {
return false;
}
- talk_base::CritScope cs(&capture_crit_);
+ rtc::CritScope cs(&capture_crit_);
if (IsRendererRegistered(*video_renderer)) {
return false;
}
@@ -78,7 +78,7 @@
if (!video_renderer) {
return false;
}
- talk_base::CritScope cs(&capture_crit_);
+ rtc::CritScope cs(&capture_crit_);
for (VideoRenderers::iterator iter = video_renderers_.begin();
iter != video_renderers_.end(); ++iter) {
if (video_renderer == iter->renderer) {
@@ -97,7 +97,7 @@
void CaptureRenderAdapter::OnVideoFrame(VideoCapturer* capturer,
const VideoFrame* video_frame) {
- talk_base::CritScope cs(&capture_crit_);
+ rtc::CritScope cs(&capture_crit_);
if (video_renderers_.empty()) {
return;
}
diff --git a/media/base/capturerenderadapter.h b/media/base/capturerenderadapter.h
index 1df9131..0b1ed97 100644
--- a/media/base/capturerenderadapter.h
+++ b/media/base/capturerenderadapter.h
@@ -36,9 +36,9 @@
#include <vector>
-#include "talk/base/criticalsection.h"
-#include "talk/base/sigslot.h"
#include "talk/media/base/videocapturer.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
@@ -83,7 +83,7 @@
VideoRenderers video_renderers_;
VideoCapturer* video_capturer_;
// Critical section synchronizing the capture thread.
- mutable talk_base::CriticalSection capture_crit_;
+ mutable rtc::CriticalSection capture_crit_;
};
} // namespace cricket
diff --git a/media/base/codec.cc b/media/base/codec.cc
index 6e65560..e4ab540 100644
--- a/media/base/codec.cc
+++ b/media/base/codec.cc
@@ -30,14 +30,15 @@
#include <algorithm>
#include <sstream>
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
static const int kMaxStaticPayloadId = 95;
+const int kMaxPayloadId = 127;
bool FeedbackParam::operator==(const FeedbackParam& other) const {
return _stricmp(other.id().c_str(), id().c_str()) == 0 &&
@@ -107,7 +108,7 @@
CodecParameterMap::const_iterator iter = params.find(name);
if (iter == params.end())
return false;
- return talk_base::FromString(iter->second, out);
+ return rtc::FromString(iter->second, out);
}
void Codec::SetParam(const std::string& name, const std::string& value) {
@@ -115,7 +116,11 @@
}
void Codec::SetParam(const std::string& name, int value) {
- params[name] = talk_base::ToString(value);
+ params[name] = rtc::ToString(value);
+}
+
+bool Codec::RemoveParam(const std::string& name) {
+ return params.erase(name) == 1;
}
void Codec::AddFeedbackParam(const FeedbackParam& param) {
diff --git a/media/base/codec.h b/media/base/codec.h
index 0e9bf3c..8619620 100644
--- a/media/base/codec.h
+++ b/media/base/codec.h
@@ -39,6 +39,8 @@
typedef std::map<std::string, std::string> CodecParameterMap;
+extern const int kMaxPayloadId;
+
class FeedbackParam {
public:
FeedbackParam(const std::string& id, const std::string& param)
@@ -104,6 +106,10 @@
void SetParam(const std::string& name, const std::string& value);
void SetParam(const std::string& name, int value);
+ // It is safe to input a non-existent parameter.
+ // Returns true if the parameter existed, false if it did not exist.
+ bool RemoveParam(const std::string& name);
+
bool HasFeedbackParam(const FeedbackParam& param) const;
void AddFeedbackParam(const FeedbackParam& param);
diff --git a/media/base/codec_unittest.cc b/media/base/codec_unittest.cc
index 35d1ab7..7bd3735 100644
--- a/media/base/codec_unittest.cc
+++ b/media/base/codec_unittest.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
#include "talk/media/base/codec.h"
+#include "webrtc/base/gunit.h"
using cricket::AudioCodec;
using cricket::Codec;
@@ -278,7 +278,7 @@
EXPECT_FALSE(c1.Matches(DataCodec(95, "D", 0)));
}
-TEST_F(CodecTest, TestSetParamAndGetParam) {
+TEST_F(CodecTest, TestSetParamGetParamAndRemoveParam) {
AudioCodec codec;
codec.SetParam("a", "1");
codec.SetParam("b", "x");
@@ -295,6 +295,8 @@
EXPECT_TRUE(codec.GetParam("b", &str_value));
EXPECT_EQ("x", str_value);
EXPECT_FALSE(codec.GetParam("c", &str_value));
+ EXPECT_TRUE(codec.RemoveParam("a"));
+ EXPECT_FALSE(codec.RemoveParam("c"));
}
TEST_F(CodecTest, TestIntersectFeedbackParams) {
diff --git a/media/base/constants.cc b/media/base/constants.cc
index cd10ef7..19a960f 100644
--- a/media/base/constants.cc
+++ b/media/base/constants.cc
@@ -59,6 +59,7 @@
const char kCodecParamStereo[] = "stereo";
const char kCodecParamUseInbandFec[] = "useinbandfec";
const char kCodecParamMaxAverageBitrate[] = "maxaveragebitrate";
+const char kCodecParamMaxPlaybackRate[] = "maxplaybackrate";
const char kCodecParamSctpProtocol[] = "protocol";
const char kCodecParamSctpStreams[] = "streams";
@@ -72,6 +73,7 @@
const int kOpusDefaultSPropStereo = 0;
const int kOpusDefaultStereo = 0;
const int kOpusDefaultUseInbandFec = 0;
+const int kOpusDefaultMaxPlaybackRate = 48000;
const int kPreferredMaxPTime = 60;
const int kPreferredMinPTime = 10;
diff --git a/media/base/constants.h b/media/base/constants.h
index dc5405d..5168acb 100644
--- a/media/base/constants.h
+++ b/media/base/constants.h
@@ -47,7 +47,6 @@
extern const char kRedCodecName[];
extern const char kUlpfecCodecName[];
-
// Codec parameters
extern const int kWildcardPayloadType;
extern const char kCodecParamAssociatedPayloadType[];
@@ -63,6 +62,7 @@
extern const char kCodecParamStereo[];
extern const char kCodecParamUseInbandFec[];
extern const char kCodecParamMaxAverageBitrate[];
+extern const char kCodecParamMaxPlaybackRate[];
extern const char kCodecParamSctpProtocol[];
extern const char kCodecParamSctpStreams[];
@@ -80,6 +80,8 @@
extern const int kOpusDefaultSPropStereo;
extern const int kOpusDefaultStereo;
extern const int kOpusDefaultUseInbandFec;
+extern const int kOpusDefaultMaxPlaybackRate;
+
// Prefered values in this code base. Note that they may differ from the default
// values in http://tools.ietf.org/html/draft-spittka-payload-rtp-opus-03
// Only frames larger or equal to 10 ms are currently supported in this code
diff --git a/media/base/cpuid.h b/media/base/cpuid.h
index 3b2aa76..310b221 100644
--- a/media/base/cpuid.h
+++ b/media/base/cpuid.h
@@ -28,7 +28,7 @@
#ifndef TALK_MEDIA_BASE_CPUID_H_
#define TALK_MEDIA_BASE_CPUID_H_
-#include "talk/base/basictypes.h" // For DISALLOW_IMPLICIT_CONSTRUCTORS
+#include "webrtc/base/basictypes.h" // For DISALLOW_IMPLICIT_CONSTRUCTORS
namespace cricket {
diff --git a/media/base/cpuid_unittest.cc b/media/base/cpuid_unittest.cc
index e8fcc2c..f03b77f 100644
--- a/media/base/cpuid_unittest.cc
+++ b/media/base/cpuid_unittest.cc
@@ -29,9 +29,9 @@
#include <iostream>
-#include "talk/base/basictypes.h"
-#include "talk/base/gunit.h"
-#include "talk/base/systeminfo.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/systeminfo.h"
TEST(CpuInfoTest, CpuId) {
LOG(LS_INFO) << "ARM: "
diff --git a/media/base/device.h b/media/base/device.h
new file mode 100755
index 0000000..ced74c6
--- /dev/null
+++ b/media/base/device.h
@@ -0,0 +1,50 @@
+// libjingle
+// Copyright 2014 Google Inc.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+
+#ifndef TALK_MEDIA_BASE_DEVICE_H_
+#define TALK_MEDIA_BASE_DEVICE_H_
+
+#include "webrtc/base/stringencode.h"
+
+namespace cricket {
+
+// Used to represent an audio or video capture or render device.
+struct Device {
+ Device() {}
+ Device(const std::string& name, int id)
+ : name(name),
+ id(rtc::ToString(id)) {
+ }
+ Device(const std::string& name, const std::string& id)
+ : name(name), id(id) {}
+
+ std::string name;
+ std::string id;
+};
+
+} // namespace cricket
+
+#endif // TALK_MEDIA_BASE_DEVICE_H_
diff --git a/media/base/executablehelpers.h b/media/base/executablehelpers.h
new file mode 100644
index 0000000..2dde010
--- /dev/null
+++ b/media/base/executablehelpers.h
@@ -0,0 +1,100 @@
+/*
+ * libjingle
+ * Copyright 2014 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TALK_MEDIA_BASE_EXECUTABLEHELPERS_H_
+#define TALK_MEDIA_BASE_EXECUTABLEHELPERS_H_
+
+#ifdef OSX
+#include <mach-o/dyld.h>
+#endif
+
+#include <string>
+
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
+
+namespace rtc {
+
+// Returns the path to the running executable or an empty path.
+// TODO(thorcarpenter): Consolidate with FluteClient::get_executable_dir.
+inline Pathname GetExecutablePath() {
+ const int32 kMaxExePathSize = 255;
+#ifdef WIN32
+ TCHAR exe_path_buffer[kMaxExePathSize];
+ DWORD copied_length = GetModuleFileName(NULL, // NULL = Current process
+ exe_path_buffer, kMaxExePathSize);
+ if (0 == copied_length) {
+ LOG(LS_ERROR) << "Copied length is zero";
+ return rtc::Pathname();
+ }
+ if (kMaxExePathSize == copied_length) {
+ LOG(LS_ERROR) << "Buffer too small";
+ return rtc::Pathname();
+ }
+#ifdef UNICODE
+ std::wstring wdir(exe_path_buffer);
+ std::string dir_tmp(wdir.begin(), wdir.end());
+ rtc::Pathname path(dir_tmp);
+#else // UNICODE
+ rtc::Pathname path(exe_path_buffer);
+#endif // UNICODE
+#elif defined(OSX) || defined(LINUX)
+ char exe_path_buffer[kMaxExePathSize];
+#ifdef OSX
+ uint32_t copied_length = kMaxExePathSize - 1;
+ if (_NSGetExecutablePath(exe_path_buffer, &copied_length) == -1) {
+ LOG(LS_ERROR) << "Buffer too small";
+ return rtc::Pathname();
+ }
+#elif defined LINUX
+ int32 copied_length = kMaxExePathSize - 1;
+ const char* kProcExeFmt = "/proc/%d/exe";
+ char proc_exe_link[40];
+ snprintf(proc_exe_link, sizeof(proc_exe_link), kProcExeFmt, getpid());
+ copied_length = readlink(proc_exe_link, exe_path_buffer, copied_length);
+ if (copied_length == -1) {
+ LOG_ERR(LS_ERROR) << "Error reading link " << proc_exe_link;
+ return rtc::Pathname();
+ }
+ if (copied_length == kMaxExePathSize - 1) {
+ LOG(LS_ERROR) << "Probably truncated result when reading link "
+ << proc_exe_link;
+ return rtc::Pathname();
+ }
+ exe_path_buffer[copied_length] = '\0';
+#endif // LINUX
+ rtc::Pathname path(exe_path_buffer);
+#else // Android || IOS
+ rtc::Pathname path;
+#endif // OSX || LINUX
+ return path;
+}
+
+} // namespace rtc
+
+#endif // TALK_MEDIA_BASE_EXECUTABLEHELPERS_H_
+
diff --git a/media/base/fakemediaengine.h b/media/base/fakemediaengine.h
index 27fbeb0..a6eabef 100644
--- a/media/base/fakemediaengine.h
+++ b/media/base/fakemediaengine.h
@@ -34,13 +34,13 @@
#include <string>
#include <vector>
-#include "talk/base/buffer.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/audiorenderer.h"
#include "talk/media/base/mediaengine.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/base/streamparams.h"
#include "talk/p2p/base/sessiondescription.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
@@ -73,11 +73,11 @@
if (!sending_) {
return false;
}
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return Base::SendPacket(&packet);
}
bool SendRtcp(const void* data, int len) {
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return Base::SendRtcp(&packet);
}
@@ -191,12 +191,12 @@
return true;
}
void set_playout(bool playout) { playout_ = playout; }
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {
rtp_packets_.push_back(std::string(packet->data(), packet->length()));
}
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {
rtcp_packets_.push_back(std::string(packet->data(), packet->length()));
}
virtual void OnReadyToSend(bool ready) {
@@ -690,7 +690,7 @@
}
virtual bool SendData(const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result) {
if (send_blocked_) {
*result = SDR_BLOCK;
@@ -724,7 +724,7 @@
: loglevel_(-1),
options_changed_(false),
fail_create_channel_(false) {}
- bool Init(talk_base::Thread* worker_thread) { return true; }
+ bool Init(rtc::Thread* worker_thread) { return true; }
void Terminate() {}
void SetLogging(int level, const char* filter) {
@@ -824,7 +824,7 @@
bool SetLocalMonitor(bool enable) { return true; }
- bool StartAecDump(talk_base::PlatformFile file) { return false; }
+ bool StartAecDump(rtc::PlatformFile file) { return false; }
bool RegisterProcessor(uint32 ssrc, VoiceProcessor* voice_processor,
MediaProcessorDirection direction) {
@@ -868,7 +868,7 @@
class FakeVideoEngine : public FakeBaseEngine {
public:
- FakeVideoEngine() : renderer_(NULL), capture_(false), processor_(NULL) {
+ FakeVideoEngine() : capture_(false), processor_(NULL) {
// Add a fake video codec. Note that the name must not be "" as there are
// sanity checks against that.
codecs_.push_back(VideoCodec(0, "fake_video_codec", 0, 0, 0, 0));
@@ -926,10 +926,6 @@
options_changed_ = true;
return true;
}
- bool SetLocalRenderer(VideoRenderer* r) {
- renderer_ = r;
- return true;
- }
bool SetCapture(bool capture) {
capture_ = capture;
return true;
@@ -946,7 +942,6 @@
std::vector<VideoCodec> codecs_;
VideoEncoderConfig default_encoder_config_;
std::string in_device_;
- VideoRenderer* renderer_;
bool capture_;
VideoProcessor* processor_;
VideoOptions options_;
@@ -994,7 +989,6 @@
}
const std::string& audio_in_device() const { return voice_.in_device_; }
const std::string& audio_out_device() const { return voice_.out_device_; }
- VideoRenderer* local_renderer() { return video_.renderer_; }
int voice_loglevel() const { return voice_.loglevel_; }
const std::string& voice_logfilter() const { return voice_.logfilter_; }
int video_loglevel() const { return video_.loglevel_; }
diff --git a/media/base/fakenetworkinterface.h b/media/base/fakenetworkinterface.h
index eb0175b..3a9d135 100644
--- a/media/base/fakenetworkinterface.h
+++ b/media/base/fakenetworkinterface.h
@@ -28,32 +28,32 @@
#ifndef TALK_MEDIA_BASE_FAKENETWORKINTERFACE_H_
#define TALK_MEDIA_BASE_FAKENETWORKINTERFACE_H_
-#include <vector>
#include <map>
+#include <vector>
-#include "talk/base/buffer.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/dscp.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/thread.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/rtputils.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/thread.h"
namespace cricket {
// Fake NetworkInterface that sends/receives RTP/RTCP packets.
class FakeNetworkInterface : public MediaChannel::NetworkInterface,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
FakeNetworkInterface()
- : thread_(talk_base::Thread::Current()),
+ : thread_(rtc::Thread::Current()),
dest_(NULL),
conf_(false),
sendbuf_size_(-1),
recvbuf_size_(-1),
- dscp_(talk_base::DSCP_NO_CHANGE) {
+ dscp_(rtc::DSCP_NO_CHANGE) {
}
void SetDestination(MediaChannel* dest) { dest_ = dest; }
@@ -62,13 +62,13 @@
// the transport will send multiple copies of the packet with the specified
// SSRCs. This allows us to simulate receiving media from multiple sources.
void SetConferenceMode(bool conf, const std::vector<uint32>& ssrcs) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
conf_ = conf;
conf_sent_ssrcs_ = ssrcs;
}
int NumRtpBytes() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
int bytes = 0;
for (size_t i = 0; i < rtp_packets_.size(); ++i) {
bytes += static_cast<int>(rtp_packets_[i].length());
@@ -77,50 +77,50 @@
}
int NumRtpBytes(uint32 ssrc) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
int bytes = 0;
GetNumRtpBytesAndPackets(ssrc, &bytes, NULL);
return bytes;
}
int NumRtpPackets() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return static_cast<int>(rtp_packets_.size());
}
int NumRtpPackets(uint32 ssrc) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
int packets = 0;
GetNumRtpBytesAndPackets(ssrc, NULL, &packets);
return packets;
}
int NumSentSsrcs() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return static_cast<int>(sent_ssrcs_.size());
}
// Note: callers are responsible for deleting the returned buffer.
- const talk_base::Buffer* GetRtpPacket(int index) {
- talk_base::CritScope cs(&crit_);
+ const rtc::Buffer* GetRtpPacket(int index) {
+ rtc::CritScope cs(&crit_);
if (index >= NumRtpPackets()) {
return NULL;
}
- return new talk_base::Buffer(rtp_packets_[index]);
+ return new rtc::Buffer(rtp_packets_[index]);
}
int NumRtcpPackets() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return static_cast<int>(rtcp_packets_.size());
}
// Note: callers are responsible for deleting the returned buffer.
- const talk_base::Buffer* GetRtcpPacket(int index) {
- talk_base::CritScope cs(&crit_);
+ const rtc::Buffer* GetRtcpPacket(int index) {
+ rtc::CritScope cs(&crit_);
if (index >= NumRtcpPackets()) {
return NULL;
}
- return new talk_base::Buffer(rtcp_packets_[index]);
+ return new rtc::Buffer(rtcp_packets_[index]);
}
// Indicate that |n|'th packet for |ssrc| should be dropped.
@@ -130,12 +130,12 @@
int sendbuf_size() const { return sendbuf_size_; }
int recvbuf_size() const { return recvbuf_size_; }
- talk_base::DiffServCodePoint dscp() const { return dscp_; }
+ rtc::DiffServCodePoint dscp() const { return dscp_; }
protected:
- virtual bool SendPacket(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
- talk_base::CritScope cs(&crit_);
+ virtual bool SendPacket(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
+ rtc::CritScope cs(&crit_);
uint32 cur_ssrc = 0;
if (!GetRtpSsrc(packet->data(), packet->length(), &cur_ssrc)) {
@@ -154,7 +154,7 @@
rtp_packets_.push_back(*packet);
if (conf_) {
- talk_base::Buffer buffer_copy(*packet);
+ rtc::Buffer buffer_copy(*packet);
for (size_t i = 0; i < conf_sent_ssrcs_.size(); ++i) {
if (!SetRtpSsrc(buffer_copy.data(), buffer_copy.length(),
conf_sent_ssrcs_[i])) {
@@ -168,9 +168,9 @@
return true;
}
- virtual bool SendRtcp(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
- talk_base::CritScope cs(&crit_);
+ virtual bool SendRtcp(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
+ rtc::CritScope cs(&crit_);
rtcp_packets_.push_back(*packet);
if (!conf_) {
// don't worry about RTCP in conf mode for now
@@ -179,33 +179,33 @@
return true;
}
- virtual int SetOption(SocketType type, talk_base::Socket::Option opt,
+ virtual int SetOption(SocketType type, rtc::Socket::Option opt,
int option) {
- if (opt == talk_base::Socket::OPT_SNDBUF) {
+ if (opt == rtc::Socket::OPT_SNDBUF) {
sendbuf_size_ = option;
- } else if (opt == talk_base::Socket::OPT_RCVBUF) {
+ } else if (opt == rtc::Socket::OPT_RCVBUF) {
recvbuf_size_ = option;
- } else if (opt == talk_base::Socket::OPT_DSCP) {
- dscp_ = static_cast<talk_base::DiffServCodePoint>(option);
+ } else if (opt == rtc::Socket::OPT_DSCP) {
+ dscp_ = static_cast<rtc::DiffServCodePoint>(option);
}
return 0;
}
- void PostMessage(int id, const talk_base::Buffer& packet) {
- thread_->Post(this, id, talk_base::WrapMessageData(packet));
+ void PostMessage(int id, const rtc::Buffer& packet) {
+ thread_->Post(this, id, rtc::WrapMessageData(packet));
}
- virtual void OnMessage(talk_base::Message* msg) {
- talk_base::TypedMessageData<talk_base::Buffer>* msg_data =
- static_cast<talk_base::TypedMessageData<talk_base::Buffer>*>(
+ virtual void OnMessage(rtc::Message* msg) {
+ rtc::TypedMessageData<rtc::Buffer>* msg_data =
+ static_cast<rtc::TypedMessageData<rtc::Buffer>*>(
msg->pdata);
if (dest_) {
if (msg->message_id == ST_RTP) {
dest_->OnPacketReceived(&msg_data->data(),
- talk_base::CreatePacketTime(0));
+ rtc::CreatePacketTime(0));
} else {
dest_->OnRtcpReceived(&msg_data->data(),
- talk_base::CreatePacketTime(0));
+ rtc::CreatePacketTime(0));
}
}
delete msg_data;
@@ -236,7 +236,7 @@
}
}
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
MediaChannel* dest_;
bool conf_;
// The ssrcs used in sending out packets in conference mode.
@@ -246,12 +246,12 @@
std::map<uint32, uint32> sent_ssrcs_;
// Map to track packet-number that needs to be dropped per ssrc.
std::map<uint32, std::set<uint32> > drop_map_;
- talk_base::CriticalSection crit_;
- std::vector<talk_base::Buffer> rtp_packets_;
- std::vector<talk_base::Buffer> rtcp_packets_;
+ rtc::CriticalSection crit_;
+ std::vector<rtc::Buffer> rtp_packets_;
+ std::vector<rtc::Buffer> rtcp_packets_;
int sendbuf_size_;
int recvbuf_size_;
- talk_base::DiffServCodePoint dscp_;
+ rtc::DiffServCodePoint dscp_;
};
} // namespace cricket
diff --git a/media/base/fakescreencapturerfactory.h b/media/base/fakescreencapturerfactory.h
new file mode 100755
index 0000000..dfd7376
--- /dev/null
+++ b/media/base/fakescreencapturerfactory.h
@@ -0,0 +1,78 @@
+/*
+ * libjingle
+ * Copyright 2012 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TALK_MEDIA_BASE_FAKESCREENCAPTURERFACTORY_H_
+#define TALK_MEDIA_BASE_FAKESCREENCAPTURERFACTORY_H_
+
+#include "talk/media/base/fakevideocapturer.h"
+#include "talk/media/base/videocapturerfactory.h"
+
+namespace cricket {
+
+class FakeScreenCapturerFactory
+ : public cricket::ScreenCapturerFactory,
+ public sigslot::has_slots<> {
+ public:
+ FakeScreenCapturerFactory()
+ : window_capturer_(NULL),
+ capture_state_(cricket::CS_STOPPED) {}
+
+ virtual cricket::VideoCapturer* Create(const ScreencastId& window) {
+ if (window_capturer_ != NULL) {
+ return NULL;
+ }
+ window_capturer_ = new cricket::FakeVideoCapturer;
+ window_capturer_->SignalDestroyed.connect(
+ this,
+ &FakeScreenCapturerFactory::OnWindowCapturerDestroyed);
+ window_capturer_->SignalStateChange.connect(
+ this,
+ &FakeScreenCapturerFactory::OnStateChange);
+ return window_capturer_;
+ }
+
+ cricket::FakeVideoCapturer* window_capturer() { return window_capturer_; }
+
+ cricket::CaptureState capture_state() { return capture_state_; }
+
+ private:
+ void OnWindowCapturerDestroyed(cricket::FakeVideoCapturer* capturer) {
+ if (capturer == window_capturer_) {
+ window_capturer_ = NULL;
+ }
+ }
+ void OnStateChange(cricket::VideoCapturer*, cricket::CaptureState state) {
+ capture_state_ = state;
+ }
+
+ cricket::FakeVideoCapturer* window_capturer_;
+ cricket::CaptureState capture_state_;
+};
+
+} // namespace cricket
+
+#endif // TALK_MEDIA_BASE_FAKESCREENCAPTURERFACTORY_H_
diff --git a/media/base/fakevideocapturer.h b/media/base/fakevideocapturer.h
index 8dc69c3..e8d49c0 100644
--- a/media/base/fakevideocapturer.h
+++ b/media/base/fakevideocapturer.h
@@ -32,10 +32,13 @@
#include <vector>
-#include "talk/base/timeutils.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/timeutils.h"
+#ifdef HAVE_WEBRTC_VIDEO
+#include "talk/media/webrtc/webrtcvideoframefactory.h"
+#endif
namespace cricket {
@@ -44,9 +47,12 @@
public:
FakeVideoCapturer()
: running_(false),
- initial_unix_timestamp_(time(NULL) * talk_base::kNumNanosecsPerSec),
- next_timestamp_(talk_base::kNumNanosecsPerMillisec),
+ initial_unix_timestamp_(time(NULL) * rtc::kNumNanosecsPerSec),
+ next_timestamp_(rtc::kNumNanosecsPerMillisec),
is_screencast_(false) {
+#ifdef HAVE_WEBRTC_VIDEO
+ set_frame_factory(new cricket::WebRtcVideoFrameFactory());
+#endif
// Default supported formats. Use ResetSupportedFormats to over write.
std::vector<cricket::VideoFormat> formats;
formats.push_back(cricket::VideoFormat(1280, 720,
@@ -101,7 +107,7 @@
frame.time_stamp = initial_unix_timestamp_ + next_timestamp_;
next_timestamp_ += 33333333; // 30 fps
- talk_base::scoped_ptr<char[]> data(new char[size]);
+ rtc::scoped_ptr<char[]> data(new char[size]);
frame.data = data.get();
// Copy something non-zero into the buffer so Validate wont complain that
// the frame is all duplicate.
diff --git a/media/base/fakevideorenderer.h b/media/base/fakevideorenderer.h
index cab77dd..9ceaac8 100644
--- a/media/base/fakevideorenderer.h
+++ b/media/base/fakevideorenderer.h
@@ -28,10 +28,10 @@
#ifndef TALK_MEDIA_BASE_FAKEVIDEORENDERER_H_
#define TALK_MEDIA_BASE_FAKEVIDEORENDERER_H_
-#include "talk/base/logging.h"
-#include "talk/base/sigslot.h"
#include "talk/media/base/videoframe.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
@@ -48,7 +48,7 @@
}
virtual bool SetSize(int width, int height, int reserved) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
width_ = width;
height_ = height;
++num_set_sizes_;
@@ -57,7 +57,7 @@
}
virtual bool RenderFrame(const VideoFrame* frame) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
// TODO(zhurunz) Check with VP8 team to see if we can remove this
// tolerance on Y values.
black_frame_ = CheckFrameColorYuv(6, 48, 128, 128, 128, 128, frame);
@@ -82,23 +82,23 @@
int errors() const { return errors_; }
int width() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return width_;
}
int height() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return height_;
}
int num_set_sizes() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return num_set_sizes_;
}
int num_rendered_frames() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return num_rendered_frames_;
}
bool black_frame() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return black_frame_;
}
@@ -160,7 +160,7 @@
int num_set_sizes_;
int num_rendered_frames_;
bool black_frame_;
- mutable talk_base::CriticalSection crit_;
+ mutable rtc::CriticalSection crit_;
};
} // namespace cricket
diff --git a/media/base/filemediaengine.cc b/media/base/filemediaengine.cc
index e8c356e..460b205 100644
--- a/media/base/filemediaengine.cc
+++ b/media/base/filemediaengine.cc
@@ -27,14 +27,14 @@
#include <limits.h>
-#include "talk/base/buffer.h"
-#include "talk/base/event.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
#include "talk/media/base/rtpdump.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/base/streamparams.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/event.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/stream.h"
namespace cricket {
@@ -59,14 +59,14 @@
}
VoiceMediaChannel* FileMediaEngine::CreateChannel() {
- talk_base::FileStream* input_file_stream = NULL;
- talk_base::FileStream* output_file_stream = NULL;
+ rtc::FileStream* input_file_stream = NULL;
+ rtc::FileStream* output_file_stream = NULL;
if (voice_input_filename_.empty() && voice_output_filename_.empty())
return NULL;
if (!voice_input_filename_.empty()) {
- input_file_stream = talk_base::Filesystem::OpenFile(
- talk_base::Pathname(voice_input_filename_), "rb");
+ input_file_stream = rtc::Filesystem::OpenFile(
+ rtc::Pathname(voice_input_filename_), "rb");
if (!input_file_stream) {
LOG(LS_ERROR) << "Not able to open the input audio stream file.";
return NULL;
@@ -74,8 +74,8 @@
}
if (!voice_output_filename_.empty()) {
- output_file_stream = talk_base::Filesystem::OpenFile(
- talk_base::Pathname(voice_output_filename_), "wb");
+ output_file_stream = rtc::Filesystem::OpenFile(
+ rtc::Pathname(voice_output_filename_), "wb");
if (!output_file_stream) {
delete input_file_stream;
LOG(LS_ERROR) << "Not able to open the output audio stream file.";
@@ -89,15 +89,15 @@
VideoMediaChannel* FileMediaEngine::CreateVideoChannel(
VoiceMediaChannel* voice_ch) {
- talk_base::FileStream* input_file_stream = NULL;
- talk_base::FileStream* output_file_stream = NULL;
+ rtc::FileStream* input_file_stream = NULL;
+ rtc::FileStream* output_file_stream = NULL;
if (video_input_filename_.empty() && video_output_filename_.empty())
return NULL;
if (!video_input_filename_.empty()) {
- input_file_stream = talk_base::Filesystem::OpenFile(
- talk_base::Pathname(video_input_filename_), "rb");
+ input_file_stream = rtc::Filesystem::OpenFile(
+ rtc::Pathname(video_input_filename_), "rb");
if (!input_file_stream) {
LOG(LS_ERROR) << "Not able to open the input video stream file.";
return NULL;
@@ -105,8 +105,8 @@
}
if (!video_output_filename_.empty()) {
- output_file_stream = talk_base::Filesystem::OpenFile(
- talk_base::Pathname(video_output_filename_), "wb");
+ output_file_stream = rtc::Filesystem::OpenFile(
+ rtc::Pathname(video_output_filename_), "wb");
if (!output_file_stream) {
delete input_file_stream;
LOG(LS_ERROR) << "Not able to open the output video stream file.";
@@ -121,21 +121,21 @@
///////////////////////////////////////////////////////////////////////////
// Definition of RtpSenderReceiver.
///////////////////////////////////////////////////////////////////////////
-class RtpSenderReceiver : public talk_base::MessageHandler {
+class RtpSenderReceiver : public rtc::MessageHandler {
public:
RtpSenderReceiver(MediaChannel* channel,
- talk_base::StreamInterface* input_file_stream,
- talk_base::StreamInterface* output_file_stream,
- talk_base::Thread* sender_thread);
+ rtc::StreamInterface* input_file_stream,
+ rtc::StreamInterface* output_file_stream,
+ rtc::Thread* sender_thread);
virtual ~RtpSenderReceiver();
// Called by media channel. Context: media channel thread.
bool SetSend(bool send);
void SetSendSsrc(uint32 ssrc);
- void OnPacketReceived(talk_base::Buffer* packet);
+ void OnPacketReceived(rtc::Buffer* packet);
// Override virtual method of parent MessageHandler. Context: Worker Thread.
- virtual void OnMessage(talk_base::Message* pmsg);
+ virtual void OnMessage(rtc::Message* pmsg);
private:
// Read the next RTP dump packet, whose RTP SSRC is the same as first_ssrc_.
@@ -147,11 +147,11 @@
bool SendRtpPacket(const void* data, size_t len);
MediaChannel* media_channel_;
- talk_base::scoped_ptr<talk_base::StreamInterface> input_stream_;
- talk_base::scoped_ptr<talk_base::StreamInterface> output_stream_;
- talk_base::scoped_ptr<RtpDumpLoopReader> rtp_dump_reader_;
- talk_base::scoped_ptr<RtpDumpWriter> rtp_dump_writer_;
- talk_base::Thread* sender_thread_;
+ rtc::scoped_ptr<rtc::StreamInterface> input_stream_;
+ rtc::scoped_ptr<rtc::StreamInterface> output_stream_;
+ rtc::scoped_ptr<RtpDumpLoopReader> rtp_dump_reader_;
+ rtc::scoped_ptr<RtpDumpWriter> rtp_dump_writer_;
+ rtc::Thread* sender_thread_;
bool own_sender_thread_;
// RTP dump packet read from the input stream.
RtpDumpPacket rtp_dump_packet_;
@@ -168,16 +168,16 @@
///////////////////////////////////////////////////////////////////////////
RtpSenderReceiver::RtpSenderReceiver(
MediaChannel* channel,
- talk_base::StreamInterface* input_file_stream,
- talk_base::StreamInterface* output_file_stream,
- talk_base::Thread* sender_thread)
+ rtc::StreamInterface* input_file_stream,
+ rtc::StreamInterface* output_file_stream,
+ rtc::Thread* sender_thread)
: media_channel_(channel),
input_stream_(input_file_stream),
output_stream_(output_file_stream),
sending_(false),
first_packet_(true) {
if (sender_thread == NULL) {
- sender_thread_ = new talk_base::Thread();
+ sender_thread_ = new rtc::Thread();
own_sender_thread_ = true;
} else {
sender_thread_ = sender_thread;
@@ -211,7 +211,7 @@
sending_ = send;
if (!was_sending && sending_) {
sender_thread_->PostDelayed(0, this); // Wake up the send thread.
- start_send_time_ = talk_base::Time();
+ start_send_time_ = rtc::Time();
}
return true;
}
@@ -222,13 +222,13 @@
}
}
-void RtpSenderReceiver::OnPacketReceived(talk_base::Buffer* packet) {
+void RtpSenderReceiver::OnPacketReceived(rtc::Buffer* packet) {
if (rtp_dump_writer_) {
rtp_dump_writer_->WriteRtpPacket(packet->data(), packet->length());
}
}
-void RtpSenderReceiver::OnMessage(talk_base::Message* pmsg) {
+void RtpSenderReceiver::OnMessage(rtc::Message* pmsg) {
if (!sending_) {
// If the sender thread is not sending, ignore this message. The thread goes
// to sleep until SetSend(true) wakes it up.
@@ -240,9 +240,9 @@
}
if (ReadNextPacket(&rtp_dump_packet_)) {
- int wait = talk_base::TimeUntil(
+ int wait = rtc::TimeUntil(
start_send_time_ + rtp_dump_packet_.elapsed_time);
- wait = talk_base::_max(0, wait);
+ wait = rtc::_max(0, wait);
sender_thread_->PostDelayed(wait, this);
} else {
sender_thread_->Quit();
@@ -250,7 +250,7 @@
}
bool RtpSenderReceiver::ReadNextPacket(RtpDumpPacket* packet) {
- while (talk_base::SR_SUCCESS == rtp_dump_reader_->ReadPacket(packet)) {
+ while (rtc::SR_SUCCESS == rtp_dump_reader_->ReadPacket(packet)) {
uint32 ssrc;
if (!packet->GetRtpSsrc(&ssrc)) {
return false;
@@ -270,7 +270,7 @@
if (!media_channel_)
return false;
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return media_channel_->SendPacket(&packet);
}
@@ -278,9 +278,9 @@
// Implementation of FileVoiceChannel.
///////////////////////////////////////////////////////////////////////////
FileVoiceChannel::FileVoiceChannel(
- talk_base::StreamInterface* input_file_stream,
- talk_base::StreamInterface* output_file_stream,
- talk_base::Thread* rtp_sender_thread)
+ rtc::StreamInterface* input_file_stream,
+ rtc::StreamInterface* output_file_stream,
+ rtc::Thread* rtp_sender_thread)
: send_ssrc_(0),
rtp_sender_receiver_(new RtpSenderReceiver(this, input_file_stream,
output_file_stream,
@@ -316,7 +316,7 @@
}
void FileVoiceChannel::OnPacketReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
rtp_sender_receiver_->OnPacketReceived(packet);
}
@@ -324,9 +324,9 @@
// Implementation of FileVideoChannel.
///////////////////////////////////////////////////////////////////////////
FileVideoChannel::FileVideoChannel(
- talk_base::StreamInterface* input_file_stream,
- talk_base::StreamInterface* output_file_stream,
- talk_base::Thread* rtp_sender_thread)
+ rtc::StreamInterface* input_file_stream,
+ rtc::StreamInterface* output_file_stream,
+ rtc::Thread* rtp_sender_thread)
: send_ssrc_(0),
rtp_sender_receiver_(new RtpSenderReceiver(this, input_file_stream,
output_file_stream,
@@ -362,7 +362,7 @@
}
void FileVideoChannel::OnPacketReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
rtp_sender_receiver_->OnPacketReceived(packet);
}
diff --git a/media/base/filemediaengine.h b/media/base/filemediaengine.h
index 6656cdf..d3e99a8 100644
--- a/media/base/filemediaengine.h
+++ b/media/base/filemediaengine.h
@@ -29,13 +29,13 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stream.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediaengine.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stream.h"
-namespace talk_base {
+namespace rtc {
class StreamInterface;
}
@@ -78,7 +78,7 @@
}
// Implement pure virtual methods of MediaEngine.
- virtual bool Init(talk_base::Thread* worker_thread) {
+ virtual bool Init(rtc::Thread* worker_thread) {
return true;
}
virtual void Terminate() {}
@@ -88,7 +88,6 @@
virtual SoundclipMedia* CreateSoundclip() { return NULL; }
virtual AudioOptions GetAudioOptions() const { return AudioOptions(); }
virtual bool SetAudioOptions(const AudioOptions& options) { return true; }
- virtual bool SetVideoOptions(const VideoOptions& options) { return true; }
virtual bool SetAudioDelayOffset(int offset) { return true; }
virtual bool SetDefaultVideoEncoderConfig(const VideoEncoderConfig& config) {
return true;
@@ -113,7 +112,6 @@
virtual bool SetOutputVolume(int level) { return true; }
virtual int GetInputLevel() { return 0; }
virtual bool SetLocalMonitor(bool enable) { return true; }
- virtual bool SetLocalRenderer(VideoRenderer* renderer) { return true; }
// TODO(whyuan): control channel send?
virtual bool SetVideoCapture(bool capture) { return true; }
virtual const std::vector<AudioCodec>& audio_codecs() {
@@ -133,7 +131,7 @@
virtual bool FindVideoCodec(const VideoCodec& codec) { return true; }
virtual void SetVoiceLogging(int min_sev, const char* filter) {}
virtual void SetVideoLogging(int min_sev, const char* filter) {}
- virtual bool StartAecDump(talk_base::PlatformFile) { return false; }
+ virtual bool StartAecDump(rtc::PlatformFile) { return false; }
virtual bool RegisterVideoProcessor(VideoProcessor* processor) {
return true;
@@ -160,7 +158,7 @@
return signal_state_change_;
}
- void set_rtp_sender_thread(talk_base::Thread* thread) {
+ void set_rtp_sender_thread(rtc::Thread* thread) {
rtp_sender_thread_ = thread;
}
@@ -175,7 +173,7 @@
std::vector<RtpHeaderExtension> video_rtp_header_extensions_;
sigslot::repeater2<VideoCapturer*, CaptureState>
signal_state_change_;
- talk_base::Thread* rtp_sender_thread_;
+ rtc::Thread* rtp_sender_thread_;
DISALLOW_COPY_AND_ASSIGN(FileMediaEngine);
};
@@ -184,9 +182,9 @@
class FileVoiceChannel : public VoiceMediaChannel {
public:
- FileVoiceChannel(talk_base::StreamInterface* input_file_stream,
- talk_base::StreamInterface* output_file_stream,
- talk_base::Thread* rtp_sender_thread);
+ FileVoiceChannel(rtc::StreamInterface* input_file_stream,
+ rtc::StreamInterface* output_file_stream,
+ rtc::Thread* rtp_sender_thread);
virtual ~FileVoiceChannel();
// Implement pure virtual methods of VoiceMediaChannel.
@@ -233,10 +231,10 @@
virtual bool GetStats(VoiceMediaInfo* info) { return true; }
// Implement pure virtual methods of MediaChannel.
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {}
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {}
virtual void OnReadyToSend(bool ready) {}
virtual bool AddSendStream(const StreamParams& sp);
virtual bool RemoveSendStream(uint32 ssrc);
@@ -256,7 +254,7 @@
private:
uint32 send_ssrc_;
- talk_base::scoped_ptr<RtpSenderReceiver> rtp_sender_receiver_;
+ rtc::scoped_ptr<RtpSenderReceiver> rtp_sender_receiver_;
AudioOptions options_;
DISALLOW_COPY_AND_ASSIGN(FileVoiceChannel);
@@ -264,9 +262,9 @@
class FileVideoChannel : public VideoMediaChannel {
public:
- FileVideoChannel(talk_base::StreamInterface* input_file_stream,
- talk_base::StreamInterface* output_file_stream,
- talk_base::Thread* rtp_sender_thread);
+ FileVideoChannel(rtc::StreamInterface* input_file_stream,
+ rtc::StreamInterface* output_file_stream,
+ rtc::Thread* rtp_sender_thread);
virtual ~FileVideoChannel();
// Implement pure virtual methods of VideoMediaChannel.
@@ -304,10 +302,10 @@
virtual bool RequestIntraFrame() { return false; }
// Implement pure virtual methods of MediaChannel.
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {}
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {}
virtual void OnReadyToSend(bool ready) {}
virtual bool AddSendStream(const StreamParams& sp);
virtual bool RemoveSendStream(uint32 ssrc);
@@ -328,7 +326,7 @@
private:
uint32 send_ssrc_;
- talk_base::scoped_ptr<RtpSenderReceiver> rtp_sender_receiver_;
+ rtc::scoped_ptr<RtpSenderReceiver> rtp_sender_receiver_;
VideoOptions options_;
DISALLOW_COPY_AND_ASSIGN(FileVideoChannel);
diff --git a/media/base/filemediaengine_unittest.cc b/media/base/filemediaengine_unittest.cc
index b1b021d..c542baf 100644
--- a/media/base/filemediaengine_unittest.cc
+++ b/media/base/filemediaengine_unittest.cc
@@ -27,15 +27,15 @@
#include <set>
-#include "talk/base/buffer.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
#include "talk/media/base/filemediaengine.h"
#include "talk/media/base/rtpdump.h"
#include "talk/media/base/streamparams.h"
#include "talk/media/base/testutils.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/stream.h"
namespace cricket {
@@ -49,7 +49,7 @@
//////////////////////////////////////////////////////////////////////////////
class FileNetworkInterface : public MediaChannel::NetworkInterface {
public:
- FileNetworkInterface(talk_base::StreamInterface* output, MediaChannel* ch)
+ FileNetworkInterface(rtc::StreamInterface* output, MediaChannel* ch)
: media_channel_(ch),
num_sent_packets_(0) {
if (output) {
@@ -58,15 +58,15 @@
}
// Implement pure virtual methods of NetworkInterface.
- virtual bool SendPacket(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
+ virtual bool SendPacket(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
if (!packet) return false;
if (media_channel_) {
- media_channel_->OnPacketReceived(packet, talk_base::PacketTime());
+ media_channel_->OnPacketReceived(packet, rtc::PacketTime());
}
if (dump_writer_.get() &&
- talk_base::SR_SUCCESS != dump_writer_->WriteRtpPacket(
+ rtc::SR_SUCCESS != dump_writer_->WriteRtpPacket(
packet->data(), packet->length())) {
return false;
}
@@ -75,19 +75,19 @@
return true;
}
- virtual bool SendRtcp(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) { return false; }
+ virtual bool SendRtcp(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) { return false; }
virtual int SetOption(MediaChannel::NetworkInterface::SocketType type,
- talk_base::Socket::Option opt, int option) {
+ rtc::Socket::Option opt, int option) {
return 0;
}
- virtual void SetDefaultDSCPCode(talk_base::DiffServCodePoint dscp) {}
+ virtual void SetDefaultDSCPCode(rtc::DiffServCodePoint dscp) {}
size_t num_sent_packets() const { return num_sent_packets_; }
private:
MediaChannel* media_channel_;
- talk_base::scoped_ptr<RtpDumpWriter> dump_writer_;
+ rtc::scoped_ptr<RtpDumpWriter> dump_writer_;
size_t num_sent_packets_;
DISALLOW_COPY_AND_ASSIGN(FileNetworkInterface);
@@ -136,7 +136,7 @@
engine_->set_voice_output_filename(voice_out);
engine_->set_video_input_filename(video_in);
engine_->set_video_output_filename(video_out);
- engine_->set_rtp_sender_thread(talk_base::Thread::Current());
+ engine_->set_rtp_sender_thread(rtc::Thread::Current());
voice_channel_.reset(engine_->CreateChannel());
video_channel_.reset(engine_->CreateVideoChannel(NULL));
@@ -145,12 +145,12 @@
}
bool GetTempFilename(std::string* filename) {
- talk_base::Pathname temp_path;
- if (!talk_base::Filesystem::GetTemporaryFolder(temp_path, true, NULL)) {
+ rtc::Pathname temp_path;
+ if (!rtc::Filesystem::GetTemporaryFolder(temp_path, true, NULL)) {
return false;
}
temp_path.SetPathname(
- talk_base::Filesystem::TempFilename(temp_path, "fme-test-"));
+ rtc::Filesystem::TempFilename(temp_path, "fme-test-"));
if (filename) {
*filename = temp_path.pathname();
@@ -159,8 +159,8 @@
}
bool WriteTestPacketsToFile(const std::string& filename, size_t ssrc_count) {
- talk_base::scoped_ptr<talk_base::StreamInterface> stream(
- talk_base::Filesystem::OpenFile(talk_base::Pathname(filename), "wb"));
+ rtc::scoped_ptr<rtc::StreamInterface> stream(
+ rtc::Filesystem::OpenFile(rtc::Pathname(filename), "wb"));
bool ret = (NULL != stream.get());
RtpDumpWriter writer(stream.get());
@@ -174,19 +174,19 @@
}
void DeleteTempFile(std::string filename) {
- talk_base::Pathname pathname(filename);
- if (talk_base::Filesystem::IsFile(talk_base::Pathname(pathname))) {
- talk_base::Filesystem::DeleteFile(pathname);
+ rtc::Pathname pathname(filename);
+ if (rtc::Filesystem::IsFile(rtc::Pathname(pathname))) {
+ rtc::Filesystem::DeleteFile(pathname);
}
}
- bool GetSsrcAndPacketCounts(talk_base::StreamInterface* stream,
+ bool GetSsrcAndPacketCounts(rtc::StreamInterface* stream,
size_t* ssrc_count, size_t* packet_count) {
- talk_base::scoped_ptr<RtpDumpReader> reader(new RtpDumpReader(stream));
+ rtc::scoped_ptr<RtpDumpReader> reader(new RtpDumpReader(stream));
size_t count = 0;
RtpDumpPacket packet;
std::set<uint32> ssrcs;
- while (talk_base::SR_SUCCESS == reader->ReadPacket(&packet)) {
+ while (rtc::SR_SUCCESS == reader->ReadPacket(&packet)) {
count++;
uint32 ssrc;
if (!packet.GetRtpSsrc(&ssrc)) {
@@ -209,22 +209,20 @@
std::string voice_output_filename_;
std::string video_input_filename_;
std::string video_output_filename_;
- talk_base::scoped_ptr<FileMediaEngine> engine_;
- talk_base::scoped_ptr<VoiceMediaChannel> voice_channel_;
- talk_base::scoped_ptr<VideoMediaChannel> video_channel_;
+ rtc::scoped_ptr<FileMediaEngine> engine_;
+ rtc::scoped_ptr<VoiceMediaChannel> voice_channel_;
+ rtc::scoped_ptr<VideoMediaChannel> video_channel_;
};
TEST_F(FileMediaEngineTest, TestDefaultImplementation) {
EXPECT_TRUE(CreateEngineAndChannels("", "", "", "", 1));
- EXPECT_TRUE(engine_->Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_->Init(rtc::Thread::Current()));
EXPECT_EQ(0, engine_->GetCapabilities());
EXPECT_TRUE(NULL == voice_channel_.get());
EXPECT_TRUE(NULL == video_channel_.get());
EXPECT_TRUE(NULL == engine_->CreateSoundclip());
cricket::AudioOptions audio_options;
EXPECT_TRUE(engine_->SetAudioOptions(audio_options));
- cricket::VideoOptions video_options;
- EXPECT_TRUE(engine_->SetVideoOptions(video_options));
VideoEncoderConfig video_encoder_config;
EXPECT_TRUE(engine_->SetDefaultVideoEncoderConfig(video_encoder_config));
EXPECT_TRUE(engine_->SetSoundDevices(NULL, NULL));
@@ -232,7 +230,6 @@
EXPECT_TRUE(engine_->SetOutputVolume(0));
EXPECT_EQ(0, engine_->GetInputLevel());
EXPECT_TRUE(engine_->SetLocalMonitor(true));
- EXPECT_TRUE(engine_->SetLocalRenderer(NULL));
EXPECT_TRUE(engine_->SetVideoCapture(true));
EXPECT_EQ(0U, engine_->audio_codecs().size());
EXPECT_EQ(0U, engine_->video_codecs().size());
@@ -313,12 +310,12 @@
EXPECT_TRUE(CreateEngineAndChannels(voice_input_filename_,
voice_output_filename_, "", "", 1));
EXPECT_TRUE(NULL != voice_channel_.get());
- talk_base::MemoryStream net_dump;
+ rtc::MemoryStream net_dump;
FileNetworkInterface net_interface(&net_dump, voice_channel_.get());
voice_channel_->SetInterface(&net_interface);
// The channel is not sending yet.
- talk_base::Thread::Current()->ProcessMessages(kWaitTimeMs);
+ rtc::Thread::Current()->ProcessMessages(kWaitTimeMs);
EXPECT_EQ(0U, net_interface.num_sent_packets());
// The channel starts sending.
@@ -328,9 +325,9 @@
// The channel stops sending.
voice_channel_->SetSend(SEND_NOTHING);
// Wait until packets are all delivered.
- talk_base::Thread::Current()->ProcessMessages(kWaitTimeMs);
+ rtc::Thread::Current()->ProcessMessages(kWaitTimeMs);
size_t old_number = net_interface.num_sent_packets();
- talk_base::Thread::Current()->ProcessMessages(kWaitTimeMs);
+ rtc::Thread::Current()->ProcessMessages(kWaitTimeMs);
EXPECT_EQ(old_number, net_interface.num_sent_packets());
// The channel starts sending again.
@@ -342,7 +339,7 @@
// fault. We hence stop sending and wait until all packets are delivered
// before we exit this function.
voice_channel_->SetSend(SEND_NOTHING);
- talk_base::Thread::Current()->ProcessMessages(kWaitTimeMs);
+ rtc::Thread::Current()->ProcessMessages(kWaitTimeMs);
}
// Test the sender thread of the channel. The sender sends RTP packets
@@ -351,7 +348,7 @@
EXPECT_TRUE(CreateEngineAndChannels(voice_input_filename_,
voice_output_filename_, "", "", 1));
EXPECT_TRUE(NULL != voice_channel_.get());
- talk_base::MemoryStream net_dump;
+ rtc::MemoryStream net_dump;
FileNetworkInterface net_interface(&net_dump, voice_channel_.get());
voice_channel_->SetInterface(&net_interface);
@@ -363,7 +360,7 @@
kWaitTimeout);
voice_channel_->SetSend(SEND_NOTHING);
// Wait until packets are all delivered.
- talk_base::Thread::Current()->ProcessMessages(kWaitTimeMs);
+ rtc::Thread::Current()->ProcessMessages(kWaitTimeMs);
EXPECT_TRUE(RtpTestUtility::VerifyTestPacketsFromStream(
2 * RtpTestUtility::GetTestPacketCount(), &net_dump,
RtpTestUtility::kDefaultSsrc));
@@ -372,9 +369,9 @@
// via OnPacketReceived, which in turn writes the packets into voice_output_.
// We next verify the packets in voice_output_.
voice_channel_.reset(); // Force to close the files.
- talk_base::scoped_ptr<talk_base::StreamInterface> voice_output_;
- voice_output_.reset(talk_base::Filesystem::OpenFile(
- talk_base::Pathname(voice_output_filename_), "rb"));
+ rtc::scoped_ptr<rtc::StreamInterface> voice_output_;
+ voice_output_.reset(rtc::Filesystem::OpenFile(
+ rtc::Pathname(voice_output_filename_), "rb"));
EXPECT_TRUE(voice_output_.get() != NULL);
EXPECT_TRUE(RtpTestUtility::VerifyTestPacketsFromStream(
2 * RtpTestUtility::GetTestPacketCount(), voice_output_.get(),
@@ -389,7 +386,7 @@
const uint32 send_ssrc = RtpTestUtility::kDefaultSsrc + 1;
voice_channel_->AddSendStream(StreamParams::CreateLegacy(send_ssrc));
- talk_base::MemoryStream net_dump;
+ rtc::MemoryStream net_dump;
FileNetworkInterface net_interface(&net_dump, voice_channel_.get());
voice_channel_->SetInterface(&net_interface);
@@ -401,7 +398,7 @@
kWaitTimeout);
voice_channel_->SetSend(SEND_NOTHING);
// Wait until packets are all delivered.
- talk_base::Thread::Current()->ProcessMessages(kWaitTimeMs);
+ rtc::Thread::Current()->ProcessMessages(kWaitTimeMs);
EXPECT_TRUE(RtpTestUtility::VerifyTestPacketsFromStream(
2 * RtpTestUtility::GetTestPacketCount(), &net_dump, send_ssrc));
@@ -409,9 +406,9 @@
// via OnPacketReceived, which in turn writes the packets into voice_output_.
// We next verify the packets in voice_output_.
voice_channel_.reset(); // Force to close the files.
- talk_base::scoped_ptr<talk_base::StreamInterface> voice_output_;
- voice_output_.reset(talk_base::Filesystem::OpenFile(
- talk_base::Pathname(voice_output_filename_), "rb"));
+ rtc::scoped_ptr<rtc::StreamInterface> voice_output_;
+ voice_output_.reset(rtc::Filesystem::OpenFile(
+ rtc::Pathname(voice_output_filename_), "rb"));
EXPECT_TRUE(voice_output_.get() != NULL);
EXPECT_TRUE(RtpTestUtility::VerifyTestPacketsFromStream(
2 * RtpTestUtility::GetTestPacketCount(), voice_output_.get(),
@@ -425,9 +422,9 @@
// Verify that voice_input_filename_ contains 2 *
// RtpTestUtility::GetTestPacketCount() packets
// with different SSRCs.
- talk_base::scoped_ptr<talk_base::StreamInterface> input_stream(
- talk_base::Filesystem::OpenFile(
- talk_base::Pathname(voice_input_filename_), "rb"));
+ rtc::scoped_ptr<rtc::StreamInterface> input_stream(
+ rtc::Filesystem::OpenFile(
+ rtc::Pathname(voice_input_filename_), "rb"));
ASSERT_TRUE(NULL != input_stream.get());
size_t ssrc_count;
size_t packet_count;
@@ -441,7 +438,7 @@
// these packets have the same SSRCs (that is, the packets with different
// SSRCs are skipped by the filemediaengine).
EXPECT_TRUE(NULL != voice_channel_.get());
- talk_base::MemoryStream net_dump;
+ rtc::MemoryStream net_dump;
FileNetworkInterface net_interface(&net_dump, voice_channel_.get());
voice_channel_->SetInterface(&net_interface);
voice_channel_->SetSend(SEND_MICROPHONE);
@@ -451,7 +448,7 @@
kWaitTimeout);
voice_channel_->SetSend(SEND_NOTHING);
// Wait until packets are all delivered.
- talk_base::Thread::Current()->ProcessMessages(kWaitTimeMs);
+ rtc::Thread::Current()->ProcessMessages(kWaitTimeMs);
net_dump.Rewind();
EXPECT_TRUE(GetSsrcAndPacketCounts(&net_dump, &ssrc_count, &packet_count));
EXPECT_EQ(1U, ssrc_count);
diff --git a/media/base/hybriddataengine.h b/media/base/hybriddataengine.h
index bece492..3e7d84c 100644
--- a/media/base/hybriddataengine.h
+++ b/media/base/hybriddataengine.h
@@ -31,10 +31,10 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediaengine.h"
+#include "webrtc/base/scoped_ptr.h"
namespace cricket {
@@ -66,8 +66,8 @@
virtual const std::vector<DataCodec>& data_codecs() { return codecs_; }
private:
- talk_base::scoped_ptr<DataEngineInterface> first_;
- talk_base::scoped_ptr<DataEngineInterface> second_;
+ rtc::scoped_ptr<DataEngineInterface> first_;
+ rtc::scoped_ptr<DataEngineInterface> second_;
std::vector<DataCodec> codecs_;
};
diff --git a/media/base/hybridvideoengine.cc b/media/base/hybridvideoengine.cc
deleted file mode 100644
index 8e992f0..0000000
--- a/media/base/hybridvideoengine.cc
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/media/base/hybridvideoengine.h"
-
-#include "talk/base/logging.h"
-
-namespace cricket {
-
-HybridVideoMediaChannel::HybridVideoMediaChannel(
- HybridVideoEngineInterface* engine,
- VideoMediaChannel* channel1,
- VideoMediaChannel* channel2)
- : engine_(engine),
- channel1_(channel1),
- channel2_(channel2),
- active_channel_(NULL),
- sending_(false) {
-}
-
-HybridVideoMediaChannel::~HybridVideoMediaChannel() {
-}
-
-void HybridVideoMediaChannel::SetInterface(NetworkInterface* iface) {
- if (channel1_) {
- channel1_->SetInterface(iface);
- }
- if (channel2_) {
- channel2_->SetInterface(iface);
- }
-}
-
-bool HybridVideoMediaChannel::SetOptions(const VideoOptions &options) {
- bool ret = true;
- if (channel1_) {
- ret = channel1_->SetOptions(options);
- }
- if (channel2_ && ret) {
- ret = channel2_->SetOptions(options);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::GetOptions(VideoOptions *options) const {
- if (active_channel_) {
- return active_channel_->GetOptions(options);
- }
- if (channel1_) {
- return channel1_->GetOptions(options);
- }
- if (channel2_) {
- return channel2_->GetOptions(options);
- }
- return false;
-}
-
-bool HybridVideoMediaChannel::SetRecvCodecs(
- const std::vector<VideoCodec>& codecs) {
- // Only give each channel the codecs it knows about.
- bool ret = true;
- std::vector<VideoCodec> codecs1, codecs2;
- SplitCodecs(codecs, &codecs1, &codecs2);
- if (channel1_) {
- ret = channel1_->SetRecvCodecs(codecs1);
- }
- if (channel2_ && ret) {
- ret = channel2_->SetRecvCodecs(codecs2);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::SetRecvRtpHeaderExtensions(
- const std::vector<RtpHeaderExtension>& extensions) {
- bool ret = true;
- if (channel1_) {
- ret = channel1_->SetRecvRtpHeaderExtensions(extensions);
- }
- if (channel2_ && ret) {
- ret = channel2_->SetRecvRtpHeaderExtensions(extensions);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::SetRenderer(uint32 ssrc,
- VideoRenderer* renderer) {
- bool ret = true;
- if (channel1_) {
- ret = channel1_->SetRenderer(ssrc, renderer);
- }
- if (channel2_ && ret) {
- ret = channel2_->SetRenderer(ssrc, renderer);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::SetRender(bool render) {
- bool ret = true;
- if (channel1_) {
- ret = channel1_->SetRender(render);
- }
- if (channel2_ && ret) {
- ret = channel2_->SetRender(render);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
- bool ret = true;
- if (channel1_) {
- ret = channel1_->MuteStream(ssrc, muted);
- }
- if (channel2_ && ret) {
- ret = channel2_->MuteStream(ssrc, muted);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::SetSendCodecs(
- const std::vector<VideoCodec>& codecs) {
- // Use the input to this function to decide what impl we're going to use.
- if (!active_channel_ && !SelectActiveChannel(codecs)) {
- LOG(LS_WARNING) << "Failed to select active channel";
- return false;
- }
- // Only give the active channel the codecs it knows about.
- std::vector<VideoCodec> codecs1, codecs2;
- SplitCodecs(codecs, &codecs1, &codecs2);
- const std::vector<VideoCodec>& codecs_to_set =
- (active_channel_ == channel1_.get()) ? codecs1 : codecs2;
- bool return_value = active_channel_->SetSendCodecs(codecs_to_set);
- if (!return_value) {
- return false;
- }
- VideoCodec send_codec;
- return_value = active_channel_->GetSendCodec(&send_codec);
- if (!return_value) {
- return false;
- }
- engine_->OnNewSendResolution(send_codec.width, send_codec.height);
- active_channel_->UpdateAspectRatio(send_codec.width, send_codec.height);
- return true;
-}
-
-bool HybridVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
- if (!active_channel_) {
- return false;
- }
- return active_channel_->GetSendCodec(send_codec);
-}
-
-bool HybridVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
- const VideoFormat& format) {
- return active_channel_ && active_channel_->SetSendStreamFormat(ssrc, format);
-}
-
-bool HybridVideoMediaChannel::SetSendRtpHeaderExtensions(
- const std::vector<RtpHeaderExtension>& extensions) {
- return active_channel_ &&
- active_channel_->SetSendRtpHeaderExtensions(extensions);
-}
-
-bool HybridVideoMediaChannel::SetStartSendBandwidth(int bps) {
- return active_channel_ && active_channel_->SetStartSendBandwidth(bps);
-}
-
-bool HybridVideoMediaChannel::SetMaxSendBandwidth(int bps) {
- return active_channel_ && active_channel_->SetMaxSendBandwidth(bps);
-}
-
-bool HybridVideoMediaChannel::SetSend(bool send) {
- if (send == sending()) {
- return true; // no action required if already set.
- }
-
- bool ret = active_channel_ &&
- active_channel_->SetSend(send);
-
- // Returns error and don't connect the signal if starting up.
- // Disconnects the signal anyway if shutting down.
- if (ret || !send) {
- // TODO(juberti): Remove this hack that connects the WebRTC channel
- // to the capturer.
- if (active_channel_ == channel1_.get()) {
- engine_->OnSendChange1(channel1_.get(), send);
- } else {
- engine_->OnSendChange2(channel2_.get(), send);
- }
- // If succeeded, remember the state as is.
- // If failed to open, sending_ should be false.
- // If failed to stop, sending_ should also be false, as we disconnect the
- // capture anyway.
- // The failure on SetSend(false) is a known issue in webrtc.
- sending_ = send;
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::SetCapturer(uint32 ssrc,
- VideoCapturer* capturer) {
- bool ret = true;
- if (channel1_.get()) {
- ret = channel1_->SetCapturer(ssrc, capturer);
- }
- if (channel2_.get() && ret) {
- ret = channel2_->SetCapturer(ssrc, capturer);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::AddSendStream(const StreamParams& sp) {
- bool ret = true;
- if (channel1_) {
- ret = channel1_->AddSendStream(sp);
- }
- if (channel2_ && ret) {
- ret = channel2_->AddSendStream(sp);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::RemoveSendStream(uint32 ssrc) {
- bool ret = true;
- if (channel1_) {
- ret = channel1_->RemoveSendStream(ssrc);
- }
- if (channel2_ && ret) {
- ret = channel2_->RemoveSendStream(ssrc);
- }
- return ret;
-}
-
-bool HybridVideoMediaChannel::AddRecvStream(const StreamParams& sp) {
- return active_channel_ &&
- active_channel_->AddRecvStream(sp);
-}
-
-bool HybridVideoMediaChannel::RemoveRecvStream(uint32 ssrc) {
- return active_channel_ &&
- active_channel_->RemoveRecvStream(ssrc);
-}
-
-bool HybridVideoMediaChannel::SendIntraFrame() {
- return active_channel_ &&
- active_channel_->SendIntraFrame();
-}
-
-bool HybridVideoMediaChannel::RequestIntraFrame() {
- return active_channel_ &&
- active_channel_->RequestIntraFrame();
-}
-
-bool HybridVideoMediaChannel::GetStats(
- const StatsOptions& options, VideoMediaInfo* info) {
- // TODO(juberti): Ensure that returning no stats until SetSendCodecs is OK.
- return active_channel_ &&
- active_channel_->GetStats(options, info);
-}
-
-void HybridVideoMediaChannel::OnPacketReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
- // Eat packets until we have an active channel;
- if (active_channel_) {
- active_channel_->OnPacketReceived(packet, packet_time);
- } else {
- LOG(LS_INFO) << "HybridVideoChannel: Eating early RTP packet";
- }
-}
-
-void HybridVideoMediaChannel::OnRtcpReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
- // Eat packets until we have an active channel;
- if (active_channel_) {
- active_channel_->OnRtcpReceived(packet, packet_time);
- } else {
- LOG(LS_INFO) << "HybridVideoChannel: Eating early RTCP packet";
- }
-}
-
-void HybridVideoMediaChannel::OnReadyToSend(bool ready) {
- if (channel1_) {
- channel1_->OnReadyToSend(ready);
- }
- if (channel2_) {
- channel2_->OnReadyToSend(ready);
- }
-}
-
-void HybridVideoMediaChannel::UpdateAspectRatio(int ratio_w, int ratio_h) {
- if (active_channel_) active_channel_->UpdateAspectRatio(ratio_w, ratio_h);
-}
-
-bool HybridVideoMediaChannel::SelectActiveChannel(
- const std::vector<VideoCodec>& codecs) {
- if (!active_channel_ && !codecs.empty()) {
- if (engine_->HasCodec1(codecs[0])) {
- channel2_.reset();
- active_channel_ = channel1_.get();
- } else if (engine_->HasCodec2(codecs[0])) {
- channel1_.reset();
- active_channel_ = channel2_.get();
- }
- }
- if (NULL == active_channel_) {
- return false;
- }
- // Connect signals from the active channel.
- active_channel_->SignalMediaError.connect(
- this,
- &HybridVideoMediaChannel::OnMediaError);
- return true;
-}
-
-void HybridVideoMediaChannel::SplitCodecs(
- const std::vector<VideoCodec>& codecs,
- std::vector<VideoCodec>* codecs1, std::vector<VideoCodec>* codecs2) {
- codecs1->clear();
- codecs2->clear();
- for (size_t i = 0; i < codecs.size(); ++i) {
- if (engine_->HasCodec1(codecs[i])) {
- codecs1->push_back(codecs[i]);
- }
- if (engine_->HasCodec2(codecs[i])) {
- codecs2->push_back(codecs[i]);
- }
- }
-}
-
-void HybridVideoMediaChannel::OnMediaError(uint32 ssrc, Error error) {
- SignalMediaError(ssrc, error);
-}
-
-} // namespace cricket
diff --git a/media/base/hybridvideoengine.h b/media/base/hybridvideoengine.h
deleted file mode 100644
index 8cfb884..0000000
--- a/media/base/hybridvideoengine.h
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_MEDIA_BASE_HYBRIDVIDEOENGINE_H_
-#define TALK_MEDIA_BASE_HYBRIDVIDEOENGINE_H_
-
-#include <string>
-#include <vector>
-
-#include "talk/base/logging.h"
-#include "talk/base/sigslotrepeater.h"
-#include "talk/media/base/codec.h"
-#include "talk/media/base/mediachannel.h"
-#include "talk/media/base/videocapturer.h"
-#include "talk/media/base/videocommon.h"
-
-namespace cricket {
-
-struct Device;
-struct VideoFormat;
-class HybridVideoEngineInterface;
-class VideoCapturer;
-class VideoFrame;
-class VideoRenderer;
-
-// HybridVideoMediaChannels work with a HybridVideoEngine to combine
-// two unrelated VideoMediaChannel implementations into a single class.
-class HybridVideoMediaChannel : public VideoMediaChannel {
- public:
- HybridVideoMediaChannel(HybridVideoEngineInterface* engine,
- VideoMediaChannel* channel1,
- VideoMediaChannel* channel2);
- virtual ~HybridVideoMediaChannel();
-
- // VideoMediaChannel methods
- virtual void SetInterface(NetworkInterface* iface);
- virtual bool SetOptions(const VideoOptions& options);
- virtual bool GetOptions(VideoOptions* options) const;
- virtual bool AddSendStream(const StreamParams& sp);
- virtual bool RemoveSendStream(uint32 ssrc);
- virtual bool SetRenderer(uint32 ssrc, VideoRenderer* renderer);
- virtual bool SetRender(bool render);
- virtual bool MuteStream(uint32 ssrc, bool muted);
-
- virtual bool SetRecvCodecs(const std::vector<VideoCodec>& codecs);
- virtual bool SetRecvRtpHeaderExtensions(
- const std::vector<RtpHeaderExtension>& extensions);
-
- virtual bool SetSendCodecs(const std::vector<VideoCodec>& codecs);
- virtual bool GetSendCodec(VideoCodec* codec);
- virtual bool SetSendStreamFormat(uint32 ssrc, const VideoFormat& format);
- virtual bool SetSendRtpHeaderExtensions(
- const std::vector<RtpHeaderExtension>& extensions);
- virtual bool SetStartSendBandwidth(int bps);
- virtual bool SetMaxSendBandwidth(int bps);
- virtual bool SetSend(bool send);
-
- virtual bool AddRecvStream(const StreamParams& sp);
- virtual bool RemoveRecvStream(uint32 ssrc);
- virtual bool SetCapturer(uint32 ssrc, VideoCapturer* capturer);
-
- virtual bool SendIntraFrame();
- virtual bool RequestIntraFrame();
-
- virtual bool GetStats(const StatsOptions& options, VideoMediaInfo* info);
-
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
- virtual void OnReadyToSend(bool ready);
-
- virtual void UpdateAspectRatio(int ratio_w, int ratio_h);
-
- void OnLocalFrame(VideoCapturer*, const VideoFrame*);
- void OnLocalFrameFormat(VideoCapturer*, const VideoFormat*);
-
- bool sending() const { return sending_; }
-
- private:
- bool SelectActiveChannel(const std::vector<VideoCodec>& codecs);
- void SplitCodecs(const std::vector<VideoCodec>& codecs,
- std::vector<VideoCodec>* codecs1,
- std::vector<VideoCodec>* codecs2);
-
- void OnMediaError(uint32 ssrc, Error error);
-
- HybridVideoEngineInterface* engine_;
- talk_base::scoped_ptr<VideoMediaChannel> channel1_;
- talk_base::scoped_ptr<VideoMediaChannel> channel2_;
- VideoMediaChannel* active_channel_;
- bool sending_;
-};
-
-// Interface class for HybridVideoChannels to talk to the engine.
-class HybridVideoEngineInterface {
- public:
- virtual ~HybridVideoEngineInterface() {}
- virtual bool HasCodec1(const VideoCodec& codec) = 0;
- virtual bool HasCodec2(const VideoCodec& codec) = 0;
- virtual void OnSendChange1(VideoMediaChannel* channel1, bool send) = 0;
- virtual void OnSendChange2(VideoMediaChannel* channel1, bool send) = 0;
- virtual void OnNewSendResolution(int width, int height) = 0;
-};
-
-// The HybridVideoEngine class combines two unrelated VideoEngine impls
-// into a single class. It creates HybridVideoMediaChannels that also contain
-// a VideoMediaChannel implementation from each engine. Policy is then used
-// during call setup to determine which VideoMediaChannel should be used.
-// Currently, this policy is based on what codec the remote side wants to use.
-template<class VIDEO1, class VIDEO2>
-class HybridVideoEngine : public HybridVideoEngineInterface {
- public:
- HybridVideoEngine() {
- // Unify the codec lists.
- codecs_ = video1_.codecs();
- codecs_.insert(codecs_.end(), video2_.codecs().begin(),
- video2_.codecs().end());
-
- rtp_header_extensions_ = video1_.rtp_header_extensions();
- rtp_header_extensions_.insert(rtp_header_extensions_.end(),
- video2_.rtp_header_extensions().begin(),
- video2_.rtp_header_extensions().end());
-
- SignalCaptureStateChange.repeat(video2_.SignalCaptureStateChange);
- }
-
- bool Init(talk_base::Thread* worker_thread) {
- if (!video1_.Init(worker_thread)) {
- LOG(LS_ERROR) << "Failed to init VideoEngine1";
- return false;
- }
- if (!video2_.Init(worker_thread)) {
- LOG(LS_ERROR) << "Failed to init VideoEngine2";
- video1_.Terminate();
- return false;
- }
- return true;
- }
- void Terminate() {
- video1_.Terminate();
- video2_.Terminate();
- }
-
- int GetCapabilities() {
- return (video1_.GetCapabilities() | video2_.GetCapabilities());
- }
- HybridVideoMediaChannel* CreateChannel(VoiceMediaChannel* channel) {
- talk_base::scoped_ptr<VideoMediaChannel> channel1(
- video1_.CreateChannel(channel));
- if (!channel1) {
- LOG(LS_ERROR) << "Failed to create VideoMediaChannel1";
- return NULL;
- }
- talk_base::scoped_ptr<VideoMediaChannel> channel2(
- video2_.CreateChannel(channel));
- if (!channel2) {
- LOG(LS_ERROR) << "Failed to create VideoMediaChannel2";
- return NULL;
- }
- return new HybridVideoMediaChannel(this,
- channel1.release(), channel2.release());
- }
-
- bool SetOptions(const VideoOptions& options) {
- return video1_.SetOptions(options) && video2_.SetOptions(options);
- }
- bool SetDefaultEncoderConfig(const VideoEncoderConfig& config) {
- VideoEncoderConfig conf = config;
- if (video1_.codecs().size() > 0) {
- conf.max_codec.name = video1_.codecs()[0].name;
- if (!video1_.SetDefaultEncoderConfig(conf)) {
- LOG(LS_ERROR) << "Failed to SetDefaultEncoderConfig for video1";
- return false;
- }
- }
- if (video2_.codecs().size() > 0) {
- conf.max_codec.name = video2_.codecs()[0].name;
- if (!video2_.SetDefaultEncoderConfig(conf)) {
- LOG(LS_ERROR) << "Failed to SetDefaultEncoderConfig for video2";
- return false;
- }
- }
- return true;
- }
- VideoEncoderConfig GetDefaultEncoderConfig() const {
- // This looks pretty strange, but, in practice, it'll do sane things if
- // GetDefaultEncoderConfig is only called after SetDefaultEncoderConfig,
- // since both engines should be essentially equivalent at that point. If it
- // hasn't been called, though, we'll use the first meaningful encoder
- // config, or the config from the second video engine if neither are
- // meaningful.
- VideoEncoderConfig config = video1_.GetDefaultEncoderConfig();
- if (config.max_codec.width != 0) {
- return config;
- } else {
- return video2_.GetDefaultEncoderConfig();
- }
- }
- const std::vector<VideoCodec>& codecs() const {
- return codecs_;
- }
- const std::vector<RtpHeaderExtension>& rtp_header_extensions() const {
- return rtp_header_extensions_;
- }
- void SetLogging(int min_sev, const char* filter) {
- video1_.SetLogging(min_sev, filter);
- video2_.SetLogging(min_sev, filter);
- }
-
- VideoFormat GetStartCaptureFormat() const {
- return video2_.GetStartCaptureFormat();
- }
-
- // TODO(juberti): Remove these functions after we do the capturer refactoring.
- // For now they are set to always use the second engine for capturing, which
- // is convenient given our intended use case.
- bool SetCaptureDevice(const Device* device) {
- return video2_.SetCaptureDevice(device);
- }
- VideoCapturer* GetVideoCapturer() const {
- return video2_.GetVideoCapturer();
- }
- bool SetLocalRenderer(VideoRenderer* renderer) {
- return video2_.SetLocalRenderer(renderer);
- }
- sigslot::repeater2<VideoCapturer*, CaptureState> SignalCaptureStateChange;
-
- virtual bool HasCodec1(const VideoCodec& codec) {
- return HasCodec(video1_, codec);
- }
- virtual bool HasCodec2(const VideoCodec& codec) {
- return HasCodec(video2_, codec);
- }
- template<typename VIDEO>
- bool HasCodec(const VIDEO& engine, const VideoCodec& codec) const {
- for (std::vector<VideoCodec>::const_iterator i = engine.codecs().begin();
- i != engine.codecs().end();
- ++i) {
- if (i->Matches(codec)) {
- return true;
- }
- }
- return false;
- }
- virtual void OnSendChange1(VideoMediaChannel* channel1, bool send) {
- }
- virtual void OnSendChange2(VideoMediaChannel* channel2, bool send) {
- }
- virtual void OnNewSendResolution(int width, int height) {
- }
-
- protected:
- VIDEO1 video1_;
- VIDEO2 video2_;
- std::vector<VideoCodec> codecs_;
- std::vector<RtpHeaderExtension> rtp_header_extensions_;
-};
-
-} // namespace cricket
-
-#endif // TALK_MEDIA_BASE_HYBRIDVIDEOENGINE_H_
diff --git a/media/base/hybridvideoengine_unittest.cc b/media/base/hybridvideoengine_unittest.cc
deleted file mode 100644
index aa9d4ac..0000000
--- a/media/base/hybridvideoengine_unittest.cc
+++ /dev/null
@@ -1,486 +0,0 @@
-/*
- * libjingle
- * Copyright 2004 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/media/base/fakemediaengine.h"
-#include "talk/media/base/fakenetworkinterface.h"
-#include "talk/media/base/fakevideocapturer.h"
-#include "talk/media/base/hybridvideoengine.h"
-#include "talk/media/base/mediachannel.h"
-#include "talk/media/base/testutils.h"
-
-static const cricket::VideoCodec kGenericCodec(97, "Generic", 640, 360, 30, 0);
-static const cricket::VideoCodec kVp8Codec(100, "VP8", 640, 360, 30, 0);
-static const cricket::VideoCodec kCodecsVp8Only[] = { kVp8Codec };
-static const cricket::VideoCodec kCodecsGenericOnly[] = { kGenericCodec };
-static const cricket::VideoCodec kCodecsVp8First[] = { kVp8Codec,
- kGenericCodec };
-static const cricket::VideoCodec kCodecsGenericFirst[] = { kGenericCodec,
- kVp8Codec };
-
-using cricket::StreamParams;
-
-class FakeVp8VideoEngine : public cricket::FakeVideoEngine {
- public:
- FakeVp8VideoEngine() {
- SetCodecs(MAKE_VECTOR(kCodecsVp8Only));
- }
-};
-class FakeGenericVideoEngine : public cricket::FakeVideoEngine {
- public:
- FakeGenericVideoEngine() {
- SetCodecs(MAKE_VECTOR(kCodecsGenericOnly));
- }
-
- // For testing purposes, mimic the behavior of a media engine that throws out
- // resolutions that don't match the codec list. A width or height of 0
- // trivially will never match the codec list, so this is sufficient for
- // testing the case we want (0x0).
- virtual bool FindCodec(const cricket::VideoCodec& codec) {
- if (codec.width == 0 || codec.height == 0) {
- return false;
- } else {
- return cricket::FakeVideoEngine::FindCodec(codec);
- }
- }
-};
-class HybridVideoEngineForTest : public cricket::HybridVideoEngine<
- FakeVp8VideoEngine, FakeGenericVideoEngine> {
- public:
- HybridVideoEngineForTest()
- :
- num_ch1_send_on_(0),
- num_ch1_send_off_(0),
- send_width_(0),
- send_height_(0) { }
- cricket::FakeVideoEngine* sub_engine1() { return &video1_; }
- cricket::FakeVideoEngine* sub_engine2() { return &video2_; }
-
- // From base class HybridVideoEngine.
- void OnSendChange1(cricket::VideoMediaChannel* channel1, bool send) {
- if (send) {
- ++num_ch1_send_on_;
- } else {
- ++num_ch1_send_off_;
- }
- }
- // From base class HybridVideoEngine
- void OnNewSendResolution(int width, int height) {
- send_width_ = width;
- send_height_ = height;
- }
-
- int num_ch1_send_on() const { return num_ch1_send_on_; }
- int num_ch1_send_off() const { return num_ch1_send_off_; }
-
- int send_width() const { return send_width_; }
- int send_height() const { return send_height_; }
-
- private:
- int num_ch1_send_on_;
- int num_ch1_send_off_;
-
- int send_width_;
- int send_height_;
-};
-
-class HybridVideoEngineTest : public testing::Test {
- public:
- HybridVideoEngineTest() : sub_channel1_(NULL), sub_channel2_(NULL) {
- }
- ~HybridVideoEngineTest() {
- engine_.Terminate();
- }
- bool SetupEngine() {
- bool result = engine_.Init(talk_base::Thread::Current());
- if (result) {
- channel_.reset(engine_.CreateChannel(NULL));
- result = (channel_.get() != NULL);
- sub_channel1_ = engine_.sub_engine1()->GetChannel(0);
- sub_channel2_ = engine_.sub_engine2()->GetChannel(0);
- }
- return result;
- }
- bool SetupRenderAndAddStream(const StreamParams& sp) {
- if (!SetupEngine())
- return false;
- channel_->SetInterface(transport_.get());
- return channel_->SetRecvCodecs(engine_.codecs()) &&
- channel_->AddSendStream(sp) &&
- channel_->SetRender(true);
- }
- void DeliverPacket(const void* data, int len) {
- talk_base::Buffer packet(data, len);
- channel_->OnPacketReceived(&packet, talk_base::CreatePacketTime(0));
- }
- void DeliverRtcp(const void* data, int len) {
- talk_base::Buffer packet(data, len);
- channel_->OnRtcpReceived(&packet, talk_base::CreatePacketTime(0));
- }
-
- protected:
- void TestSetSendCodecs(cricket::FakeVideoEngine* sub_engine,
- const std::vector<cricket::VideoCodec>& codecs) {
- EXPECT_TRUE(SetupRenderAndAddStream(StreamParams::CreateLegacy(1234)));
- EXPECT_TRUE(channel_->SetSendCodecs(codecs));
- cricket::FakeVideoMediaChannel* sub_channel = sub_engine->GetChannel(0);
- ASSERT_EQ(1U, sub_channel->send_codecs().size());
- EXPECT_EQ(codecs[0], sub_channel->send_codecs()[0]);
- EXPECT_TRUE(channel_->SetSend(true));
- EXPECT_TRUE(sub_channel->sending());
- }
- void TestSetSendBandwidth(cricket::FakeVideoEngine* sub_engine,
- const std::vector<cricket::VideoCodec>& codecs,
- int start_bitrate,
- int max_bitrate) {
- EXPECT_TRUE(SetupRenderAndAddStream(StreamParams::CreateLegacy(1234)));
- EXPECT_TRUE(channel_->SetSendCodecs(codecs));
- EXPECT_TRUE(channel_->SetStartSendBandwidth(start_bitrate));
- EXPECT_TRUE(channel_->SetMaxSendBandwidth(max_bitrate));
- cricket::FakeVideoMediaChannel* sub_channel = sub_engine->GetChannel(0);
- EXPECT_EQ(start_bitrate, sub_channel->start_bps());
- EXPECT_EQ(max_bitrate, sub_channel->max_bps());
- }
- HybridVideoEngineForTest engine_;
- talk_base::scoped_ptr<cricket::HybridVideoMediaChannel> channel_;
- talk_base::scoped_ptr<cricket::FakeNetworkInterface> transport_;
- cricket::FakeVideoMediaChannel* sub_channel1_;
- cricket::FakeVideoMediaChannel* sub_channel2_;
-};
-
-TEST_F(HybridVideoEngineTest, StartupShutdown) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
- engine_.Terminate();
-}
-
-// Tests that SetDefaultVideoEncoderConfig passes down to both engines.
-TEST_F(HybridVideoEngineTest, SetDefaultVideoEncoderConfig) {
- cricket::VideoEncoderConfig config(
- cricket::VideoCodec(105, "", 640, 400, 30, 0), 1, 2);
- EXPECT_TRUE(engine_.SetDefaultEncoderConfig(config));
-
- cricket::VideoEncoderConfig config_1 = config;
- config_1.max_codec.name = kCodecsVp8Only[0].name;
- EXPECT_EQ(config_1, engine_.sub_engine1()->default_encoder_config());
-
- cricket::VideoEncoderConfig config_2 = config;
- config_2.max_codec.name = kCodecsGenericOnly[0].name;
- EXPECT_EQ(config_2, engine_.sub_engine2()->default_encoder_config());
-}
-
-// Tests that GetDefaultVideoEncoderConfig picks a meaningful encoder config
-// based on the underlying engine config and then after a call to
-// SetDefaultEncoderConfig on the hybrid engine.
-TEST_F(HybridVideoEngineTest, SetDefaultVideoEncoderConfigDefaultValue) {
- cricket::VideoEncoderConfig blank_config;
- cricket::VideoEncoderConfig meaningful_config1(
- cricket::VideoCodec(111, "abcd", 320, 240, 30, 0), 1, 2);
- cricket::VideoEncoderConfig meaningful_config2(
- cricket::VideoCodec(111, "abcd", 1280, 720, 30, 0), 1, 2);
- cricket::VideoEncoderConfig meaningful_config3(
- cricket::VideoCodec(111, "abcd", 640, 360, 30, 0), 1, 2);
- engine_.sub_engine1()->SetDefaultEncoderConfig(blank_config);
- engine_.sub_engine2()->SetDefaultEncoderConfig(blank_config);
- EXPECT_EQ(blank_config, engine_.GetDefaultEncoderConfig());
-
- engine_.sub_engine2()->SetDefaultEncoderConfig(meaningful_config2);
- EXPECT_EQ(meaningful_config2, engine_.GetDefaultEncoderConfig());
-
- engine_.sub_engine1()->SetDefaultEncoderConfig(meaningful_config1);
- EXPECT_EQ(meaningful_config1, engine_.GetDefaultEncoderConfig());
-
- EXPECT_TRUE(engine_.SetDefaultEncoderConfig(meaningful_config3));
- // The overall config should now match, though the codec name will have been
- // rewritten for the first media engine.
- meaningful_config3.max_codec.name = kCodecsVp8Only[0].name;
- EXPECT_EQ(meaningful_config3, engine_.GetDefaultEncoderConfig());
-}
-
-// Tests that our engine has the right codecs in the right order.
-TEST_F(HybridVideoEngineTest, CheckCodecs) {
- const std::vector<cricket::VideoCodec>& c = engine_.codecs();
- ASSERT_EQ(2U, c.size());
- EXPECT_EQ(kVp8Codec, c[0]);
- EXPECT_EQ(kGenericCodec, c[1]);
-}
-
-// Tests that our engine has the right caps.
-TEST_F(HybridVideoEngineTest, CheckCaps) {
- EXPECT_EQ(cricket::VIDEO_SEND | cricket::VIDEO_RECV,
- engine_.GetCapabilities());
-}
-
-// Tests that we can create and destroy a channel.
-TEST_F(HybridVideoEngineTest, CreateChannel) {
- EXPECT_TRUE(SetupEngine());
- EXPECT_TRUE(sub_channel1_ != NULL);
- EXPECT_TRUE(sub_channel2_ != NULL);
-}
-
-// Tests that we properly handle failures in CreateChannel.
-TEST_F(HybridVideoEngineTest, CreateChannelFail) {
- engine_.sub_engine1()->set_fail_create_channel(true);
- EXPECT_FALSE(SetupEngine());
- EXPECT_TRUE(channel_.get() == NULL);
- EXPECT_TRUE(sub_channel1_ == NULL);
- EXPECT_TRUE(sub_channel2_ == NULL);
- engine_.sub_engine1()->set_fail_create_channel(false);
- engine_.sub_engine2()->set_fail_create_channel(true);
- EXPECT_FALSE(SetupEngine());
- EXPECT_TRUE(channel_.get() == NULL);
- EXPECT_TRUE(sub_channel1_ == NULL);
- EXPECT_TRUE(sub_channel2_ == NULL);
-}
-
-// Test that we set our inbound codecs and settings properly.
-TEST_F(HybridVideoEngineTest, SetLocalDescription) {
- EXPECT_TRUE(SetupEngine());
- channel_->SetInterface(transport_.get());
- EXPECT_TRUE(channel_->SetRecvCodecs(engine_.codecs()));
- ASSERT_EQ(1U, sub_channel1_->recv_codecs().size());
- ASSERT_EQ(1U, sub_channel2_->recv_codecs().size());
- EXPECT_EQ(kVp8Codec, sub_channel1_->recv_codecs()[0]);
- EXPECT_EQ(kGenericCodec, sub_channel2_->recv_codecs()[0]);
- StreamParams stream;
- stream.id = "TestStream";
- stream.ssrcs.push_back(1234);
- stream.cname = "5678";
- EXPECT_TRUE(channel_->AddSendStream(stream));
- EXPECT_EQ(1234U, sub_channel1_->send_ssrc());
- EXPECT_EQ(1234U, sub_channel2_->send_ssrc());
- EXPECT_EQ("5678", sub_channel1_->rtcp_cname());
- EXPECT_EQ("5678", sub_channel2_->rtcp_cname());
- EXPECT_TRUE(channel_->SetRender(true));
- // We've called SetRender, so we should be playing out, but not yet sending.
- EXPECT_TRUE(sub_channel1_->playout());
- EXPECT_TRUE(sub_channel2_->playout());
- EXPECT_FALSE(sub_channel1_->sending());
- EXPECT_FALSE(sub_channel2_->sending());
- // We may get SetSend(false) calls during call setup.
- // Since this causes no change in state, they should no-op and return true.
- EXPECT_TRUE(channel_->SetSend(false));
- EXPECT_FALSE(sub_channel1_->sending());
- EXPECT_FALSE(sub_channel2_->sending());
-}
-
-TEST_F(HybridVideoEngineTest, OnNewSendResolution) {
- EXPECT_TRUE(SetupEngine());
- EXPECT_TRUE(channel_->SetSendCodecs(MAKE_VECTOR(kCodecsVp8First)));
- EXPECT_EQ(640, engine_.send_width());
- EXPECT_EQ(360, engine_.send_height());
-}
-
-// Test that we converge to the active channel for engine 1.
-TEST_F(HybridVideoEngineTest, SetSendCodecs1) {
- // This will nuke the object that sub_channel2_ points to.
- TestSetSendCodecs(engine_.sub_engine1(), MAKE_VECTOR(kCodecsVp8First));
- EXPECT_TRUE(engine_.sub_engine2()->GetChannel(0) == NULL);
-}
-
-// Test that we converge to the active channel for engine 2.
-TEST_F(HybridVideoEngineTest, SetSendCodecs2) {
- // This will nuke the object that sub_channel1_ points to.
- TestSetSendCodecs(engine_.sub_engine2(), MAKE_VECTOR(kCodecsGenericFirst));
- EXPECT_TRUE(engine_.sub_engine1()->GetChannel(0) == NULL);
-}
-
-// Test that we don't accidentally eat 0x0 in SetSendCodecs
-TEST_F(HybridVideoEngineTest, SetSendCodecs0x0) {
- EXPECT_TRUE(SetupRenderAndAddStream(StreamParams::CreateLegacy(1234)));
- // Send using generic codec, but with 0x0 resolution.
- std::vector<cricket::VideoCodec> codecs(MAKE_VECTOR(kCodecsGenericFirst));
- codecs.resize(1);
- codecs[0].width = 0;
- codecs[0].height = 0;
- EXPECT_TRUE(channel_->SetSendCodecs(codecs));
-}
-
-// Test setting the send bandwidth for VP8.
-TEST_F(HybridVideoEngineTest, SetSendBandwidth1) {
- TestSetSendBandwidth(engine_.sub_engine1(),
- MAKE_VECTOR(kCodecsVp8First),
- 100000,
- 384000);
-}
-
-// Test setting the send bandwidth for a generic codec.
-TEST_F(HybridVideoEngineTest, SetSendBandwidth2) {
- TestSetSendBandwidth(engine_.sub_engine2(),
- MAKE_VECTOR(kCodecsGenericFirst),
- 100001,
- 384002);
-}
-
-// Test that we dump RTP packets that arrive early.
-TEST_F(HybridVideoEngineTest, HandleEarlyRtp) {
- static const uint8 kPacket[1024] = { 0 };
- static const uint8 kRtcp[1024] = { 1 };
- EXPECT_TRUE(SetupRenderAndAddStream(StreamParams::CreateLegacy(1234)));
- DeliverPacket(kPacket, sizeof(kPacket));
- DeliverRtcp(kRtcp, sizeof(kRtcp));
- EXPECT_TRUE(sub_channel1_->CheckNoRtp());
- EXPECT_TRUE(sub_channel2_->CheckNoRtp());
- EXPECT_TRUE(sub_channel1_->CheckNoRtcp());
- EXPECT_TRUE(sub_channel2_->CheckNoRtcp());
-}
-
-// Test that we properly pass on normal RTP packets.
-TEST_F(HybridVideoEngineTest, HandleRtp) {
- static const uint8 kPacket[1024] = { 0 };
- static const uint8 kRtcp[1024] = { 1 };
- EXPECT_TRUE(SetupRenderAndAddStream(StreamParams::CreateLegacy(1234)));
- EXPECT_TRUE(channel_->SetSendCodecs(MAKE_VECTOR(kCodecsVp8First)));
- EXPECT_TRUE(channel_->SetSend(true));
- DeliverPacket(kPacket, sizeof(kPacket));
- DeliverRtcp(kRtcp, sizeof(kRtcp));
- EXPECT_TRUE(sub_channel1_->CheckRtp(kPacket, sizeof(kPacket)));
- EXPECT_TRUE(sub_channel1_->CheckRtcp(kRtcp, sizeof(kRtcp)));
-}
-
-// Test that we properly connect media error signal.
-TEST_F(HybridVideoEngineTest, MediaErrorSignal) {
- cricket::VideoMediaErrorCatcher catcher;
-
- // Verify no signal from either channel before the active channel is set.
- EXPECT_TRUE(SetupEngine());
- channel_->SignalMediaError.connect(&catcher,
- &cricket::VideoMediaErrorCatcher::OnError);
- sub_channel1_->SignalMediaError(1, cricket::VideoMediaChannel::ERROR_OTHER);
- EXPECT_EQ(0U, catcher.ssrc());
- sub_channel2_->SignalMediaError(2,
- cricket::VideoMediaChannel::ERROR_REC_DEVICE_OPEN_FAILED);
- EXPECT_EQ(0U, catcher.ssrc());
-
- // Set vp8 as active channel and verify that a signal comes from it.
- EXPECT_TRUE(channel_->SetSendCodecs(MAKE_VECTOR(kCodecsVp8First)));
- sub_channel1_->SignalMediaError(1, cricket::VideoMediaChannel::ERROR_OTHER);
- EXPECT_EQ(cricket::VideoMediaChannel::ERROR_OTHER, catcher.error());
- EXPECT_EQ(1U, catcher.ssrc());
-
- // Set generic codec as active channel and verify that a signal comes from it.
- EXPECT_TRUE(SetupEngine());
- channel_->SignalMediaError.connect(&catcher,
- &cricket::VideoMediaErrorCatcher::OnError);
- EXPECT_TRUE(channel_->SetSendCodecs(MAKE_VECTOR(kCodecsGenericFirst)));
- sub_channel2_->SignalMediaError(2,
- cricket::VideoMediaChannel::ERROR_REC_DEVICE_OPEN_FAILED);
- EXPECT_EQ(cricket::VideoMediaChannel::ERROR_REC_DEVICE_OPEN_FAILED,
- catcher.error());
- EXPECT_EQ(2U, catcher.ssrc());
-}
-
-// Test that SetSend doesn't re-enter.
-TEST_F(HybridVideoEngineTest, RepeatSetSend) {
- EXPECT_TRUE(SetupEngine());
- EXPECT_TRUE(channel_->SetSendCodecs(MAKE_VECTOR(kCodecsVp8First)));
-
- // Verify initial status.
- EXPECT_FALSE(channel_->sending());
- EXPECT_FALSE(sub_channel1_->sending());
- EXPECT_EQ(0, engine_.num_ch1_send_on());
- EXPECT_EQ(0, engine_.num_ch1_send_off());
-
- // Verfiy SetSend(true) works correctly.
- EXPECT_TRUE(channel_->SetSend(true));
- EXPECT_TRUE(channel_->sending());
- EXPECT_TRUE(sub_channel1_->sending());
- EXPECT_EQ(1, engine_.num_ch1_send_on());
- EXPECT_EQ(0, engine_.num_ch1_send_off());
-
- // SetSend(true) again and verify nothing changes.
- EXPECT_TRUE(channel_->SetSend(true));
- EXPECT_TRUE(channel_->sending());
- EXPECT_TRUE(sub_channel1_->sending());
- EXPECT_EQ(1, engine_.num_ch1_send_on());
- EXPECT_EQ(0, engine_.num_ch1_send_off());
-
- // Verify SetSend(false) works correctly.
- EXPECT_TRUE(channel_->SetSend(false));
- EXPECT_FALSE(channel_->sending());
- EXPECT_FALSE(sub_channel1_->sending());
- EXPECT_EQ(1, engine_.num_ch1_send_on());
- EXPECT_EQ(1, engine_.num_ch1_send_off());
-
- // SetSend(false) again and verfiy nothing changes.
- EXPECT_TRUE(channel_->SetSend(false));
- EXPECT_FALSE(channel_->sending());
- EXPECT_FALSE(sub_channel1_->sending());
- EXPECT_EQ(1, engine_.num_ch1_send_on());
- EXPECT_EQ(1, engine_.num_ch1_send_off());
-}
-
-// Test that SetOptions.
-TEST_F(HybridVideoEngineTest, SetOptions) {
- cricket::VideoOptions vmo;
- vmo.video_high_bitrate.Set(true);
- vmo.system_low_adaptation_threshhold.Set(0.10f);
- EXPECT_TRUE(SetupEngine());
- EXPECT_TRUE(channel_->SetOptions(vmo));
-
- bool high_bitrate;
- float low;
- EXPECT_TRUE(sub_channel1_->GetOptions(&vmo));
- EXPECT_TRUE(vmo.video_high_bitrate.Get(&high_bitrate));
- EXPECT_TRUE(high_bitrate);
- EXPECT_TRUE(vmo.system_low_adaptation_threshhold.Get(&low));
- EXPECT_EQ(0.10f, low);
- EXPECT_TRUE(sub_channel2_->GetOptions(&vmo));
- EXPECT_TRUE(vmo.video_high_bitrate.Get(&high_bitrate));
- EXPECT_TRUE(high_bitrate);
- EXPECT_TRUE(vmo.system_low_adaptation_threshhold.Get(&low));
- EXPECT_EQ(0.10f, low);
-
- vmo.video_high_bitrate.Set(false);
- vmo.system_low_adaptation_threshhold.Set(0.50f);
-
- EXPECT_TRUE(channel_->SetOptions(vmo));
- EXPECT_TRUE(sub_channel1_->GetOptions(&vmo));
- EXPECT_TRUE(vmo.video_high_bitrate.Get(&high_bitrate));
- EXPECT_FALSE(high_bitrate);
- EXPECT_TRUE(vmo.system_low_adaptation_threshhold.Get(&low));
- EXPECT_EQ(0.50f, low);
- EXPECT_TRUE(sub_channel2_->GetOptions(&vmo));
- EXPECT_TRUE(vmo.video_high_bitrate.Get(&high_bitrate));
- EXPECT_FALSE(high_bitrate);
- EXPECT_TRUE(vmo.system_low_adaptation_threshhold.Get(&low));
- EXPECT_EQ(0.50f, low);
-}
-
-TEST_F(HybridVideoEngineTest, SetCapturer) {
- EXPECT_TRUE(SetupEngine());
- // Set vp8 as active channel and verify that capturer can be set.
- EXPECT_TRUE(channel_->SetSendCodecs(MAKE_VECTOR(kCodecsVp8First)));
- cricket::FakeVideoCapturer fake_video_capturer;
- EXPECT_TRUE(channel_->SetCapturer(0, &fake_video_capturer));
- EXPECT_TRUE(channel_->SetCapturer(0, NULL));
-
- // Set generic codec active channel and verify that capturer can be set.
- EXPECT_TRUE(SetupEngine());
- EXPECT_TRUE(channel_->SetSendCodecs(MAKE_VECTOR(kCodecsGenericFirst)));
- EXPECT_TRUE(channel_->SetCapturer(0, &fake_video_capturer));
- EXPECT_TRUE(channel_->SetCapturer(0, NULL));
-}
diff --git a/media/base/mediachannel.h b/media/base/mediachannel.h
index 34d2def..5232e5d 100644
--- a/media/base/mediachannel.h
+++ b/media/base/mediachannel.h
@@ -31,20 +31,20 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/buffer.h"
-#include "talk/base/dscp.h"
-#include "talk/base/logging.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socket.h"
-#include "talk/base/window.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/streamparams.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/socket.h"
+#include "webrtc/base/window.h"
// TODO(juberti): re-evaluate this include
#include "talk/session/media/audiomonitor.h"
-namespace talk_base {
+namespace rtc {
class Buffer;
class RateLimiter;
class Timing;
@@ -104,7 +104,7 @@
}
std::string ToString() const {
- return set_ ? talk_base::ToString(val_) : "";
+ return set_ ? rtc::ToString(val_) : "";
}
bool operator==(const Settable<T>& o) const {
@@ -182,7 +182,7 @@
recording_sample_rate.SetFrom(change.recording_sample_rate);
playout_sample_rate.SetFrom(change.playout_sample_rate);
dscp.SetFrom(change.dscp);
- opus_fec.SetFrom(change.opus_fec);
+ combined_audio_video_bwe.SetFrom(change.combined_audio_video_bwe);
}
bool operator==(const AudioOptions& o) const {
@@ -209,7 +209,7 @@
recording_sample_rate == o.recording_sample_rate &&
playout_sample_rate == o.playout_sample_rate &&
dscp == o.dscp &&
- opus_fec == o.opus_fec;
+ combined_audio_video_bwe == o.combined_audio_video_bwe;
}
std::string ToString() const {
@@ -240,7 +240,7 @@
ost << ToStringIfSet("recording_sample_rate", recording_sample_rate);
ost << ToStringIfSet("playout_sample_rate", playout_sample_rate);
ost << ToStringIfSet("dscp", dscp);
- ost << ToStringIfSet("opus_fec", opus_fec);
+ ost << ToStringIfSet("combined_audio_video_bwe", combined_audio_video_bwe);
ost << "}";
return ost.str();
}
@@ -278,8 +278,8 @@
Settable<uint32> playout_sample_rate;
// Set DSCP value for packet sent from audio channel.
Settable<bool> dscp;
- // Set Opus FEC
- Settable<bool> opus_fec;
+ // Enable combined audio+bandwidth BWE.
+ Settable<bool> combined_audio_video_bwe;
};
// Options that can be applied to a VideoMediaChannel or a VideoMediaEngine.
@@ -312,8 +312,6 @@
video_start_bitrate.SetFrom(change.video_start_bitrate);
video_temporal_layer_screencast.SetFrom(
change.video_temporal_layer_screencast);
- video_temporal_layer_realtime.SetFrom(
- change.video_temporal_layer_realtime);
video_leaky_bucket.SetFrom(change.video_leaky_bucket);
video_highest_bitrate.SetFrom(change.video_highest_bitrate);
cpu_overuse_detection.SetFrom(change.cpu_overuse_detection);
@@ -331,15 +329,11 @@
system_high_adaptation_threshhold.SetFrom(
change.system_high_adaptation_threshhold);
buffered_mode_latency.SetFrom(change.buffered_mode_latency);
- lower_min_bitrate.SetFrom(change.lower_min_bitrate);
dscp.SetFrom(change.dscp);
suspend_below_min_bitrate.SetFrom(change.suspend_below_min_bitrate);
unsignalled_recv_stream_limit.SetFrom(change.unsignalled_recv_stream_limit);
use_simulcast_adapter.SetFrom(change.use_simulcast_adapter);
- skip_encoding_unused_streams.SetFrom(change.skip_encoding_unused_streams);
screencast_min_bitrate.SetFrom(change.screencast_min_bitrate);
- use_improved_wifi_bandwidth_estimator.SetFrom(
- change.use_improved_wifi_bandwidth_estimator);
use_payload_padding.SetFrom(change.use_payload_padding);
}
@@ -354,7 +348,6 @@
video_high_bitrate == o.video_high_bitrate &&
video_start_bitrate == o.video_start_bitrate &&
video_temporal_layer_screencast == o.video_temporal_layer_screencast &&
- video_temporal_layer_realtime == o.video_temporal_layer_realtime &&
video_leaky_bucket == o.video_leaky_bucket &&
video_highest_bitrate == o.video_highest_bitrate &&
cpu_overuse_detection == o.cpu_overuse_detection &&
@@ -372,15 +365,11 @@
system_high_adaptation_threshhold ==
o.system_high_adaptation_threshhold &&
buffered_mode_latency == o.buffered_mode_latency &&
- lower_min_bitrate == o.lower_min_bitrate &&
dscp == o.dscp &&
suspend_below_min_bitrate == o.suspend_below_min_bitrate &&
unsignalled_recv_stream_limit == o.unsignalled_recv_stream_limit &&
use_simulcast_adapter == o.use_simulcast_adapter &&
- skip_encoding_unused_streams == o.skip_encoding_unused_streams &&
screencast_min_bitrate == o.screencast_min_bitrate &&
- use_improved_wifi_bandwidth_estimator ==
- o.use_improved_wifi_bandwidth_estimator &&
use_payload_padding == o.use_payload_padding;
}
@@ -398,8 +387,6 @@
ost << ToStringIfSet("start bitrate", video_start_bitrate);
ost << ToStringIfSet("video temporal layer screencast",
video_temporal_layer_screencast);
- ost << ToStringIfSet("video temporal layer realtime",
- video_temporal_layer_realtime);
ost << ToStringIfSet("leaky bucket", video_leaky_bucket);
ost << ToStringIfSet("highest video bitrate", video_highest_bitrate);
ost << ToStringIfSet("cpu overuse detection", cpu_overuse_detection);
@@ -416,18 +403,13 @@
ost << ToStringIfSet("low", system_low_adaptation_threshhold);
ost << ToStringIfSet("high", system_high_adaptation_threshhold);
ost << ToStringIfSet("buffered mode latency", buffered_mode_latency);
- ost << ToStringIfSet("lower min bitrate", lower_min_bitrate);
ost << ToStringIfSet("dscp", dscp);
ost << ToStringIfSet("suspend below min bitrate",
suspend_below_min_bitrate);
ost << ToStringIfSet("num channels for early receive",
unsignalled_recv_stream_limit);
ost << ToStringIfSet("use simulcast adapter", use_simulcast_adapter);
- ost << ToStringIfSet("skip encoding unused streams",
- skip_encoding_unused_streams);
ost << ToStringIfSet("screencast min bitrate", screencast_min_bitrate);
- ost << ToStringIfSet("improved wifi bwe",
- use_improved_wifi_bandwidth_estimator);
ost << ToStringIfSet("payload padding", use_payload_padding);
ost << "}";
return ost.str();
@@ -453,8 +435,6 @@
Settable<int> video_start_bitrate;
// Experimental: Enable WebRTC layered screencast.
Settable<bool> video_temporal_layer_screencast;
- // Experimental: Enable WebRTC temporal layer strategy for realtime video.
- Settable<bool> video_temporal_layer_realtime;
// Enable WebRTC leaky bucket when sending media packets.
Settable<bool> video_leaky_bucket;
// Set highest bitrate mode for video.
@@ -491,8 +471,6 @@
SettablePercent system_high_adaptation_threshhold;
// Specify buffered mode latency in milliseconds.
Settable<int> buffered_mode_latency;
- // Make minimum configured send bitrate even lower than usual, at 30kbit.
- Settable<bool> lower_min_bitrate;
// Set DSCP value for packet sent from video channel.
Settable<bool> dscp;
// Enable WebRTC suspension of video. No video frames will be sent when the
@@ -502,13 +480,8 @@
Settable<int> unsignalled_recv_stream_limit;
// Enable use of simulcast adapter.
Settable<bool> use_simulcast_adapter;
- // Enables the encoder to skip encoding stream not actually sent due to too
- // low available bit rate.
- Settable<bool> skip_encoding_unused_streams;
// Force screencast to use a minimum bitrate
Settable<int> screencast_min_bitrate;
- // Enable improved bandwidth estiamtor on wifi.
- Settable<bool> use_improved_wifi_bandwidth_estimator;
// Enable payload padding.
Settable<bool> use_payload_padding;
};
@@ -579,12 +552,12 @@
public:
enum SocketType { ST_RTP, ST_RTCP };
virtual bool SendPacket(
- talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp = talk_base::DSCP_NO_CHANGE) = 0;
+ rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp = rtc::DSCP_NO_CHANGE) = 0;
virtual bool SendRtcp(
- talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp = talk_base::DSCP_NO_CHANGE) = 0;
- virtual int SetOption(SocketType type, talk_base::Socket::Option opt,
+ rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp = rtc::DSCP_NO_CHANGE) = 0;
+ virtual int SetOption(SocketType type, rtc::Socket::Option opt,
int option) = 0;
virtual ~NetworkInterface() {}
};
@@ -594,16 +567,16 @@
// Sets the abstract interface class for sending RTP/RTCP data.
virtual void SetInterface(NetworkInterface *iface) {
- talk_base::CritScope cs(&network_interface_crit_);
+ rtc::CritScope cs(&network_interface_crit_);
network_interface_ = iface;
}
// Called when a RTP packet is received.
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) = 0;
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) = 0;
// Called when a RTCP packet is received.
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) = 0;
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) = 0;
// Called when the socket's ability to send has changed.
virtual void OnReadyToSend(bool ready) = 0;
// Creates a new outgoing media stream with SSRCs and CNAME as described
@@ -639,18 +612,18 @@
virtual bool SetMaxSendBandwidth(int bps) = 0;
// Base method to send packet using NetworkInterface.
- bool SendPacket(talk_base::Buffer* packet) {
+ bool SendPacket(rtc::Buffer* packet) {
return DoSendPacket(packet, false);
}
- bool SendRtcp(talk_base::Buffer* packet) {
+ bool SendRtcp(rtc::Buffer* packet) {
return DoSendPacket(packet, true);
}
int SetOption(NetworkInterface::SocketType type,
- talk_base::Socket::Option opt,
+ rtc::Socket::Option opt,
int option) {
- talk_base::CritScope cs(&network_interface_crit_);
+ rtc::CritScope cs(&network_interface_crit_);
if (!network_interface_)
return -1;
@@ -659,22 +632,22 @@
protected:
// This method sets DSCP |value| on both RTP and RTCP channels.
- int SetDscp(talk_base::DiffServCodePoint value) {
+ int SetDscp(rtc::DiffServCodePoint value) {
int ret;
ret = SetOption(NetworkInterface::ST_RTP,
- talk_base::Socket::OPT_DSCP,
+ rtc::Socket::OPT_DSCP,
value);
if (ret == 0) {
ret = SetOption(NetworkInterface::ST_RTCP,
- talk_base::Socket::OPT_DSCP,
+ rtc::Socket::OPT_DSCP,
value);
}
return ret;
}
private:
- bool DoSendPacket(talk_base::Buffer* packet, bool rtcp) {
- talk_base::CritScope cs(&network_interface_crit_);
+ bool DoSendPacket(rtc::Buffer* packet, bool rtcp) {
+ rtc::CritScope cs(&network_interface_crit_);
if (!network_interface_)
return false;
@@ -685,7 +658,7 @@
// |network_interface_| can be accessed from the worker_thread and
// from any MediaEngine threads. This critical section is to protect accessing
// of network_interface_ object.
- talk_base::CriticalSection network_interface_crit_;
+ rtc::CriticalSection network_interface_crit_;
NetworkInterface* network_interface_;
};
@@ -901,6 +874,7 @@
nominal_bitrate(0),
preferred_bitrate(0),
adapt_reason(0),
+ adapt_changes(0),
capture_jitter_ms(0),
avg_encode_ms(0),
encode_usage_percent(0),
@@ -922,6 +896,7 @@
int nominal_bitrate;
int preferred_bitrate;
int adapt_reason;
+ int adapt_changes;
int capture_jitter_ms;
int avg_encode_ms;
int encode_usage_percent;
@@ -1305,7 +1280,7 @@
virtual bool SendData(
const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result = NULL) = 0;
// Signals when data is received (params, data, len)
sigslot::signal3<const ReceiveDataParams&,
diff --git a/media/base/mediacommon.h b/media/base/mediacommon.h
index e0d7eca..6eb5457 100644
--- a/media/base/mediacommon.h
+++ b/media/base/mediacommon.h
@@ -28,7 +28,7 @@
#ifndef TALK_MEDIA_BASE_MEDIACOMMON_H_
#define TALK_MEDIA_BASE_MEDIACOMMON_H_
-#include "talk/base/stringencode.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
diff --git a/media/base/mediaengine.cc b/media/base/mediaengine.cc
index 289f229..d38a312 100644
--- a/media/base/mediaengine.cc
+++ b/media/base/mediaengine.cc
@@ -27,90 +27,40 @@
#include "talk/media/base/mediaengine.h"
-namespace cricket {
-const int MediaEngineInterface::kDefaultAudioDelayOffset = 0;
-}
-
#if !defined(DISABLE_MEDIA_ENGINE_FACTORY)
-#if defined(HAVE_LINPHONE)
-#include "talk/media/other/linphonemediaengine.h"
-#endif // HAVE_LINPHONE
-#if defined(HAVE_WEBRTC_VOICE)
-#include "talk/media/webrtc/webrtcvoiceengine.h"
-#endif // HAVE_WEBRTC_VOICE
-#if defined(HAVE_WEBRTC_VIDEO)
-#include "talk/media/webrtc/webrtcvideoengine.h"
-#endif // HAVE_WEBRTC_VIDEO
-#if defined(HAVE_LMI)
-#include "talk/media/base/hybridvideoengine.h"
-#include "talk/media/lmi/lmimediaengine.h"
-#endif // HAVE_LMI
+#if defined(HAVE_WEBRTC_VOICE) && defined(HAVE_WEBRTC_VIDEO)
+#include "talk/media/webrtc/webrtcmediaengine.h"
+#endif // HAVE_WEBRTC_VOICE && HAVE_WEBRTC_VIDEO
+
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG
namespace cricket {
-#if defined(HAVE_WEBRTC_VOICE)
-#define AUDIO_ENG_NAME WebRtcVoiceEngine
-#else
-#define AUDIO_ENG_NAME NullVoiceEngine
-#endif
-
-#if defined(HAVE_WEBRTC_VIDEO)
-#if !defined(HAVE_LMI)
-template<>
-CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine>::
- CompositeMediaEngine() {
- video_.SetVoiceEngine(&voice_);
-}
-#define VIDEO_ENG_NAME WebRtcVideoEngine
-#else
-// If we have both WebRtcVideoEngine and LmiVideoEngine, enable dual-stack.
-// This small class here allows us to hook the WebRtcVideoChannel up to
-// the capturer owned by the LMI engine, without infecting the rest of the
-// HybridVideoEngine classes with this abstraction violation.
-class WebRtcLmiHybridVideoEngine
- : public HybridVideoEngine<WebRtcVideoEngine, LmiVideoEngine> {
- public:
- void SetVoiceEngine(WebRtcVoiceEngine* engine) {
- video1_.SetVoiceEngine(engine);
- }
-};
-template<>
-CompositeMediaEngine<WebRtcVoiceEngine, WebRtcLmiHybridVideoEngine>::
- CompositeMediaEngine() {
- video_.SetVoiceEngine(&voice_);
-}
-#define VIDEO_ENG_NAME WebRtcLmiHybridVideoEngine
-#endif
-#elif defined(HAVE_LMI)
-#define VIDEO_ENG_NAME LmiVideoEngine
-#else
-#define VIDEO_ENG_NAME NullVideoEngine
-#endif
MediaEngineFactory::MediaEngineCreateFunction
MediaEngineFactory::create_function_ = NULL;
+
MediaEngineFactory::MediaEngineCreateFunction
MediaEngineFactory::SetCreateFunction(MediaEngineCreateFunction function) {
MediaEngineCreateFunction old_function = create_function_;
create_function_ = function;
return old_function;
-};
+}
+// TODO(pthatcher): Remove this method and require all the users of
+// media engines to choose one explictly, or at least remove the
+// default behavior and require calling SetCreateFunction explictly.
MediaEngineInterface* MediaEngineFactory::Create() {
if (create_function_) {
return create_function_();
- } else {
-#if defined(HAVE_LINPHONE)
- return new LinphoneMediaEngine("", "");
-#elif defined(AUDIO_ENG_NAME) && defined(VIDEO_ENG_NAME)
- return new CompositeMediaEngine<AUDIO_ENG_NAME, VIDEO_ENG_NAME>();
-#else
- return new NullMediaEngine();
-#endif
}
+#if defined(HAVE_WEBRTC_VOICE) && defined(HAVE_WEBRTC_VIDEO)
+ return WebRtcMediaEngineFactory::Create();
+#else
+ return new NullMediaEngine();
+#endif // HAVE_WEBRTC_VIDEO && HAVE_WEBRTC_VOICE
}
}; // namespace cricket
diff --git a/media/base/mediaengine.h b/media/base/mediaengine.h
index 326b722..f30e3b1 100644
--- a/media/base/mediaengine.h
+++ b/media/base/mediaengine.h
@@ -37,8 +37,6 @@
#include <string>
#include <vector>
-#include "talk/base/fileutils.h"
-#include "talk/base/sigslotrepeater.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediacommon.h"
@@ -47,6 +45,8 @@
#include "talk/media/base/videoprocessor.h"
#include "talk/media/base/voiceprocessor.h"
#include "talk/media/devices/devicemanager.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/sigslotrepeater.h"
#if defined(GOOGLE_CHROME_BUILD) || defined(CHROMIUM_BUILD)
#define DISABLE_MEDIA_ENGINE_FACTORY
@@ -69,7 +69,7 @@
// Initialization
// Starts the engine.
- virtual bool Init(talk_base::Thread* worker_thread) = 0;
+ virtual bool Init(rtc::Thread* worker_thread) = 0;
// Shuts down the engine.
virtual void Terminate() = 0;
// Returns what the engine is capable of, as a set of Capabilities, above.
@@ -91,8 +91,6 @@
virtual AudioOptions GetAudioOptions() const = 0;
// Sets global audio options. "options" are from AudioOptions, above.
virtual bool SetAudioOptions(const AudioOptions& options) = 0;
- // Sets global video options. "options" are from VideoOptions, above.
- virtual bool SetVideoOptions(const VideoOptions& options) = 0;
// Sets the value used by the echo canceller to offset delay values obtained
// from the OS.
virtual bool SetAudioDelayOffset(int offset) = 0;
@@ -124,7 +122,6 @@
// when a VoiceMediaChannel starts sending.
virtual bool SetLocalMonitor(bool enable) = 0;
// Installs a callback for raw frames from the local camera.
- virtual bool SetLocalRenderer(VideoRenderer* renderer) = 0;
virtual const std::vector<AudioCodec>& audio_codecs() = 0;
virtual const std::vector<RtpHeaderExtension>&
@@ -138,7 +135,7 @@
virtual void SetVideoLogging(int min_sev, const char* filter) = 0;
// Starts AEC dump using existing file.
- virtual bool StartAecDump(talk_base::PlatformFile file) = 0;
+ virtual bool StartAecDump(rtc::PlatformFile file) = 0;
// Voice processors for effects.
virtual bool RegisterVoiceProcessor(uint32 ssrc,
@@ -180,7 +177,7 @@
public:
CompositeMediaEngine() {}
virtual ~CompositeMediaEngine() {}
- virtual bool Init(talk_base::Thread* worker_thread) {
+ virtual bool Init(rtc::Thread* worker_thread) {
if (!voice_.Init(worker_thread))
return false;
if (!video_.Init(worker_thread)) {
@@ -214,9 +211,6 @@
virtual bool SetAudioOptions(const AudioOptions& options) {
return voice_.SetOptions(options);
}
- virtual bool SetVideoOptions(const VideoOptions& options) {
- return video_.SetOptions(options);
- }
virtual bool SetAudioDelayOffset(int offset) {
return voice_.SetDelayOffset(offset);
}
@@ -245,10 +239,6 @@
virtual bool SetLocalMonitor(bool enable) {
return voice_.SetLocalMonitor(enable);
}
- virtual bool SetLocalRenderer(VideoRenderer* renderer) {
- return video_.SetLocalRenderer(renderer);
- }
-
virtual const std::vector<AudioCodec>& audio_codecs() {
return voice_.codecs();
}
@@ -269,7 +259,7 @@
video_.SetLogging(min_sev, filter);
}
- virtual bool StartAecDump(talk_base::PlatformFile file) {
+ virtual bool StartAecDump(rtc::PlatformFile file) {
return voice_.StartAecDump(file);
}
@@ -301,7 +291,7 @@
// a video engine is desired.
class NullVoiceEngine {
public:
- bool Init(talk_base::Thread* worker_thread) { return true; }
+ bool Init(rtc::Thread* worker_thread) { return true; }
void Terminate() {}
int GetCapabilities() { return 0; }
// If you need this to return an actual channel, use FakeMediaEngine instead.
@@ -329,7 +319,7 @@
return rtp_header_extensions_;
}
void SetLogging(int min_sev, const char* filter) {}
- bool StartAecDump(talk_base::PlatformFile file) { return false; }
+ bool StartAecDump(rtc::PlatformFile file) { return false; }
bool RegisterProcessor(uint32 ssrc,
VoiceProcessor* voice_processor,
MediaProcessorDirection direction) { return true; }
@@ -346,7 +336,7 @@
// a voice engine is desired.
class NullVideoEngine {
public:
- bool Init(talk_base::Thread* worker_thread) { return true; }
+ bool Init(rtc::Thread* worker_thread) { return true; }
void Terminate() {}
int GetCapabilities() { return 0; }
// If you need this to return an actual channel, use FakeMediaEngine instead.
@@ -361,7 +351,6 @@
bool SetDefaultEncoderConfig(const VideoEncoderConfig& config) {
return true;
}
- bool SetLocalRenderer(VideoRenderer* renderer) { return true; }
const std::vector<VideoCodec>& codecs() { return codecs_; }
const std::vector<RtpHeaderExtension>& rtp_header_extensions() {
return rtp_header_extensions_;
diff --git a/media/base/mutedvideocapturer.cc b/media/base/mutedvideocapturer.cc
index 0c74b9f..f122c30 100644
--- a/media/base/mutedvideocapturer.cc
+++ b/media/base/mutedvideocapturer.cc
@@ -1,135 +1,2 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
-#include "talk/media/base/mutedvideocapturer.h"
-#include "talk/media/base/videoframe.h"
-
-#if defined(HAVE_WEBRTC_VIDEO)
-#include "talk/media/webrtc/webrtcvideoframe.h"
-#endif // HAVE_WEBRTC_VIDEO
-
-
-namespace cricket {
-
-const char MutedVideoCapturer::kCapturerId[] = "muted_camera";
-
-class MutedFramesGenerator : public talk_base::MessageHandler {
- public:
- explicit MutedFramesGenerator(const VideoFormat& format);
- virtual ~MutedFramesGenerator();
-
- // Called every |interval| ms. From |format|.interval given in the
- // constructor.
- sigslot::signal1<VideoFrame*> SignalFrame;
-
- protected:
- virtual void OnMessage(talk_base::Message* message);
-
- private:
- talk_base::Thread capture_thread_;
- talk_base::scoped_ptr<VideoFrame> muted_frame_;
- const VideoFormat format_;
- const int interval_;
- uint32 create_time_;
-};
-
-MutedFramesGenerator::MutedFramesGenerator(const VideoFormat& format)
- : format_(format),
- interval_(static_cast<int>(format.interval /
- talk_base::kNumNanosecsPerMillisec)),
- create_time_(talk_base::Time()) {
- capture_thread_.Start();
- capture_thread_.PostDelayed(interval_, this);
-}
-
-MutedFramesGenerator::~MutedFramesGenerator() { capture_thread_.Clear(this); }
-
-void MutedFramesGenerator::OnMessage(talk_base::Message* message) {
- // Queue a new frame as soon as possible to minimize drift.
- capture_thread_.PostDelayed(interval_, this);
- if (!muted_frame_) {
-#if defined(HAVE_WEBRTC_VIDEO)
-#define VIDEO_FRAME_NAME WebRtcVideoFrame
-#endif
-#if defined(VIDEO_FRAME_NAME)
- muted_frame_.reset(new VIDEO_FRAME_NAME());
-#else
- return;
-#endif
- }
- uint32 current_timestamp = talk_base::Time();
- // Delta between create time and current time will be correct even if there is
- // a wraparound since they are unsigned integers.
- uint32 elapsed_time = current_timestamp - create_time_;
- if (!muted_frame_->InitToBlack(format_.width, format_.height, 1, 1,
- elapsed_time, current_timestamp)) {
- LOG(LS_ERROR) << "Failed to create a black frame.";
- }
- SignalFrame(muted_frame_.get());
-}
-
-MutedVideoCapturer::MutedVideoCapturer() { SetId(kCapturerId); }
-
-MutedVideoCapturer::~MutedVideoCapturer() { Stop(); }
-
-bool MutedVideoCapturer::GetBestCaptureFormat(const VideoFormat& desired,
- VideoFormat* best_format) {
- *best_format = desired;
- return true;
-}
-
-CaptureState MutedVideoCapturer::Start(const VideoFormat& capture_format) {
- if (frame_generator_.get()) {
- return CS_RUNNING;
- }
- frame_generator_.reset(new MutedFramesGenerator(capture_format));
- frame_generator_->SignalFrame
- .connect(this, &MutedVideoCapturer::OnMutedFrame);
- SetCaptureFormat(&capture_format);
- return CS_RUNNING;
-}
-
-void MutedVideoCapturer::Stop() {
- frame_generator_.reset();
- SetCaptureFormat(NULL);
-}
-
-bool MutedVideoCapturer::IsRunning() { return frame_generator_.get() != NULL; }
-
-bool MutedVideoCapturer::GetPreferredFourccs(std::vector<uint32>* fourccs) {
- fourccs->clear();
- fourccs->push_back(cricket::FOURCC_I420);
- return true;
-}
-
-void MutedVideoCapturer::OnMutedFrame(VideoFrame* muted_frame) {
- SignalVideoFrame(this, muted_frame);
-}
-
-} // namespace cricket
+// TODO(pthatcher): Delete this file. Pulse won't work without it for
+// some reason.
diff --git a/media/base/mutedvideocapturer.h b/media/base/mutedvideocapturer.h
deleted file mode 100644
index fb249a9..0000000
--- a/media/base/mutedvideocapturer.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_MEDIA_BASE_MUTEDVIDEOCAPTURER_H_
-#define TALK_MEDIA_BASE_MUTEDVIDEOCAPTURER_H_
-
-#include "talk/base/thread.h"
-#include "talk/media/base/videocapturer.h"
-
-namespace cricket {
-
-class MutedFramesGenerator;
-
-class MutedVideoCapturer : public VideoCapturer {
- public:
- static const char kCapturerId[];
-
- MutedVideoCapturer();
- virtual ~MutedVideoCapturer();
- virtual bool GetBestCaptureFormat(const VideoFormat& desired,
- VideoFormat* best_format);
- virtual CaptureState Start(const VideoFormat& capture_format);
- virtual void Stop();
- virtual bool IsRunning();
- virtual bool IsScreencast() const { return false; }
- virtual bool GetPreferredFourccs(std::vector<uint32>* fourccs);
-
- protected:
- void OnMutedFrame(VideoFrame* muted_frame);
-
- talk_base::scoped_ptr<MutedFramesGenerator> frame_generator_;
-};
-
-} // namespace cricket
-
-#endif // TALK_MEDIA_BASE_MUTEDVIDEOCAPTURER_H_
diff --git a/media/base/mutedvideocapturer_unittest.cc b/media/base/mutedvideocapturer_unittest.cc
deleted file mode 100644
index dfb56df..0000000
--- a/media/base/mutedvideocapturer_unittest.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * libjingle
- * Copyright 2012 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/media/base/mutedvideocapturer.h"
-
-#include "talk/base/gunit.h"
-#include "talk/media/base/videoframe.h"
-
-class MutedVideoCapturerTest : public sigslot::has_slots<>,
- public testing::Test {
- protected:
- void SetUp() {
- frames_received_ = 0;
- capturer_.SignalVideoFrame
- .connect(this, &MutedVideoCapturerTest::OnVideoFrame);
- }
- void OnVideoFrame(cricket::VideoCapturer* capturer,
- const cricket::VideoFrame* muted_frame) {
- EXPECT_EQ(capturer, &capturer_);
- ++frames_received_;
- received_width_ = muted_frame->GetWidth();
- received_height_ = muted_frame->GetHeight();
- }
- int frames_received() { return frames_received_; }
- bool ReceivedCorrectFormat() {
- return (received_width_ == capturer_.GetCaptureFormat()->width) &&
- (received_height_ == capturer_.GetCaptureFormat()->height);
- }
-
- cricket::MutedVideoCapturer capturer_;
- int frames_received_;
- cricket::VideoFormat capture_format_;
- int received_width_;
- int received_height_;
-};
-
-TEST_F(MutedVideoCapturerTest, GetBestCaptureFormat) {
- cricket::VideoFormat format(640, 360, cricket::VideoFormat::FpsToInterval(30),
- cricket::FOURCC_I420);
- cricket::VideoFormat best_format;
- EXPECT_TRUE(capturer_.GetBestCaptureFormat(format, &best_format));
- EXPECT_EQ(format.width, best_format.width);
- EXPECT_EQ(format.height, best_format.height);
- EXPECT_EQ(format.interval, best_format.interval);
- EXPECT_EQ(format.fourcc, best_format.fourcc);
-}
-
-TEST_F(MutedVideoCapturerTest, IsScreencast) {
- EXPECT_FALSE(capturer_.IsScreencast());
-}
-
-TEST_F(MutedVideoCapturerTest, GetPreferredFourccs) {
- std::vector<uint32> fourccs;
- EXPECT_TRUE(capturer_.GetPreferredFourccs(&fourccs));
- EXPECT_EQ(fourccs.size(), 1u);
- EXPECT_TRUE(capturer_.GetPreferredFourccs(&fourccs));
- EXPECT_EQ(fourccs.size(), 1u);
- EXPECT_EQ(fourccs[0], cricket::FOURCC_I420);
-}
-
-TEST_F(MutedVideoCapturerTest, Capturing) {
- cricket::VideoFormat format(640, 360, cricket::VideoFormat::FpsToInterval(30),
- cricket::FOURCC_I420);
- EXPECT_EQ(capturer_.Start(format), cricket::CS_RUNNING);
- EXPECT_EQ(capturer_.Start(format), cricket::CS_RUNNING);
- EXPECT_TRUE(capturer_.IsRunning());
- // 100 ms should be enough to receive 3 frames at FPS of 30.
- EXPECT_EQ_WAIT(frames_received(), 1, 100);
- EXPECT_TRUE(ReceivedCorrectFormat());
- capturer_.Stop();
- EXPECT_FALSE(capturer_.IsRunning());
-}
diff --git a/media/base/rtpdataengine.cc b/media/base/rtpdataengine.cc
index 3d0efc4..0acc43a 100644
--- a/media/base/rtpdataengine.cc
+++ b/media/base/rtpdataengine.cc
@@ -27,15 +27,15 @@
#include "talk/media/base/rtpdataengine.h"
-#include "talk/base/buffer.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/ratelimiter.h"
-#include "talk/base/timing.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/base/streamparams.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/ratelimiter.h"
+#include "webrtc/base/timing.h"
namespace cricket {
@@ -55,7 +55,7 @@
data_codecs_.push_back(
DataCodec(kGoogleRtpDataCodecId,
kGoogleRtpDataCodecName, 0));
- SetTiming(new talk_base::Timing());
+ SetTiming(new rtc::Timing());
}
DataMediaChannel* RtpDataEngine::CreateChannel(
@@ -92,7 +92,7 @@
return false;
}
-RtpDataMediaChannel::RtpDataMediaChannel(talk_base::Timing* timing) {
+RtpDataMediaChannel::RtpDataMediaChannel(rtc::Timing* timing) {
Construct(timing);
}
@@ -100,11 +100,11 @@
Construct(NULL);
}
-void RtpDataMediaChannel::Construct(talk_base::Timing* timing) {
+void RtpDataMediaChannel::Construct(rtc::Timing* timing) {
sending_ = false;
receiving_ = false;
timing_ = timing;
- send_limiter_.reset(new talk_base::RateLimiter(kDataMaxBandwidth / 8, 1.0));
+ send_limiter_.reset(new rtc::RateLimiter(kDataMaxBandwidth / 8, 1.0));
}
@@ -187,7 +187,7 @@
// And we should probably allow more than one per stream.
rtp_clock_by_send_ssrc_[stream.first_ssrc()] = new RtpClock(
kDataCodecClockrate,
- talk_base::CreateRandomNonZeroId(), talk_base::CreateRandomNonZeroId());
+ rtc::CreateRandomNonZeroId(), rtc::CreateRandomNonZeroId());
LOG(LS_INFO) << "Added data send stream '" << stream.id
<< "' with ssrc=" << stream.first_ssrc();
@@ -231,7 +231,7 @@
}
void RtpDataMediaChannel::OnPacketReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
RtpHeader header;
if (!GetRtpHeader(packet->data(), packet->length(), &header)) {
// Don't want to log for every corrupt packet.
@@ -294,14 +294,14 @@
if (bps <= 0) {
bps = kDataMaxBandwidth;
}
- send_limiter_.reset(new talk_base::RateLimiter(bps / 8, 1.0));
+ send_limiter_.reset(new rtc::RateLimiter(bps / 8, 1.0));
LOG(LS_INFO) << "RtpDataMediaChannel::SetSendBandwidth to " << bps << "bps.";
return true;
}
bool RtpDataMediaChannel::SendData(
const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result) {
if (result) {
// If we return true, we'll set this to SDR_SUCCESS.
@@ -353,7 +353,7 @@
rtp_clock_by_send_ssrc_[header.ssrc]->Tick(
now, &header.seq_num, &header.timestamp);
- talk_base::Buffer packet;
+ rtc::Buffer packet;
packet.SetCapacity(packet_len);
packet.SetLength(kMinRtpPacketLen);
if (!SetRtpHeader(packet.data(), packet.length(), header)) {
diff --git a/media/base/rtpdataengine.h b/media/base/rtpdataengine.h
index d5abeef..787ba26 100644
--- a/media/base/rtpdataengine.h
+++ b/media/base/rtpdataengine.h
@@ -31,10 +31,10 @@
#include <string>
#include <vector>
-#include "talk/base/timing.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediaengine.h"
+#include "webrtc/base/timing.h"
namespace cricket {
@@ -51,13 +51,13 @@
}
// Mostly for testing with a fake clock. Ownership is passed in.
- void SetTiming(talk_base::Timing* timing) {
+ void SetTiming(rtc::Timing* timing) {
timing_.reset(timing);
}
private:
std::vector<DataCodec> data_codecs_;
- talk_base::scoped_ptr<talk_base::Timing> timing_;
+ rtc::scoped_ptr<rtc::Timing> timing_;
};
// Keep track of sequence number and timestamp of an RTP stream. The
@@ -86,13 +86,13 @@
class RtpDataMediaChannel : public DataMediaChannel {
public:
// Timing* Used for the RtpClock
- explicit RtpDataMediaChannel(talk_base::Timing* timing);
+ explicit RtpDataMediaChannel(rtc::Timing* timing);
// Sets Timing == NULL, so you'll need to call set_timer() before
// using it. This is needed by FakeMediaEngine.
RtpDataMediaChannel();
virtual ~RtpDataMediaChannel();
- void set_timing(talk_base::Timing* timing) {
+ void set_timing(rtc::Timing* timing) {
timing_ = timing;
}
@@ -116,28 +116,28 @@
receiving_ = receive;
return true;
}
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {}
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {}
virtual void OnReadyToSend(bool ready) {}
virtual bool SendData(
const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result);
private:
- void Construct(talk_base::Timing* timing);
+ void Construct(rtc::Timing* timing);
bool sending_;
bool receiving_;
- talk_base::Timing* timing_;
+ rtc::Timing* timing_;
std::vector<DataCodec> send_codecs_;
std::vector<DataCodec> recv_codecs_;
std::vector<StreamParams> send_streams_;
std::vector<StreamParams> recv_streams_;
std::map<uint32, RtpClock*> rtp_clock_by_send_ssrc_;
- talk_base::scoped_ptr<talk_base::RateLimiter> send_limiter_;
+ rtc::scoped_ptr<rtc::RateLimiter> send_limiter_;
};
} // namespace cricket
diff --git a/media/base/rtpdataengine_unittest.cc b/media/base/rtpdataengine_unittest.cc
index 640c18d..1f0a237 100644
--- a/media/base/rtpdataengine_unittest.cc
+++ b/media/base/rtpdataengine_unittest.cc
@@ -27,18 +27,18 @@
#include <string>
-#include "talk/base/buffer.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/timing.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/fakenetworkinterface.h"
#include "talk/media/base/rtpdataengine.h"
#include "talk/media/base/rtputils.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/timing.h"
-class FakeTiming : public talk_base::Timing {
+class FakeTiming : public rtc::Timing {
public:
FakeTiming() : now_(0.0) {}
@@ -84,11 +84,11 @@
class RtpDataMediaChannelTest : public testing::Test {
protected:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
virtual void SetUp() {
@@ -149,7 +149,7 @@
std::string GetSentData(int index) {
// Assume RTP header of length 12
- talk_base::scoped_ptr<const talk_base::Buffer> packet(
+ rtc::scoped_ptr<const rtc::Buffer> packet(
iface_->GetRtpPacket(index));
if (packet->length() > 12) {
return std::string(packet->data() + 12, packet->length() - 12);
@@ -159,7 +159,7 @@
}
cricket::RtpHeader GetSentDataHeader(int index) {
- talk_base::scoped_ptr<const talk_base::Buffer> packet(
+ rtc::scoped_ptr<const rtc::Buffer> packet(
iface_->GetRtpPacket(index));
cricket::RtpHeader header;
GetRtpHeader(packet->data(), packet->length(), &header);
@@ -167,15 +167,15 @@
}
private:
- talk_base::scoped_ptr<cricket::RtpDataEngine> dme_;
+ rtc::scoped_ptr<cricket::RtpDataEngine> dme_;
// Timing passed into dme_. Owned by dme_;
FakeTiming* timing_;
- talk_base::scoped_ptr<cricket::FakeNetworkInterface> iface_;
- talk_base::scoped_ptr<FakeDataReceiver> receiver_;
+ rtc::scoped_ptr<cricket::FakeNetworkInterface> iface_;
+ rtc::scoped_ptr<FakeDataReceiver> receiver_;
};
TEST_F(RtpDataMediaChannelTest, SetUnknownCodecs) {
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
cricket::DataCodec known_codec;
known_codec.id = 103;
@@ -203,7 +203,7 @@
}
TEST_F(RtpDataMediaChannelTest, AddRemoveSendStream) {
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
cricket::StreamParams stream1;
stream1.add_ssrc(41);
@@ -218,7 +218,7 @@
}
TEST_F(RtpDataMediaChannelTest, AddRemoveRecvStream) {
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
cricket::StreamParams stream1;
stream1.add_ssrc(41);
@@ -233,12 +233,12 @@
}
TEST_F(RtpDataMediaChannelTest, SendData) {
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
cricket::SendDataParams params;
params.ssrc = 42;
unsigned char data[] = "food";
- talk_base::Buffer payload(data, 4);
+ rtc::Buffer payload(data, 4);
unsigned char padded_data[] = {
0x00, 0x00, 0x00, 0x00,
'f', 'o', 'o', 'd',
@@ -275,7 +275,7 @@
// Length too large;
std::string x10000(10000, 'x');
EXPECT_FALSE(dmc->SendData(
- params, talk_base::Buffer(x10000.data(), x10000.length()), &result));
+ params, rtc::Buffer(x10000.data(), x10000.length()), &result));
EXPECT_EQ(cricket::SDR_ERROR, result);
EXPECT_FALSE(HasSentData(0));
@@ -311,12 +311,12 @@
TEST_F(RtpDataMediaChannelTest, SendDataMultipleClocks) {
// Timings owned by RtpDataEngines.
FakeTiming* timing1 = new FakeTiming();
- talk_base::scoped_ptr<cricket::RtpDataEngine> dme1(CreateEngine(timing1));
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc1(
+ rtc::scoped_ptr<cricket::RtpDataEngine> dme1(CreateEngine(timing1));
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc1(
CreateChannel(dme1.get()));
FakeTiming* timing2 = new FakeTiming();
- talk_base::scoped_ptr<cricket::RtpDataEngine> dme2(CreateEngine(timing2));
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc2(
+ rtc::scoped_ptr<cricket::RtpDataEngine> dme2(CreateEngine(timing2));
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc2(
CreateChannel(dme2.get()));
ASSERT_TRUE(dmc1->SetSend(true));
@@ -343,7 +343,7 @@
params2.ssrc = 42;
unsigned char data[] = "foo";
- talk_base::Buffer payload(data, 3);
+ rtc::Buffer payload(data, 3);
cricket::SendDataResult result;
EXPECT_TRUE(dmc1->SendData(params1, payload, &result));
@@ -372,7 +372,7 @@
}
TEST_F(RtpDataMediaChannelTest, SendDataRate) {
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
ASSERT_TRUE(dmc->SetSend(true));
@@ -390,7 +390,7 @@
cricket::SendDataParams params;
params.ssrc = 42;
unsigned char data[] = "food";
- talk_base::Buffer payload(data, 4);
+ rtc::Buffer payload(data, 4);
cricket::SendDataResult result;
// With rtp overhead of 32 bytes, each one of our packets is 36
@@ -427,18 +427,18 @@
0x00, 0x00, 0x00, 0x00,
'a', 'b', 'c', 'd', 'e'
};
- talk_base::Buffer packet(data, sizeof(data));
+ rtc::Buffer packet(data, sizeof(data));
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
// SetReceived not called.
- dmc->OnPacketReceived(&packet, talk_base::PacketTime());
+ dmc->OnPacketReceived(&packet, rtc::PacketTime());
EXPECT_FALSE(HasReceivedData());
dmc->SetReceive(true);
// Unknown payload id
- dmc->OnPacketReceived(&packet, talk_base::PacketTime());
+ dmc->OnPacketReceived(&packet, rtc::PacketTime());
EXPECT_FALSE(HasReceivedData());
cricket::DataCodec codec;
@@ -449,7 +449,7 @@
ASSERT_TRUE(dmc->SetRecvCodecs(codecs));
// Unknown stream
- dmc->OnPacketReceived(&packet, talk_base::PacketTime());
+ dmc->OnPacketReceived(&packet, rtc::PacketTime());
EXPECT_FALSE(HasReceivedData());
cricket::StreamParams stream;
@@ -457,7 +457,7 @@
ASSERT_TRUE(dmc->AddRecvStream(stream));
// Finally works!
- dmc->OnPacketReceived(&packet, talk_base::PacketTime());
+ dmc->OnPacketReceived(&packet, rtc::PacketTime());
EXPECT_TRUE(HasReceivedData());
EXPECT_EQ("abcde", GetReceivedData());
EXPECT_EQ(5U, GetReceivedDataLen());
@@ -467,11 +467,11 @@
unsigned char data[] = {
0x80, 0x65, 0x00, 0x02
};
- talk_base::Buffer packet(data, sizeof(data));
+ rtc::Buffer packet(data, sizeof(data));
- talk_base::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
+ rtc::scoped_ptr<cricket::RtpDataMediaChannel> dmc(CreateChannel());
// Too short
- dmc->OnPacketReceived(&packet, talk_base::PacketTime());
+ dmc->OnPacketReceived(&packet, rtc::PacketTime());
EXPECT_FALSE(HasReceivedData());
}
diff --git a/media/base/rtpdump.cc b/media/base/rtpdump.cc
index 10c835c..61001a8 100644
--- a/media/base/rtpdump.cc
+++ b/media/base/rtpdump.cc
@@ -31,10 +31,10 @@
#include <string>
-#include "talk/base/byteorder.h"
-#include "talk/base/logging.h"
-#include "talk/base/timeutils.h"
#include "talk/media/base/rtputils.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/timeutils.h"
namespace {
static const int kRtpSsrcOffset = 8;
@@ -53,7 +53,7 @@
padding(0) {
}
-void RtpDumpFileHeader::WriteToByteBuffer(talk_base::ByteBuffer* buf) {
+void RtpDumpFileHeader::WriteToByteBuffer(rtc::ByteBuffer* buf) {
buf->WriteUInt32(start_sec);
buf->WriteUInt32(start_usec);
buf->WriteUInt32(source);
@@ -111,14 +111,14 @@
ssrc_override_ = ssrc;
}
-talk_base::StreamResult RtpDumpReader::ReadPacket(RtpDumpPacket* packet) {
- if (!packet) return talk_base::SR_ERROR;
+rtc::StreamResult RtpDumpReader::ReadPacket(RtpDumpPacket* packet) {
+ if (!packet) return rtc::SR_ERROR;
- talk_base::StreamResult res = talk_base::SR_SUCCESS;
+ rtc::StreamResult res = rtc::SR_SUCCESS;
// Read the file header if it has not been read yet.
if (!file_header_read_) {
res = ReadFileHeader();
- if (res != talk_base::SR_SUCCESS) {
+ if (res != rtc::SR_SUCCESS) {
return res;
}
file_header_read_ = true;
@@ -127,10 +127,10 @@
// Read the RTP dump packet header.
char header[RtpDumpPacket::kHeaderLength];
res = stream_->ReadAll(header, sizeof(header), NULL, NULL);
- if (res != talk_base::SR_SUCCESS) {
+ if (res != rtc::SR_SUCCESS) {
return res;
}
- talk_base::ByteBuffer buf(header, sizeof(header));
+ rtc::ByteBuffer buf(header, sizeof(header));
uint16 dump_packet_len;
uint16 data_len;
// Read the full length of the rtpdump packet, including the rtpdump header.
@@ -150,31 +150,31 @@
// If the packet is RTP and we have specified a ssrc, replace the RTP ssrc
// with the specified ssrc.
- if (res == talk_base::SR_SUCCESS &&
+ if (res == rtc::SR_SUCCESS &&
packet->IsValidRtpPacket() &&
ssrc_override_ != 0) {
- talk_base::SetBE32(&packet->data[kRtpSsrcOffset], ssrc_override_);
+ rtc::SetBE32(&packet->data[kRtpSsrcOffset], ssrc_override_);
}
return res;
}
-talk_base::StreamResult RtpDumpReader::ReadFileHeader() {
+rtc::StreamResult RtpDumpReader::ReadFileHeader() {
// Read the first line.
std::string first_line;
- talk_base::StreamResult res = stream_->ReadLine(&first_line);
- if (res != talk_base::SR_SUCCESS) {
+ rtc::StreamResult res = stream_->ReadLine(&first_line);
+ if (res != rtc::SR_SUCCESS) {
return res;
}
if (!CheckFirstLine(first_line)) {
- return talk_base::SR_ERROR;
+ return rtc::SR_ERROR;
}
// Read the 16 byte file header.
char header[RtpDumpFileHeader::kHeaderLength];
res = stream_->ReadAll(header, sizeof(header), NULL, NULL);
- if (res == talk_base::SR_SUCCESS) {
- talk_base::ByteBuffer buf(header, sizeof(header));
+ if (res == rtc::SR_SUCCESS) {
+ rtc::ByteBuffer buf(header, sizeof(header));
uint32 start_sec;
uint32 start_usec;
buf.ReadUInt32(&start_sec);
@@ -204,7 +204,7 @@
///////////////////////////////////////////////////////////////////////////
// Implementation of RtpDumpLoopReader.
///////////////////////////////////////////////////////////////////////////
-RtpDumpLoopReader::RtpDumpLoopReader(talk_base::StreamInterface* stream)
+RtpDumpLoopReader::RtpDumpLoopReader(rtc::StreamInterface* stream)
: RtpDumpReader(stream),
loop_count_(0),
elapsed_time_increases_(0),
@@ -220,16 +220,16 @@
prev_rtp_timestamp_(0) {
}
-talk_base::StreamResult RtpDumpLoopReader::ReadPacket(RtpDumpPacket* packet) {
- if (!packet) return talk_base::SR_ERROR;
+rtc::StreamResult RtpDumpLoopReader::ReadPacket(RtpDumpPacket* packet) {
+ if (!packet) return rtc::SR_ERROR;
- talk_base::StreamResult res = RtpDumpReader::ReadPacket(packet);
- if (talk_base::SR_SUCCESS == res) {
+ rtc::StreamResult res = RtpDumpReader::ReadPacket(packet);
+ if (rtc::SR_SUCCESS == res) {
if (0 == loop_count_) {
// During the first loop, we update the statistics of the input stream.
UpdateStreamStatistics(*packet);
}
- } else if (talk_base::SR_EOS == res) {
+ } else if (rtc::SR_EOS == res) {
if (0 == loop_count_) {
// At the end of the first loop, calculate elapsed_time_increases_,
// rtp_seq_num_increase_, and rtp_timestamp_increase_, which will be
@@ -244,7 +244,7 @@
}
}
- if (talk_base::SR_SUCCESS == res && loop_count_ > 0) {
+ if (rtc::SR_SUCCESS == res && loop_count_ > 0) {
// During the second and later loops, we update the elapsed time of the dump
// packet. If the dumped packet is a RTP packet, we also update its RTP
// sequence number and timestamp.
@@ -307,7 +307,7 @@
sequence += loop_count_ * rtp_seq_num_increase_;
timestamp += loop_count_ * rtp_timestamp_increase_;
// Write the updated sequence number and timestamp back to the RTP packet.
- talk_base::ByteBuffer buffer;
+ rtc::ByteBuffer buffer;
buffer.WriteUInt16(sequence);
buffer.WriteUInt32(timestamp);
memcpy(&packet->data[2], buffer.Data(), buffer.Length());
@@ -318,11 +318,11 @@
// Implementation of RtpDumpWriter.
///////////////////////////////////////////////////////////////////////////
-RtpDumpWriter::RtpDumpWriter(talk_base::StreamInterface* stream)
+RtpDumpWriter::RtpDumpWriter(rtc::StreamInterface* stream)
: stream_(stream),
packet_filter_(PF_ALL),
file_header_written_(false),
- start_time_ms_(talk_base::Time()),
+ start_time_ms_(rtc::Time()),
warn_slow_writes_delay_(kWarnSlowWritesDelayMs) {
}
@@ -332,32 +332,32 @@
}
uint32 RtpDumpWriter::GetElapsedTime() const {
- return talk_base::TimeSince(start_time_ms_);
+ return rtc::TimeSince(start_time_ms_);
}
-talk_base::StreamResult RtpDumpWriter::WriteFileHeader() {
- talk_base::StreamResult res = WriteToStream(
+rtc::StreamResult RtpDumpWriter::WriteFileHeader() {
+ rtc::StreamResult res = WriteToStream(
RtpDumpFileHeader::kFirstLine,
strlen(RtpDumpFileHeader::kFirstLine));
- if (res != talk_base::SR_SUCCESS) {
+ if (res != rtc::SR_SUCCESS) {
return res;
}
- talk_base::ByteBuffer buf;
- RtpDumpFileHeader file_header(talk_base::Time(), 0, 0);
+ rtc::ByteBuffer buf;
+ RtpDumpFileHeader file_header(rtc::Time(), 0, 0);
file_header.WriteToByteBuffer(&buf);
return WriteToStream(buf.Data(), buf.Length());
}
-talk_base::StreamResult RtpDumpWriter::WritePacket(
+rtc::StreamResult RtpDumpWriter::WritePacket(
const void* data, size_t data_len, uint32 elapsed, bool rtcp) {
- if (!stream_ || !data || 0 == data_len) return talk_base::SR_ERROR;
+ if (!stream_ || !data || 0 == data_len) return rtc::SR_ERROR;
- talk_base::StreamResult res = talk_base::SR_SUCCESS;
+ rtc::StreamResult res = rtc::SR_SUCCESS;
// Write the file header if it has not been written yet.
if (!file_header_written_) {
res = WriteFileHeader();
- if (res != talk_base::SR_SUCCESS) {
+ if (res != rtc::SR_SUCCESS) {
return res;
}
file_header_written_ = true;
@@ -366,17 +366,17 @@
// Figure out what to write.
size_t write_len = FilterPacket(data, data_len, rtcp);
if (write_len == 0) {
- return talk_base::SR_SUCCESS;
+ return rtc::SR_SUCCESS;
}
// Write the dump packet header.
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
buf.WriteUInt16(static_cast<uint16>(
RtpDumpPacket::kHeaderLength + write_len));
buf.WriteUInt16(static_cast<uint16>(rtcp ? 0 : data_len));
buf.WriteUInt32(elapsed);
res = WriteToStream(buf.Data(), buf.Length());
- if (res != talk_base::SR_SUCCESS) {
+ if (res != rtc::SR_SUCCESS) {
return res;
}
@@ -408,12 +408,12 @@
return filtered_len;
}
-talk_base::StreamResult RtpDumpWriter::WriteToStream(
+rtc::StreamResult RtpDumpWriter::WriteToStream(
const void* data, size_t data_len) {
- uint32 before = talk_base::Time();
- talk_base::StreamResult result =
+ uint32 before = rtc::Time();
+ rtc::StreamResult result =
stream_->WriteAll(data, data_len, NULL, NULL);
- uint32 delay = talk_base::TimeSince(before);
+ uint32 delay = rtc::TimeSince(before);
if (delay >= warn_slow_writes_delay_) {
LOG(LS_WARNING) << "Slow RtpDump: took " << delay << "ms to write "
<< data_len << " bytes.";
diff --git a/media/base/rtpdump.h b/media/base/rtpdump.h
index ceacab2..33c31c9 100644
--- a/media/base/rtpdump.h
+++ b/media/base/rtpdump.h
@@ -33,9 +33,9 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/stream.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/stream.h"
namespace cricket {
@@ -57,7 +57,7 @@
struct RtpDumpFileHeader {
RtpDumpFileHeader(uint32 start_ms, uint32 s, uint16 p);
- void WriteToByteBuffer(talk_base::ByteBuffer* buf);
+ void WriteToByteBuffer(rtc::ByteBuffer* buf);
static const char kFirstLine[];
static const size_t kHeaderLength = 16;
@@ -104,7 +104,7 @@
class RtpDumpReader {
public:
- explicit RtpDumpReader(talk_base::StreamInterface* stream)
+ explicit RtpDumpReader(rtc::StreamInterface* stream)
: stream_(stream),
file_header_read_(false),
first_line_and_file_header_len_(0),
@@ -115,10 +115,10 @@
// Use the specified ssrc, rather than the ssrc from dump, for RTP packets.
void SetSsrc(uint32 ssrc);
- virtual talk_base::StreamResult ReadPacket(RtpDumpPacket* packet);
+ virtual rtc::StreamResult ReadPacket(RtpDumpPacket* packet);
protected:
- talk_base::StreamResult ReadFileHeader();
+ rtc::StreamResult ReadFileHeader();
bool RewindToFirstDumpPacket() {
return stream_->SetPosition(first_line_and_file_header_len_);
}
@@ -127,7 +127,7 @@
// Check if its matches "#!rtpplay1.0 address/port\n".
bool CheckFirstLine(const std::string& first_line);
- talk_base::StreamInterface* stream_;
+ rtc::StreamInterface* stream_;
bool file_header_read_;
size_t first_line_and_file_header_len_;
uint32 start_time_ms_;
@@ -143,8 +143,8 @@
// RTP packets and RTCP packets.
class RtpDumpLoopReader : public RtpDumpReader {
public:
- explicit RtpDumpLoopReader(talk_base::StreamInterface* stream);
- virtual talk_base::StreamResult ReadPacket(RtpDumpPacket* packet);
+ explicit RtpDumpLoopReader(rtc::StreamInterface* stream);
+ virtual rtc::StreamResult ReadPacket(RtpDumpPacket* packet);
private:
// During the first loop, update the statistics, including packet count, frame
@@ -186,19 +186,19 @@
class RtpDumpWriter {
public:
- explicit RtpDumpWriter(talk_base::StreamInterface* stream);
+ explicit RtpDumpWriter(rtc::StreamInterface* stream);
// Filter to control what packets we actually record.
void set_packet_filter(int filter);
// Write a RTP or RTCP packet. The parameters data points to the packet and
// data_len is its length.
- talk_base::StreamResult WriteRtpPacket(const void* data, size_t data_len) {
+ rtc::StreamResult WriteRtpPacket(const void* data, size_t data_len) {
return WritePacket(data, data_len, GetElapsedTime(), false);
}
- talk_base::StreamResult WriteRtcpPacket(const void* data, size_t data_len) {
+ rtc::StreamResult WriteRtcpPacket(const void* data, size_t data_len) {
return WritePacket(data, data_len, GetElapsedTime(), true);
}
- talk_base::StreamResult WritePacket(const RtpDumpPacket& packet) {
+ rtc::StreamResult WritePacket(const RtpDumpPacket& packet) {
return WritePacket(&packet.data[0], packet.data.size(), packet.elapsed_time,
packet.is_rtcp());
}
@@ -211,15 +211,15 @@
}
protected:
- talk_base::StreamResult WriteFileHeader();
+ rtc::StreamResult WriteFileHeader();
private:
- talk_base::StreamResult WritePacket(const void* data, size_t data_len,
+ rtc::StreamResult WritePacket(const void* data, size_t data_len,
uint32 elapsed, bool rtcp);
size_t FilterPacket(const void* data, size_t data_len, bool rtcp);
- talk_base::StreamResult WriteToStream(const void* data, size_t data_len);
+ rtc::StreamResult WriteToStream(const void* data, size_t data_len);
- talk_base::StreamInterface* stream_;
+ rtc::StreamInterface* stream_;
int packet_filter_;
bool file_header_written_;
uint32 start_time_ms_; // Time when the record starts.
diff --git a/media/base/rtpdump_unittest.cc b/media/base/rtpdump_unittest.cc
index c327189..acf60b9 100644
--- a/media/base/rtpdump_unittest.cc
+++ b/media/base/rtpdump_unittest.cc
@@ -27,12 +27,12 @@
#include <string>
-#include "talk/base/bytebuffer.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
#include "talk/media/base/rtpdump.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/base/testutils.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -40,7 +40,7 @@
// Test that we read the correct header fields from the RTP/RTCP packet.
TEST(RtpDumpTest, ReadRtpDumpPacket) {
- talk_base::ByteBuffer rtp_buf;
+ rtc::ByteBuffer rtp_buf;
RtpTestUtility::kTestRawRtpPackets[0].WriteToByteBuffer(kTestSsrc, &rtp_buf);
RtpDumpPacket rtp_packet(rtp_buf.Data(), rtp_buf.Length(), 0, false);
@@ -61,7 +61,7 @@
EXPECT_EQ(kTestSsrc, ssrc);
EXPECT_FALSE(rtp_packet.GetRtcpType(&type));
- talk_base::ByteBuffer rtcp_buf;
+ rtc::ByteBuffer rtcp_buf;
RtpTestUtility::kTestRawRtcpPackets[0].WriteToByteBuffer(&rtcp_buf);
RtpDumpPacket rtcp_packet(rtcp_buf.Data(), rtcp_buf.Length(), 0, true);
@@ -75,48 +75,48 @@
// Test that we read only the RTP dump file.
TEST(RtpDumpTest, ReadRtpDumpFile) {
RtpDumpPacket packet;
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
- talk_base::scoped_ptr<RtpDumpReader> reader;
+ rtc::scoped_ptr<RtpDumpReader> reader;
// Write a RTP packet to the stream, which is a valid RTP dump. Next, we will
// change the first line to make the RTP dump valid or invalid.
ASSERT_TRUE(RtpTestUtility::WriteTestPackets(1, false, kTestSsrc, &writer));
stream.Rewind();
reader.reset(new RtpDumpReader(&stream));
- EXPECT_EQ(talk_base::SR_SUCCESS, reader->ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader->ReadPacket(&packet));
// The first line is correct.
stream.Rewind();
const char new_line[] = "#!rtpplay1.0 1.1.1.1/1\n";
- EXPECT_EQ(talk_base::SR_SUCCESS,
+ EXPECT_EQ(rtc::SR_SUCCESS,
stream.WriteAll(new_line, strlen(new_line), NULL, NULL));
stream.Rewind();
reader.reset(new RtpDumpReader(&stream));
- EXPECT_EQ(talk_base::SR_SUCCESS, reader->ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader->ReadPacket(&packet));
// The first line is not correct: not started with #!rtpplay1.0.
stream.Rewind();
const char new_line2[] = "#!rtpplaz1.0 0.0.0.0/0\n";
- EXPECT_EQ(talk_base::SR_SUCCESS,
+ EXPECT_EQ(rtc::SR_SUCCESS,
stream.WriteAll(new_line2, strlen(new_line2), NULL, NULL));
stream.Rewind();
reader.reset(new RtpDumpReader(&stream));
- EXPECT_EQ(talk_base::SR_ERROR, reader->ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_ERROR, reader->ReadPacket(&packet));
// The first line is not correct: no port.
stream.Rewind();
const char new_line3[] = "#!rtpplay1.0 0.0.0.0//\n";
- EXPECT_EQ(talk_base::SR_SUCCESS,
+ EXPECT_EQ(rtc::SR_SUCCESS,
stream.WriteAll(new_line3, strlen(new_line3), NULL, NULL));
stream.Rewind();
reader.reset(new RtpDumpReader(&stream));
- EXPECT_EQ(talk_base::SR_ERROR, reader->ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_ERROR, reader->ReadPacket(&packet));
}
// Test that we read the same RTP packets that rtp dump writes.
TEST(RtpDumpTest, WriteReadSameRtp) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
ASSERT_TRUE(RtpTestUtility::WriteTestPackets(
RtpTestUtility::GetTestPacketCount(), false, kTestSsrc, &writer));
@@ -127,13 +127,13 @@
RtpDumpPacket packet;
RtpDumpReader reader(&stream);
for (size_t i = 0; i < RtpTestUtility::GetTestPacketCount(); ++i) {
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
uint32 ssrc;
EXPECT_TRUE(GetRtpSsrc(&packet.data[0], packet.data.size(), &ssrc));
EXPECT_EQ(kTestSsrc, ssrc);
}
// No more packets to read.
- EXPECT_EQ(talk_base::SR_EOS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader.ReadPacket(&packet));
// Rewind the stream and read again with a specified ssrc.
stream.Rewind();
@@ -141,7 +141,7 @@
const uint32 send_ssrc = kTestSsrc + 1;
reader_w_ssrc.SetSsrc(send_ssrc);
for (size_t i = 0; i < RtpTestUtility::GetTestPacketCount(); ++i) {
- EXPECT_EQ(talk_base::SR_SUCCESS, reader_w_ssrc.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader_w_ssrc.ReadPacket(&packet));
EXPECT_FALSE(packet.is_rtcp());
EXPECT_EQ(packet.original_data_len, packet.data.size());
uint32 ssrc;
@@ -149,12 +149,12 @@
EXPECT_EQ(send_ssrc, ssrc);
}
// No more packets to read.
- EXPECT_EQ(talk_base::SR_EOS, reader_w_ssrc.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader_w_ssrc.ReadPacket(&packet));
}
// Test that we read the same RTCP packets that rtp dump writes.
TEST(RtpDumpTest, WriteReadSameRtcp) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
ASSERT_TRUE(RtpTestUtility::WriteTestPackets(
RtpTestUtility::GetTestPacketCount(), true, kTestSsrc, &writer));
@@ -166,17 +166,17 @@
RtpDumpReader reader(&stream);
reader.SetSsrc(kTestSsrc + 1); // Does not affect RTCP packet.
for (size_t i = 0; i < RtpTestUtility::GetTestPacketCount(); ++i) {
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
EXPECT_TRUE(packet.is_rtcp());
EXPECT_EQ(0U, packet.original_data_len);
}
// No more packets to read.
- EXPECT_EQ(talk_base::SR_EOS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader.ReadPacket(&packet));
}
// Test dumping only RTP packet headers.
TEST(RtpDumpTest, WriteReadRtpHeadersOnly) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
writer.set_packet_filter(PF_RTPHEADER);
@@ -192,7 +192,7 @@
RtpDumpPacket packet;
RtpDumpReader reader(&stream);
for (size_t i = 0; i < RtpTestUtility::GetTestPacketCount(); ++i) {
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
EXPECT_FALSE(packet.is_rtcp());
size_t len = 0;
packet.GetRtpHeaderLen(&len);
@@ -200,12 +200,12 @@
EXPECT_GT(packet.original_data_len, packet.data.size());
}
// No more packets to read.
- EXPECT_EQ(talk_base::SR_EOS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader.ReadPacket(&packet));
}
// Test dumping only RTCP packets.
TEST(RtpDumpTest, WriteReadRtcpOnly) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
writer.set_packet_filter(PF_RTCPPACKET);
@@ -220,18 +220,18 @@
RtpDumpPacket packet;
RtpDumpReader reader(&stream);
for (size_t i = 0; i < RtpTestUtility::GetTestPacketCount(); ++i) {
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
EXPECT_TRUE(packet.is_rtcp());
EXPECT_EQ(0U, packet.original_data_len);
}
// No more packets to read.
- EXPECT_EQ(talk_base::SR_EOS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader.ReadPacket(&packet));
}
// Test that RtpDumpLoopReader reads RTP packets continously and the elapsed
// time, the sequence number, and timestamp are maintained properly.
TEST(RtpDumpTest, LoopReadRtp) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
ASSERT_TRUE(RtpTestUtility::WriteTestPackets(
RtpTestUtility::GetTestPacketCount(), false, kTestSsrc, &writer));
@@ -242,7 +242,7 @@
// Test that RtpDumpLoopReader reads RTCP packets continously and the elapsed
// time is maintained properly.
TEST(RtpDumpTest, LoopReadRtcp) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
ASSERT_TRUE(RtpTestUtility::WriteTestPackets(
RtpTestUtility::GetTestPacketCount(), true, kTestSsrc, &writer));
@@ -253,7 +253,7 @@
// Test that RtpDumpLoopReader reads continously from stream with a single RTP
// packets.
TEST(RtpDumpTest, LoopReadSingleRtp) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
ASSERT_TRUE(RtpTestUtility::WriteTestPackets(1, false, kTestSsrc, &writer));
@@ -261,21 +261,21 @@
RtpDumpPacket packet;
stream.Rewind();
RtpDumpReader reader(&stream);
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
- EXPECT_EQ(talk_base::SR_EOS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader.ReadPacket(&packet));
// The loop reader reads three packets from the input stream.
stream.Rewind();
RtpDumpLoopReader loop_reader(&stream);
- EXPECT_EQ(talk_base::SR_SUCCESS, loop_reader.ReadPacket(&packet));
- EXPECT_EQ(talk_base::SR_SUCCESS, loop_reader.ReadPacket(&packet));
- EXPECT_EQ(talk_base::SR_SUCCESS, loop_reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, loop_reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, loop_reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, loop_reader.ReadPacket(&packet));
}
// Test that RtpDumpLoopReader reads continously from stream with a single RTCP
// packets.
TEST(RtpDumpTest, LoopReadSingleRtcp) {
- talk_base::MemoryStream stream;
+ rtc::MemoryStream stream;
RtpDumpWriter writer(&stream);
ASSERT_TRUE(RtpTestUtility::WriteTestPackets(1, true, kTestSsrc, &writer));
@@ -283,15 +283,15 @@
RtpDumpPacket packet;
stream.Rewind();
RtpDumpReader reader(&stream);
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
- EXPECT_EQ(talk_base::SR_EOS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader.ReadPacket(&packet));
// The loop reader reads three packets from the input stream.
stream.Rewind();
RtpDumpLoopReader loop_reader(&stream);
- EXPECT_EQ(talk_base::SR_SUCCESS, loop_reader.ReadPacket(&packet));
- EXPECT_EQ(talk_base::SR_SUCCESS, loop_reader.ReadPacket(&packet));
- EXPECT_EQ(talk_base::SR_SUCCESS, loop_reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, loop_reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, loop_reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, loop_reader.ReadPacket(&packet));
}
} // namespace cricket
diff --git a/media/base/rtputils.cc b/media/base/rtputils.cc
index 5215c3b..8c35983 100644
--- a/media/base/rtputils.cc
+++ b/media/base/rtputils.cc
@@ -50,7 +50,7 @@
return false;
}
*value = static_cast<int>(
- talk_base::GetBE16(static_cast<const uint8*>(data) + offset));
+ rtc::GetBE16(static_cast<const uint8*>(data) + offset));
return true;
}
@@ -58,7 +58,7 @@
if (!data || !value) {
return false;
}
- *value = talk_base::GetBE32(static_cast<const uint8*>(data) + offset);
+ *value = rtc::GetBE32(static_cast<const uint8*>(data) + offset);
return true;
}
@@ -66,7 +66,7 @@
if (!data) {
return false;
}
- talk_base::Set8(data, offset, value);
+ rtc::Set8(data, offset, value);
return true;
}
@@ -74,7 +74,7 @@
if (!data) {
return false;
}
- talk_base::SetBE16(static_cast<uint8*>(data) + offset, value);
+ rtc::SetBE16(static_cast<uint8*>(data) + offset, value);
return true;
}
@@ -82,7 +82,7 @@
if (!data) {
return false;
}
- talk_base::SetBE32(static_cast<uint8*>(data) + offset, value);
+ rtc::SetBE32(static_cast<uint8*>(data) + offset, value);
return true;
}
@@ -134,7 +134,7 @@
// If there's an extension, read and add in the extension size.
if (header[0] & 0x10) {
if (len < header_size + sizeof(uint32)) return false;
- header_size += ((talk_base::GetBE16(header + header_size + 2) + 1) *
+ header_size += ((rtc::GetBE16(header + header_size + 2) + 1) *
sizeof(uint32));
if (len < header_size) return false;
}
@@ -176,7 +176,7 @@
if (!GetRtcpType(data, len, &pl_type)) return false;
// SDES packet parsing is not supported.
if (pl_type == kRtcpTypeSDES) return false;
- *value = talk_base::GetBE32(static_cast<const uint8*>(data) + 4);
+ *value = rtc::GetBE32(static_cast<const uint8*>(data) + 4);
return true;
}
@@ -223,4 +223,15 @@
SetRtpSsrc(data, len, header.ssrc));
}
+bool IsRtpPacket(const void* data, size_t len) {
+ if (len < kMinRtpPacketLen)
+ return false;
+
+ int version = 0;
+ if (!GetRtpVersion(data, len, &version))
+ return false;
+
+ return version == kRtpVersion;
+}
+
} // namespace cricket
diff --git a/media/base/rtputils.h b/media/base/rtputils.h
index 6f76866..ca69ace 100644
--- a/media/base/rtputils.h
+++ b/media/base/rtputils.h
@@ -28,7 +28,7 @@
#ifndef TALK_MEDIA_BASE_RTPUTILS_H_
#define TALK_MEDIA_BASE_RTPUTILS_H_
-#include "talk/base/byteorder.h"
+#include "webrtc/base/byteorder.h"
namespace cricket {
@@ -74,6 +74,7 @@
// Assumes version 2, no padding, no extensions, no csrcs.
bool SetRtpHeader(void* data, size_t len, const RtpHeader& header);
+bool IsRtpPacket(const void* data, size_t len);
} // namespace cricket
#endif // TALK_MEDIA_BASE_RTPUTILS_H_
diff --git a/media/base/rtputils_unittest.cc b/media/base/rtputils_unittest.cc
index d3ea521..cec4f71 100644
--- a/media/base/rtputils_unittest.cc
+++ b/media/base/rtputils_unittest.cc
@@ -25,9 +25,9 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
#include "talk/media/base/fakertp.h"
#include "talk/media/base/rtputils.h"
+#include "webrtc/base/gunit.h"
namespace cricket {
diff --git a/media/base/screencastid.h b/media/base/screencastid.h
index d1f84f3..b70c172 100644
--- a/media/base/screencastid.h
+++ b/media/base/screencastid.h
@@ -9,8 +9,8 @@
#include <string>
#include <vector>
-#include "talk/base/window.h"
-#include "talk/base/windowpicker.h"
+#include "webrtc/base/window.h"
+#include "webrtc/base/windowpicker.h"
namespace cricket {
@@ -24,16 +24,16 @@
// Default constructor indicates invalid ScreencastId.
ScreencastId() : type_(INVALID) {}
- explicit ScreencastId(const talk_base::WindowId& id)
+ explicit ScreencastId(const rtc::WindowId& id)
: type_(WINDOW), window_(id) {
}
- explicit ScreencastId(const talk_base::DesktopId& id)
+ explicit ScreencastId(const rtc::DesktopId& id)
: type_(DESKTOP), desktop_(id) {
}
Type type() const { return type_; }
- const talk_base::WindowId& window() const { return window_; }
- const talk_base::DesktopId& desktop() const { return desktop_; }
+ const rtc::WindowId& window() const { return window_; }
+ const rtc::DesktopId& desktop() const { return desktop_; }
// Title is an optional parameter.
const std::string& title() const { return title_; }
@@ -78,8 +78,8 @@
private:
Type type_;
- talk_base::WindowId window_;
- talk_base::DesktopId desktop_;
+ rtc::WindowId window_;
+ rtc::DesktopId desktop_;
std::string title_; // Optional.
};
diff --git a/media/base/streamparams.cc b/media/base/streamparams.cc
index 19d8269..09bfefb 100644
--- a/media/base/streamparams.cc
+++ b/media/base/streamparams.cc
@@ -97,6 +97,26 @@
ost << "}";
return ost.str();
}
+void StreamParams::GetPrimarySsrcs(std::vector<uint32>* ssrcs) const {
+ const SsrcGroup* sim_group = get_ssrc_group(kSimSsrcGroupSemantics);
+ if (sim_group == NULL) {
+ ssrcs->push_back(first_ssrc());
+ } else {
+ for (size_t i = 0; i < sim_group->ssrcs.size(); ++i) {
+ ssrcs->push_back(sim_group->ssrcs[i]);
+ }
+ }
+}
+
+void StreamParams::GetFidSsrcs(const std::vector<uint32>& primary_ssrcs,
+ std::vector<uint32>* fid_ssrcs) const {
+ for (size_t i = 0; i < primary_ssrcs.size(); ++i) {
+ uint32 fid_ssrc;
+ if (GetFidSsrc(primary_ssrcs[i], &fid_ssrc)) {
+ fid_ssrcs->push_back(fid_ssrc);
+ }
+ }
+}
bool StreamParams::AddSecondarySsrc(const std::string& semantics,
uint32 primary_ssrc,
diff --git a/media/base/streamparams.h b/media/base/streamparams.h
index b57f1f7..e36c094 100644
--- a/media/base/streamparams.h
+++ b/media/base/streamparams.h
@@ -44,11 +44,11 @@
#define TALK_MEDIA_BASE_STREAMPARAMS_H_
#include <algorithm>
-#include <string>
#include <set>
+#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
+#include "webrtc/base/basictypes.h"
namespace cricket {
@@ -141,6 +141,16 @@
return GetSecondarySsrc(kFidSsrcGroupSemantics, primary_ssrc, fid_ssrc);
}
+ // Convenience to get all the SIM SSRCs if there are SIM ssrcs, or
+ // the first SSRC otherwise.
+ void GetPrimarySsrcs(std::vector<uint32>* ssrcs) const;
+
+ // Convenience to get all the FID SSRCs for the given primary ssrcs.
+ // If a given primary SSRC does not have a FID SSRC, the list of FID
+ // SSRCS will be smaller than the list of primary SSRCs.
+ void GetFidSsrcs(const std::vector<uint32>& primary_ssrcs,
+ std::vector<uint32>* fid_ssrcs) const;
+
std::string ToString() const;
// Resource of the MUC jid of the participant of with this stream.
diff --git a/media/base/streamparams_unittest.cc b/media/base/streamparams_unittest.cc
index f3a03d6..c24403b 100644
--- a/media/base/streamparams_unittest.cc
+++ b/media/base/streamparams_unittest.cc
@@ -25,9 +25,9 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
#include "talk/media/base/streamparams.h"
#include "talk/media/base/testutils.h"
+#include "webrtc/base/gunit.h"
static const uint32 kSsrcs1[] = {1};
static const uint32 kSsrcs2[] = {1, 2};
@@ -159,6 +159,38 @@
EXPECT_FALSE(sp_invalid.GetFidSsrc(13, &fid_ssrc));
}
+TEST(StreamParams, GetPrimaryAndFidSsrcs) {
+ cricket::StreamParams sp;
+ sp.ssrcs.push_back(1);
+ sp.ssrcs.push_back(2);
+ sp.ssrcs.push_back(3);
+
+ std::vector<uint32> primary_ssrcs;
+ sp.GetPrimarySsrcs(&primary_ssrcs);
+ std::vector<uint32> fid_ssrcs;
+ sp.GetFidSsrcs(primary_ssrcs, &fid_ssrcs);
+ ASSERT_EQ(1u, primary_ssrcs.size());
+ EXPECT_EQ(1u, primary_ssrcs[0]);
+ ASSERT_EQ(0u, fid_ssrcs.size());
+
+ sp.ssrc_groups.push_back(
+ cricket::SsrcGroup(cricket::kSimSsrcGroupSemantics, sp.ssrcs));
+ sp.AddFidSsrc(1, 10);
+ sp.AddFidSsrc(2, 20);
+
+ primary_ssrcs.clear();
+ sp.GetPrimarySsrcs(&primary_ssrcs);
+ fid_ssrcs.clear();
+ sp.GetFidSsrcs(primary_ssrcs, &fid_ssrcs);
+ ASSERT_EQ(3u, primary_ssrcs.size());
+ EXPECT_EQ(1u, primary_ssrcs[0]);
+ EXPECT_EQ(2u, primary_ssrcs[1]);
+ EXPECT_EQ(3u, primary_ssrcs[2]);
+ ASSERT_EQ(2u, fid_ssrcs.size());
+ EXPECT_EQ(10u, fid_ssrcs[0]);
+ EXPECT_EQ(20u, fid_ssrcs[1]);
+}
+
TEST(StreamParams, ToString) {
cricket::StreamParams sp =
CreateStreamParamsWithSsrcGroup("XYZ", kSsrcs2, ARRAY_SIZE(kSsrcs2));
diff --git a/media/base/testutils.cc b/media/base/testutils.cc
index 7320613..84fd05c 100644
--- a/media/base/testutils.cc
+++ b/media/base/testutils.cc
@@ -29,16 +29,17 @@
#include <math.h>
-#include "talk/base/bytebuffer.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/testutils.h"
+#include "talk/media/base/executablehelpers.h"
#include "talk/media/base/rtpdump.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/testutils.h"
namespace cricket {
@@ -46,7 +47,7 @@
// Implementation of RawRtpPacket
/////////////////////////////////////////////////////////////////////////
void RawRtpPacket::WriteToByteBuffer(
- uint32 in_ssrc, talk_base::ByteBuffer *buf) const {
+ uint32 in_ssrc, rtc::ByteBuffer *buf) const {
if (!buf) return;
buf->WriteUInt8(ver_to_cc);
@@ -57,7 +58,7 @@
buf->WriteBytes(payload, sizeof(payload));
}
-bool RawRtpPacket::ReadFromByteBuffer(talk_base::ByteBuffer* buf) {
+bool RawRtpPacket::ReadFromByteBuffer(rtc::ByteBuffer* buf) {
if (!buf) return false;
bool ret = true;
@@ -83,7 +84,7 @@
/////////////////////////////////////////////////////////////////////////
// Implementation of RawRtcpPacket
/////////////////////////////////////////////////////////////////////////
-void RawRtcpPacket::WriteToByteBuffer(talk_base::ByteBuffer *buf) const {
+void RawRtcpPacket::WriteToByteBuffer(rtc::ByteBuffer *buf) const {
if (!buf) return;
buf->WriteUInt8(ver_to_count);
@@ -92,7 +93,7 @@
buf->WriteBytes(payload, sizeof(payload));
}
-bool RawRtcpPacket::ReadFromByteBuffer(talk_base::ByteBuffer* buf) {
+bool RawRtcpPacket::ReadFromByteBuffer(rtc::ByteBuffer* buf) {
if (!buf) return false;
bool ret = true;
@@ -128,7 +129,7 @@
};
size_t RtpTestUtility::GetTestPacketCount() {
- return talk_base::_min(
+ return rtc::_min(
ARRAY_SIZE(kTestRawRtpPackets),
ARRAY_SIZE(kTestRawRtcpPackets));
}
@@ -140,7 +141,7 @@
bool result = true;
uint32 elapsed_time_ms = 0;
for (size_t i = 0; i < count && result; ++i) {
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
if (rtcp) {
kTestRawRtcpPackets[i].WriteToByteBuffer(&buf);
} else {
@@ -149,13 +150,13 @@
RtpDumpPacket dump_packet(buf.Data(), buf.Length(), elapsed_time_ms, rtcp);
elapsed_time_ms += kElapsedTimeInterval;
- result &= (talk_base::SR_SUCCESS == writer->WritePacket(dump_packet));
+ result &= (rtc::SR_SUCCESS == writer->WritePacket(dump_packet));
}
return result;
}
bool RtpTestUtility::VerifyTestPacketsFromStream(
- size_t count, talk_base::StreamInterface* stream, uint32 ssrc) {
+ size_t count, rtc::StreamInterface* stream, uint32 ssrc) {
if (!stream) return false;
uint32 prev_elapsed_time = 0;
@@ -168,13 +169,13 @@
size_t index = i % GetTestPacketCount();
RtpDumpPacket packet;
- result &= (talk_base::SR_SUCCESS == reader.ReadPacket(&packet));
+ result &= (rtc::SR_SUCCESS == reader.ReadPacket(&packet));
// Check the elapsed time of the dump packet.
result &= (packet.elapsed_time >= prev_elapsed_time);
prev_elapsed_time = packet.elapsed_time;
// Check the RTP or RTCP packet.
- talk_base::ByteBuffer buf(reinterpret_cast<const char*>(&packet.data[0]),
+ rtc::ByteBuffer buf(reinterpret_cast<const char*>(&packet.data[0]),
packet.data.size());
if (packet.is_rtcp()) {
// RTCP packet.
@@ -204,7 +205,7 @@
bool header_only) {
if (!dump || !raw) return false;
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
raw->WriteToByteBuffer(RtpTestUtility::kDefaultSsrc, &buf);
if (header_only) {
@@ -255,10 +256,15 @@
// Returns the absolute path to a file in the testdata/ directory.
std::string GetTestFilePath(const std::string& filename) {
// Locate test data directory.
- talk_base::Pathname path = testing::GetTalkDirectory();
+#ifdef ENABLE_WEBRTC
+ rtc::Pathname path = rtc::GetExecutablePath();
+ EXPECT_FALSE(path.empty());
+ path.AppendPathname("../../talk/");
+#else
+ rtc::Pathname path = testing::GetTalkDirectory();
EXPECT_FALSE(path.empty()); // must be run from inside "talk"
- path.AppendFolder("media");
- path.AppendFolder("testdata");
+#endif
+ path.AppendFolder("media/testdata/");
path.SetFilename(filename);
return path.pathname();
}
@@ -269,25 +275,25 @@
std::stringstream ss;
ss << prefix << "." << width << "x" << height << "_P420.yuv";
- talk_base::scoped_ptr<talk_base::FileStream> stream(
- talk_base::Filesystem::OpenFile(talk_base::Pathname(
+ rtc::scoped_ptr<rtc::FileStream> stream(
+ rtc::Filesystem::OpenFile(rtc::Pathname(
GetTestFilePath(ss.str())), "rb"));
if (!stream) {
return false;
}
- talk_base::StreamResult res =
+ rtc::StreamResult res =
stream->ReadAll(out, I420_SIZE(width, height), NULL, NULL);
- return (res == talk_base::SR_SUCCESS);
+ return (res == rtc::SR_SUCCESS);
}
// Dumps the YUV image out to a file, for visual inspection.
// PYUV tool can be used to view dump files.
void DumpPlanarYuvTestImage(const std::string& prefix, const uint8* img,
int w, int h) {
- talk_base::FileStream fs;
+ rtc::FileStream fs;
char filename[256];
- talk_base::sprintfn(filename, sizeof(filename), "%s.%dx%d_P420.yuv",
+ rtc::sprintfn(filename, sizeof(filename), "%s.%dx%d_P420.yuv",
prefix.c_str(), w, h);
fs.Open(filename, "wb", NULL);
fs.Write(img, I420_SIZE(w, h), NULL, NULL);
@@ -297,9 +303,9 @@
// ffplay tool can be used to view dump files.
void DumpPlanarArgbTestImage(const std::string& prefix, const uint8* img,
int w, int h) {
- talk_base::FileStream fs;
+ rtc::FileStream fs;
char filename[256];
- talk_base::sprintfn(filename, sizeof(filename), "%s.%dx%d_ARGB.raw",
+ rtc::sprintfn(filename, sizeof(filename), "%s.%dx%d_ARGB.raw",
prefix.c_str(), w, h);
fs.Open(filename, "wb", NULL);
fs.Write(img, ARGB_SIZE(w, h), NULL, NULL);
diff --git a/media/base/testutils.h b/media/base/testutils.h
index dd13d5a..f5a460f 100644
--- a/media/base/testutils.h
+++ b/media/base/testutils.h
@@ -34,14 +34,14 @@
#if !defined(DISABLE_YUV)
#include "libyuv/compare.h"
#endif
-#include "talk/base/basictypes.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/window.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/window.h"
-namespace talk_base {
+namespace rtc {
class ByteBuffer;
class StreamInterface;
}
@@ -63,8 +63,8 @@
class VideoFrame;
struct RawRtpPacket {
- void WriteToByteBuffer(uint32 in_ssrc, talk_base::ByteBuffer* buf) const;
- bool ReadFromByteBuffer(talk_base::ByteBuffer* buf);
+ void WriteToByteBuffer(uint32 in_ssrc, rtc::ByteBuffer* buf) const;
+ bool ReadFromByteBuffer(rtc::ByteBuffer* buf);
// Check if this packet is the same as the specified packet except the
// sequence number and timestamp, which should be the same as the specified
// parameters.
@@ -81,8 +81,8 @@
};
struct RawRtcpPacket {
- void WriteToByteBuffer(talk_base::ByteBuffer* buf) const;
- bool ReadFromByteBuffer(talk_base::ByteBuffer* buf);
+ void WriteToByteBuffer(rtc::ByteBuffer* buf) const;
+ bool ReadFromByteBuffer(rtc::ByteBuffer* buf);
bool EqualsTo(const RawRtcpPacket& packet) const;
uint8 ver_to_count;
@@ -107,7 +107,7 @@
// payload. If the stream is a RTCP stream, verify the RTCP header and
// payload.
static bool VerifyTestPacketsFromStream(
- size_t count, talk_base::StreamInterface* stream, uint32 ssrc);
+ size_t count, rtc::StreamInterface* stream, uint32 ssrc);
// Verify the dump packet is the same as the raw RTP packet.
static bool VerifyPacket(const RtpDumpPacket* dump,
@@ -153,16 +153,16 @@
class ScreencastEventCatcher : public sigslot::has_slots<> {
public:
- ScreencastEventCatcher() : ssrc_(0), ev_(talk_base::WE_RESIZE) { }
+ ScreencastEventCatcher() : ssrc_(0), ev_(rtc::WE_RESIZE) { }
uint32 ssrc() const { return ssrc_; }
- talk_base::WindowEvent event() const { return ev_; }
- void OnEvent(uint32 ssrc, talk_base::WindowEvent ev) {
+ rtc::WindowEvent event() const { return ev_; }
+ void OnEvent(uint32 ssrc, rtc::WindowEvent ev) {
ssrc_ = ssrc;
ev_ = ev;
}
private:
uint32 ssrc_;
- talk_base::WindowEvent ev_;
+ rtc::WindowEvent ev_;
};
class VideoMediaErrorCatcher : public sigslot::has_slots<> {
diff --git a/media/base/videoadapter.cc b/media/base/videoadapter.cc
index 76ec527..f8dcd38 100644
--- a/media/base/videoadapter.cc
+++ b/media/base/videoadapter.cc
@@ -27,11 +27,11 @@
#include <limits.h> // For INT_MAX
-#include "talk/base/logging.h"
-#include "talk/base/timeutils.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/timeutils.h"
namespace cricket {
@@ -178,10 +178,10 @@
}
void VideoAdapter::SetInputFormat(const VideoFormat& format) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
int64 old_input_interval = input_format_.interval;
input_format_ = format;
- output_format_.interval = talk_base::_max(
+ output_format_.interval = rtc::_max(
output_format_.interval, input_format_.interval);
if (old_input_interval != input_format_.interval) {
LOG(LS_INFO) << "VAdapt input interval changed from "
@@ -219,11 +219,11 @@
}
void VideoAdapter::SetOutputFormat(const VideoFormat& format) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
int64 old_output_interval = output_format_.interval;
output_format_ = format;
output_num_pixels_ = output_format_.width * output_format_.height;
- output_format_.interval = talk_base::_max(
+ output_format_.interval = rtc::_max(
output_format_.interval, input_format_.interval);
if (old_output_interval != output_format_.interval) {
LOG(LS_INFO) << "VAdapt output interval changed from "
@@ -232,7 +232,7 @@
}
const VideoFormat& VideoAdapter::input_format() {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
return input_format_;
}
@@ -241,12 +241,12 @@
}
const VideoFormat& VideoAdapter::output_format() {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
return output_format_;
}
void VideoAdapter::SetBlackOutput(bool black) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
black_output_ = black;
}
@@ -263,7 +263,7 @@
// not resolution.
bool VideoAdapter::AdaptFrame(VideoFrame* in_frame,
VideoFrame** out_frame) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
if (!in_frame || !out_frame) {
return false;
}
@@ -489,7 +489,7 @@
// A remote view request for a new resolution.
void CoordinatedVideoAdapter::OnOutputFormatRequest(const VideoFormat& format) {
- talk_base::CritScope cs(&request_critical_section_);
+ rtc::CritScope cs(&request_critical_section_);
if (!view_adaptation_) {
return;
}
@@ -553,7 +553,7 @@
// A Bandwidth GD request for new resolution
void CoordinatedVideoAdapter::OnEncoderResolutionRequest(
int width, int height, AdaptRequest request) {
- talk_base::CritScope cs(&request_critical_section_);
+ rtc::CritScope cs(&request_critical_section_);
if (!gd_adaptation_) {
return;
}
@@ -589,7 +589,7 @@
// A Bandwidth GD request for new resolution
void CoordinatedVideoAdapter::OnCpuResolutionRequest(AdaptRequest request) {
- talk_base::CritScope cs(&request_critical_section_);
+ rtc::CritScope cs(&request_critical_section_);
if (!cpu_adaptation_) {
return;
}
@@ -644,7 +644,7 @@
// TODO(fbarchard): Move outside adapter.
void CoordinatedVideoAdapter::OnCpuLoadUpdated(
int current_cpus, int max_cpus, float process_load, float system_load) {
- talk_base::CritScope cs(&request_critical_section_);
+ rtc::CritScope cs(&request_critical_section_);
if (!cpu_adaptation_) {
return;
}
diff --git a/media/base/videoadapter.h b/media/base/videoadapter.h
index 0634942..0a9e27e 100644
--- a/media/base/videoadapter.h
+++ b/media/base/videoadapter.h
@@ -26,11 +26,11 @@
#ifndef TALK_MEDIA_BASE_VIDEOADAPTER_H_ // NOLINT
#define TALK_MEDIA_BASE_VIDEOADAPTER_H_
-#include "talk/base/common.h" // For ASSERT
-#include "talk/base/criticalsection.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/common.h" // For ASSERT
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
@@ -72,6 +72,8 @@
void set_scale_third(bool enable);
bool scale_third() const { return scale_third_; }
+ int adaptation_changes() const { return adaption_changes_; }
+
protected:
float FindClosestScale(int width, int height, int target_num_pixels);
float FindClosestViewScale(int width, int height, int target_num_pixels);
@@ -97,9 +99,9 @@
bool black_output_; // Flag to tell if we need to black output_frame_.
bool is_black_; // Flag to tell if output_frame_ is currently black.
int64 interval_next_frame_;
- talk_base::scoped_ptr<VideoFrame> output_frame_;
+ rtc::scoped_ptr<VideoFrame> output_frame_;
// The critical section to protect the above variables.
- talk_base::CriticalSection critical_section_;
+ rtc::CriticalSection critical_section_;
DISALLOW_COPY_AND_ASSIGN(VideoAdapter);
};
@@ -204,7 +206,7 @@
int cpu_desired_num_pixels_;
CoordinatedVideoAdapter::AdaptReason adapt_reason_;
// The critical section to protect handling requests.
- talk_base::CriticalSection request_critical_section_;
+ rtc::CriticalSection request_critical_section_;
// The weighted average of cpu load over time. It's always updated (if cpu
// adaptation is on), but only used if cpu_smoothing_ is set.
diff --git a/media/base/videoadapter_unittest.cc b/media/base/videoadapter_unittest.cc
new file mode 100755
index 0000000..04bf3d1
--- /dev/null
+++ b/media/base/videoadapter_unittest.cc
@@ -0,0 +1,1346 @@
+/*
+ * libjingle
+ * Copyright 2010 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// If we don't have a WebRtcVideoFrame, just skip all of these tests.
+#if defined(HAVE_WEBRTC_VIDEO)
+#include <limits.h> // For INT_MAX
+#include <string>
+#include <vector>
+
+#include "talk/media/base/mediachannel.h"
+#include "talk/media/base/testutils.h"
+#include "talk/media/base/videoadapter.h"
+#include "talk/media/devices/filevideocapturer.h"
+#include "talk/media/webrtc/webrtcvideoframe.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/sigslot.h"
+
+namespace cricket {
+
+namespace {
+ static const uint32 kWaitTimeout = 3000U; // 3 seconds.
+ static const uint32 kShortWaitTimeout = 1000U; // 1 second.
+ void UpdateCpuLoad(CoordinatedVideoAdapter* adapter,
+ int current_cpus, int max_cpus, float process_load, float system_load) {
+ adapter->set_cpu_load_min_samples(1);
+ adapter->OnCpuLoadUpdated(current_cpus, max_cpus,
+ process_load, system_load);
+ }
+}
+
+class VideoAdapterTest : public testing::Test {
+ public:
+ virtual void SetUp() {
+ capturer_.reset(new FileVideoCapturer);
+ EXPECT_TRUE(capturer_->Init(GetTestFilePath(
+ "captured-320x240-2s-48.frames")));
+ capture_format_ = capturer_->GetSupportedFormats()->at(0);
+ capture_format_.interval = VideoFormat::FpsToInterval(50);
+ adapter_.reset(new VideoAdapter());
+ adapter_->SetInputFormat(capture_format_);
+
+ listener_.reset(new VideoCapturerListener(adapter_.get()));
+ capturer_->SignalFrameCaptured.connect(
+ listener_.get(), &VideoCapturerListener::OnFrameCaptured);
+ }
+
+ virtual void TearDown() {
+ // Explicitly disconnect the VideoCapturer before to avoid data races
+ // (frames delivered to VideoCapturerListener while it's being destructed).
+ capturer_->SignalFrameCaptured.disconnect_all();
+ }
+
+ protected:
+ class VideoCapturerListener: public sigslot::has_slots<> {
+ public:
+ struct Stats {
+ int captured_frames;
+ int dropped_frames;
+ bool last_adapt_was_no_op;
+
+ int adapted_width;
+ int adapted_height;
+ };
+
+ explicit VideoCapturerListener(VideoAdapter* adapter)
+ : video_adapter_(adapter),
+ adapted_frame_(NULL),
+ copied_output_frame_(),
+ captured_frames_(0),
+ dropped_frames_(0),
+ last_adapt_was_no_op_(false) {
+ }
+
+ void OnFrameCaptured(VideoCapturer* capturer,
+ const CapturedFrame* captured_frame) {
+ WebRtcVideoFrame temp_i420;
+ EXPECT_TRUE(temp_i420.Init(captured_frame,
+ captured_frame->width, abs(captured_frame->height)));
+ VideoFrame* out_frame = NULL;
+ rtc::CritScope lock(&crit_);
+ EXPECT_TRUE(video_adapter_->AdaptFrame(&temp_i420, &out_frame));
+ if (out_frame) {
+ if (out_frame == &temp_i420) {
+ last_adapt_was_no_op_ = true;
+ copied_output_frame_.reset(temp_i420.Copy());
+ adapted_frame_ = copied_output_frame_.get();
+ } else {
+ last_adapt_was_no_op_ = false;
+ adapted_frame_ = out_frame;
+ copied_output_frame_.reset();
+ }
+ } else {
+ ++dropped_frames_;
+ }
+ ++captured_frames_;
+ }
+
+ Stats GetStats() {
+ rtc::CritScope lock(&crit_);
+ Stats stats;
+ stats.captured_frames = captured_frames_;
+ stats.dropped_frames = dropped_frames_;
+ stats.last_adapt_was_no_op = last_adapt_was_no_op_;
+ if (adapted_frame_ != NULL) {
+ stats.adapted_width = static_cast<int>(adapted_frame_->GetWidth());
+ stats.adapted_height = static_cast<int>(adapted_frame_->GetHeight());
+ } else {
+ stats.adapted_width = stats.adapted_height = -1;
+ }
+
+ return stats;
+ }
+
+ VideoFrame* CopyAdaptedFrame() {
+ rtc::CritScope lock(&crit_);
+ if (adapted_frame_ == NULL) {
+ return NULL;
+ }
+ return adapted_frame_->Copy();
+ }
+
+ private:
+ rtc::CriticalSection crit_;
+ VideoAdapter* video_adapter_;
+ const VideoFrame* adapted_frame_;
+ rtc::scoped_ptr<VideoFrame> copied_output_frame_;
+ int captured_frames_;
+ int dropped_frames_;
+ bool last_adapt_was_no_op_;
+ };
+
+ class CpuAdapterListener: public sigslot::has_slots<> {
+ public:
+ CpuAdapterListener() : received_cpu_signal_(false) {}
+ void OnCpuAdaptationSignalled() { received_cpu_signal_ = true; }
+ bool received_cpu_signal() { return received_cpu_signal_; }
+ private:
+ bool received_cpu_signal_;
+ };
+
+ void VerifyAdaptedResolution(const VideoCapturerListener::Stats& stats,
+ int width,
+ int height) {
+ EXPECT_EQ(width, stats.adapted_width);
+ EXPECT_EQ(height, stats.adapted_height);
+ }
+
+ rtc::scoped_ptr<FileVideoCapturer> capturer_;
+ rtc::scoped_ptr<VideoAdapter> adapter_;
+ rtc::scoped_ptr<VideoCapturerListener> listener_;
+ VideoFormat capture_format_;
+};
+
+
+// Test adapter remembers exact pixel count
+TEST_F(VideoAdapterTest, AdaptNumPixels) {
+ adapter_->SetOutputNumPixels(123456);
+ EXPECT_EQ(123456, adapter_->GetOutputNumPixels());
+}
+
+// Test adapter is constructed but not activated. Expect no frame drop and no
+// resolution change.
+TEST_F(VideoAdapterTest, AdaptInactive) {
+ // Output resolution is not set.
+ EXPECT_EQ(INT_MAX, adapter_->GetOutputNumPixels());
+
+ // Call Adapter with some frames.
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify no frame drop and no resolution change.
+ VideoCapturerListener::Stats stats = listener_->GetStats();
+ EXPECT_GE(stats.captured_frames, 10);
+ EXPECT_EQ(0, stats.dropped_frames);
+ VerifyAdaptedResolution(stats, capture_format_.width, capture_format_.height);
+}
+
+// Do not adapt the frame rate or the resolution. Expect no frame drop and no
+// resolution change.
+TEST_F(VideoAdapterTest, AdaptNothing) {
+ adapter_->SetOutputFormat(capture_format_);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify no frame drop and no resolution change.
+ VideoCapturerListener::Stats stats = listener_->GetStats();
+ EXPECT_GE(stats.captured_frames, 10);
+ EXPECT_EQ(0, stats.dropped_frames);
+ VerifyAdaptedResolution(stats, capture_format_.width, capture_format_.height);
+ EXPECT_TRUE(stats.last_adapt_was_no_op);
+}
+
+TEST_F(VideoAdapterTest, AdaptZeroInterval) {
+ VideoFormat format = capturer_->GetSupportedFormats()->at(0);
+ format.interval = 0;
+ adapter_->SetInputFormat(format);
+ adapter_->SetOutputFormat(format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify no crash and that frames aren't dropped.
+ VideoCapturerListener::Stats stats = listener_->GetStats();
+ EXPECT_GE(stats.captured_frames, 10);
+ EXPECT_EQ(0, stats.dropped_frames);
+ VerifyAdaptedResolution(stats, capture_format_.width, capture_format_.height);
+}
+
+// Adapt the frame rate to be half of the capture rate at the beginning. Expect
+// the number of dropped frames to be half of the number the captured frames.
+TEST_F(VideoAdapterTest, AdaptFramerate) {
+ VideoFormat request_format = capture_format_;
+ request_format.interval *= 2;
+ adapter_->SetOutputFormat(request_format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify frame drop and no resolution change.
+ VideoCapturerListener::Stats stats = listener_->GetStats();
+ EXPECT_GE(stats.captured_frames, 10);
+ EXPECT_EQ(stats.captured_frames / 2, stats.dropped_frames);
+ VerifyAdaptedResolution(stats, capture_format_.width, capture_format_.height);
+}
+
+// Adapt the frame rate to be half of the capture rate at the beginning. Expect
+// the number of dropped frames to be half of the number the captured frames.
+TEST_F(VideoAdapterTest, AdaptFramerateVariable) {
+ VideoFormat request_format = capture_format_;
+ request_format.interval = request_format.interval * 3 / 2;
+ adapter_->SetOutputFormat(request_format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 30, kWaitTimeout);
+
+ // Verify frame drop and no resolution change.
+ VideoCapturerListener::Stats stats = listener_->GetStats();
+ EXPECT_GE(stats.captured_frames, 30);
+ // Verify 2 / 3 kept (20) and 1 / 3 dropped (10).
+ EXPECT_EQ(stats.captured_frames * 1 / 3, stats.dropped_frames);
+ VerifyAdaptedResolution(stats, capture_format_.width, capture_format_.height);
+}
+
+// Adapt the frame rate to be half of the capture rate after capturing no less
+// than 10 frames. Expect no frame dropped before adaptation and frame dropped
+// after adaptation.
+TEST_F(VideoAdapterTest, AdaptFramerateOntheFly) {
+ VideoFormat request_format = capture_format_;
+ adapter_->SetOutputFormat(request_format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify no frame drop before adaptation.
+ EXPECT_EQ(0, listener_->GetStats().dropped_frames);
+
+ // Adapat the frame rate.
+ request_format.interval *= 2;
+ adapter_->SetOutputFormat(request_format);
+
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 20, kWaitTimeout);
+
+ // Verify frame drop after adaptation.
+ EXPECT_GT(listener_->GetStats().dropped_frames, 0);
+}
+
+// Adapt the frame resolution to be a quarter of the capture resolution at the
+// beginning. Expect resolution change.
+TEST_F(VideoAdapterTest, AdaptResolution) {
+ VideoFormat request_format = capture_format_;
+ request_format.width /= 2;
+ request_format.height /= 2;
+ adapter_->SetOutputFormat(request_format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify no frame drop and resolution change.
+ VideoCapturerListener::Stats stats = listener_->GetStats();
+ EXPECT_EQ(0, stats.dropped_frames);
+ VerifyAdaptedResolution(stats, request_format.width, request_format.height);
+}
+
+// Adapt the frame resolution to half width. Expect resolution change.
+TEST_F(VideoAdapterTest, AdaptResolutionNarrow) {
+ VideoFormat request_format = capture_format_;
+ request_format.width /= 2;
+ adapter_->set_scale_third(true);
+ adapter_->SetOutputFormat(request_format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify resolution change.
+ VerifyAdaptedResolution(listener_->GetStats(), 213, 160);
+}
+
+// Adapt the frame resolution to half height. Expect resolution change.
+TEST_F(VideoAdapterTest, AdaptResolutionWide) {
+ VideoFormat request_format = capture_format_;
+ request_format.height /= 2;
+ adapter_->set_scale_third(true);
+ adapter_->SetOutputFormat(request_format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify resolution change.
+ VerifyAdaptedResolution(listener_->GetStats(), 213, 160);
+}
+
+// Adapt the frame resolution to be a quarter of the capture resolution after
+// capturing no less than 10 frames. Expect no resolution change before
+// adaptation and resolution change after adaptation.
+TEST_F(VideoAdapterTest, AdaptResolutionOnTheFly) {
+ VideoFormat request_format = capture_format_;
+ adapter_->SetOutputFormat(request_format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify no resolution change before adaptation.
+ VerifyAdaptedResolution(
+ listener_->GetStats(), request_format.width, request_format.height);
+
+ // Adapt the frame resolution.
+ request_format.width /= 2;
+ request_format.height /= 2;
+ adapter_->SetOutputFormat(request_format);
+ int captured_frames = listener_->GetStats().captured_frames;
+ EXPECT_TRUE_WAIT(
+ !capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= captured_frames + 10,
+ kWaitTimeout);
+
+ // Verify resolution change after adaptation.
+ VerifyAdaptedResolution(
+ listener_->GetStats(), request_format.width, request_format.height);
+}
+
+// Black the output frame.
+TEST_F(VideoAdapterTest, BlackOutput) {
+ adapter_->SetOutputFormat(capture_format_);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+ // Verify that the output frame is not black.
+ rtc::scoped_ptr<VideoFrame> adapted_frame(listener_->CopyAdaptedFrame());
+ EXPECT_NE(16, *adapted_frame->GetYPlane());
+ EXPECT_NE(128, *adapted_frame->GetUPlane());
+ EXPECT_NE(128, *adapted_frame->GetVPlane());
+
+ adapter_->SetBlackOutput(true);
+ int captured_frames = listener_->GetStats().captured_frames;
+ EXPECT_TRUE_WAIT(
+ !capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= captured_frames + 10,
+ kWaitTimeout);
+ // Verify that the output frame is black.
+ adapted_frame.reset(listener_->CopyAdaptedFrame());
+ EXPECT_EQ(16, *adapted_frame->GetYPlane());
+ EXPECT_EQ(128, *adapted_frame->GetUPlane());
+ EXPECT_EQ(128, *adapted_frame->GetVPlane());
+
+ // Verify that the elapsed time and timestamp of the black frame increase.
+ int64 elapsed_time = adapted_frame->GetElapsedTime();
+ int64 timestamp = adapted_frame->GetTimeStamp();
+ captured_frames = listener_->GetStats().captured_frames;
+ EXPECT_TRUE_WAIT(
+ !capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= captured_frames + 10,
+ kWaitTimeout);
+
+ adapted_frame.reset(listener_->CopyAdaptedFrame());
+ EXPECT_GT(adapted_frame->GetElapsedTime(), elapsed_time);
+ EXPECT_GT(adapted_frame->GetTimeStamp(), timestamp);
+
+ // Change the output size
+ VideoFormat request_format = capture_format_;
+ request_format.width /= 2;
+ request_format.height /= 2;
+ adapter_->SetOutputFormat(request_format);
+ captured_frames = listener_->GetStats().captured_frames;
+ EXPECT_TRUE_WAIT(
+ !capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= captured_frames + 10,
+ kWaitTimeout);
+
+ // Verify resolution change after adaptation.
+ VerifyAdaptedResolution(
+ listener_->GetStats(), request_format.width, request_format.height);
+ // Verify that the output frame is black.
+ adapted_frame.reset(listener_->CopyAdaptedFrame());
+ EXPECT_EQ(16, *adapted_frame->GetYPlane());
+ EXPECT_EQ(128, *adapted_frame->GetUPlane());
+ EXPECT_EQ(128, *adapted_frame->GetVPlane());
+}
+
+// Drop all frames.
+TEST_F(VideoAdapterTest, DropAllFrames) {
+ VideoFormat format; // with resolution 0x0.
+ adapter_->SetOutputFormat(format);
+ EXPECT_EQ(CS_RUNNING, capturer_->Start(capture_format_));
+ EXPECT_TRUE_WAIT(!capturer_->IsRunning() ||
+ listener_->GetStats().captured_frames >= 10, kWaitTimeout);
+
+ // Verify all frames are dropped.
+ VideoCapturerListener::Stats stats = listener_->GetStats();
+ EXPECT_GE(stats.captured_frames, 10);
+ EXPECT_EQ(stats.captured_frames, stats.dropped_frames);
+}
+
+TEST(CoordinatedVideoAdapterTest, TestCoordinatedWithoutCpuAdaptation) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(false);
+
+ VideoFormat format(640, 400, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ adapter.set_scale_third(true);
+ EXPECT_EQ(format, adapter.input_format());
+ EXPECT_TRUE(adapter.output_format().IsSize0x0());
+
+ // Server format request 640x400.
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Server format request 1280x720, higher than input. Adapt nothing.
+ format.width = 1280;
+ format.height = 720;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Cpu load is high, but cpu adaptation is disabled. Adapt nothing.
+ adapter.OnCpuLoadUpdated(1, 1, 0.99f, 0.99f);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Encoder resolution request: downgrade with different size. Adapt nothing.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Encoder resolution request: downgrade.
+ adapter.OnEncoderResolutionRequest(640, 400,
+ CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Encoder resolution request: downgrade. But GD off. Adapt nothing.
+ adapter.set_gd_adaptation(false);
+ adapter.OnEncoderResolutionRequest(480, 300,
+ CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+ adapter.set_gd_adaptation(true);
+
+ // Encoder resolution request: downgrade.
+ adapter.OnEncoderResolutionRequest(480, 300,
+ CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Encoder resolution request: keep. Adapt nothing.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::KEEP);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Encoder resolution request: upgrade.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Server format request 0x0.
+ format.width = 0;
+ format.height = 0;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_TRUE(adapter.output_format().IsSize0x0());
+
+ // Server format request 320x200.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Server format request 160x100. But view disabled. Adapt nothing.
+ adapter.set_view_adaptation(false);
+ format.width = 160;
+ format.height = 100;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+ adapter.set_view_adaptation(true);
+
+ // Enable View Switch. Expect adapt down.
+ adapter.set_view_switch(true);
+ format.width = 160;
+ format.height = 100;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(160, adapter.output_format().width);
+ EXPECT_EQ(100, adapter.output_format().height);
+
+ // Encoder resolution request: upgrade. Adapt nothing.
+ adapter.OnEncoderResolutionRequest(160, 100,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(160, adapter.output_format().width);
+ EXPECT_EQ(100, adapter.output_format().height);
+
+ // Request View of 2 / 3. Expect adapt down.
+ adapter.set_view_switch(true);
+ format.width = (640 * 2 + 1) / 3;
+ format.height = (400 * 2 + 1) / 3;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ((640 * 2 + 1) / 3, adapter.output_format().width);
+ EXPECT_EQ((400 * 2 + 1) / 3, adapter.output_format().height);
+
+
+ // Request View of 3 / 8. Expect adapt down.
+ adapter.set_view_switch(true);
+ format.width = 640 * 3 / 8;
+ format.height = 400 * 3 / 8;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640 * 3 / 8, adapter.output_format().width);
+ EXPECT_EQ(400 * 3 / 8, adapter.output_format().height);
+
+ // View Switch back up. Expect adapt.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ adapter.set_view_switch(false);
+
+ // Encoder resolution request: upgrade. Constrained by server request.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Server format request 480x300.
+ format.width = 480;
+ format.height = 300;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+}
+
+TEST(CoordinatedVideoAdapterTest, TestCoordinatedWithCpuAdaptation) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(true);
+ EXPECT_FALSE(adapter.cpu_smoothing());
+ VideoFormat format(640, 400, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+
+ // Server format request 640x400.
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Process load is medium, but system load is high. Downgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.55f, 0.98f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // CPU high, but cpu adaptation disabled. Adapt nothing.
+ adapter.set_cpu_adaptation(false);
+ adapter.OnCpuLoadUpdated(1, 1, 0.55f, 0.98f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+ adapter.set_cpu_adaptation(true);
+
+ // System load is high, but time has not elaspsed. Adapt nothing.
+ adapter.set_cpu_load_min_samples(2);
+ adapter.OnCpuLoadUpdated(1, 1, 0.55f, 0.98f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Process load is medium, but system load is high. Downgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.55f, 0.98f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is CPU.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_CPU,
+ adapter.adapt_reason());
+
+ // Server format request 320x200. Same as CPU. Do nothing.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is CPU and VIEW.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_CPU +
+ CoordinatedVideoAdapter::ADAPTREASON_VIEW,
+ adapter.adapt_reason());
+
+ // Process load and system load are normal. Adapt nothing.
+ UpdateCpuLoad(&adapter, 1, 1, 0.5f, 0.8f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Process load and system load are low, but view is still low. Adapt nothing.
+ UpdateCpuLoad(&adapter, 1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is VIEW.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_VIEW,
+ adapter.adapt_reason());
+
+ // Server format request 640x400. Cpu is still low. Upgrade.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Test reason for adapting is CPU.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_CPU,
+ adapter.adapt_reason());
+
+ // Encoder resolution request: downgrade.
+ adapter.OnEncoderResolutionRequest(480, 300,
+ CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is BANDWIDTH.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_BANDWIDTH,
+ adapter.adapt_reason());
+
+ // Process load and system load are low. Constrained by GD. Adapt nothing
+ adapter.OnCpuLoadUpdated(1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Encoder resolution request: upgrade.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Encoder resolution request: upgrade. Constrained by CPU.
+ adapter.OnEncoderResolutionRequest(480, 300,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Server format request 640x400. Constrained by CPU.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+}
+
+TEST(CoordinatedVideoAdapterTest, TestCoordinatedWithCpuRequest) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(true);
+ EXPECT_FALSE(adapter.cpu_smoothing());
+ VideoFormat format(640, 400, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+
+ // Server format request 640x400.
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // CPU resolution request: downgrade. Adapt down.
+ adapter.OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // CPU resolution request: keep. Do nothing.
+ adapter.OnCpuResolutionRequest(CoordinatedVideoAdapter::KEEP);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // CPU resolution request: downgrade, but cpu adaptation disabled.
+ // Adapt nothing.
+ adapter.set_cpu_adaptation(false);
+ adapter.OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // CPU resolution request: downgrade. Adapt down.
+ adapter.set_cpu_adaptation(true);
+ adapter.OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is CPU.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_CPU,
+ adapter.adapt_reason());
+
+ // CPU resolution request: downgrade, but already at minimum. Do nothing.
+ adapter.OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Server format request 320x200. Same as CPU. Do nothing.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is CPU and VIEW.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_CPU +
+ CoordinatedVideoAdapter::ADAPTREASON_VIEW,
+ adapter.adapt_reason());
+
+ // CPU resolution request: upgrade, but view request still low. Do nothing.
+ adapter.OnCpuResolutionRequest(CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is VIEW.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_VIEW,
+ adapter.adapt_reason());
+
+ // Server format request 640x400. Cpu is still low. Upgrade.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Test reason for adapting is CPU.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_CPU,
+ adapter.adapt_reason());
+
+ // Encoder resolution request: downgrade.
+ adapter.OnEncoderResolutionRequest(480, 300,
+ CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Test reason for adapting is BANDWIDTH.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_BANDWIDTH,
+ adapter.adapt_reason());
+
+ // Process load and system load are low. Constrained by GD. Adapt nothing
+ adapter.OnCpuLoadUpdated(1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Encoder resolution request: upgrade.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Encoder resolution request: upgrade. Constrained by CPU.
+ adapter.OnEncoderResolutionRequest(480, 300,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Server format request 640x400. Constrained by CPU.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+}
+
+TEST(CoordinatedVideoAdapterTest, TestViewRequestPlusCameraSwitch) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_view_switch(true);
+
+ // Start at HD.
+ VideoFormat format(1280, 720, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ EXPECT_EQ(format, adapter.input_format());
+ EXPECT_TRUE(adapter.output_format().IsSize0x0());
+
+ // View request for VGA.
+ format.width = 640;
+ format.height = 360;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(360, adapter.output_format().height);
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_VIEW, adapter.adapt_reason());
+
+ // Now, the camera reopens at VGA.
+ // Both the frame and the output format should be 640x360.
+ WebRtcVideoFrame in_frame;
+ in_frame.InitToBlack(640, 360, 1, 1, 33, 33);
+ VideoFrame* out_frame;
+ adapter.AdaptFrame(&in_frame, &out_frame);
+ EXPECT_EQ(640u, out_frame->GetWidth());
+ EXPECT_EQ(360u, out_frame->GetHeight());
+ // At this point, the view is no longer adapted, since the input has resized
+ // small enough to fit the last view request.
+ EXPECT_EQ(0, adapter.adapt_reason());
+
+ // And another view request comes in for 640x360, which should have no
+ // real impact.
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(360, adapter.output_format().height);
+ EXPECT_EQ(0, adapter.adapt_reason());
+}
+
+TEST(CoordinatedVideoAdapterTest, TestVGAWidth) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_view_switch(true);
+
+ // Start at 640x480, for cameras that don't support 640x360.
+ VideoFormat format(640, 480, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ EXPECT_EQ(format, adapter.input_format());
+ EXPECT_TRUE(adapter.output_format().IsSize0x0());
+
+ // Output format is 640x360, though.
+ format.width = 640;
+ format.height = 360;
+ adapter.SetOutputFormat(format);
+
+ // And also a view request comes for 640x360.
+ adapter.OnOutputFormatRequest(format);
+ // At this point, we have to adapt down to something lower.
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(360, adapter.output_format().height);
+
+ // But if frames come in at 640x360, we shouldn't adapt them down.
+ // Fake a 640x360 frame.
+ WebRtcVideoFrame in_frame;
+ in_frame.InitToBlack(640, 360, 1, 1, 33, 33);
+ VideoFrame* out_frame;
+ adapter.AdaptFrame(&in_frame, &out_frame);
+
+ EXPECT_EQ(640u, out_frame->GetWidth());
+ EXPECT_EQ(360u, out_frame->GetHeight());
+
+ // Similarly, no-op adapt requests for other reasons shouldn't change
+ // adaptation state (before a previous bug, the previous EXPECTs would
+ // fail and the following would succeed, as the no-op CPU request would
+ // fix the adaptation state).
+ adapter.set_cpu_adaptation(true);
+ UpdateCpuLoad(&adapter, 1, 1, 0.7f, 0.7f);
+ adapter.AdaptFrame(&in_frame, &out_frame);
+
+ EXPECT_EQ(640u, out_frame->GetWidth());
+ EXPECT_EQ(360u, out_frame->GetHeight());
+}
+
+// When adapting resolution for CPU or GD, the quantity of pixels that the
+// request is based on is reduced to half or double, and then an actual
+// resolution is snapped to, rounding to the closest actual resolution.
+// This works well for some tolerance to 3/4, odd widths and aspect ratios
+// that dont exactly match, but is not best behavior for ViewRequests which
+// need to be be strictly respected to avoid going over the resolution budget
+// given to the codec - 854x480 total pixels.
+// ViewRequest must find a lower resolution.
+TEST(CoordinatedVideoAdapterTest, TestCoordinatedViewRequestDown) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(false);
+
+ VideoFormat format(960, 540, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ adapter.set_scale_third(true);
+ EXPECT_EQ(format, adapter.input_format());
+ EXPECT_TRUE(adapter.output_format().IsSize0x0());
+
+ // Server format request 640x400. Expect HVGA.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(360, adapter.output_format().height);
+
+ // Test reason for adapting is VIEW.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_VIEW, adapter.adapt_reason());
+}
+
+// Test that we downgrade video for cpu up to two times.
+TEST(CoordinatedVideoAdapterTest, TestCpuDowngradeTimes) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(true);
+ EXPECT_FALSE(adapter.cpu_smoothing());
+ VideoFormat format(640, 400, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+
+ // Server format request 640x400.
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Process load and system load are low. Do not change the cpu desired format
+ // and do not adapt.
+ adapter.OnCpuLoadUpdated(1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // System load is high. Downgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // System load is high. Downgrade again.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // System load is still high. Do not downgrade any more.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Process load and system load are low. Upgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // System load is high. Downgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // System load is still high. Do not downgrade any more.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+}
+
+// Test that we respect CPU adapter threshold values.
+TEST(CoordinatedVideoAdapterTest, TestAdapterCpuThreshold) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(true);
+ EXPECT_FALSE(adapter.cpu_smoothing());
+ VideoFormat format(640, 400, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+
+ // Server format request 640x400.
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Process load and system load are low. Do not change the cpu desired format
+ // and do not adapt.
+ adapter.OnCpuLoadUpdated(1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // System load is high. Downgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Test reason for adapting is CPU.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_CPU, adapter.adapt_reason());
+
+ // System load is high. Normally downgrade but threshold is high. Do nothing.
+ adapter.set_high_system_threshold(0.98f); // Set threshold high.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // System load is medium. Normally do nothing, threshold is low. Adapt down.
+ adapter.set_high_system_threshold(0.75f); // Set threshold low.
+ UpdateCpuLoad(&adapter, 1, 1, 0.8f, 0.8f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+}
+
+
+// Test that for an upgrade cpu request, we actually upgrade the desired format;
+// for a downgrade request, we downgrade from the output format.
+TEST(CoordinatedVideoAdapterTest, TestRealCpuUpgrade) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(true);
+ adapter.set_cpu_smoothing(true);
+ VideoFormat format(640, 400, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+
+ // Server format request 640x400.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Process load and system load are low. Do not change the cpu desired format
+ // and do not adapt.
+ UpdateCpuLoad(&adapter, 1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Server format request 320x200.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Process load and system load are low. Do not change the cpu desired format
+ // and do not adapt.
+ UpdateCpuLoad(&adapter, 1, 1, 0.2f, 0.3f);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Server format request 640x400. Set to 640x400 immediately.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Server format request 320x200.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Process load is high, but system is not. Do not change the cpu desired
+ // format and do not adapt.
+ for (size_t i = 0; i < 10; ++i) {
+ UpdateCpuLoad(&adapter, 1, 1, 0.75f, 0.8f);
+ }
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+}
+
+// Test that for an upgrade encoder request, we actually upgrade the desired
+// format; for a downgrade request, we downgrade from the output format.
+TEST(CoordinatedVideoAdapterTest, TestRealEncoderUpgrade) {
+ CoordinatedVideoAdapter adapter;
+ adapter.set_cpu_adaptation(true);
+ adapter.set_cpu_smoothing(true);
+ VideoFormat format(640, 400, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+
+ // Server format request 640x400.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Encoder resolution request. Do not change the encoder desired format and
+ // do not adapt.
+ adapter.OnEncoderResolutionRequest(640, 400,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(400, adapter.output_format().height);
+
+ // Server format request 320x200.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Encoder resolution request. Do not change the encoder desired format and
+ // do not adapt.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::UPGRADE);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Server format request 640x400. Set to 640x400 immediately.
+ format.width = 640;
+ format.height = 400;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(300, adapter.output_format().height);
+
+ // Test reason for adapting is BANDWIDTH.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_BANDWIDTH,
+ adapter.adapt_reason());
+
+ // Server format request 320x200.
+ format.width = 320;
+ format.height = 200;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(200, adapter.output_format().height);
+
+ // Encoder resolution request. Downgrade from 320x200.
+ adapter.OnEncoderResolutionRequest(320, 200,
+ CoordinatedVideoAdapter::DOWNGRADE);
+ EXPECT_EQ(240, adapter.output_format().width);
+ EXPECT_EQ(150, adapter.output_format().height);
+}
+
+TEST(CoordinatedVideoAdapterTest, TestNormalizeOutputFormat) {
+ CoordinatedVideoAdapter adapter;
+ // The input format is 640x360 and the output is limited to 16:9.
+ VideoFormat format(640, 360, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+
+ format.width = 320;
+ format.height = 180;
+ format.interval = VideoFormat::FpsToInterval(15);
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(180, adapter.output_format().height);
+ EXPECT_EQ(VideoFormat::FpsToInterval(15), adapter.output_format().interval);
+
+ format.width = 320;
+ format.height = 200;
+ format.interval = VideoFormat::FpsToInterval(40);
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(180, adapter.output_format().height);
+ EXPECT_EQ(VideoFormat::FpsToInterval(30), adapter.output_format().interval);
+
+ // Test reason for adapting is VIEW. Should work even with normalization.
+ EXPECT_EQ(CoordinatedVideoAdapter::ADAPTREASON_VIEW,
+ adapter.adapt_reason());
+
+ format.width = 320;
+ format.height = 240;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(180, adapter.output_format().height);
+
+ // The input format is 640x480 and the output will be 4:3.
+ format.width = 640;
+ format.height = 480;
+ adapter.SetInputFormat(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(240, adapter.output_format().height);
+
+ format.width = 320;
+ format.height = 240;
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(240, adapter.output_format().height);
+
+ // The input format is initialized after the output. At that time, the output
+ // height is adjusted.
+ format.width = 0;
+ format.height = 0;
+ adapter.SetInputFormat(format);
+
+ format.width = 320;
+ format.height = 240;
+ format.interval = VideoFormat::FpsToInterval(30);
+ adapter.OnOutputFormatRequest(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(240, adapter.output_format().height);
+ EXPECT_EQ(VideoFormat::FpsToInterval(30), adapter.output_format().interval);
+
+ format.width = 640;
+ format.height = 480;
+ format.interval = VideoFormat::FpsToInterval(15);
+ adapter.SetInputFormat(format);
+ EXPECT_EQ(320, adapter.output_format().width);
+ EXPECT_EQ(240, adapter.output_format().height);
+ EXPECT_EQ(VideoFormat::FpsToInterval(15), adapter.output_format().interval);
+}
+
+// Test that we downgrade video for cpu up to two times.
+TEST_F(VideoAdapterTest, CpuDowngradeAndSignal) {
+ CoordinatedVideoAdapter adapter;
+ CpuAdapterListener cpu_listener;
+ adapter.SignalCpuAdaptationUnable.connect(
+ &cpu_listener, &CpuAdapterListener::OnCpuAdaptationSignalled);
+
+ adapter.set_cpu_adaptation(true);
+ EXPECT_FALSE(adapter.cpu_smoothing());
+ VideoFormat format(640, 360, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ adapter.OnOutputFormatRequest(format);
+
+ // System load is high. Downgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+
+ // System load is high. Downgrade again.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+
+ // System load is still high. Do not downgrade any more. Ensure we have not
+ // signalled until after the cpu warning though.
+ EXPECT_TRUE(!cpu_listener.received_cpu_signal());
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ EXPECT_TRUE_WAIT(cpu_listener.received_cpu_signal(), kWaitTimeout);
+}
+
+// Test that we downgrade video for cpu up to two times.
+TEST_F(VideoAdapterTest, CpuDowngradeAndDontSignal) {
+ CoordinatedVideoAdapter adapter;
+ CpuAdapterListener cpu_listener;
+ adapter.SignalCpuAdaptationUnable.connect(
+ &cpu_listener, &CpuAdapterListener::OnCpuAdaptationSignalled);
+
+ adapter.set_cpu_adaptation(true);
+ adapter.set_cpu_smoothing(true);
+ VideoFormat format(640, 360, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ adapter.OnOutputFormatRequest(format);
+
+ // System load is high. Downgrade.
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+
+ // System load is high, process is not, Do not downgrade again.
+ UpdateCpuLoad(&adapter, 1, 1, 0.25f, 0.95f);
+
+ // System load is high, process is not, Do not downgrade again and do not
+ // signal.
+ adapter.set_cpu_adaptation(false);
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ rtc::Thread::Current()->ProcessMessages(kShortWaitTimeout);
+ EXPECT_TRUE(!cpu_listener.received_cpu_signal());
+ adapter.set_cpu_adaptation(true);
+}
+
+// Test that we require enough time before we downgrade.
+TEST_F(VideoAdapterTest, CpuMinTimeRequirement) {
+ CoordinatedVideoAdapter adapter;
+ CpuAdapterListener cpu_listener;
+ adapter.SignalCpuAdaptationUnable.connect(
+ &cpu_listener, &CpuAdapterListener::OnCpuAdaptationSignalled);
+
+ adapter.set_cpu_adaptation(true);
+ adapter.set_cpu_smoothing(true);
+ VideoFormat format(640, 360, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ adapter.OnOutputFormatRequest(format);
+
+ EXPECT_EQ(3, adapter.cpu_load_min_samples());
+ adapter.set_cpu_load_min_samples(5);
+
+ for (size_t i = 0; i < 4; ++i) {
+ adapter.OnCpuLoadUpdated(1, 1, 1.0f, 1.0f);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(360, adapter.output_format().height);
+ }
+ // The computed cpu load should now be around 93.5%, with the coefficient of
+ // 0.4 and a seed value of 0.5. That should be high enough to adapt, but it
+ // isn't enough samples, so we shouldn't have adapted on any of the previous
+ // samples.
+
+ // One more sample is enough, though, once enough time has passed.
+ adapter.OnCpuLoadUpdated(1, 1, 1.0f, 1.0f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(270, adapter.output_format().height);
+
+ // Now the cpu is lower, but we still need enough samples to upgrade.
+ for (size_t i = 0; i < 4; ++i) {
+ adapter.OnCpuLoadUpdated(1, 1, 0.1f, 0.1f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(270, adapter.output_format().height);
+ }
+
+ // One more sample is enough, once time has elapsed.
+ adapter.OnCpuLoadUpdated(1, 1, 1.0f, 1.0f);
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(360, adapter.output_format().height);
+}
+
+TEST_F(VideoAdapterTest, CpuIgnoresSpikes) {
+ CoordinatedVideoAdapter adapter;
+ CpuAdapterListener cpu_listener;
+ adapter.SignalCpuAdaptationUnable.connect(
+ &cpu_listener, &CpuAdapterListener::OnCpuAdaptationSignalled);
+
+ adapter.set_cpu_adaptation(true);
+ adapter.set_cpu_smoothing(true);
+ VideoFormat format(640, 360, VideoFormat::FpsToInterval(30), FOURCC_I420);
+ adapter.SetInputFormat(format);
+ adapter.OnOutputFormatRequest(format);
+
+ // System load is high. Downgrade.
+ for (size_t i = 0; i < 5; ++i) {
+ UpdateCpuLoad(&adapter, 1, 1, 0.95f, 0.95f);
+ }
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(270, adapter.output_format().height);
+
+ // Now we're in a state where we could upgrade or downgrade, so get to a
+ // steady state of about 75% cpu usage.
+ for (size_t i = 0; i < 5; ++i) {
+ UpdateCpuLoad(&adapter, 1, 1, 0.75f, 0.75f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(270, adapter.output_format().height);
+ }
+
+ // Now, the cpu spikes for two samples, but then goes back to
+ // normal. This shouldn't cause adaptation.
+ UpdateCpuLoad(&adapter, 1, 1, 0.90f, 0.90f);
+ UpdateCpuLoad(&adapter, 1, 1, 0.90f, 0.90f);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(270, adapter.output_format().height);
+ // Back to the steady state for awhile.
+ for (size_t i = 0; i < 5; ++i) {
+ UpdateCpuLoad(&adapter, 1, 1, 0.75, 0.75);
+ EXPECT_EQ(480, adapter.output_format().width);
+ EXPECT_EQ(270, adapter.output_format().height);
+ }
+
+ // Now, system cpu usage is starting to drop down. But it takes a bit before
+ // it gets all the way there.
+ for (size_t i = 0; i < 10; ++i) {
+ UpdateCpuLoad(&adapter, 1, 1, 0.5f, 0.5f);
+ }
+ EXPECT_EQ(640, adapter.output_format().width);
+ EXPECT_EQ(360, adapter.output_format().height);
+}
+
+} // namespace cricket
+#endif // HAVE_WEBRTC_VIDEO
diff --git a/media/base/videocapturer.cc b/media/base/videocapturer.cc
index 59860a4..c722012 100644
--- a/media/base/videocapturer.cc
+++ b/media/base/videocapturer.cc
@@ -32,16 +32,17 @@
#if !defined(DISABLE_YUV)
#include "libyuv/scale_argb.h"
#endif
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/systeminfo.h"
+#include "talk/media/base/videoframefactory.h"
#include "talk/media/base/videoprocessor.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/systeminfo.h"
#if defined(HAVE_WEBRTC_VIDEO)
#include "talk/media/webrtc/webrtcvideoframe.h"
+#include "talk/media/webrtc/webrtcvideoframefactory.h"
#endif // HAVE_WEBRTC_VIDEO
-
namespace cricket {
namespace {
@@ -63,7 +64,7 @@
static const int kYU12Penalty = 16; // Needs to be higher than MJPG index.
#endif
static const int kDefaultScreencastFps = 5;
-typedef talk_base::TypedMessageData<CaptureState> StateChangeParams;
+typedef rtc::TypedMessageData<CaptureState> StateChangeParams;
// Limit stats data collections to ~20 seconds of 30fps data before dropping
// old data in case stats aren't reset for long periods of time.
@@ -99,14 +100,14 @@
// Implementation of class VideoCapturer
/////////////////////////////////////////////////////////////////////
VideoCapturer::VideoCapturer()
- : thread_(talk_base::Thread::Current()),
+ : thread_(rtc::Thread::Current()),
adapt_frame_drops_data_(kMaxAccumulatorSize),
effect_frame_drops_data_(kMaxAccumulatorSize),
frame_time_data_(kMaxAccumulatorSize) {
Construct();
}
-VideoCapturer::VideoCapturer(talk_base::Thread* thread)
+VideoCapturer::VideoCapturer(rtc::Thread* thread)
: thread_(thread),
adapt_frame_drops_data_(kMaxAccumulatorSize),
effect_frame_drops_data_(kMaxAccumulatorSize),
@@ -129,6 +130,14 @@
adapt_frame_drops_ = 0;
effect_frame_drops_ = 0;
previous_frame_time_ = 0.0;
+#ifdef HAVE_WEBRTC_VIDEO
+ // There are lots of video capturers out there that don't call
+ // set_frame_factory. We can either go change all of them, or we
+ // can set this default.
+ // TODO(pthatcher): Remove this hack and require the frame factory
+ // to be passed in the constructor.
+ set_frame_factory(new WebRtcVideoFrameFactory());
+#endif
}
const std::vector<VideoFormat>* VideoCapturer::GetSupportedFormats() const {
@@ -176,7 +185,7 @@
return false;
}
LOG(LS_INFO) << "Pausing a camera.";
- talk_base::scoped_ptr<VideoFormat> capture_format_when_paused(
+ rtc::scoped_ptr<VideoFormat> capture_format_when_paused(
capture_format_ ? new VideoFormat(*capture_format_) : NULL);
Stop();
SetCaptureState(CS_PAUSED);
@@ -284,14 +293,14 @@
}
void VideoCapturer::AddVideoProcessor(VideoProcessor* video_processor) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ASSERT(std::find(video_processors_.begin(), video_processors_.end(),
video_processor) == video_processors_.end());
video_processors_.push_back(video_processor);
}
bool VideoCapturer::RemoveVideoProcessor(VideoProcessor* video_processor) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
VideoProcessors::iterator found = std::find(
video_processors_.begin(), video_processors_.end(), video_processor);
if (found == video_processors_.end()) {
@@ -328,7 +337,7 @@
VariableInfo<int>* effect_drops_stats,
VariableInfo<double>* frame_time_stats,
VideoFormat* last_captured_frame_format) {
- talk_base::CritScope cs(&frame_stats_crit_);
+ rtc::CritScope cs(&frame_stats_crit_);
GetVariableSnapshot(adapt_frame_drops_data_, adapt_drops_stats);
GetVariableSnapshot(effect_frame_drops_data_, effect_drops_stats);
GetVariableSnapshot(frame_time_data_, frame_time_stats);
@@ -352,10 +361,6 @@
if (SignalVideoFrame.is_empty()) {
return;
}
-#if defined(HAVE_WEBRTC_VIDEO)
-#define VIDEO_FRAME_NAME WebRtcVideoFrame
-#endif
-#if defined(VIDEO_FRAME_NAME)
#if !defined(DISABLE_YUV)
if (IsScreencast()) {
int scaled_width, scaled_height;
@@ -407,7 +412,7 @@
// TODO(fbarchard): Avoid scale and convert if muted.
// Temporary buffer is scoped here so it will persist until i420_frame.Init()
// makes a copy of the frame, converting to I420.
- talk_base::scoped_ptr<uint8[]> temp_buffer;
+ rtc::scoped_ptr<uint8[]> temp_buffer;
// YUY2 can be scaled vertically using an ARGB scaler. Aspect ratio is only
// a problem on OSX. OSX always converts webcams to YUY2 or UYVY.
bool can_scale =
@@ -501,8 +506,15 @@
&desired_width, &desired_height);
}
- VIDEO_FRAME_NAME i420_frame;
- if (!i420_frame.Alias(captured_frame, desired_width, desired_height)) {
+ if (!frame_factory_) {
+ LOG(LS_ERROR) << "No video frame factory.";
+ return;
+ }
+
+ rtc::scoped_ptr<VideoFrame> i420_frame(
+ frame_factory_->CreateAliasedFrame(
+ captured_frame, desired_width, desired_height));
+ if (!i420_frame) {
// TODO(fbarchard): LOG more information about captured frame attributes.
LOG(LS_ERROR) << "Couldn't convert to I420! "
<< "From " << ToString(captured_frame) << " To "
@@ -510,7 +522,7 @@
return;
}
- VideoFrame* adapted_frame = &i420_frame;
+ VideoFrame* adapted_frame = i420_frame.get();
if (enable_video_adapter_ && !IsScreencast()) {
VideoFrame* out_frame = NULL;
video_adapter_.AdaptFrame(adapted_frame, &out_frame);
@@ -528,13 +540,12 @@
return;
}
if (muted_) {
+ // TODO(pthatcher): Use frame_factory_->CreateBlackFrame() instead.
adapted_frame->SetToBlack();
}
SignalVideoFrame(this, adapted_frame);
UpdateStats(captured_frame);
-
-#endif // VIDEO_FRAME_NAME
}
void VideoCapturer::SetCaptureState(CaptureState state) {
@@ -547,10 +558,10 @@
thread_->Post(this, MSG_STATE_CHANGE, state_params);
}
-void VideoCapturer::OnMessage(talk_base::Message* message) {
+void VideoCapturer::OnMessage(rtc::Message* message) {
switch (message->message_id) {
case MSG_STATE_CHANGE: {
- talk_base::scoped_ptr<StateChangeParams> p(
+ rtc::scoped_ptr<StateChangeParams> p(
static_cast<StateChangeParams*>(message->pdata));
SignalStateChange(this, p->data());
break;
@@ -667,7 +678,7 @@
bool VideoCapturer::ApplyProcessors(VideoFrame* video_frame) {
bool drop_frame = false;
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
for (VideoProcessors::iterator iter = video_processors_.begin();
iter != video_processors_.end(); ++iter) {
(*iter)->OnFrame(kDummyVideoSsrc, video_frame, &drop_frame);
@@ -710,7 +721,7 @@
void VideoCapturer::UpdateStats(const CapturedFrame* captured_frame) {
// Update stats protected from fetches from different thread.
- talk_base::CritScope cs(&frame_stats_crit_);
+ rtc::CritScope cs(&frame_stats_crit_);
last_captured_frame_format_.width = captured_frame->width;
last_captured_frame_format_.height = captured_frame->height;
@@ -731,7 +742,7 @@
template<class T>
void VideoCapturer::GetVariableSnapshot(
- const talk_base::RollingAccumulator<T>& data,
+ const rtc::RollingAccumulator<T>& data,
VariableInfo<T>* stats) {
stats->max_val = data.ComputeMax();
stats->mean = data.ComputeMean();
diff --git a/media/base/videocapturer.h b/media/base/videocapturer.h
index 6b1c46d..45b64ea 100644
--- a/media/base/videocapturer.h
+++ b/media/base/videocapturer.h
@@ -31,18 +31,19 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/rollingaccumulator.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
-#include "talk/base/timing.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/videoadapter.h"
#include "talk/media/base/videocommon.h"
+#include "talk/media/base/videoframefactory.h"
#include "talk/media/devices/devicemanager.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/rollingaccumulator.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timing.h"
namespace cricket {
@@ -125,14 +126,14 @@
//
class VideoCapturer
: public sigslot::has_slots<>,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
typedef std::vector<VideoProcessor*> VideoProcessors;
// All signals are marshalled to |thread| or the creating thread if
// none is provided.
VideoCapturer();
- explicit VideoCapturer(talk_base::Thread* thread);
+ explicit VideoCapturer(rtc::Thread* thread);
virtual ~VideoCapturer() {}
// Gets the id of the underlying device, which is available after the capturer
@@ -273,7 +274,7 @@
// resolution of 2048 x 1280.
int screencast_max_pixels() const { return screencast_max_pixels_; }
void set_screencast_max_pixels(int p) {
- screencast_max_pixels_ = talk_base::_max(0, p);
+ screencast_max_pixels_ = rtc::_max(0, p);
}
// If true, run video adaptation. By default, video adaptation is enabled
@@ -289,6 +290,11 @@
return &video_adapter_;
}
+ // Takes ownership.
+ void set_frame_factory(VideoFrameFactory* frame_factory) {
+ frame_factory_.reset(frame_factory);
+ }
+
// Gets statistics for tracked variables recorded since the last call to
// GetStats. Note that calling GetStats resets any gathered data so it
// should be called only periodically to log statistics.
@@ -304,7 +310,7 @@
void SetCaptureState(CaptureState state);
// Marshals SignalStateChange onto thread_.
- void OnMessage(talk_base::Message* message);
+ void OnMessage(rtc::Message* message);
// subclasses override this virtual method to provide a vector of fourccs, in
// order of preference, that are expected by the media engine.
@@ -326,6 +332,7 @@
}
void SetSupportedFormats(const std::vector<VideoFormat>& formats);
+ VideoFrameFactory* frame_factory() { return frame_factory_.get(); }
private:
void Construct();
@@ -355,15 +362,16 @@
// RollingAccumulator into stats.
template<class T>
static void GetVariableSnapshot(
- const talk_base::RollingAccumulator<T>& data,
+ const rtc::RollingAccumulator<T>& data,
VariableInfo<T>* stats);
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
std::string id_;
CaptureState capture_state_;
- talk_base::scoped_ptr<VideoFormat> capture_format_;
+ rtc::scoped_ptr<VideoFrameFactory> frame_factory_;
+ rtc::scoped_ptr<VideoFormat> capture_format_;
std::vector<VideoFormat> supported_formats_;
- talk_base::scoped_ptr<VideoFormat> max_format_;
+ rtc::scoped_ptr<VideoFormat> max_format_;
std::vector<VideoFormat> filtered_supported_formats_;
int ratio_w_; // View resolution. e.g. 1280 x 720.
@@ -379,19 +387,19 @@
bool enable_video_adapter_;
CoordinatedVideoAdapter video_adapter_;
- talk_base::Timing frame_length_time_reporter_;
- talk_base::CriticalSection frame_stats_crit_;
+ rtc::Timing frame_length_time_reporter_;
+ rtc::CriticalSection frame_stats_crit_;
int adapt_frame_drops_;
- talk_base::RollingAccumulator<int> adapt_frame_drops_data_;
+ rtc::RollingAccumulator<int> adapt_frame_drops_data_;
int effect_frame_drops_;
- talk_base::RollingAccumulator<int> effect_frame_drops_data_;
+ rtc::RollingAccumulator<int> effect_frame_drops_data_;
double previous_frame_time_;
- talk_base::RollingAccumulator<double> frame_time_data_;
+ rtc::RollingAccumulator<double> frame_time_data_;
// The captured frame format before potential adapation.
VideoFormat last_captured_frame_format_;
- talk_base::CriticalSection crit_;
+ rtc::CriticalSection crit_;
VideoProcessors video_processors_;
DISALLOW_COPY_AND_ASSIGN(VideoCapturer);
diff --git a/media/base/videocapturer_unittest.cc b/media/base/videocapturer_unittest.cc
index 9f025e3..1760d8a 100644
--- a/media/base/videocapturer_unittest.cc
+++ b/media/base/videocapturer_unittest.cc
@@ -1,26 +1,42 @@
-// Copyright 2008 Google Inc.
+/*
+ * libjingle
+ * Copyright 2008 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
#include <stdio.h>
#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
#include "talk/media/base/fakemediaprocessor.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/base/fakevideorenderer.h"
#include "talk/media/base/testutils.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videoprocessor.h"
-
-// If HAS_I420_FRAME is not defined the video capturer will not be able to
-// provide OnVideoFrame-callbacks since they require cricket::CapturedFrame to
-// be decoded as a cricket::VideoFrame (i.e. an I420 frame). This functionality
-// only exist if HAS_I420_FRAME is defined below. I420 frames are also a
-// requirement for the VideoProcessors so they will not be called either.
-#if defined(HAVE_WEBRTC_VIDEO)
-#define HAS_I420_FRAME
-#endif
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
using cricket::FakeVideoCapturer;
@@ -113,7 +129,7 @@
EXPECT_EQ_WAIT(cricket::CS_STOPPED, capture_state(), kMsCallbackWait);
EXPECT_EQ(2, num_state_changes());
capturer_.Stop();
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
EXPECT_EQ(2, num_state_changes());
}
@@ -135,7 +151,7 @@
EXPECT_TRUE(capturer_.IsRunning());
EXPECT_GE(1, num_state_changes());
capturer_.Stop();
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
EXPECT_FALSE(capturer_.IsRunning());
}
@@ -682,7 +698,12 @@
EXPECT_EQ(360, best.height);
}
-#if defined(HAS_I420_FRAME)
+// If HAVE_WEBRTC_VIDEO is not defined the video capturer will not be able to
+// provide OnVideoFrame-callbacks since they require cricket::CapturedFrame to
+// be decoded as a cricket::VideoFrame (i.e. an I420 frame). This functionality
+// only exist if HAVE_WEBRTC_VIDEO is defined below. I420 frames are also a
+// requirement for the VideoProcessors so they will not be called either.
+#if defined(HAVE_WEBRTC_VIDEO)
TEST_F(VideoCapturerTest, VideoFrame) {
EXPECT_EQ(cricket::CS_RUNNING, capturer_.Start(cricket::VideoFormat(
640,
@@ -735,7 +756,7 @@
EXPECT_TRUE(capturer_.CaptureFrame());
EXPECT_EQ(0, video_frames_received());
}
-#endif // HAS_I420_FRAME
+#endif // HAVE_WEBRTC_VIDEO
bool HdFormatInList(const std::vector<cricket::VideoFormat>& formats) {
for (std::vector<cricket::VideoFormat>::const_iterator found =
diff --git a/media/base/videocapturerfactory.h b/media/base/videocapturerfactory.h
new file mode 100755
index 0000000..009a5ee
--- /dev/null
+++ b/media/base/videocapturerfactory.h
@@ -0,0 +1,55 @@
+// libjingle
+// Copyright 2014 Google Inc.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+
+#ifndef TALK_MEDIA_BASE_VIDEOCAPTURERFACTORY_H_
+#define TALK_MEDIA_BASE_VIDEOCAPTURERFACTORY_H_
+
+#include "talk/media/base/device.h"
+#include "talk/media/base/screencastid.h"
+
+namespace cricket {
+
+class VideoCapturer;
+
+class VideoDeviceCapturerFactory {
+ public:
+ VideoDeviceCapturerFactory() {}
+ virtual ~VideoDeviceCapturerFactory() {}
+
+ virtual VideoCapturer* Create(const Device& device) = 0;
+};
+
+class ScreenCapturerFactory {
+ public:
+ ScreenCapturerFactory() {}
+ virtual ~ScreenCapturerFactory() {}
+
+ virtual VideoCapturer* Create(const ScreencastId& screenid) = 0;
+};
+
+} // namespace cricket
+
+#endif // TALK_MEDIA_BASE_VIDEOCAPTURERFACTORY_H_
diff --git a/media/base/videocommon.cc b/media/base/videocommon.cc
index 12d0ee7..7c35d2a 100644
--- a/media/base/videocommon.cc
+++ b/media/base/videocommon.cc
@@ -29,7 +29,7 @@
#include <math.h>
#include <sstream>
-#include "talk/base/common.h"
+#include "webrtc/base/common.h"
namespace cricket {
diff --git a/media/base/videocommon.h b/media/base/videocommon.h
index c83a3d8..a175c13 100644
--- a/media/base/videocommon.h
+++ b/media/base/videocommon.h
@@ -30,8 +30,8 @@
#include <string>
-#include "talk/base/basictypes.h"
-#include "talk/base/timeutils.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/timeutils.h"
namespace cricket {
@@ -44,8 +44,8 @@
// Minimum interval is 10k fps.
#define FPS_TO_INTERVAL(fps) \
- (fps ? talk_base::kNumNanosecsPerSec / fps : \
- talk_base::kNumNanosecsPerSec / 10000)
+ (fps ? rtc::kNumNanosecsPerSec / fps : \
+ rtc::kNumNanosecsPerSec / 10000)
//////////////////////////////////////////////////////////////////////////////
// Definition of FourCC codes
@@ -186,7 +186,7 @@
struct VideoFormat : VideoFormatPod {
static const int64 kMinimumInterval =
- talk_base::kNumNanosecsPerSec / 10000; // 10k fps.
+ rtc::kNumNanosecsPerSec / 10000; // 10k fps.
VideoFormat() {
Construct(0, 0, 0, 0);
@@ -208,21 +208,21 @@
}
static int64 FpsToInterval(int fps) {
- return fps ? talk_base::kNumNanosecsPerSec / fps : kMinimumInterval;
+ return fps ? rtc::kNumNanosecsPerSec / fps : kMinimumInterval;
}
static int IntervalToFps(int64 interval) {
if (!interval) {
return 0;
}
- return static_cast<int>(talk_base::kNumNanosecsPerSec / interval);
+ return static_cast<int>(rtc::kNumNanosecsPerSec / interval);
}
static float IntervalToFpsFloat(int64 interval) {
if (!interval) {
return 0.f;
}
- return static_cast<float>(talk_base::kNumNanosecsPerSec) /
+ return static_cast<float>(rtc::kNumNanosecsPerSec) /
static_cast<float>(interval);
}
diff --git a/media/base/videocommon_unittest.cc b/media/base/videocommon_unittest.cc
index 90bcd0a..daa9881 100644
--- a/media/base/videocommon_unittest.cc
+++ b/media/base/videocommon_unittest.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/gunit.h"
namespace cricket {
@@ -55,8 +55,8 @@
// Test conversion between interval and fps
TEST(VideoCommonTest, TestVideoFormatFps) {
EXPECT_EQ(VideoFormat::kMinimumInterval, VideoFormat::FpsToInterval(0));
- EXPECT_EQ(talk_base::kNumNanosecsPerSec / 20, VideoFormat::FpsToInterval(20));
- EXPECT_EQ(20, VideoFormat::IntervalToFps(talk_base::kNumNanosecsPerSec / 20));
+ EXPECT_EQ(rtc::kNumNanosecsPerSec / 20, VideoFormat::FpsToInterval(20));
+ EXPECT_EQ(20, VideoFormat::IntervalToFps(rtc::kNumNanosecsPerSec / 20));
EXPECT_EQ(0, VideoFormat::IntervalToFps(0));
}
diff --git a/media/base/videoengine_unittest.h b/media/base/videoengine_unittest.h
index 382fb77..8eab347 100644
--- a/media/base/videoengine_unittest.h
+++ b/media/base/videoengine_unittest.h
@@ -29,14 +29,14 @@
#include <string>
#include <vector>
-#include "talk/base/bytebuffer.h"
-#include "talk/base/gunit.h"
-#include "talk/base/timeutils.h"
#include "talk/media/base/fakenetworkinterface.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/base/fakevideorenderer.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/streamparams.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/timeutils.h"
#ifdef WIN32
#include <objbase.h> // NOLINT
@@ -61,6 +61,7 @@
EXPECT_EQ(0, (r).errors()); \
static const uint32 kTimeout = 5000U;
+static const uint32 kDefaultReceiveSsrc = 0;
static const uint32 kSsrc = 1234u;
static const uint32 kRtxSsrc = 4321u;
static const uint32 kSsrcs4[] = {1, 2, 3, 4};
@@ -86,7 +87,7 @@
inline int TimeBetweenSend(const cricket::VideoCodec& codec) {
return static_cast<int>(
cricket::VideoFormat::FpsToInterval(codec.framerate) /
- talk_base::kNumNanosecsPerMillisec);
+ rtc::kNumNanosecsPerMillisec);
}
// Fake video engine that makes it possible to test enabling and disabling
@@ -133,7 +134,7 @@
}
#define TEST_POST_VIDEOENGINE_INIT(TestClass, func) \
TEST_F(TestClass, func##PostInit) { \
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current())); \
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current())); \
func##Body(); \
engine_.Terminate(); \
}
@@ -143,7 +144,7 @@
protected:
// Tests starting and stopping the engine, and creating a channel.
void StartupShutdown() {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
cricket::VideoMediaChannel* channel = engine_.CreateChannel(NULL);
EXPECT_TRUE(channel != NULL);
delete channel;
@@ -158,7 +159,7 @@
EXPECT_EQ(S_OK, CoInitializeEx(NULL, COINIT_MULTITHREADED));
// Engine should start even with COM already inited.
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
engine_.Terminate();
// Refcount after terminate should be 1; this tests if it is nonzero.
EXPECT_EQ(S_FALSE, CoInitializeEx(NULL, COINIT_MULTITHREADED));
@@ -178,7 +179,7 @@
engine_.codecs()[0].name,
1280, 800, 30, 0);
- // set max settings of 1280x960x30
+ // set max settings of 1280x800x30
EXPECT_TRUE(engine_.SetDefaultEncoderConfig(
cricket::VideoEncoderConfig(max_settings)));
@@ -313,6 +314,43 @@
EXPECT_PRED4(IsEqualRes, out, 160, 120, 10);
}
+ // This is the new way of constraining codec size, where we no longer maintain
+ // a list of the supported formats. Instead, CanSendCodec will just downscale
+ // the resolution by 2 until the width is below clamp.
+ void ConstrainNewCodec2Body() {
+ cricket::VideoCodec empty, in, out;
+ cricket::VideoCodec max_settings(engine_.codecs()[0].id,
+ engine_.codecs()[0].name,
+ 1280, 800, 30, 0);
+
+ // Set max settings of 1280x800x30
+ EXPECT_TRUE(engine_.SetDefaultEncoderConfig(
+ cricket::VideoEncoderConfig(max_settings)));
+
+ // Don't constrain the max resolution
+ in = max_settings;
+ EXPECT_TRUE(engine_.CanSendCodec(in, empty, &out));
+ EXPECT_PRED2(IsEqualCodec, out, in);
+
+ // Constrain resolution greater than the max width.
+ in.width = 1380;
+ in.height = 800;
+ EXPECT_TRUE(engine_.CanSendCodec(in, empty, &out));
+ EXPECT_PRED4(IsEqualRes, out, 690, 400, 30);
+
+ // Don't constrain resolution when only the height is greater than max.
+ in.width = 960;
+ in.height = 1280;
+ EXPECT_TRUE(engine_.CanSendCodec(in, empty, &out));
+ EXPECT_PRED4(IsEqualRes, out, 960, 1280, 30);
+
+ // Don't constrain smaller format.
+ in.width = 640;
+ in.height = 480;
+ EXPECT_TRUE(engine_.CanSendCodec(in, empty, &out));
+ EXPECT_PRED4(IsEqualRes, out, 640, 480, 30);
+ }
+
void ConstrainRunningCodecBody() {
cricket::VideoCodec in, out, current;
cricket::VideoCodec max_settings(engine_.codecs()[0].id,
@@ -441,7 +479,7 @@
}
VideoEngineOverride<E> engine_;
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> video_capturer_;
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> video_capturer_;
};
template<class E, class C>
@@ -456,24 +494,27 @@
virtual void SetUp() {
cricket::Device device("test", "device");
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_.reset(engine_.CreateChannel(NULL));
EXPECT_TRUE(channel_.get() != NULL);
ConnectVideoChannelError();
network_interface_.SetDestination(channel_.get());
channel_->SetInterface(&network_interface_);
- SetRendererAsDefault();
media_error_ = cricket::VideoMediaChannel::ERROR_NONE;
channel_->SetRecvCodecs(engine_.codecs());
EXPECT_TRUE(channel_->AddSendStream(DefaultSendStreamParams()));
-
- video_capturer_.reset(new cricket::FakeVideoCapturer);
+ video_capturer_.reset(CreateFakeVideoCapturer());
cricket::VideoFormat format(640, 480,
cricket::VideoFormat::FpsToInterval(30),
cricket::FOURCC_I420);
EXPECT_EQ(cricket::CS_RUNNING, video_capturer_->Start(format));
EXPECT_TRUE(channel_->SetCapturer(kSsrc, video_capturer_.get()));
}
+
+ virtual cricket::FakeVideoCapturer* CreateFakeVideoCapturer() {
+ return new cricket::FakeVideoCapturer();
+ }
+
// Utility method to setup an additional stream to send and receive video.
// Used to test send and recv between two streams.
void SetUpSecondStream() {
@@ -490,6 +531,7 @@
// SetUp() already added kSsrc make sure duplicate SSRCs cant be added.
EXPECT_TRUE(channel_->AddRecvStream(
cricket::StreamParams::CreateLegacy(kSsrc)));
+ EXPECT_TRUE(channel_->SetRenderer(kSsrc, &renderer_));
EXPECT_FALSE(channel_->AddSendStream(
cricket::StreamParams::CreateLegacy(kSsrc)));
EXPECT_TRUE(channel_->AddSendStream(
@@ -497,7 +539,7 @@
// We dont add recv for the second stream.
// Setup the receive and renderer for second stream after send.
- video_capturer_2_.reset(new cricket::FakeVideoCapturer());
+ video_capturer_2_.reset(CreateFakeVideoCapturer());
cricket::VideoFormat format(640, 480,
cricket::VideoFormat::FpsToInterval(30),
cricket::FOURCC_I420);
@@ -516,9 +558,6 @@
bool SetDefaultCodec() {
return SetOneCodec(DefaultCodec());
}
- void SetRendererAsDefault() {
- EXPECT_TRUE(channel_->SetRenderer(0, &renderer_));
- }
bool SetOneCodec(int pt, const char* name, int w, int h, int fr) {
return SetOneCodec(cricket::VideoCodec(pt, name, w, h, fr, 0));
@@ -560,7 +599,7 @@
do {
packets = NumRtpPackets();
// 100 ms should be long enough.
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
} while (NumRtpPackets() > packets);
return NumRtpPackets();
}
@@ -572,7 +611,7 @@
video_capturer_->CaptureFrame();
}
bool WaitAndSendFrame(int wait_ms) {
- bool ret = talk_base::Thread::Current()->ProcessMessages(wait_ms);
+ bool ret = rtc::Thread::Current()->ProcessMessages(wait_ms);
ret &= SendFrame();
return ret;
}
@@ -612,24 +651,24 @@
int NumSentSsrcs() {
return network_interface_.NumSentSsrcs();
}
- const talk_base::Buffer* GetRtpPacket(int index) {
+ const rtc::Buffer* GetRtpPacket(int index) {
return network_interface_.GetRtpPacket(index);
}
int NumRtcpPackets() {
return network_interface_.NumRtcpPackets();
}
- const talk_base::Buffer* GetRtcpPacket(int index) {
+ const rtc::Buffer* GetRtcpPacket(int index) {
return network_interface_.GetRtcpPacket(index);
}
- static int GetPayloadType(const talk_base::Buffer* p) {
+ static int GetPayloadType(const rtc::Buffer* p) {
int pt = -1;
ParseRtpPacket(p, NULL, &pt, NULL, NULL, NULL, NULL);
return pt;
}
- static bool ParseRtpPacket(const talk_base::Buffer* p, bool* x, int* pt,
+ static bool ParseRtpPacket(const rtc::Buffer* p, bool* x, int* pt,
int* seqnum, uint32* tstamp, uint32* ssrc,
std::string* payload) {
- talk_base::ByteBuffer buf(p->data(), p->length());
+ rtc::ByteBuffer buf(p->data(), p->length());
uint8 u08 = 0;
uint16 u16 = 0;
uint32 u32 = 0;
@@ -688,8 +727,8 @@
bool CountRtcpFir(int start_index, int stop_index, int* fir_count) {
int count = 0;
for (int i = start_index; i < stop_index; ++i) {
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtcpPacket(i));
- talk_base::ByteBuffer buf(p->data(), p->length());
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtcpPacket(i));
+ rtc::ByteBuffer buf(p->data(), p->length());
size_t total_len = 0;
// The packet may be a compound RTCP packet.
while (total_len < p->length()) {
@@ -756,7 +795,7 @@
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(SendFrame());
EXPECT_TRUE_WAIT(NumRtpPackets() > 0, kTimeout);
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
EXPECT_EQ(codec.id, GetPayloadType(p.get()));
}
// Tests that we can send and receive frames.
@@ -764,10 +803,11 @@
EXPECT_TRUE(SetOneCodec(codec));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_EQ(0, renderer_.num_rendered_frames());
EXPECT_TRUE(SendFrame());
EXPECT_FRAME_WAIT(1, codec.width, codec.height, kTimeout);
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
EXPECT_EQ(codec.id, GetPayloadType(p.get()));
}
// Tests that we only get a VideoRenderer::SetSize() callback when needed.
@@ -776,12 +816,13 @@
EXPECT_TRUE(SetOneCodec(codec));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_EQ(0, renderer_.num_rendered_frames());
EXPECT_TRUE(WaitAndSendFrame(30));
EXPECT_FRAME_WAIT(1, codec.width, codec.height, kTimeout);
EXPECT_TRUE(WaitAndSendFrame(30));
EXPECT_FRAME_WAIT(2, codec.width, codec.height, kTimeout);
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
EXPECT_EQ(codec.id, GetPayloadType(p.get()));
EXPECT_EQ(1, renderer_.num_set_sizes());
@@ -797,6 +838,7 @@
EXPECT_TRUE(SetOneCodec(codec));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_EQ(0, renderer_.num_rendered_frames());
for (int i = 0; i < duration_sec; ++i) {
for (int frame = 1; frame <= fps; ++frame) {
@@ -815,7 +857,7 @@
// Therefore insert frames (and call GetStats each sec) for a few seconds
// before testing stats.
}
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
EXPECT_EQ(codec.id, GetPayloadType(p.get()));
}
@@ -917,7 +959,8 @@
vmo.conference_mode.Set(true);
EXPECT_TRUE(channel_->SetOptions(vmo));
EXPECT_TRUE(channel_->AddRecvStream(
- cricket::StreamParams::CreateLegacy(1234)));
+ cricket::StreamParams::CreateLegacy(kSsrc)));
+ EXPECT_TRUE(channel_->SetRenderer(kSsrc, &renderer_));
channel_->UpdateAspectRatio(640, 400);
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
@@ -927,8 +970,8 @@
// Add an additional capturer, and hook up a renderer to receive it.
cricket::FakeVideoRenderer renderer1;
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> capturer(
- new cricket::FakeVideoCapturer);
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> capturer(
+ CreateFakeVideoCapturer());
capturer->SetScreencast(true);
const int kTestWidth = 160;
const int kTestHeight = 120;
@@ -979,7 +1022,7 @@
EXPECT_TRUE(SendFrame());
EXPECT_TRUE_WAIT(NumRtpPackets() > 0, kTimeout);
uint32 ssrc = 0;
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
ParseRtpPacket(p.get(), NULL, NULL, NULL, NULL, &ssrc, NULL);
EXPECT_EQ(kSsrc, ssrc);
EXPECT_EQ(NumRtpPackets(), NumRtpPackets(ssrc));
@@ -1001,7 +1044,7 @@
EXPECT_TRUE(WaitAndSendFrame(0));
EXPECT_TRUE_WAIT(NumRtpPackets() > 0, kTimeout);
uint32 ssrc = 0;
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
ParseRtpPacket(p.get(), NULL, NULL, NULL, NULL, &ssrc, NULL);
EXPECT_EQ(999u, ssrc);
EXPECT_EQ(NumRtpPackets(), NumRtpPackets(ssrc));
@@ -1017,15 +1060,15 @@
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
- talk_base::Buffer packet1(data1, sizeof(data1));
- talk_base::SetBE32(packet1.data() + 8, kSsrc);
- channel_->SetRenderer(0, NULL);
+ rtc::Buffer packet1(data1, sizeof(data1));
+ rtc::SetBE32(packet1.data() + 8, kSsrc);
+ channel_->SetRenderer(kDefaultReceiveSsrc, NULL);
EXPECT_TRUE(SetDefaultCodec());
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
EXPECT_EQ(0, renderer_.num_rendered_frames());
- channel_->OnPacketReceived(&packet1, talk_base::PacketTime());
- SetRendererAsDefault();
+ channel_->OnPacketReceived(&packet1, rtc::PacketTime());
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_TRUE(SendFrame());
EXPECT_FRAME_WAIT(1, DefaultCodec().width, DefaultCodec().height, kTimeout);
}
@@ -1046,12 +1089,13 @@
EXPECT_TRUE(SetOneCodec(DefaultCodec()));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_TRUE(SendFrame());
EXPECT_FRAME_WAIT(1, DefaultCodec().width, DefaultCodec().height, kTimeout);
EXPECT_GE(2, NumRtpPackets());
uint32 ssrc = 0;
size_t last_packet = NumRtpPackets() - 1;
- talk_base::scoped_ptr<const talk_base::Buffer>
+ rtc::scoped_ptr<const rtc::Buffer>
p(GetRtpPacket(static_cast<int>(last_packet)));
ParseRtpPacket(p.get(), NULL, NULL, NULL, NULL, &ssrc, NULL);
EXPECT_EQ(kSsrc, ssrc);
@@ -1114,8 +1158,7 @@
EXPECT_TRUE(channel_->AddRecvStream(
cricket::StreamParams::CreateLegacy(2)));
EXPECT_TRUE(channel_->GetRenderer(1, &renderer));
- // Verify the first AddRecvStream hook up to the default renderer.
- EXPECT_EQ(&renderer_, renderer);
+ EXPECT_TRUE(renderer == NULL);
EXPECT_TRUE(channel_->GetRenderer(2, &renderer));
EXPECT_TRUE(NULL == renderer);
@@ -1159,7 +1202,7 @@
cricket::StreamParams::CreateLegacy(2)));
EXPECT_TRUE(channel_->GetRenderer(1, &renderer));
// Verify the first AddRecvStream hook up to the default renderer.
- EXPECT_EQ(&renderer_, renderer);
+ EXPECT_TRUE(renderer == NULL);
EXPECT_TRUE(channel_->GetRenderer(2, &renderer));
EXPECT_TRUE(NULL == renderer);
@@ -1254,7 +1297,7 @@
EXPECT_FRAME_ON_RENDERER_WAIT(
renderer2, 1, DefaultCodec().width, DefaultCodec().height, kTimeout);
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
EXPECT_EQ(DefaultCodec().id, GetPayloadType(p.get()));
EXPECT_EQ(DefaultCodec().width, renderer1.width());
EXPECT_EQ(DefaultCodec().height, renderer1.height());
@@ -1273,11 +1316,12 @@
EXPECT_TRUE(SetOneCodec(codec));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_EQ(0, renderer_.num_rendered_frames());
EXPECT_TRUE(SendFrame());
EXPECT_FRAME_WAIT(1, codec.width, codec.height, kTimeout);
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> capturer(
- new cricket::FakeVideoCapturer);
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> capturer(
+ CreateFakeVideoCapturer());
capturer->SetScreencast(true);
cricket::VideoFormat format(480, 360,
cricket::VideoFormat::FpsToInterval(30),
@@ -1292,7 +1336,7 @@
int captured_frames = 1;
for (int iterations = 0; iterations < 2; ++iterations) {
EXPECT_TRUE(channel_->SetCapturer(kSsrc, capturer.get()));
- talk_base::Thread::Current()->ProcessMessages(time_between_send);
+ rtc::Thread::Current()->ProcessMessages(time_between_send);
EXPECT_TRUE(capturer->CaptureCustomFrame(format.width, format.height,
cricket::FOURCC_I420));
++captured_frames;
@@ -1333,6 +1377,7 @@
EXPECT_TRUE(SetOneCodec(DefaultCodec()));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_EQ(0, renderer_.num_rendered_frames());
EXPECT_TRUE(SendFrame());
EXPECT_FRAME_WAIT(1, 640, 400, kTimeout);
@@ -1344,7 +1389,7 @@
// No capturer was added, so this RemoveCapturer should
// fail.
EXPECT_FALSE(channel_->SetCapturer(kSsrc, NULL));
- talk_base::Thread::Current()->ProcessMessages(300);
+ rtc::Thread::Current()->ProcessMessages(300);
// Verify no more frames were sent.
EXPECT_EQ(2, renderer_.num_rendered_frames());
}
@@ -1369,8 +1414,8 @@
EXPECT_TRUE(channel_->SetRenderer(1, &renderer1));
EXPECT_TRUE(channel_->AddSendStream(
cricket::StreamParams::CreateLegacy(1)));
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> capturer1(
- new cricket::FakeVideoCapturer);
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> capturer1(
+ CreateFakeVideoCapturer());
capturer1->SetScreencast(true);
EXPECT_EQ(cricket::CS_RUNNING, capturer1->Start(capture_format));
// Set up additional stream 2.
@@ -1381,8 +1426,8 @@
EXPECT_TRUE(channel_->SetRenderer(2, &renderer2));
EXPECT_TRUE(channel_->AddSendStream(
cricket::StreamParams::CreateLegacy(2)));
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> capturer2(
- new cricket::FakeVideoCapturer);
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> capturer2(
+ CreateFakeVideoCapturer());
capturer2->SetScreencast(true);
EXPECT_EQ(cricket::CS_RUNNING, capturer2->Start(capture_format));
// State for all the streams.
@@ -1439,8 +1484,8 @@
// Registering an external capturer is currently the same as screen casting
// (update the test when this changes).
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> capturer(
- new cricket::FakeVideoCapturer);
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> capturer(
+ CreateFakeVideoCapturer());
capturer->SetScreencast(true);
const std::vector<cricket::VideoFormat>* formats =
capturer->GetSupportedFormats();
@@ -1449,10 +1494,9 @@
// Capture frame to not get same frame timestamps as previous capturer.
capturer->CaptureFrame();
EXPECT_TRUE(channel_->SetCapturer(kSsrc, capturer.get()));
- EXPECT_TRUE(talk_base::Thread::Current()->ProcessMessages(30));
+ EXPECT_TRUE(rtc::Thread::Current()->ProcessMessages(30));
EXPECT_TRUE(capturer->CaptureCustomFrame(kWidth, kHeight,
cricket::FOURCC_ARGB));
- EXPECT_TRUE(capturer->CaptureFrame());
EXPECT_GT_FRAME_ON_RENDERER_WAIT(
renderer, 2, kScaledWidth, kScaledHeight, kTimeout);
EXPECT_TRUE(channel_->SetCapturer(kSsrc, NULL));
@@ -1460,6 +1504,7 @@
// Tests that we can adapt video resolution with 16:10 aspect ratio properly.
void AdaptResolution16x10() {
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
cricket::VideoCodec codec(DefaultCodec());
codec.width = 640;
codec.height = 400;
@@ -1473,6 +1518,7 @@
}
// Tests that we can adapt video resolution with 4:3 aspect ratio properly.
void AdaptResolution4x3() {
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
cricket::VideoCodec codec(DefaultCodec());
codec.width = 640;
codec.height = 400;
@@ -1493,10 +1539,11 @@
EXPECT_TRUE(SetOneCodec(codec));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_EQ(0, renderer_.num_rendered_frames());
EXPECT_TRUE(SendFrame());
EXPECT_TRUE(SendFrame());
- talk_base::Thread::Current()->ProcessMessages(500);
+ rtc::Thread::Current()->ProcessMessages(500);
EXPECT_EQ(0, renderer_.num_rendered_frames());
}
// Tests that we can reduce the frame rate on demand properly.
@@ -1513,7 +1560,7 @@
EXPECT_TRUE(WaitAndSendFrame(30)); // Should be rendered.
frame_count += 2;
EXPECT_FRAME_WAIT(frame_count, codec.width, codec.height, kTimeout);
- talk_base::scoped_ptr<const talk_base::Buffer> p(GetRtpPacket(0));
+ rtc::scoped_ptr<const rtc::Buffer> p(GetRtpPacket(0));
EXPECT_EQ(codec.id, GetPayloadType(p.get()));
// The channel requires 15 fps.
@@ -1546,6 +1593,25 @@
frame_count += 2;
EXPECT_EQ_WAIT(frame_count, renderer_.num_rendered_frames(), kTimeout);
}
+ // Tests that adapted frames won't be upscaled to a higher resolution.
+ void SendsLowerResolutionOnSmallerFrames() {
+ cricket::VideoCodec codec = DefaultCodec();
+ codec.width = 320;
+ codec.height = 240;
+ EXPECT_TRUE(SetOneCodec(codec));
+ EXPECT_TRUE(SetSend(true));
+ EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
+ EXPECT_EQ(0, renderer_.num_rendered_frames());
+ EXPECT_TRUE(SendFrame());
+ EXPECT_FRAME_WAIT(1, codec.width, codec.height, kTimeout);
+
+ // Check that we send smaller frames at the new resolution.
+ EXPECT_TRUE(rtc::Thread::Current()->ProcessMessages(33));
+ EXPECT_TRUE(video_capturer_->CaptureCustomFrame(
+ codec.width / 2, codec.height / 2, cricket::FOURCC_I420));
+ EXPECT_FRAME_WAIT(2, codec.width / 2, codec.height / 2, kTimeout);
+ }
// Tests that we can set the send stream format properly.
void SetSendStreamFormat() {
cricket::VideoCodec codec(DefaultCodec());
@@ -1575,7 +1641,7 @@
EXPECT_TRUE(channel_->SetSendStreamFormat(kSsrc, format));
EXPECT_TRUE(SendFrame());
EXPECT_TRUE(SendFrame());
- talk_base::Thread::Current()->ProcessMessages(500);
+ rtc::Thread::Current()->ProcessMessages(500);
EXPECT_EQ(frame_count, renderer_.num_rendered_frames());
}
// Test that setting send stream format to 0x0 resolution will result in
@@ -1585,6 +1651,7 @@
EXPECT_TRUE(SetSendStreamFormat(kSsrc, DefaultCodec()));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
EXPECT_EQ(0, renderer_.num_rendered_frames());
// This frame should be received.
EXPECT_TRUE(SendFrame());
@@ -1599,14 +1666,13 @@
EXPECT_TRUE(channel_->SetSendStreamFormat(kSsrc, format));
// This frame should not be received.
EXPECT_TRUE(WaitAndSendFrame(
- static_cast<int>(interval/talk_base::kNumNanosecsPerMillisec)));
- talk_base::Thread::Current()->ProcessMessages(500);
+ static_cast<int>(interval/rtc::kNumNanosecsPerMillisec)));
+ rtc::Thread::Current()->ProcessMessages(500);
EXPECT_EQ(1, renderer_.num_rendered_frames());
}
// Tests that we can mute and unmute the channel properly.
void MuteStream() {
- int frame_count = 0;
EXPECT_TRUE(SetDefaultCodec());
cricket::FakeVideoCapturer video_capturer;
video_capturer.Start(
@@ -1617,9 +1683,11 @@
EXPECT_TRUE(channel_->SetCapturer(kSsrc, &video_capturer));
EXPECT_TRUE(SetSend(true));
EXPECT_TRUE(channel_->SetRender(true));
- EXPECT_EQ(frame_count, renderer_.num_rendered_frames());
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
+ EXPECT_EQ(0, renderer_.num_rendered_frames());
// Mute the channel and expect black output frame.
+ int frame_count = 0;
EXPECT_TRUE(channel_->MuteStream(kSsrc, true));
EXPECT_TRUE(video_capturer.CaptureFrame());
++frame_count;
@@ -1628,7 +1696,7 @@
// Unmute the channel and expect non-black output frame.
EXPECT_TRUE(channel_->MuteStream(kSsrc, false));
- EXPECT_TRUE(talk_base::Thread::Current()->ProcessMessages(30));
+ EXPECT_TRUE(rtc::Thread::Current()->ProcessMessages(30));
EXPECT_TRUE(video_capturer.CaptureFrame());
++frame_count;
EXPECT_EQ_WAIT(frame_count, renderer_.num_rendered_frames(), kTimeout);
@@ -1636,19 +1704,27 @@
// Test that we can also Mute using the correct send stream SSRC.
EXPECT_TRUE(channel_->MuteStream(kSsrc, true));
- EXPECT_TRUE(talk_base::Thread::Current()->ProcessMessages(30));
+ EXPECT_TRUE(rtc::Thread::Current()->ProcessMessages(30));
EXPECT_TRUE(video_capturer.CaptureFrame());
++frame_count;
EXPECT_EQ_WAIT(frame_count, renderer_.num_rendered_frames(), kTimeout);
EXPECT_TRUE(renderer_.black_frame());
EXPECT_TRUE(channel_->MuteStream(kSsrc, false));
- EXPECT_TRUE(talk_base::Thread::Current()->ProcessMessages(30));
+ EXPECT_TRUE(rtc::Thread::Current()->ProcessMessages(30));
EXPECT_TRUE(video_capturer.CaptureFrame());
++frame_count;
EXPECT_EQ_WAIT(frame_count, renderer_.num_rendered_frames(), kTimeout);
EXPECT_FALSE(renderer_.black_frame());
+ // Test that muting an existing stream succeeds even if it's muted.
+ EXPECT_TRUE(channel_->MuteStream(kSsrc, true));
+ EXPECT_TRUE(channel_->MuteStream(kSsrc, true));
+
+ // Test that unmuting an existing stream succeeds even if it's not muted.
+ EXPECT_TRUE(channel_->MuteStream(kSsrc, false));
+ EXPECT_TRUE(channel_->MuteStream(kSsrc, false));
+
// Test that muting an invalid stream fails.
EXPECT_FALSE(channel_->MuteStream(kSsrc+1, true));
EXPECT_TRUE(channel_->SetCapturer(kSsrc, NULL));
@@ -1671,7 +1747,6 @@
EXPECT_FALSE(channel_->RemoveSendStream(kSsrcs4[kSsrcsSize - 1]));
}
-
// Two streams one channel tests.
// Tests that we can send and receive frames.
@@ -1693,23 +1768,23 @@
void TwoStreamsReUseFirstStream(const cricket::VideoCodec& codec) {
SetUpSecondStream();
// Default channel used by the first stream.
- EXPECT_EQ(kSsrc, channel_->GetDefaultChannelSsrc());
+ EXPECT_EQ(kSsrc, channel_->GetDefaultSendChannelSsrc());
EXPECT_TRUE(channel_->RemoveRecvStream(kSsrc));
EXPECT_FALSE(channel_->RemoveRecvStream(kSsrc));
EXPECT_TRUE(channel_->RemoveSendStream(kSsrc));
EXPECT_FALSE(channel_->RemoveSendStream(kSsrc));
// Default channel is no longer used by a stream.
- EXPECT_EQ(0u, channel_->GetDefaultChannelSsrc());
- SetRendererAsDefault();
+ EXPECT_EQ(0u, channel_->GetDefaultSendChannelSsrc());
uint32 new_ssrc = kSsrc + 100;
EXPECT_TRUE(channel_->AddSendStream(
cricket::StreamParams::CreateLegacy(new_ssrc)));
// Re-use default channel.
- EXPECT_EQ(new_ssrc, channel_->GetDefaultChannelSsrc());
+ EXPECT_EQ(new_ssrc, channel_->GetDefaultSendChannelSsrc());
EXPECT_FALSE(channel_->AddSendStream(
cricket::StreamParams::CreateLegacy(new_ssrc)));
EXPECT_TRUE(channel_->AddRecvStream(
cricket::StreamParams::CreateLegacy(new_ssrc)));
+ EXPECT_TRUE(channel_->SetRenderer(new_ssrc, &renderer_));
EXPECT_FALSE(channel_->AddRecvStream(
cricket::StreamParams::CreateLegacy(new_ssrc)));
@@ -1717,7 +1792,7 @@
SendAndReceive(codec);
EXPECT_TRUE(channel_->RemoveSendStream(new_ssrc));
- EXPECT_EQ(0u, channel_->GetDefaultChannelSsrc());
+ EXPECT_EQ(0u, channel_->GetDefaultSendChannelSsrc());
}
// Tests that we can send and receive frames with early receive.
@@ -1737,7 +1812,7 @@
// instead of packets.
EXPECT_EQ(0, renderer2_.num_rendered_frames());
// Give a chance for the decoder to process before adding the receiver.
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
// Test sending and receiving on second stream.
EXPECT_TRUE(channel_->AddRecvStream(
cricket::StreamParams::CreateLegacy(kSsrc + 2)));
@@ -1763,11 +1838,11 @@
EXPECT_TRUE(channel_->SetRender(true));
Send(codec);
EXPECT_EQ_WAIT(2, NumRtpPackets(), kTimeout);
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
EXPECT_EQ_WAIT(1, renderer_.num_rendered_frames(), kTimeout);
EXPECT_EQ_WAIT(0, renderer2_.num_rendered_frames(), kTimeout);
// Give a chance for the decoder to process before adding the receiver.
- talk_base::Thread::Current()->ProcessMessages(10);
+ rtc::Thread::Current()->ProcessMessages(10);
// Test sending and receiving on second stream.
EXPECT_TRUE(channel_->AddRecvStream(
cricket::StreamParams::CreateLegacy(kSsrc + 2)));
@@ -1798,7 +1873,7 @@
// is no registered recv channel for the ssrc.
EXPECT_TRUE_WAIT(renderer_.num_rendered_frames() >= 1, kTimeout);
// Give a chance for the decoder to process before adding the receiver.
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
// Test sending and receiving on second stream.
EXPECT_TRUE(channel_->AddRecvStream(
cricket::StreamParams::CreateLegacy(kSsrc + 2)));
@@ -1831,16 +1906,16 @@
// instead of packets.
EXPECT_EQ(0, renderer2_.num_rendered_frames());
// Give a chance for the decoder to process before adding the receiver.
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
// Ensure that we can remove the unsignalled recv stream that was created
// when the first video packet with unsignalled recv ssrc is received.
EXPECT_TRUE(channel_->RemoveRecvStream(kSsrc + 2));
}
VideoEngineOverride<E> engine_;
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> video_capturer_;
- talk_base::scoped_ptr<cricket::FakeVideoCapturer> video_capturer_2_;
- talk_base::scoped_ptr<C> channel_;
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> video_capturer_;
+ rtc::scoped_ptr<cricket::FakeVideoCapturer> video_capturer_2_;
+ rtc::scoped_ptr<C> channel_;
cricket::FakeNetworkInterface network_interface_;
cricket::FakeVideoRenderer renderer_;
cricket::VideoMediaChannel::Error media_error_;
diff --git a/media/base/videoframe.cc b/media/base/videoframe.cc
index cf5f852..018d065 100644
--- a/media/base/videoframe.cc
+++ b/media/base/videoframe.cc
@@ -35,17 +35,17 @@
#include "libyuv/scale.h"
#endif
-#include "talk/base/logging.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/logging.h"
namespace cricket {
// Round to 2 pixels because Chroma channels are half size.
#define ROUNDTO2(v) (v & ~1)
-talk_base::StreamResult VideoFrame::Write(talk_base::StreamInterface* stream,
+rtc::StreamResult VideoFrame::Write(rtc::StreamInterface* stream,
int* error) {
- talk_base::StreamResult result = talk_base::SR_SUCCESS;
+ rtc::StreamResult result = rtc::SR_SUCCESS;
const uint8* src_y = GetYPlane();
const uint8* src_u = GetUPlane();
const uint8* src_v = GetVPlane();
@@ -62,21 +62,21 @@
// Write Y.
for (size_t row = 0; row < height; ++row) {
result = stream->Write(src_y + row * y_pitch, width, NULL, error);
- if (result != talk_base::SR_SUCCESS) {
+ if (result != rtc::SR_SUCCESS) {
return result;
}
}
// Write U.
for (size_t row = 0; row < half_height; ++row) {
result = stream->Write(src_u + row * u_pitch, half_width, NULL, error);
- if (result != talk_base::SR_SUCCESS) {
+ if (result != rtc::SR_SUCCESS) {
return result;
}
}
// Write V.
for (size_t row = 0; row < half_height; ++row) {
result = stream->Write(src_v + row * v_pitch, half_width, NULL, error);
- if (result != talk_base::SR_SUCCESS) {
+ if (result != rtc::SR_SUCCESS) {
return result;
}
}
@@ -235,7 +235,7 @@
}
static const size_t kMaxSampleSize = 1000000000u;
-// Returns whether a sample is valid
+// Returns whether a sample is valid.
bool VideoFrame::Validate(uint32 fourcc, int w, int h,
const uint8 *sample, size_t sample_size) {
if (h < 0) {
@@ -311,6 +311,11 @@
<< " " << sample_size;
return false;
}
+ // TODO(fbarchard): Make function to dump information about frames.
+ uint8 four_samples[4] = { 0, 0, 0, 0 };
+ for (size_t i = 0; i < ARRAY_SIZE(four_samples) && i < sample_size; ++i) {
+ four_samples[i] = sample[i];
+ }
if (sample_size < expected_size) {
LOG(LS_ERROR) << "Size field is too small."
<< " format: " << GetFourccName(format)
@@ -318,10 +323,10 @@
<< " size: " << w << "x" << h
<< " " << sample_size
<< " expected: " << expected_size
- << " sample[0..3]: " << static_cast<int>(sample[0])
- << ", " << static_cast<int>(sample[1])
- << ", " << static_cast<int>(sample[2])
- << ", " << static_cast<int>(sample[3]);
+ << " sample[0..3]: " << static_cast<int>(four_samples[0])
+ << ", " << static_cast<int>(four_samples[1])
+ << ", " << static_cast<int>(four_samples[2])
+ << ", " << static_cast<int>(four_samples[3]);
return false;
}
if (sample_size > kMaxSampleSize) {
@@ -331,13 +336,14 @@
<< " size: " << w << "x" << h
<< " " << sample_size
<< " expected: " << 2 * expected_size
- << " sample[0..3]: " << static_cast<int>(sample[0])
- << ", " << static_cast<int>(sample[1])
- << ", " << static_cast<int>(sample[2])
- << ", " << static_cast<int>(sample[3]);
+ << " sample[0..3]: " << static_cast<int>(four_samples[0])
+ << ", " << static_cast<int>(four_samples[1])
+ << ", " << static_cast<int>(four_samples[2])
+ << ", " << static_cast<int>(four_samples[3]);
return false;
}
// Show large size warning once every 100 frames.
+ // TODO(fbarchard): Make frame counter atomic for thread safety.
static int large_warn100 = 0;
size_t large_expected_size = expected_size * 2;
if (expected_bpp >= 8 &&
@@ -350,27 +356,14 @@
<< " size: " << w << "x" << h
<< " bytes: " << sample_size
<< " expected: " << large_expected_size
- << " sample[0..3]: " << static_cast<int>(sample[0])
- << ", " << static_cast<int>(sample[1])
- << ", " << static_cast<int>(sample[2])
- << ", " << static_cast<int>(sample[3]);
- }
- // Scan pages to ensure they are there and don't contain a single value and
- // to generate an error.
- if (!memcmp(sample + sample_size - 8, sample + sample_size - 4, 4) &&
- !memcmp(sample, sample + 4, sample_size - 4)) {
- LOG(LS_WARNING) << "Duplicate value for all pixels."
- << " format: " << GetFourccName(format)
- << " bpp: " << expected_bpp
- << " size: " << w << "x" << h
- << " bytes: " << sample_size
- << " expected: " << expected_size
- << " sample[0..3]: " << static_cast<int>(sample[0])
- << ", " << static_cast<int>(sample[1])
- << ", " << static_cast<int>(sample[2])
- << ", " << static_cast<int>(sample[3]);
+ << " sample[0..3]: " << static_cast<int>(four_samples[0])
+ << ", " << static_cast<int>(four_samples[1])
+ << ", " << static_cast<int>(four_samples[2])
+ << ", " << static_cast<int>(four_samples[3]);
}
+ // TODO(fbarchard): Add duplicate pixel check.
+ // TODO(fbarchard): Use frame counter atomic for thread safety.
static bool valid_once = true;
if (valid_once) {
valid_once = false;
@@ -380,10 +373,10 @@
<< " size: " << w << "x" << h
<< " bytes: " << sample_size
<< " expected: " << expected_size
- << " sample[0..3]: " << static_cast<int>(sample[0])
- << ", " << static_cast<int>(sample[1])
- << ", " << static_cast<int>(sample[2])
- << ", " << static_cast<int>(sample[3]);
+ << " sample[0..3]: " << static_cast<int>(four_samples[0])
+ << ", " << static_cast<int>(four_samples[1])
+ << ", " << static_cast<int>(four_samples[2])
+ << ", " << static_cast<int>(four_samples[3]);
}
return true;
}
diff --git a/media/base/videoframe.h b/media/base/videoframe.h
index fe5ff01..d94e470 100644
--- a/media/base/videoframe.h
+++ b/media/base/videoframe.h
@@ -28,8 +28,8 @@
#ifndef TALK_MEDIA_BASE_VIDEOFRAME_H_
#define TALK_MEDIA_BASE_VIDEOFRAME_H_
-#include "talk/base/basictypes.h"
-#include "talk/base/stream.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/stream.h"
namespace cricket {
@@ -126,10 +126,10 @@
virtual void CopyToFrame(VideoFrame* target) const;
// Writes the frame into the given stream and returns the StreamResult.
- // See talk/base/stream.h for a description of StreamResult and error.
+ // See webrtc/base/stream.h for a description of StreamResult and error.
// Error may be NULL. If a non-success value is returned from
// StreamInterface::Write(), we immediately return with that value.
- virtual talk_base::StreamResult Write(talk_base::StreamInterface *stream,
+ virtual rtc::StreamResult Write(rtc::StreamInterface *stream,
int *error);
// Converts the I420 data to RGB of a certain type such as ARGB and ABGR.
diff --git a/media/base/videoframe_unittest.h b/media/base/videoframe_unittest.h
index d7be7e3..483fc34 100644
--- a/media/base/videoframe_unittest.h
+++ b/media/base/videoframe_unittest.h
@@ -35,13 +35,13 @@
#include "libyuv/format_conversion.h"
#include "libyuv/planar_functions.h"
#include "libyuv/rotate.h"
-#include "talk/base/gunit.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/testutils.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/stringutils.h"
#if defined(_MSC_VER)
#define ALIGN16(var) __declspec(align(16)) var
@@ -89,16 +89,16 @@
bool LoadFrame(const std::string& filename, uint32 format,
int32 width, int32 height, int dw, int dh, int rotation,
T* frame) {
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(LoadSample(filename));
+ rtc::scoped_ptr<rtc::MemoryStream> ms(LoadSample(filename));
return LoadFrame(ms.get(), format, width, height, dw, dh, rotation, frame);
}
// Load a video frame from a memory stream.
- bool LoadFrame(talk_base::MemoryStream* ms, uint32 format,
+ bool LoadFrame(rtc::MemoryStream* ms, uint32 format,
int32 width, int32 height, T* frame) {
return LoadFrame(ms, format, width, height,
width, abs(height), 0, frame);
}
- bool LoadFrame(talk_base::MemoryStream* ms, uint32 format,
+ bool LoadFrame(rtc::MemoryStream* ms, uint32 format,
int32 width, int32 height, int dw, int dh, int rotation,
T* frame) {
if (!ms) {
@@ -130,19 +130,23 @@
return ret;
}
- talk_base::MemoryStream* LoadSample(const std::string& filename) {
- talk_base::Pathname path(cricket::GetTestFilePath(filename));
- talk_base::scoped_ptr<talk_base::FileStream> fs(
- talk_base::Filesystem::OpenFile(path, "rb"));
+ rtc::MemoryStream* LoadSample(const std::string& filename) {
+ rtc::Pathname path(cricket::GetTestFilePath(filename));
+ rtc::scoped_ptr<rtc::FileStream> fs(
+ rtc::Filesystem::OpenFile(path, "rb"));
if (!fs.get()) {
+ LOG(LS_ERROR) << "Could not open test file path: " << path.pathname()
+ << " from current dir "
+ << rtc::Filesystem::GetCurrentDirectory().pathname();
return NULL;
}
char buf[4096];
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
- new talk_base::MemoryStream());
- talk_base::StreamResult res = Flow(fs.get(), buf, sizeof(buf), ms.get());
- if (res != talk_base::SR_SUCCESS) {
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
+ new rtc::MemoryStream());
+ rtc::StreamResult res = Flow(fs.get(), buf, sizeof(buf), ms.get());
+ if (res != rtc::SR_SUCCESS) {
+ LOG(LS_ERROR) << "Could not load test file path: " << path.pathname();
return NULL;
}
@@ -153,24 +157,24 @@
bool DumpFrame(const std::string& prefix,
const cricket::VideoFrame& frame) {
char filename[256];
- talk_base::sprintfn(filename, sizeof(filename), "%s.%dx%d_P420.yuv",
+ rtc::sprintfn(filename, sizeof(filename), "%s.%dx%d_P420.yuv",
prefix.c_str(), frame.GetWidth(), frame.GetHeight());
size_t out_size = cricket::VideoFrame::SizeOf(frame.GetWidth(),
frame.GetHeight());
- talk_base::scoped_ptr<uint8[]> out(new uint8[out_size]);
+ rtc::scoped_ptr<uint8[]> out(new uint8[out_size]);
frame.CopyToBuffer(out.get(), out_size);
return DumpSample(filename, out.get(), out_size);
}
bool DumpSample(const std::string& filename, const void* buffer, int size) {
- talk_base::Pathname path(filename);
- talk_base::scoped_ptr<talk_base::FileStream> fs(
- talk_base::Filesystem::OpenFile(path, "wb"));
+ rtc::Pathname path(filename);
+ rtc::scoped_ptr<rtc::FileStream> fs(
+ rtc::Filesystem::OpenFile(path, "wb"));
if (!fs.get()) {
return false;
}
- return (fs->Write(buffer, size, NULL, NULL) == talk_base::SR_SUCCESS);
+ return (fs->Write(buffer, size, NULL, NULL) == rtc::SR_SUCCESS);
}
// Create a test image in the desired color space.
@@ -179,15 +183,15 @@
// The pattern is { { green, orange }, { blue, purple } }
// There is also a gradient within each square to ensure that the luma
// values are handled properly.
- talk_base::MemoryStream* CreateYuv422Sample(uint32 fourcc,
+ rtc::MemoryStream* CreateYuv422Sample(uint32 fourcc,
uint32 width, uint32 height) {
int y1_pos, y2_pos, u_pos, v_pos;
if (!GetYuv422Packing(fourcc, &y1_pos, &y2_pos, &u_pos, &v_pos)) {
return NULL;
}
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
- new talk_base::MemoryStream);
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
+ new rtc::MemoryStream);
int awidth = (width + 1) & ~1;
int size = awidth * 2 * height;
if (!ms->ReserveSize(size)) {
@@ -207,10 +211,10 @@
}
// Create a test image for YUV 420 formats with 12 bits per pixel.
- talk_base::MemoryStream* CreateYuvSample(uint32 width, uint32 height,
+ rtc::MemoryStream* CreateYuvSample(uint32 width, uint32 height,
uint32 bpp) {
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
- new talk_base::MemoryStream);
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
+ new rtc::MemoryStream);
if (!ms->ReserveSize(width * height * bpp / 8)) {
return NULL;
}
@@ -222,15 +226,15 @@
return ms.release();
}
- talk_base::MemoryStream* CreateRgbSample(uint32 fourcc,
+ rtc::MemoryStream* CreateRgbSample(uint32 fourcc,
uint32 width, uint32 height) {
int r_pos, g_pos, b_pos, bytes;
if (!GetRgbPacking(fourcc, &r_pos, &g_pos, &b_pos, &bytes)) {
return NULL;
}
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
- new talk_base::MemoryStream);
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
+ new rtc::MemoryStream);
if (!ms->ReserveSize(width * height * bytes)) {
return NULL;
}
@@ -249,7 +253,7 @@
// Simple conversion routines to verify the optimized VideoFrame routines.
// Converts from the specified colorspace to I420.
- bool ConvertYuv422(const talk_base::MemoryStream* ms,
+ bool ConvertYuv422(const rtc::MemoryStream* ms,
uint32 fourcc, uint32 width, uint32 height,
T* frame) {
int y1_pos, y2_pos, u_pos, v_pos;
@@ -287,7 +291,7 @@
// Convert RGB to 420.
// A negative height inverts the image.
- bool ConvertRgb(const talk_base::MemoryStream* ms,
+ bool ConvertRgb(const rtc::MemoryStream* ms,
uint32 fourcc, int32 width, int32 height,
T* frame) {
int r_pos, g_pos, b_pos, bytes;
@@ -419,17 +423,22 @@
const uint8* u, uint32 upitch,
const uint8* v, uint32 vpitch,
int max_error) {
- return IsSize(frame, width, height) &&
+ return IsSize(frame,
+ static_cast<uint32>(width),
+ static_cast<uint32>(height)) &&
frame.GetPixelWidth() == pixel_width &&
frame.GetPixelHeight() == pixel_height &&
frame.GetElapsedTime() == elapsed_time &&
frame.GetTimeStamp() == time_stamp &&
IsPlaneEqual("y", frame.GetYPlane(), frame.GetYPitch(), y, ypitch,
- width, height, max_error) &&
+ static_cast<uint32>(width),
+ static_cast<uint32>(height), max_error) &&
IsPlaneEqual("u", frame.GetUPlane(), frame.GetUPitch(), u, upitch,
- (width + 1) / 2, (height + 1) / 2, max_error) &&
+ static_cast<uint32>((width + 1) / 2),
+ static_cast<uint32>((height + 1) / 2), max_error) &&
IsPlaneEqual("v", frame.GetVPlane(), frame.GetVPitch(), v, vpitch,
- (width + 1) / 2, (height + 1) / 2, max_error);
+ static_cast<uint32>((width + 1) / 2),
+ static_cast<uint32>((height + 1) / 2), max_error);
}
static bool IsEqual(const cricket::VideoFrame& frame1,
@@ -482,7 +491,7 @@
void ConstructI420() {
T frame;
EXPECT_TRUE(IsNull(frame));
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuvSample(kWidth, kHeight, 12));
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_I420,
kWidth, kHeight, &frame));
@@ -497,7 +506,7 @@
// Test constructing an image from a YV12 buffer.
void ConstructYV12() {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuvSample(kWidth, kHeight, 12));
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_YV12,
kWidth, kHeight, &frame));
@@ -514,7 +523,7 @@
T frame1, frame2;
ASSERT_TRUE(LoadFrameNoRepeat(&frame1));
size_t buf_size = kWidth * kHeight * 2;
- talk_base::scoped_ptr<uint8[]> buf(new uint8[buf_size + kAlignment]);
+ rtc::scoped_ptr<uint8[]> buf(new uint8[buf_size + kAlignment]);
uint8* y = ALIGNP(buf.get(), kAlignment);
uint8* u = y + kWidth * kHeight;
uint8* v = u + (kWidth / 2) * kHeight;
@@ -535,7 +544,7 @@
T frame1, frame2;
ASSERT_TRUE(LoadFrameNoRepeat(&frame1));
size_t buf_size = kWidth * kHeight * 2;
- talk_base::scoped_ptr<uint8[]> buf(new uint8[buf_size + kAlignment]);
+ rtc::scoped_ptr<uint8[]> buf(new uint8[buf_size + kAlignment]);
uint8* yuy2 = ALIGNP(buf.get(), kAlignment);
EXPECT_EQ(0, libyuv::I420ToYUY2(frame1.GetYPlane(), frame1.GetYPitch(),
frame1.GetUPlane(), frame1.GetUPitch(),
@@ -552,7 +561,7 @@
T frame1, frame2;
ASSERT_TRUE(LoadFrameNoRepeat(&frame1));
size_t buf_size = kWidth * kHeight * 2;
- talk_base::scoped_ptr<uint8[]> buf(new uint8[buf_size + kAlignment + 1]);
+ rtc::scoped_ptr<uint8[]> buf(new uint8[buf_size + kAlignment + 1]);
uint8* yuy2 = ALIGNP(buf.get(), kAlignment) + 1;
EXPECT_EQ(0, libyuv::I420ToYUY2(frame1.GetYPlane(), frame1.GetYPitch(),
frame1.GetUPlane(), frame1.GetUPitch(),
@@ -568,7 +577,7 @@
// Normal is 1280x720. Wide is 12800x72
void ConstructYuy2Wide() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_YUY2, kWidth * 10, kHeight / 10));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertYuv422(ms.get(), cricket::FOURCC_YUY2,
@@ -582,7 +591,7 @@
// Test constructing an image from a UYVY buffer.
void ConstructUyvy() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_UYVY, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertYuv422(ms.get(), cricket::FOURCC_UYVY, kWidth, kHeight,
@@ -596,7 +605,7 @@
// We are merely verifying that the code succeeds and is free of crashes.
void ConstructM420() {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuvSample(kWidth, kHeight, 12));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_M420,
@@ -605,7 +614,7 @@
void ConstructQ420() {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuvSample(kWidth, kHeight, 12));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_Q420,
@@ -614,7 +623,7 @@
void ConstructNV21() {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuvSample(kWidth, kHeight, 12));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_NV21,
@@ -623,7 +632,7 @@
void ConstructNV12() {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuvSample(kWidth, kHeight, 12));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_NV12,
@@ -634,7 +643,7 @@
// Due to rounding, some pixels may differ slightly from the VideoFrame impl.
void ConstructABGR() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_ABGR, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_ABGR, kWidth, kHeight,
@@ -648,7 +657,7 @@
// Due to rounding, some pixels may differ slightly from the VideoFrame impl.
void ConstructARGB() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_ARGB, kWidth, kHeight,
@@ -662,7 +671,7 @@
// Normal is 1280x720. Wide is 12800x72
void ConstructARGBWide() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_ARGB, kWidth * 10, kHeight / 10));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_ARGB,
@@ -676,7 +685,7 @@
// Due to rounding, some pixels may differ slightly from the VideoFrame impl.
void ConstructBGRA() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_BGRA, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_BGRA, kWidth, kHeight,
@@ -690,7 +699,7 @@
// Due to rounding, some pixels may differ slightly from the VideoFrame impl.
void Construct24BG() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_24BG, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_24BG, kWidth, kHeight,
@@ -704,7 +713,7 @@
// Due to rounding, some pixels may differ slightly from the VideoFrame impl.
void ConstructRaw() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_RAW, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_RAW, kWidth, kHeight,
@@ -718,8 +727,8 @@
void ConstructRGB565() {
T frame1, frame2;
size_t out_size = kWidth * kHeight * 2;
- talk_base::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
- uint8 *out = ALIGNP(outbuf.get(), kAlignment);
+ rtc::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
+ uint8* out = ALIGNP(outbuf.get(), kAlignment);
T frame;
ASSERT_TRUE(LoadFrameNoRepeat(&frame1));
EXPECT_EQ(out_size, frame1.ConvertToRgbBuffer(cricket::FOURCC_RGBP,
@@ -734,8 +743,8 @@
void ConstructARGB1555() {
T frame1, frame2;
size_t out_size = kWidth * kHeight * 2;
- talk_base::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
- uint8 *out = ALIGNP(outbuf.get(), kAlignment);
+ rtc::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
+ uint8* out = ALIGNP(outbuf.get(), kAlignment);
T frame;
ASSERT_TRUE(LoadFrameNoRepeat(&frame1));
EXPECT_EQ(out_size, frame1.ConvertToRgbBuffer(cricket::FOURCC_RGBO,
@@ -750,8 +759,8 @@
void ConstructARGB4444() {
T frame1, frame2;
size_t out_size = kWidth * kHeight * 2;
- talk_base::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
- uint8 *out = ALIGNP(outbuf.get(), kAlignment);
+ rtc::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
+ uint8* out = ALIGNP(outbuf.get(), kAlignment);
T frame;
ASSERT_TRUE(LoadFrameNoRepeat(&frame1));
EXPECT_EQ(out_size, frame1.ConvertToRgbBuffer(cricket::FOURCC_R444,
@@ -769,14 +778,14 @@
#define TEST_BYR(NAME, BAYER) \
void NAME() { \
size_t bayer_size = kWidth * kHeight; \
- talk_base::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
+ rtc::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
bayer_size + kAlignment]); \
- uint8 *bayer = ALIGNP(bayerbuf.get(), kAlignment); \
+ uint8* bayer = ALIGNP(bayerbuf.get(), kAlignment); \
T frame1, frame2; \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms( \
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight)); \
ASSERT_TRUE(ms.get() != NULL); \
- libyuv::ARGBToBayer##BAYER(reinterpret_cast<uint8 *>(ms->GetBuffer()), \
+ libyuv::ARGBToBayer##BAYER(reinterpret_cast<uint8* >(ms->GetBuffer()), \
kWidth * 4, \
bayer, kWidth, \
kWidth, kHeight); \
@@ -798,7 +807,7 @@
#define TEST_MIRROR(FOURCC, BPP) \
void Construct##FOURCC##Mirror() { \
T frame1, frame2, frame3; \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms( \
CreateYuvSample(kWidth, kHeight, BPP)); \
ASSERT_TRUE(ms.get() != NULL); \
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_##FOURCC, \
@@ -812,8 +821,8 @@
reinterpret_cast<uint8*>(ms->GetBuffer()), \
data_size, \
1, 1, 0, 0, 0)); \
- int width_rotate = frame1.GetWidth(); \
- int height_rotate = frame1.GetHeight(); \
+ int width_rotate = static_cast<int>(frame1.GetWidth()); \
+ int height_rotate = static_cast<int>(frame1.GetHeight()); \
EXPECT_TRUE(frame3.InitToBlack(width_rotate, height_rotate, 1, 1, 0, 0)); \
libyuv::I420Mirror(frame2.GetYPlane(), frame2.GetYPitch(), \
frame2.GetUPlane(), frame2.GetUPitch(), \
@@ -831,7 +840,7 @@
#define TEST_ROTATE(FOURCC, BPP, ROTATE) \
void Construct##FOURCC##Rotate##ROTATE() { \
T frame1, frame2, frame3; \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms( \
CreateYuvSample(kWidth, kHeight, BPP)); \
ASSERT_TRUE(ms.get() != NULL); \
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_##FOURCC, \
@@ -845,8 +854,8 @@
reinterpret_cast<uint8*>(ms->GetBuffer()), \
data_size, \
1, 1, 0, 0, 0)); \
- int width_rotate = frame1.GetWidth(); \
- int height_rotate = frame1.GetHeight(); \
+ int width_rotate = static_cast<int>(frame1.GetWidth()); \
+ int height_rotate = static_cast<int>(frame1.GetHeight()); \
EXPECT_TRUE(frame3.InitToBlack(width_rotate, height_rotate, 1, 1, 0, 0)); \
libyuv::I420Rotate(frame2.GetYPlane(), frame2.GetYPitch(), \
frame2.GetUPlane(), frame2.GetUPitch(), \
@@ -887,7 +896,7 @@
// Test constructing an image from a UYVY buffer rotated 90 degrees.
void ConstructUyvyRotate90() {
T frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_UYVY, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_UYVY,
@@ -898,7 +907,7 @@
// Test constructing an image from a UYVY buffer rotated 180 degrees.
void ConstructUyvyRotate180() {
T frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_UYVY, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_UYVY,
@@ -909,7 +918,7 @@
// Test constructing an image from a UYVY buffer rotated 270 degrees.
void ConstructUyvyRotate270() {
T frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_UYVY, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_UYVY,
@@ -920,7 +929,7 @@
// Test constructing an image from a YUY2 buffer rotated 90 degrees.
void ConstructYuy2Rotate90() {
T frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_YUY2, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_YUY2,
@@ -931,7 +940,7 @@
// Test constructing an image from a YUY2 buffer rotated 180 degrees.
void ConstructYuy2Rotate180() {
T frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_YUY2, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_YUY2,
@@ -942,7 +951,7 @@
// Test constructing an image from a YUY2 buffer rotated 270 degrees.
void ConstructYuy2Rotate270() {
T frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_YUY2, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_YUY2,
@@ -994,8 +1003,8 @@
}
// Convert back to ARGB.
size_t out_size = 4;
- talk_base::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
- uint8 *out = ALIGNP(outbuf.get(), kAlignment);
+ rtc::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
+ uint8* out = ALIGNP(outbuf.get(), kAlignment);
EXPECT_EQ(out_size, frame.ConvertToRgbBuffer(cricket::FOURCC_ARGB,
out,
@@ -1031,8 +1040,8 @@
}
// Convert back to ARGB
size_t out_size = 10 * 4;
- talk_base::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
- uint8 *out = ALIGNP(outbuf.get(), kAlignment);
+ rtc::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment]);
+ uint8* out = ALIGNP(outbuf.get(), kAlignment);
EXPECT_EQ(out_size, frame.ConvertToRgbBuffer(cricket::FOURCC_ARGB,
out,
@@ -1055,7 +1064,7 @@
// Test constructing an image from a YUY2 buffer with horizontal cropping.
void ConstructYuy2CropHorizontal() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_YUY2, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertYuv422(ms.get(), cricket::FOURCC_YUY2, kWidth, kHeight,
@@ -1068,7 +1077,7 @@
// Test constructing an image from an ARGB buffer with horizontal cropping.
void ConstructARGBCropHorizontal() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_ARGB, kWidth, kHeight,
@@ -1153,7 +1162,7 @@
void ValidateFrame(const char* name, uint32 fourcc, int data_adjust,
int size_adjust, bool expected_result) {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(LoadSample(name));
+ rtc::scoped_ptr<rtc::MemoryStream> ms(LoadSample(name));
ASSERT_TRUE(ms.get() != NULL);
const uint8* sample = reinterpret_cast<const uint8*>(ms.get()->GetBuffer());
size_t sample_size;
@@ -1163,7 +1172,7 @@
// Allocate a buffer with end page aligned.
const int kPadToHeapSized = 16 * 1024 * 1024;
- talk_base::scoped_ptr<uint8[]> page_buffer(
+ rtc::scoped_ptr<uint8[]> page_buffer(
new uint8[((data_size + kPadToHeapSized + 4095) & ~4095)]);
uint8* data_ptr = page_buffer.get();
if (!data_ptr) {
@@ -1172,7 +1181,7 @@
return;
}
data_ptr += kPadToHeapSized + (-(static_cast<int>(data_size)) & 4095);
- memcpy(data_ptr, sample, talk_base::_min(data_size, sample_size));
+ memcpy(data_ptr, sample, rtc::_min(data_size, sample_size));
for (int i = 0; i < repeat_; ++i) {
EXPECT_EQ(expected_result, frame.Validate(fourcc, kWidth, kHeight,
data_ptr,
@@ -1269,7 +1278,7 @@
// Test constructing an image from a YUY2 buffer (and synonymous formats).
void ConstructYuy2Aliases() {
T frame1, frame2, frame3, frame4;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_YUY2, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertYuv422(ms.get(), cricket::FOURCC_YUY2, kWidth, kHeight,
@@ -1288,7 +1297,7 @@
// Test constructing an image from a UYVY buffer (and synonymous formats).
void ConstructUyvyAliases() {
T frame1, frame2, frame3, frame4;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_UYVY, kWidth, kHeight));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertYuv422(ms.get(), cricket::FOURCC_UYVY, kWidth, kHeight,
@@ -1343,7 +1352,7 @@
T frame1, frame2;
for (int height = kMinHeightAll; height <= kMaxHeightAll; ++height) {
for (int width = kMinWidthAll; width <= kMaxWidthAll; ++width) {
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateYuv422Sample(cricket::FOURCC_YUY2, width, height));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertYuv422(ms.get(), cricket::FOURCC_YUY2, width, height,
@@ -1361,7 +1370,7 @@
T frame1, frame2;
for (int height = kMinHeightAll; height <= kMaxHeightAll; ++height) {
for (int width = kMinWidthAll; width <= kMaxWidthAll; ++width) {
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_ARGB, width, height));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_ARGB, width, height,
@@ -1376,7 +1385,7 @@
const int kOddHeight = 260;
for (int j = 0; j < 2; ++j) {
for (int i = 0; i < 2; ++i) {
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
CreateRgbSample(cricket::FOURCC_ARGB, kOddWidth + i, kOddHeight + j));
ASSERT_TRUE(ms.get() != NULL);
EXPECT_TRUE(ConvertRgb(ms.get(), cricket::FOURCC_ARGB,
@@ -1392,7 +1401,7 @@
// Tests re-initing an existing image.
void Reset() {
T frame1, frame2;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
LoadSample(kImageFilename));
ASSERT_TRUE(ms.get() != NULL);
size_t data_size;
@@ -1429,10 +1438,10 @@
int astride = kWidth * bpp + rowpad;
size_t out_size = astride * kHeight;
- talk_base::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment + 1]);
+ rtc::scoped_ptr<uint8[]> outbuf(new uint8[out_size + kAlignment + 1]);
memset(outbuf.get(), 0, out_size + kAlignment + 1);
- uint8 *outtop = ALIGNP(outbuf.get(), kAlignment);
- uint8 *out = outtop;
+ uint8* outtop = ALIGNP(outbuf.get(), kAlignment);
+ uint8* out = outtop;
int stride = astride;
if (invert) {
out += (kHeight - 1) * stride; // Point to last row.
@@ -1843,7 +1852,7 @@
void ConvertToI422Buffer() {
T frame1, frame2;
size_t out_size = kWidth * kHeight * 2;
- talk_base::scoped_ptr<uint8[]> buf(new uint8[out_size + kAlignment]);
+ rtc::scoped_ptr<uint8[]> buf(new uint8[out_size + kAlignment]);
uint8* y = ALIGNP(buf.get(), kAlignment);
uint8* u = y + kWidth * kHeight;
uint8* v = u + (kWidth / 2) * kHeight;
@@ -1867,11 +1876,11 @@
#define TEST_TOBYR(NAME, BAYER) \
void NAME() { \
size_t bayer_size = kWidth * kHeight; \
- talk_base::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
+ rtc::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
bayer_size + kAlignment]); \
- uint8 *bayer = ALIGNP(bayerbuf.get(), kAlignment); \
+ uint8* bayer = ALIGNP(bayerbuf.get(), kAlignment); \
T frame; \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms( \
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight)); \
ASSERT_TRUE(ms.get() != NULL); \
for (int i = 0; i < repeat_; ++i) { \
@@ -1880,7 +1889,7 @@
bayer, kWidth, \
kWidth, kHeight); \
} \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms2( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms2( \
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight)); \
size_t data_size; \
bool ret = ms2->GetSize(&data_size); \
@@ -1896,11 +1905,11 @@
} \
void NAME##Unaligned() { \
size_t bayer_size = kWidth * kHeight; \
- talk_base::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
+ rtc::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
bayer_size + 1 + kAlignment]); \
- uint8 *bayer = ALIGNP(bayerbuf.get(), kAlignment) + 1; \
+ uint8* bayer = ALIGNP(bayerbuf.get(), kAlignment) + 1; \
T frame; \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms( \
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight)); \
ASSERT_TRUE(ms.get() != NULL); \
for (int i = 0; i < repeat_; ++i) { \
@@ -1909,7 +1918,7 @@
bayer, kWidth, \
kWidth, kHeight); \
} \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms2( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms2( \
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight)); \
size_t data_size; \
bool ret = ms2->GetSize(&data_size); \
@@ -1933,14 +1942,14 @@
#define TEST_BYRTORGB(NAME, BAYER) \
void NAME() { \
size_t bayer_size = kWidth * kHeight; \
- talk_base::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
+ rtc::scoped_ptr<uint8[]> bayerbuf(new uint8[ \
bayer_size + kAlignment]); \
- uint8 *bayer1 = ALIGNP(bayerbuf.get(), kAlignment); \
+ uint8* bayer1 = ALIGNP(bayerbuf.get(), kAlignment); \
for (int i = 0; i < kWidth * kHeight; ++i) { \
bayer1[i] = static_cast<uint8>(i * 33u + 183u); \
} \
T frame; \
- talk_base::scoped_ptr<talk_base::MemoryStream> ms( \
+ rtc::scoped_ptr<rtc::MemoryStream> ms( \
CreateRgbSample(cricket::FOURCC_ARGB, kWidth, kHeight)); \
ASSERT_TRUE(ms.get() != NULL); \
for (int i = 0; i < repeat_; ++i) { \
@@ -1949,9 +1958,9 @@
kWidth * 4, \
kWidth, kHeight); \
} \
- talk_base::scoped_ptr<uint8[]> bayer2buf(new uint8[ \
+ rtc::scoped_ptr<uint8[]> bayer2buf(new uint8[ \
bayer_size + kAlignment]); \
- uint8 *bayer2 = ALIGNP(bayer2buf.get(), kAlignment); \
+ uint8* bayer2 = ALIGNP(bayer2buf.get(), kAlignment); \
libyuv::ARGBToBayer##BAYER(reinterpret_cast<uint8*>(ms->GetBuffer()), \
kWidth * 4, \
bayer2, kWidth, \
@@ -1973,8 +1982,8 @@
///////////////////
void Copy() {
- talk_base::scoped_ptr<T> source(new T);
- talk_base::scoped_ptr<cricket::VideoFrame> target;
+ rtc::scoped_ptr<T> source(new T);
+ rtc::scoped_ptr<cricket::VideoFrame> target;
ASSERT_TRUE(LoadFrameNoRepeat(source.get()));
target.reset(source->Copy());
EXPECT_TRUE(IsEqual(*source, *target, 0));
@@ -1983,8 +1992,8 @@
}
void CopyIsRef() {
- talk_base::scoped_ptr<T> source(new T);
- talk_base::scoped_ptr<cricket::VideoFrame> target;
+ rtc::scoped_ptr<T> source(new T);
+ rtc::scoped_ptr<cricket::VideoFrame> target;
ASSERT_TRUE(LoadFrameNoRepeat(source.get()));
target.reset(source->Copy());
EXPECT_TRUE(IsEqual(*source, *target, 0));
@@ -1994,8 +2003,8 @@
}
void MakeExclusive() {
- talk_base::scoped_ptr<T> source(new T);
- talk_base::scoped_ptr<cricket::VideoFrame> target;
+ rtc::scoped_ptr<T> source(new T);
+ rtc::scoped_ptr<cricket::VideoFrame> target;
ASSERT_TRUE(LoadFrameNoRepeat(source.get()));
target.reset(source->Copy());
EXPECT_TRUE(target->MakeExclusive());
@@ -2007,13 +2016,13 @@
void CopyToBuffer() {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
LoadSample(kImageFilename));
ASSERT_TRUE(ms.get() != NULL);
ASSERT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_I420, kWidth, kHeight,
&frame));
size_t out_size = kWidth * kHeight * 3 / 2;
- talk_base::scoped_ptr<uint8[]> out(new uint8[out_size]);
+ rtc::scoped_ptr<uint8[]> out(new uint8[out_size]);
for (int i = 0; i < repeat_; ++i) {
EXPECT_EQ(out_size, frame.CopyToBuffer(out.get(), out_size));
}
@@ -2022,7 +2031,7 @@
void CopyToFrame() {
T source;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
LoadSample(kImageFilename));
ASSERT_TRUE(ms.get() != NULL);
ASSERT_TRUE(LoadFrame(ms.get(), cricket::FOURCC_I420, kWidth, kHeight,
@@ -2041,10 +2050,10 @@
void Write() {
T frame;
- talk_base::scoped_ptr<talk_base::MemoryStream> ms(
+ rtc::scoped_ptr<rtc::MemoryStream> ms(
LoadSample(kImageFilename));
ASSERT_TRUE(ms.get() != NULL);
- talk_base::MemoryStream ms2;
+ rtc::MemoryStream ms2;
size_t size;
ASSERT_TRUE(ms->GetSize(&size));
ASSERT_TRUE(ms2.ReserveSize(size));
@@ -2053,7 +2062,7 @@
for (int i = 0; i < repeat_; ++i) {
ms2.SetPosition(0u); // Useful when repeat_ > 1.
int error;
- EXPECT_EQ(talk_base::SR_SUCCESS, frame.Write(&ms2, &error));
+ EXPECT_EQ(rtc::SR_SUCCESS, frame.Write(&ms2, &error));
}
size_t out_size = cricket::VideoFrame::SizeOf(kWidth, kHeight);
EXPECT_EQ(0, memcmp(ms2.GetBuffer(), ms->GetBuffer(), out_size));
@@ -2061,7 +2070,7 @@
void CopyToBuffer1Pixel() {
size_t out_size = 3;
- talk_base::scoped_ptr<uint8[]> out(new uint8[out_size + 1]);
+ rtc::scoped_ptr<uint8[]> out(new uint8[out_size + 1]);
memset(out.get(), 0xfb, out_size + 1); // Fill buffer
uint8 pixel[3] = { 1, 2, 3 };
T frame;
diff --git a/media/base/videoframefactory.h b/media/base/videoframefactory.h
new file mode 100755
index 0000000..301ec1c
--- /dev/null
+++ b/media/base/videoframefactory.h
@@ -0,0 +1,52 @@
+// libjingle
+// Copyright 2014 Google Inc.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+
+#ifndef TALK_MEDIA_BASE_VIDEOFRAMEFACTORY_H_
+#define TALK_MEDIA_BASE_VIDEOFRAMEFACTORY_H_
+
+namespace cricket {
+
+struct CapturedFrame;
+class VideoFrame;
+
+// Creates cricket::VideoFrames, or a subclass of cricket::VideoFrame
+// depending on the subclass of VideoFrameFactory.
+class VideoFrameFactory {
+ public:
+ VideoFrameFactory() {}
+ virtual ~VideoFrameFactory() {}
+
+ // The returned frame aliases the aliased_frame if the input color
+ // space allows for aliasing, otherwise a color conversion will
+ // occur. For safety, |input_frame| must outlive the returned
+ // frame. Returns NULL if conversion fails.
+ virtual VideoFrame* CreateAliasedFrame(
+ const CapturedFrame* input_frame, int width, int height) const = 0;
+};
+
+} // namespace cricket
+
+#endif // TALK_MEDIA_BASE_VIDEOFRAMEFACTORY_H_
diff --git a/media/base/videoprocessor.h b/media/base/videoprocessor.h
index 412d989..da8020e 100755
--- a/media/base/videoprocessor.h
+++ b/media/base/videoprocessor.h
@@ -28,8 +28,8 @@
#ifndef TALK_MEDIA_BASE_VIDEOPROCESSOR_H_
#define TALK_MEDIA_BASE_VIDEOPROCESSOR_H_
-#include "talk/base/sigslot.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
diff --git a/media/base/videorenderer.h b/media/base/videorenderer.h
index ccbe978..73b0eab 100644
--- a/media/base/videorenderer.h
+++ b/media/base/videorenderer.h
@@ -32,7 +32,7 @@
#include <string>
#endif // _DEBUG
-#include "talk/base/sigslot.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
diff --git a/media/base/voiceprocessor.h b/media/base/voiceprocessor.h
index 576bdca..c2c3387 100755
--- a/media/base/voiceprocessor.h
+++ b/media/base/voiceprocessor.h
@@ -28,9 +28,9 @@
#ifndef TALK_MEDIA_BASE_VOICEPROCESSOR_H_
#define TALK_MEDIA_BASE_VOICEPROCESSOR_H_
-#include "talk/base/basictypes.h"
-#include "talk/base/sigslot.h"
#include "talk/media/base/audioframe.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
diff --git a/media/base/yuvframegenerator.cc b/media/base/yuvframegenerator.cc
index 57b5314..bffa715 100644
--- a/media/base/yuvframegenerator.cc
+++ b/media/base/yuvframegenerator.cc
@@ -3,8 +3,8 @@
#include <string.h>
#include <sstream>
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/common.h"
namespace cricket {
diff --git a/media/base/yuvframegenerator.h b/media/base/yuvframegenerator.h
index 4adf971..104fb54 100644
--- a/media/base/yuvframegenerator.h
+++ b/media/base/yuvframegenerator.h
@@ -12,7 +12,7 @@
#ifndef TALK_MEDIA_BASE_YUVFRAMEGENERATOR_H_
#define TALK_MEDIA_BASE_YUVFRAMEGENERATOR_H_
-#include "talk/base/basictypes.h"
+#include "webrtc/base/basictypes.h"
namespace cricket {
diff --git a/media/devices/carbonvideorenderer.cc b/media/devices/carbonvideorenderer.cc
index 71abf26..29a51f3 100644
--- a/media/devices/carbonvideorenderer.cc
+++ b/media/devices/carbonvideorenderer.cc
@@ -27,9 +27,9 @@
#include "talk/media/devices/carbonvideorenderer.h"
-#include "talk/base/logging.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -65,7 +65,7 @@
bool CarbonVideoRenderer::DrawFrame() {
// Grab the image lock to make sure it is not changed why we'll draw it.
- talk_base::CritScope cs(&image_crit_);
+ rtc::CritScope cs(&image_crit_);
if (image_.get() == NULL) {
// Nothing to draw, just return.
@@ -111,7 +111,7 @@
bool CarbonVideoRenderer::SetSize(int width, int height, int reserved) {
if (width != image_width_ || height != image_height_) {
// Grab the image lock while changing its size.
- talk_base::CritScope cs(&image_crit_);
+ rtc::CritScope cs(&image_crit_);
image_width_ = width;
image_height_ = height;
image_.reset(new uint8[width * height * 4]);
@@ -126,7 +126,7 @@
}
{
// Grab the image lock so we are not trashing up the image being drawn.
- talk_base::CritScope cs(&image_crit_);
+ rtc::CritScope cs(&image_crit_);
frame->ConvertToRgbBuffer(cricket::FOURCC_ABGR,
image_.get(),
frame->GetWidth() * frame->GetHeight() * 4,
diff --git a/media/devices/carbonvideorenderer.h b/media/devices/carbonvideorenderer.h
index 6c52fcf..4a5989e 100644
--- a/media/devices/carbonvideorenderer.h
+++ b/media/devices/carbonvideorenderer.h
@@ -31,9 +31,9 @@
#include <Carbon/Carbon.h>
-#include "talk/base/criticalsection.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/scoped_ptr.h"
namespace cricket {
@@ -57,8 +57,8 @@
static OSStatus DrawEventHandler(EventHandlerCallRef handler,
EventRef event,
void* data);
- talk_base::scoped_ptr<uint8[]> image_;
- talk_base::CriticalSection image_crit_;
+ rtc::scoped_ptr<uint8[]> image_;
+ rtc::CriticalSection image_crit_;
int image_width_;
int image_height_;
int x_;
diff --git a/media/devices/devicemanager.cc b/media/devices/devicemanager.cc
index 75b935c..04ea82f 100644
--- a/media/devices/devicemanager.cc
+++ b/media/devices/devicemanager.cc
@@ -27,34 +27,29 @@
#include "talk/media/devices/devicemanager.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/windowpicker.h"
-#include "talk/base/windowpickerfactory.h"
#include "talk/media/base/mediacommon.h"
+#include "talk/media/base/videocapturerfactory.h"
#include "talk/media/devices/deviceinfo.h"
#include "talk/media/devices/filevideocapturer.h"
#include "talk/media/devices/yuvframescapturer.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/windowpicker.h"
+#include "webrtc/base/windowpickerfactory.h"
-#if defined(HAVE_WEBRTC_VIDEO)
-#include "talk/media/webrtc/webrtcvideocapturer.h"
-#endif
-
-
-#if defined(HAVE_WEBRTC_VIDEO)
-#define VIDEO_CAPTURER_NAME WebRtcVideoCapturer
-#endif
-
+#ifdef HAVE_WEBRTC_VIDEO
+#include "talk/media/webrtc/webrtcvideocapturerfactory.h"
+#endif // HAVE_WEBRTC_VIDEO
namespace {
bool StringMatchWithWildcard(
const std::pair<const std::basic_string<char>, cricket::VideoFormat> key,
const std::string& val) {
- return talk_base::string_match(val.c_str(), key.first.c_str());
+ return rtc::string_match(val.c_str(), key.first.c_str());
}
} // namespace
@@ -64,29 +59,12 @@
// Initialize to empty string.
const char DeviceManagerInterface::kDefaultDeviceName[] = "";
-class DefaultVideoCapturerFactory : public VideoCapturerFactory {
- public:
- DefaultVideoCapturerFactory() {}
- virtual ~DefaultVideoCapturerFactory() {}
-
- VideoCapturer* Create(const Device& device) {
-#if defined(VIDEO_CAPTURER_NAME)
- VIDEO_CAPTURER_NAME* return_value = new VIDEO_CAPTURER_NAME;
- if (!return_value->Init(device)) {
- delete return_value;
- return NULL;
- }
- return return_value;
-#else
- return NULL;
-#endif
- }
-};
-
DeviceManager::DeviceManager()
: initialized_(false),
- device_video_capturer_factory_(new DefaultVideoCapturerFactory),
- window_picker_(talk_base::WindowPickerFactory::CreateWindowPicker()) {
+ window_picker_(rtc::WindowPickerFactory::CreateWindowPicker()) {
+#ifdef HAVE_WEBRTC_VIDEO
+ SetVideoDeviceCapturerFactory(new WebRtcVideoDeviceCapturerFactory());
+#endif // HAVE_WEBRTC_VIDEO
}
DeviceManager::~DeviceManager() {
@@ -187,7 +165,7 @@
bool DeviceManager::GetFakeVideoCaptureDevice(const std::string& name,
Device* out) const {
- if (talk_base::Filesystem::IsFile(name)) {
+ if (rtc::Filesystem::IsFile(name)) {
*out = FileVideoCapturer::CreateFileVideoCapturerDevice(name);
return true;
}
@@ -212,12 +190,16 @@
}
VideoCapturer* DeviceManager::CreateVideoCapturer(const Device& device) const {
- VideoCapturer* capturer = ConstructFakeVideoCapturer(device);
+ VideoCapturer* capturer = MaybeConstructFakeVideoCapturer(device);
if (capturer) {
return capturer;
}
- capturer = device_video_capturer_factory_->Create(device);
+ if (!video_device_capturer_factory_) {
+ LOG(LS_ERROR) << "No video capturer factory for devices.";
+ return NULL;
+ }
+ capturer = video_device_capturer_factory_->Create(device);
if (!capturer) {
return NULL;
}
@@ -231,7 +213,7 @@
return capturer;
}
-VideoCapturer* DeviceManager::ConstructFakeVideoCapturer(
+VideoCapturer* DeviceManager::MaybeConstructFakeVideoCapturer(
const Device& device) const {
// TODO(hellner): Throw out the creation of a file video capturer once the
// refactoring is completed.
@@ -242,7 +224,7 @@
return NULL;
}
LOG(LS_INFO) << "Created file video capturer " << device.name;
- capturer->set_repeat(talk_base::kForever);
+ capturer->set_repeat(rtc::kForever);
return capturer;
}
@@ -255,46 +237,28 @@
}
bool DeviceManager::GetWindows(
- std::vector<talk_base::WindowDescription>* descriptions) {
+ std::vector<rtc::WindowDescription>* descriptions) {
if (!window_picker_) {
return false;
}
return window_picker_->GetWindowList(descriptions);
}
-VideoCapturer* DeviceManager::CreateWindowCapturer(talk_base::WindowId window) {
-#if defined(WINDOW_CAPTURER_NAME)
- WINDOW_CAPTURER_NAME* window_capturer = new WINDOW_CAPTURER_NAME();
- if (!window_capturer->Init(window)) {
- delete window_capturer;
- return NULL;
- }
- return window_capturer;
-#else
- return NULL;
-#endif
-}
-
bool DeviceManager::GetDesktops(
- std::vector<talk_base::DesktopDescription>* descriptions) {
+ std::vector<rtc::DesktopDescription>* descriptions) {
if (!window_picker_) {
return false;
}
return window_picker_->GetDesktopList(descriptions);
}
-VideoCapturer* DeviceManager::CreateDesktopCapturer(
- talk_base::DesktopId desktop) {
-#if defined(DESKTOP_CAPTURER_NAME)
- DESKTOP_CAPTURER_NAME* desktop_capturer = new DESKTOP_CAPTURER_NAME();
- if (!desktop_capturer->Init(desktop.index())) {
- delete desktop_capturer;
+VideoCapturer* DeviceManager::CreateScreenCapturer(
+ const ScreencastId& screenid) const {
+ if (!screen_capturer_factory_) {
+ LOG(LS_ERROR) << "No video capturer factory for screens.";
return NULL;
}
- return desktop_capturer;
-#else
- return NULL;
-#endif
+ return screen_capturer_factory_->Create(screenid);
}
bool DeviceManager::GetAudioDevices(bool input,
diff --git a/media/devices/devicemanager.h b/media/devices/devicemanager.h
index f6099f3..982c679 100644
--- a/media/devices/devicemanager.h
+++ b/media/devices/devicemanager.h
@@ -32,13 +32,16 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/window.h"
+#include "talk/media/base/device.h"
+#include "talk/media/base/screencastid.h"
+#include "talk/media/base/videocapturerfactory.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/window.h"
-namespace talk_base {
+namespace rtc {
class DesktopDescription;
class WindowDescription;
@@ -49,28 +52,6 @@
class VideoCapturer;
-// Used to represent an audio or video capture or render device.
-struct Device {
- Device() {}
- Device(const std::string& first, int second)
- : name(first),
- id(talk_base::ToString(second)) {
- }
- Device(const std::string& first, const std::string& second)
- : name(first), id(second) {}
-
- std::string name;
- std::string id;
-};
-
-class VideoCapturerFactory {
- public:
- VideoCapturerFactory() {}
- virtual ~VideoCapturerFactory() {}
-
- virtual VideoCapturer* Create(const Device& device) = 0;
-};
-
// DeviceManagerInterface - interface to manage the audio and
// video devices on the system.
class DeviceManagerInterface {
@@ -94,6 +75,14 @@
virtual bool GetVideoCaptureDevices(std::vector<Device>* devs) = 0;
virtual bool GetVideoCaptureDevice(const std::string& name, Device* out) = 0;
+ // If the device manager needs to create video capturers, here is
+ // how to control which video capturers are created. These take
+ // ownership of the factories.
+ virtual void SetVideoDeviceCapturerFactory(
+ VideoDeviceCapturerFactory* video_device_capturer_factory) = 0;
+ virtual void SetScreenCapturerFactory(
+ ScreenCapturerFactory* screen_capturer_factory) = 0;
+
// Caps the capture format according to max format for capturers created
// by CreateVideoCapturer(). See ConstrainSupportedFormats() in
// videocapturer.h for more detail.
@@ -108,13 +97,11 @@
virtual VideoCapturer* CreateVideoCapturer(const Device& device) const = 0;
virtual bool GetWindows(
- std::vector<talk_base::WindowDescription>* descriptions) = 0;
- virtual VideoCapturer* CreateWindowCapturer(talk_base::WindowId window) = 0;
-
+ std::vector<rtc::WindowDescription>* descriptions) = 0;
virtual bool GetDesktops(
- std::vector<talk_base::DesktopDescription>* descriptions) = 0;
- virtual VideoCapturer* CreateDesktopCapturer(
- talk_base::DesktopId desktop) = 0;
+ std::vector<rtc::DesktopDescription>* descriptions) = 0;
+ virtual VideoCapturer* CreateScreenCapturer(
+ const ScreencastId& screenid) const = 0;
sigslot::signal0<> SignalDevicesChange;
@@ -142,11 +129,6 @@
DeviceManager();
virtual ~DeviceManager();
- void set_device_video_capturer_factory(
- VideoCapturerFactory* device_video_capturer_factory) {
- device_video_capturer_factory_.reset(device_video_capturer_factory);
- }
-
// Initialization
virtual bool Init();
virtual void Terminate();
@@ -164,19 +146,29 @@
virtual bool GetVideoCaptureDevices(std::vector<Device>* devs);
virtual bool GetVideoCaptureDevice(const std::string& name, Device* out);
+ virtual void SetVideoDeviceCapturerFactory(
+ VideoDeviceCapturerFactory* video_device_capturer_factory) {
+ video_device_capturer_factory_.reset(video_device_capturer_factory);
+ }
+ virtual void SetScreenCapturerFactory(
+ ScreenCapturerFactory* screen_capturer_factory) {
+ screen_capturer_factory_.reset(screen_capturer_factory);
+ }
+
+
virtual void SetVideoCaptureDeviceMaxFormat(const std::string& usb_id,
const VideoFormat& max_format);
virtual void ClearVideoCaptureDeviceMaxFormat(const std::string& usb_id);
+ // TODO(pthatcher): Rename to CreateVideoDeviceCapturer.
virtual VideoCapturer* CreateVideoCapturer(const Device& device) const;
virtual bool GetWindows(
- std::vector<talk_base::WindowDescription>* descriptions);
- virtual VideoCapturer* CreateWindowCapturer(talk_base::WindowId window);
-
+ std::vector<rtc::WindowDescription>* descriptions);
virtual bool GetDesktops(
- std::vector<talk_base::DesktopDescription>* descriptions);
- virtual VideoCapturer* CreateDesktopCapturer(talk_base::DesktopId desktop);
+ std::vector<rtc::DesktopDescription>* descriptions);
+ virtual VideoCapturer* CreateScreenCapturer(
+ const ScreencastId& screenid) const;
// The exclusion_list MUST be a NULL terminated list.
static bool FilterDevices(std::vector<Device>* devices,
@@ -202,13 +194,16 @@
static bool ShouldDeviceBeIgnored(const std::string& device_name,
const char* const exclusion_list[]);
bool GetFakeVideoCaptureDevice(const std::string& name, Device* out) const;
- VideoCapturer* ConstructFakeVideoCapturer(const Device& device) const;
+ VideoCapturer* MaybeConstructFakeVideoCapturer(const Device& device) const;
bool initialized_;
- talk_base::scoped_ptr<VideoCapturerFactory> device_video_capturer_factory_;
+ rtc::scoped_ptr<
+ VideoDeviceCapturerFactory> video_device_capturer_factory_;
+ rtc::scoped_ptr<
+ ScreenCapturerFactory> screen_capturer_factory_;
std::map<std::string, VideoFormat> max_formats_;
- talk_base::scoped_ptr<DeviceWatcher> watcher_;
- talk_base::scoped_ptr<talk_base::WindowPicker> window_picker_;
+ rtc::scoped_ptr<DeviceWatcher> watcher_;
+ rtc::scoped_ptr<rtc::WindowPicker> window_picker_;
};
} // namespace cricket
diff --git a/media/devices/devicemanager_unittest.cc b/media/devices/devicemanager_unittest.cc
index d8564ea..f259c7d 100644
--- a/media/devices/devicemanager_unittest.cc
+++ b/media/devices/devicemanager_unittest.cc
@@ -28,31 +28,33 @@
#include "talk/media/devices/devicemanager.h"
#ifdef WIN32
-#include "talk/base/win32.h"
#include <objbase.h>
+#include "webrtc/base/win32.h"
#endif
#include <string>
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stream.h"
-#include "talk/base/windowpickerfactory.h"
#include "talk/media/base/fakevideocapturer.h"
+#include "talk/media/base/screencastid.h"
#include "talk/media/base/testutils.h"
+#include "talk/media/base/videocapturerfactory.h"
#include "talk/media/devices/filevideocapturer.h"
#include "talk/media/devices/v4llookup.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/windowpickerfactory.h"
#ifdef LINUX
// TODO(juberti): Figure out why this doesn't compile on Windows.
-#include "talk/base/fileutils_mock.h"
+#include "webrtc/base/fileutils_mock.h"
#endif // LINUX
-using talk_base::Pathname;
-using talk_base::FileTimeType;
-using talk_base::scoped_ptr;
+using rtc::Pathname;
+using rtc::FileTimeType;
+using rtc::scoped_ptr;
using cricket::Device;
using cricket::DeviceManager;
using cricket::DeviceManagerFactory;
@@ -65,24 +67,38 @@
cricket::VideoFormat::FpsToInterval(30),
cricket::FOURCC_I420);
-class FakeVideoCapturerFactory : public cricket::VideoCapturerFactory {
+class FakeVideoDeviceCapturerFactory :
+ public cricket::VideoDeviceCapturerFactory {
public:
- FakeVideoCapturerFactory() {}
- virtual ~FakeVideoCapturerFactory() {}
+ FakeVideoDeviceCapturerFactory() {}
+ virtual ~FakeVideoDeviceCapturerFactory() {}
virtual cricket::VideoCapturer* Create(const cricket::Device& device) {
return new cricket::FakeVideoCapturer;
}
};
+class FakeScreenCapturerFactory : public cricket::ScreenCapturerFactory {
+ public:
+ FakeScreenCapturerFactory() {}
+ virtual ~FakeScreenCapturerFactory() {}
+
+ virtual cricket::VideoCapturer* Create(
+ const cricket::ScreencastId& screenid) {
+ return new cricket::FakeVideoCapturer;
+ }
+};
+
class DeviceManagerTestFake : public testing::Test {
public:
virtual void SetUp() {
dm_.reset(DeviceManagerFactory::Create());
EXPECT_TRUE(dm_->Init());
DeviceManager* device_manager = static_cast<DeviceManager*>(dm_.get());
- device_manager->set_device_video_capturer_factory(
- new FakeVideoCapturerFactory());
+ device_manager->SetVideoDeviceCapturerFactory(
+ new FakeVideoDeviceCapturerFactory());
+ device_manager->SetScreenCapturerFactory(
+ new FakeScreenCapturerFactory());
}
virtual void TearDown() {
@@ -290,17 +306,17 @@
devices.push_back("/dev/video5");
cricket::V4LLookup::SetV4LLookup(new FakeV4LLookup(devices));
- std::vector<talk_base::FakeFileSystem::File> files;
- files.push_back(talk_base::FakeFileSystem::File("/dev/video0", ""));
- files.push_back(talk_base::FakeFileSystem::File("/dev/video5", ""));
- files.push_back(talk_base::FakeFileSystem::File(
+ std::vector<rtc::FakeFileSystem::File> files;
+ files.push_back(rtc::FakeFileSystem::File("/dev/video0", ""));
+ files.push_back(rtc::FakeFileSystem::File("/dev/video5", ""));
+ files.push_back(rtc::FakeFileSystem::File(
"/sys/class/video4linux/video0/name", "Video Device 1"));
- files.push_back(talk_base::FakeFileSystem::File(
+ files.push_back(rtc::FakeFileSystem::File(
"/sys/class/video4linux/video1/model", "Bad Device"));
files.push_back(
- talk_base::FakeFileSystem::File("/sys/class/video4linux/video5/model",
+ rtc::FakeFileSystem::File("/sys/class/video4linux/video5/model",
"Video Device 2"));
- talk_base::FilesystemScope fs(new talk_base::FakeFileSystem(files));
+ rtc::FilesystemScope fs(new rtc::FakeFileSystem(files));
scoped_ptr<DeviceManagerInterface> dm(DeviceManagerFactory::Create());
std::vector<Device> video_ins;
@@ -317,19 +333,19 @@
devices.push_back("/dev/video5");
cricket::V4LLookup::SetV4LLookup(new FakeV4LLookup(devices));
- std::vector<talk_base::FakeFileSystem::File> files;
- files.push_back(talk_base::FakeFileSystem::File("/dev/video0", ""));
- files.push_back(talk_base::FakeFileSystem::File("/dev/video5", ""));
- files.push_back(talk_base::FakeFileSystem::File(
+ std::vector<rtc::FakeFileSystem::File> files;
+ files.push_back(rtc::FakeFileSystem::File("/dev/video0", ""));
+ files.push_back(rtc::FakeFileSystem::File("/dev/video5", ""));
+ files.push_back(rtc::FakeFileSystem::File(
"/proc/video/dev/video0",
"param1: value1\nname: Video Device 1\n param2: value2\n"));
- files.push_back(talk_base::FakeFileSystem::File(
+ files.push_back(rtc::FakeFileSystem::File(
"/proc/video/dev/video1",
"param1: value1\nname: Bad Device\n param2: value2\n"));
- files.push_back(talk_base::FakeFileSystem::File(
+ files.push_back(rtc::FakeFileSystem::File(
"/proc/video/dev/video5",
"param1: value1\nname: Video Device 2\n param2: value2\n"));
- talk_base::FilesystemScope fs(new talk_base::FakeFileSystem(files));
+ rtc::FilesystemScope fs(new rtc::FakeFileSystem(files));
scoped_ptr<DeviceManagerInterface> dm(DeviceManagerFactory::Create());
std::vector<Device> video_ins;
@@ -346,11 +362,11 @@
devices.push_back("/dev/video5");
cricket::V4LLookup::SetV4LLookup(new FakeV4LLookup(devices));
- std::vector<talk_base::FakeFileSystem::File> files;
- files.push_back(talk_base::FakeFileSystem::File("/dev/video0", ""));
- files.push_back(talk_base::FakeFileSystem::File("/dev/video1", ""));
- files.push_back(talk_base::FakeFileSystem::File("/dev/video5", ""));
- talk_base::FilesystemScope fs(new talk_base::FakeFileSystem(files));
+ std::vector<rtc::FakeFileSystem::File> files;
+ files.push_back(rtc::FakeFileSystem::File("/dev/video0", ""));
+ files.push_back(rtc::FakeFileSystem::File("/dev/video1", ""));
+ files.push_back(rtc::FakeFileSystem::File("/dev/video5", ""));
+ rtc::FilesystemScope fs(new rtc::FakeFileSystem(files));
scoped_ptr<DeviceManagerInterface> dm(DeviceManagerFactory::Create());
std::vector<Device> video_ins;
@@ -365,44 +381,46 @@
// TODO(noahric): These are flaky on windows on headless machines.
#ifndef WIN32
TEST(DeviceManagerTest, GetWindows) {
- if (!talk_base::WindowPickerFactory::IsSupported()) {
+ if (!rtc::WindowPickerFactory::IsSupported()) {
LOG(LS_INFO) << "skipping test: window capturing is not supported with "
<< "current configuration.";
return;
}
scoped_ptr<DeviceManagerInterface> dm(DeviceManagerFactory::Create());
- std::vector<talk_base::WindowDescription> descriptions;
+ dm->SetScreenCapturerFactory(new FakeScreenCapturerFactory());
+ std::vector<rtc::WindowDescription> descriptions;
EXPECT_TRUE(dm->Init());
if (!dm->GetWindows(&descriptions) || descriptions.empty()) {
LOG(LS_INFO) << "skipping test: window capturing. Does not have any "
<< "windows to capture.";
return;
}
- scoped_ptr<cricket::VideoCapturer> capturer(dm->CreateWindowCapturer(
- descriptions.front().id()));
+ scoped_ptr<cricket::VideoCapturer> capturer(dm->CreateScreenCapturer(
+ cricket::ScreencastId(descriptions.front().id())));
EXPECT_FALSE(capturer.get() == NULL);
// TODO(hellner): creating a window capturer and immediately deleting it
// results in "Continuous Build and Test Mainline - Mac opt" failure (crash).
// Remove the following line as soon as this has been resolved.
- talk_base::Thread::Current()->ProcessMessages(1);
+ rtc::Thread::Current()->ProcessMessages(1);
}
TEST(DeviceManagerTest, GetDesktops) {
- if (!talk_base::WindowPickerFactory::IsSupported()) {
+ if (!rtc::WindowPickerFactory::IsSupported()) {
LOG(LS_INFO) << "skipping test: desktop capturing is not supported with "
<< "current configuration.";
return;
}
scoped_ptr<DeviceManagerInterface> dm(DeviceManagerFactory::Create());
- std::vector<talk_base::DesktopDescription> descriptions;
+ dm->SetScreenCapturerFactory(new FakeScreenCapturerFactory());
+ std::vector<rtc::DesktopDescription> descriptions;
EXPECT_TRUE(dm->Init());
if (!dm->GetDesktops(&descriptions) || descriptions.empty()) {
LOG(LS_INFO) << "skipping test: desktop capturing. Does not have any "
<< "desktops to capture.";
return;
}
- scoped_ptr<cricket::VideoCapturer> capturer(dm->CreateDesktopCapturer(
- descriptions.front().id()));
+ scoped_ptr<cricket::VideoCapturer> capturer(dm->CreateScreenCapturer(
+ cricket::ScreencastId(descriptions.front().id())));
EXPECT_FALSE(capturer.get() == NULL);
}
#endif // !WIN32
diff --git a/media/devices/dummydevicemanager_unittest.cc b/media/devices/dummydevicemanager_unittest.cc
index 1abf1ea..9f4eb41 100644
--- a/media/devices/dummydevicemanager_unittest.cc
+++ b/media/devices/dummydevicemanager_unittest.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
#include "talk/media/devices/dummydevicemanager.h"
+#include "webrtc/base/gunit.h"
using cricket::Device;
using cricket::DummyDeviceManager;
diff --git a/media/devices/fakedevicemanager.h b/media/devices/fakedevicemanager.h
index 0dbed43..a4b2b86 100644
--- a/media/devices/fakedevicemanager.h
+++ b/media/devices/fakedevicemanager.h
@@ -31,11 +31,12 @@
#include <string>
#include <vector>
-#include "talk/base/window.h"
-#include "talk/base/windowpicker.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/base/mediacommon.h"
#include "talk/media/devices/devicemanager.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/window.h"
+#include "webrtc/base/windowpicker.h"
namespace cricket {
@@ -79,6 +80,13 @@
*devs = vidcap_devices_;
return true;
}
+ virtual void SetVideoDeviceCapturerFactory(
+ VideoDeviceCapturerFactory* video_device_capturer_factory) {
+ }
+ virtual void SetScreenCapturerFactory(
+ ScreenCapturerFactory* screen_capturer_factory) {
+ screen_capturer_factory_.reset(screen_capturer_factory);
+ }
virtual void SetVideoCaptureDeviceMaxFormat(const std::string& usb_id,
const VideoFormat& max_format) {
max_formats_[usb_id] = max_format;
@@ -97,36 +105,43 @@
virtual VideoCapturer* CreateVideoCapturer(const Device& device) const {
return new FakeVideoCapturer();
}
+ virtual VideoCapturer* CreateScreenCapturer(
+ const ScreencastId& screenid) const {
+ if (!screen_capturer_factory_) {
+ return new FakeVideoCapturer();
+ }
+ return screen_capturer_factory_->Create(screenid);
+ }
virtual bool GetWindows(
- std::vector<talk_base::WindowDescription>* descriptions) {
+ std::vector<rtc::WindowDescription>* descriptions) {
descriptions->clear();
const uint32_t id = 1u; // Note that 0 is not a valid ID.
- const talk_base::WindowId window_id =
- talk_base::WindowId::Cast(id);
+ const rtc::WindowId window_id =
+ rtc::WindowId::Cast(id);
std::string title = "FakeWindow";
- talk_base::WindowDescription window_description(window_id, title);
+ rtc::WindowDescription window_description(window_id, title);
descriptions->push_back(window_description);
return true;
}
- virtual VideoCapturer* CreateWindowCapturer(talk_base::WindowId window) {
+ virtual VideoCapturer* CreateWindowCapturer(rtc::WindowId window) {
if (!window.IsValid()) {
return NULL;
}
return new FakeVideoCapturer;
}
virtual bool GetDesktops(
- std::vector<talk_base::DesktopDescription>* descriptions) {
+ std::vector<rtc::DesktopDescription>* descriptions) {
descriptions->clear();
const int id = 0;
const int valid_index = 0;
- const talk_base::DesktopId desktop_id =
- talk_base::DesktopId::Cast(id, valid_index);
+ const rtc::DesktopId desktop_id =
+ rtc::DesktopId::Cast(id, valid_index);
std::string title = "FakeDesktop";
- talk_base::DesktopDescription desktop_description(desktop_id, title);
+ rtc::DesktopDescription desktop_description(desktop_id, title);
descriptions->push_back(desktop_description);
return true;
}
- virtual VideoCapturer* CreateDesktopCapturer(talk_base::DesktopId desktop) {
+ virtual VideoCapturer* CreateDesktopCapturer(rtc::DesktopId desktop) {
if (!desktop.IsValid()) {
return NULL;
}
@@ -215,6 +230,8 @@
std::vector<Device> output_devices_;
std::vector<Device> vidcap_devices_;
std::map<std::string, VideoFormat> max_formats_;
+ rtc::scoped_ptr<
+ ScreenCapturerFactory> screen_capturer_factory_;
};
} // namespace cricket
diff --git a/media/devices/filevideocapturer.cc b/media/devices/filevideocapturer.cc
index e79783f..dcb776f 100644
--- a/media/devices/filevideocapturer.cc
+++ b/media/devices/filevideocapturer.cc
@@ -27,10 +27,10 @@
#include "talk/media/devices/filevideocapturer.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -53,7 +53,7 @@
}
bool VideoRecorder::RecordFrame(const CapturedFrame& frame) {
- if (talk_base::SS_CLOSED == video_file_.GetState()) {
+ if (rtc::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return false;
}
@@ -66,7 +66,7 @@
if (write_header_) {
// Convert the frame header to bytebuffer.
- talk_base::ByteBuffer buffer;
+ rtc::ByteBuffer buffer;
buffer.WriteUInt32(frame.width);
buffer.WriteUInt32(frame.height);
buffer.WriteUInt32(frame.fourcc);
@@ -77,7 +77,7 @@
buffer.WriteUInt32(size);
// Write the bytebuffer to file.
- if (talk_base::SR_SUCCESS != video_file_.Write(buffer.Data(),
+ if (rtc::SR_SUCCESS != video_file_.Write(buffer.Data(),
buffer.Length(),
NULL,
NULL)) {
@@ -86,7 +86,7 @@
}
}
// Write the frame data to file.
- if (talk_base::SR_SUCCESS != video_file_.Write(frame.data,
+ if (rtc::SR_SUCCESS != video_file_.Write(frame.data,
size,
NULL,
NULL)) {
@@ -102,7 +102,7 @@
// frames from a file.
///////////////////////////////////////////////////////////////////////
class FileVideoCapturer::FileReadThread
- : public talk_base::Thread, public talk_base::MessageHandler {
+ : public rtc::Thread, public rtc::MessageHandler {
public:
explicit FileReadThread(FileVideoCapturer* capturer)
: capturer_(capturer),
@@ -123,12 +123,12 @@
Thread::Run();
}
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
finished_ = true;
}
// Override virtual method of parent MessageHandler. Context: Worker Thread.
- virtual void OnMessage(talk_base::Message* /*pmsg*/) {
+ virtual void OnMessage(rtc::Message* /*pmsg*/) {
int waiting_time_ms = 0;
if (capturer_ && capturer_->ReadFrame(false, &waiting_time_ms)) {
PostDelayed(waiting_time_ms, this);
@@ -139,13 +139,13 @@
// Check if Run() is finished.
bool Finished() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return finished_;
}
private:
FileVideoCapturer* capturer_;
- mutable talk_base::CriticalSection crit_;
+ mutable rtc::CriticalSection crit_;
bool finished_;
DISALLOW_COPY_AND_ASSIGN(FileReadThread);
@@ -188,7 +188,7 @@
}
// Read the first frame's header to determine the supported format.
CapturedFrame frame;
- if (talk_base::SR_SUCCESS != ReadFrameHeader(&frame)) {
+ if (rtc::SR_SUCCESS != ReadFrameHeader(&frame)) {
LOG(LS_ERROR) << "Failed to read the first frame header";
video_file_.Close();
return false;
@@ -230,7 +230,7 @@
return CS_FAILED;
}
- if (talk_base::SS_CLOSED == video_file_.GetState()) {
+ if (rtc::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return CS_NO_DEVICE;
} else if (!video_file_.SetPosition(0)) {
@@ -242,7 +242,7 @@
// Create a thread to read the file.
file_read_thread_ = new FileReadThread(this);
start_time_ns_ = kNumNanoSecsPerMilliSec *
- static_cast<int64>(talk_base::Time());
+ static_cast<int64>(rtc::Time());
bool ret = file_read_thread_->Start();
if (ret) {
LOG(LS_INFO) << "File video capturer '" << GetId() << "' started";
@@ -275,13 +275,13 @@
return true;
}
-talk_base::StreamResult FileVideoCapturer::ReadFrameHeader(
+rtc::StreamResult FileVideoCapturer::ReadFrameHeader(
CapturedFrame* frame) {
// We first read kFrameHeaderSize bytes from the file stream to a memory
// buffer, then construct a bytebuffer from the memory buffer, and finally
// read the frame header from the bytebuffer.
char header[CapturedFrame::kFrameHeaderSize];
- talk_base::StreamResult sr;
+ rtc::StreamResult sr;
size_t bytes_read;
int error;
sr = video_file_.Read(header,
@@ -290,11 +290,11 @@
&error);
LOG(LS_VERBOSE) << "Read frame header: stream_result = " << sr
<< ", bytes read = " << bytes_read << ", error = " << error;
- if (talk_base::SR_SUCCESS == sr) {
+ if (rtc::SR_SUCCESS == sr) {
if (CapturedFrame::kFrameHeaderSize != bytes_read) {
- return talk_base::SR_EOS;
+ return rtc::SR_EOS;
}
- talk_base::ByteBuffer buffer(header, CapturedFrame::kFrameHeaderSize);
+ rtc::ByteBuffer buffer(header, CapturedFrame::kFrameHeaderSize);
buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->width));
buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->height));
buffer.ReadUInt32(&frame->fourcc);
@@ -310,7 +310,7 @@
// Executed in the context of FileReadThread.
bool FileVideoCapturer::ReadFrame(bool first_frame, int* wait_time_ms) {
- uint32 start_read_time_ms = talk_base::Time();
+ uint32 start_read_time_ms = rtc::Time();
// 1. Signal the previously read frame to downstream.
if (!first_frame) {
@@ -321,14 +321,14 @@
}
// 2. Read the next frame.
- if (talk_base::SS_CLOSED == video_file_.GetState()) {
+ if (rtc::SS_CLOSED == video_file_.GetState()) {
LOG(LS_ERROR) << "File not opened yet";
return false;
}
// 2.1 Read the frame header.
- talk_base::StreamResult result = ReadFrameHeader(&captured_frame_);
- if (talk_base::SR_EOS == result) { // Loop back if repeat.
- if (repeat_ != talk_base::kForever) {
+ rtc::StreamResult result = ReadFrameHeader(&captured_frame_);
+ if (rtc::SR_EOS == result) { // Loop back if repeat.
+ if (repeat_ != rtc::kForever) {
if (repeat_ > 0) {
--repeat_;
} else {
@@ -340,7 +340,7 @@
result = ReadFrameHeader(&captured_frame_);
}
}
- if (talk_base::SR_SUCCESS != result) {
+ if (rtc::SR_SUCCESS != result) {
LOG(LS_ERROR) << "Failed to read the frame header";
return false;
}
@@ -351,7 +351,7 @@
captured_frame_.data = new char[frame_buffer_size_];
}
// 2.3 Read the frame adata.
- if (talk_base::SR_SUCCESS != video_file_.Read(captured_frame_.data,
+ if (rtc::SR_SUCCESS != video_file_.Read(captured_frame_.data,
captured_frame_.data_size,
NULL, NULL)) {
LOG(LS_ERROR) << "Failed to read frame data";
@@ -370,7 +370,7 @@
GetCaptureFormat()->interval :
captured_frame_.time_stamp - last_frame_timestamp_ns_;
int interval_ms = static_cast<int>(interval_ns / kNumNanoSecsPerMilliSec);
- interval_ms -= talk_base::Time() - start_read_time_ms;
+ interval_ms -= rtc::Time() - start_read_time_ms;
if (interval_ms > 0) {
*wait_time_ms = interval_ms;
}
diff --git a/media/devices/filevideocapturer.h b/media/devices/filevideocapturer.h
index e3e39b4..2b81aa9 100644
--- a/media/devices/filevideocapturer.h
+++ b/media/devices/filevideocapturer.h
@@ -37,11 +37,11 @@
#include <string>
#include <vector>
-#include "talk/base/stream.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/videocapturer.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/stringutils.h"
-namespace talk_base {
+namespace rtc {
class FileStream;
}
@@ -65,7 +65,7 @@
bool RecordFrame(const CapturedFrame& frame);
private:
- talk_base::FileStream video_file_;
+ rtc::FileStream video_file_;
bool write_header_;
DISALLOW_COPY_AND_ASSIGN(VideoRecorder);
@@ -80,7 +80,7 @@
// Determines if the given device is actually a video file, to be captured
// with a FileVideoCapturer.
static bool IsFileVideoCapturerDevice(const Device& device) {
- return talk_base::starts_with(device.id.c_str(), kVideoFileDevicePrefix);
+ return rtc::starts_with(device.id.c_str(), kVideoFileDevicePrefix);
}
// Creates a fake device for the given filename.
@@ -91,7 +91,7 @@
}
// Set how many times to repeat reading the file. Repeat forever if the
- // parameter is talk_base::kForever(-1); no repeat if the parameter is 0 or
+ // parameter is rtc::kForever(-1); no repeat if the parameter is 0 or
// less than -1.
void set_repeat(int repeat) { repeat_ = repeat; }
@@ -120,7 +120,7 @@
virtual bool GetPreferredFourccs(std::vector<uint32>* fourccs);
// Read the frame header from the file stream, video_file_.
- talk_base::StreamResult ReadFrameHeader(CapturedFrame* frame);
+ rtc::StreamResult ReadFrameHeader(CapturedFrame* frame);
// Read a frame and determine how long to wait for the next frame. If the
// frame is read successfully, Set the output parameter, wait_time_ms and
@@ -138,7 +138,7 @@
class FileReadThread; // Forward declaration, defined in .cc.
static const char* kVideoFileDevicePrefix;
- talk_base::FileStream video_file_;
+ rtc::FileStream video_file_;
CapturedFrame captured_frame_;
// The number of bytes allocated buffer for captured_frame_.data.
uint32 frame_buffer_size_;
diff --git a/media/devices/filevideocapturer_unittest.cc b/media/devices/filevideocapturer_unittest.cc
index 610d4f1..7bc873c 100644
--- a/media/devices/filevideocapturer_unittest.cc
+++ b/media/devices/filevideocapturer_unittest.cc
@@ -30,11 +30,11 @@
#include <string>
#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
#include "talk/media/base/testutils.h"
#include "talk/media/devices/filevideocapturer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
namespace {
@@ -82,7 +82,7 @@
bool resolution_changed_;
};
- talk_base::scoped_ptr<cricket::FileVideoCapturer> capturer_;
+ rtc::scoped_ptr<cricket::FileVideoCapturer> capturer_;
cricket::VideoFormat capture_format_;
};
@@ -158,7 +158,7 @@
VideoCapturerListener listener;
capturer_->SignalFrameCaptured.connect(
&listener, &VideoCapturerListener::OnFrameCaptured);
- capturer_->set_repeat(talk_base::kForever);
+ capturer_->set_repeat(rtc::kForever);
capture_format_ = capturer_->GetSupportedFormats()->at(0);
capture_format_.interval = cricket::VideoFormat::FpsToInterval(50);
EXPECT_EQ(cricket::CS_RUNNING, capturer_->Start(capture_format_));
diff --git a/media/devices/gdivideorenderer.cc b/media/devices/gdivideorenderer.cc
index 9633eb6..b38da19 100755
--- a/media/devices/gdivideorenderer.cc
+++ b/media/devices/gdivideorenderer.cc
@@ -29,11 +29,11 @@
#include "talk/media/devices/gdivideorenderer.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
-#include "talk/base/win32window.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/win32window.h"
namespace cricket {
@@ -41,7 +41,7 @@
// Definition of private class VideoWindow. We use a worker thread to manage
// the window.
/////////////////////////////////////////////////////////////////////////////
-class GdiVideoRenderer::VideoWindow : public talk_base::Win32Window {
+class GdiVideoRenderer::VideoWindow : public rtc::Win32Window {
public:
VideoWindow(int x, int y, int width, int height);
virtual ~VideoWindow();
@@ -58,14 +58,14 @@
bool RenderFrame(const VideoFrame* frame);
protected:
- // Override virtual method of talk_base::Win32Window. Context: worker Thread.
+ // Override virtual method of rtc::Win32Window. Context: worker Thread.
virtual bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
LRESULT& result);
private:
enum { kSetSizeMsg = WM_USER, kRenderFrameMsg};
- class WindowThread : public talk_base::Thread {
+ class WindowThread : public rtc::Thread {
public:
explicit WindowThread(VideoWindow* window) : window_(window) {}
@@ -73,7 +73,7 @@
Stop();
}
- // Override virtual method of talk_base::Thread. Context: worker Thread.
+ // Override virtual method of rtc::Thread. Context: worker Thread.
virtual void Run() {
// Initialize the window
if (!window_ || !window_->Initialize()) {
@@ -98,8 +98,8 @@
void OnRenderFrame(const VideoFrame* frame);
BITMAPINFO bmi_;
- talk_base::scoped_ptr<uint8[]> image_;
- talk_base::scoped_ptr<WindowThread> window_thread_;
+ rtc::scoped_ptr<uint8[]> image_;
+ rtc::scoped_ptr<WindowThread> window_thread_;
// The initial position of the window.
int initial_x_;
int initial_y_;
@@ -180,7 +180,7 @@
}
bool GdiVideoRenderer::VideoWindow::Initialize() {
- if (!talk_base::Win32Window::Create(
+ if (!rtc::Win32Window::Create(
NULL, L"Video Renderer",
WS_OVERLAPPEDWINDOW | WS_SIZEBOX,
WS_EX_APPWINDOW,
diff --git a/media/devices/gdivideorenderer.h b/media/devices/gdivideorenderer.h
index da3897d..5124cdf 100755
--- a/media/devices/gdivideorenderer.h
+++ b/media/devices/gdivideorenderer.h
@@ -30,8 +30,8 @@
#define TALK_MEDIA_DEVICES_GDIVIDEORENDERER_H_
#ifdef WIN32
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/scoped_ptr.h"
namespace cricket {
@@ -48,7 +48,7 @@
private:
class VideoWindow; // forward declaration, defined in the .cc file
- talk_base::scoped_ptr<VideoWindow> window_;
+ rtc::scoped_ptr<VideoWindow> window_;
// The initial position of the window.
int initial_x_;
int initial_y_;
diff --git a/media/devices/gtkvideorenderer.cc b/media/devices/gtkvideorenderer.cc
index a926879..49c7009 100755
--- a/media/devices/gtkvideorenderer.cc
+++ b/media/devices/gtkvideorenderer.cc
@@ -27,8 +27,8 @@
#include "talk/media/devices/gtkvideorenderer.h"
-#include <glib.h>
#include <gdk/gdk.h>
+#include <glib.h>
#include <gtk/gtk.h>
#include "talk/media/base/videocommon.h"
diff --git a/media/devices/gtkvideorenderer.h b/media/devices/gtkvideorenderer.h
index 744c19f..4d7243f 100755
--- a/media/devices/gtkvideorenderer.h
+++ b/media/devices/gtkvideorenderer.h
@@ -29,9 +29,9 @@
#ifndef TALK_MEDIA_DEVICES_GTKVIDEORENDERER_H_
#define TALK_MEDIA_DEVICES_GTKVIDEORENDERER_H_
-#include "talk/base/basictypes.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/videorenderer.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/scoped_ptr.h"
typedef struct _GtkWidget GtkWidget; // forward declaration, defined in gtk.h
@@ -56,7 +56,7 @@
// Check if the window has been closed.
bool IsClosed() const;
- talk_base::scoped_ptr<uint8[]> image_;
+ rtc::scoped_ptr<uint8[]> image_;
GtkWidget* window_;
GtkWidget* draw_area_;
// The initial position of the window.
diff --git a/media/devices/libudevsymboltable.cc b/media/devices/libudevsymboltable.cc
index 20154e1..351a1e7 100644
--- a/media/devices/libudevsymboltable.cc
+++ b/media/devices/libudevsymboltable.cc
@@ -29,20 +29,20 @@
#include <dlfcn.h>
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
namespace cricket {
#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME LIBUDEV_SYMBOLS_CLASS_NAME
#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST LIBUDEV_SYMBOLS_LIST
#define LATE_BINDING_SYMBOL_TABLE_DLL_NAME "libudev.so.0"
-#include "talk/base/latebindingsymboltable.cc.def"
+#include "webrtc/base/latebindingsymboltable.cc.def"
#undef LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
#undef LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
#undef LATE_BINDING_SYMBOL_TABLE_DLL_NAME
-bool IsWrongLibUDevAbiVersion(talk_base::DllHandle libudev_0) {
- talk_base::DllHandle libudev_1 = dlopen("libudev.so.1",
+bool IsWrongLibUDevAbiVersion(rtc::DllHandle libudev_0) {
+ rtc::DllHandle libudev_1 = dlopen("libudev.so.1",
RTLD_NOW|RTLD_LOCAL|RTLD_NOLOAD);
bool unsafe_symlink = (libudev_0 == libudev_1);
if (unsafe_symlink) {
diff --git a/media/devices/libudevsymboltable.h b/media/devices/libudevsymboltable.h
index aa8c590..f764cd2 100644
--- a/media/devices/libudevsymboltable.h
+++ b/media/devices/libudevsymboltable.h
@@ -30,7 +30,7 @@
#include <libudev.h>
-#include "talk/base/latebindingsymboltable.h"
+#include "webrtc/base/latebindingsymboltable.h"
namespace cricket {
@@ -62,7 +62,7 @@
#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME LIBUDEV_SYMBOLS_CLASS_NAME
#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST LIBUDEV_SYMBOLS_LIST
-#include "talk/base/latebindingsymboltable.h.def"
+#include "webrtc/base/latebindingsymboltable.h.def"
#undef LATE_BINDING_SYMBOL_TABLE_CLASS_NAME
#undef LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST
@@ -72,7 +72,7 @@
// it has caused crashes in the wild. This function checks if the DllHandle that
// we got back for libudev.so.0 is actually for libudev.so.1. If so, the library
// cannot safely be used.
-bool IsWrongLibUDevAbiVersion(talk_base::DllHandle libudev_0);
+bool IsWrongLibUDevAbiVersion(rtc::DllHandle libudev_0);
} // namespace cricket
diff --git a/media/devices/linuxdeviceinfo.cc b/media/devices/linuxdeviceinfo.cc
index b1bc9dd..0b22e15 100644
--- a/media/devices/linuxdeviceinfo.cc
+++ b/media/devices/linuxdeviceinfo.cc
@@ -27,8 +27,8 @@
#include "talk/media/devices/deviceinfo.h"
-#include "talk/base/common.h" // for ASSERT
#include "talk/media/devices/libudevsymboltable.h"
+#include "webrtc/base/common.h" // for ASSERT
namespace cricket {
@@ -94,7 +94,7 @@
bool GetUsbProperty(const Device& device, const char* property_name,
std::string* property) {
- talk_base::scoped_ptr<ScopedLibUdev> libudev_context(ScopedLibUdev::Create());
+ rtc::scoped_ptr<ScopedLibUdev> libudev_context(ScopedLibUdev::Create());
if (!libudev_context) {
return false;
}
diff --git a/media/devices/linuxdevicemanager.cc b/media/devices/linuxdevicemanager.cc
index 8e58d99..d122169 100644
--- a/media/devices/linuxdevicemanager.cc
+++ b/media/devices/linuxdevicemanager.cc
@@ -28,21 +28,21 @@
#include "talk/media/devices/linuxdevicemanager.h"
#include <unistd.h>
-#include "talk/base/fileutils.h"
-#include "talk/base/linux.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/stream.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
#include "talk/media/base/mediacommon.h"
#include "talk/media/devices/libudevsymboltable.h"
#include "talk/media/devices/v4llookup.h"
-#include "talk/sound/platformsoundsystem.h"
-#include "talk/sound/platformsoundsystemfactory.h"
-#include "talk/sound/sounddevicelocator.h"
-#include "talk/sound/soundsysteminterface.h"
+#include "webrtc/sound/platformsoundsystem.h"
+#include "webrtc/sound/platformsoundsystemfactory.h"
+#include "webrtc/sound/sounddevicelocator.h"
+#include "webrtc/sound/soundsysteminterface.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/linux.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -52,7 +52,7 @@
class LinuxDeviceWatcher
: public DeviceWatcher,
- private talk_base::Dispatcher {
+ private rtc::Dispatcher {
public:
explicit LinuxDeviceWatcher(DeviceManagerInterface* dm);
virtual ~LinuxDeviceWatcher();
@@ -89,7 +89,7 @@
};
LinuxDeviceManager::LinuxDeviceManager()
- : sound_system_(new PlatformSoundSystemFactory()) {
+ : sound_system_(new rtc::PlatformSoundSystemFactory()) {
set_watcher(new LinuxDeviceWatcher(this));
}
@@ -102,7 +102,7 @@
if (!sound_system_.get()) {
return false;
}
- SoundSystemInterface::SoundDeviceLocatorList list;
+ rtc::SoundSystemInterface::SoundDeviceLocatorList list;
bool success;
if (input) {
success = sound_system_->EnumerateCaptureDevices(&list);
@@ -118,12 +118,12 @@
// device at index 0, but Enumerate(Capture|Playback)Devices does not include
// a locator for the default device.
int index = 1;
- for (SoundSystemInterface::SoundDeviceLocatorList::iterator i = list.begin();
+ for (rtc::SoundSystemInterface::SoundDeviceLocatorList::iterator i = list.begin();
i != list.end();
++i, ++index) {
devs->push_back(Device((*i)->name(), index));
}
- SoundSystemInterface::ClearSoundDeviceLocatorList(&list);
+ rtc::SoundSystemInterface::ClearSoundDeviceLocatorList(&list);
sound_system_.release();
return FilterDevices(devs, kFilteredAudioDevicesName);
}
@@ -135,10 +135,10 @@
static void ScanDeviceDirectory(const std::string& devdir,
std::vector<Device>* devices) {
- talk_base::scoped_ptr<talk_base::DirectoryIterator> directoryIterator(
- talk_base::Filesystem::IterateDirectory());
+ rtc::scoped_ptr<rtc::DirectoryIterator> directoryIterator(
+ rtc::Filesystem::IterateDirectory());
- if (directoryIterator->Iterate(talk_base::Pathname(devdir))) {
+ if (directoryIterator->Iterate(rtc::Pathname(devdir))) {
do {
std::string filename = directoryIterator->Name();
std::string device_name = devdir + filename;
@@ -155,11 +155,11 @@
static std::string GetVideoDeviceNameK2_6(const std::string& device_meta_path) {
std::string device_name;
- talk_base::scoped_ptr<talk_base::FileStream> device_meta_stream(
- talk_base::Filesystem::OpenFile(device_meta_path, "r"));
+ rtc::scoped_ptr<rtc::FileStream> device_meta_stream(
+ rtc::Filesystem::OpenFile(device_meta_path, "r"));
if (device_meta_stream) {
- if (device_meta_stream->ReadLine(&device_name) != talk_base::SR_SUCCESS) {
+ if (device_meta_stream->ReadLine(&device_name) != rtc::SR_SUCCESS) {
LOG(LS_ERROR) << "Failed to read V4L2 device meta " << device_meta_path;
}
device_meta_stream->Close();
@@ -179,20 +179,20 @@
}
static std::string GetVideoDeviceNameK2_4(const std::string& device_meta_path) {
- talk_base::ConfigParser::MapVector all_values;
+ rtc::ConfigParser::MapVector all_values;
- talk_base::ConfigParser config_parser;
- talk_base::FileStream* file_stream =
- talk_base::Filesystem::OpenFile(device_meta_path, "r");
+ rtc::ConfigParser config_parser;
+ rtc::FileStream* file_stream =
+ rtc::Filesystem::OpenFile(device_meta_path, "r");
if (file_stream == NULL) return "";
config_parser.Attach(file_stream);
config_parser.Parse(&all_values);
- for (talk_base::ConfigParser::MapVector::iterator i = all_values.begin();
+ for (rtc::ConfigParser::MapVector::iterator i = all_values.begin();
i != all_values.end(); ++i) {
- talk_base::ConfigParser::SimpleMap::iterator device_name_i =
+ rtc::ConfigParser::SimpleMap::iterator device_name_i =
i->find("name");
if (device_name_i != i->end()) {
@@ -244,8 +244,8 @@
MetaType meta;
std::string metadata_dir;
- talk_base::scoped_ptr<talk_base::DirectoryIterator> directoryIterator(
- talk_base::Filesystem::IterateDirectory());
+ rtc::scoped_ptr<rtc::DirectoryIterator> directoryIterator(
+ rtc::Filesystem::IterateDirectory());
// Try and guess kernel version
if (directoryIterator->Iterate(kVideoMetaPathK2_6)) {
@@ -302,10 +302,10 @@
LinuxDeviceWatcher::~LinuxDeviceWatcher() {
}
-static talk_base::PhysicalSocketServer* CurrentSocketServer() {
- talk_base::SocketServer* ss =
- talk_base::ThreadManager::Instance()->WrapCurrentThread()->socketserver();
- return reinterpret_cast<talk_base::PhysicalSocketServer*>(ss);
+static rtc::PhysicalSocketServer* CurrentSocketServer() {
+ rtc::SocketServer* ss =
+ rtc::ThreadManager::Instance()->WrapCurrentThread()->socketserver();
+ return reinterpret_cast<rtc::PhysicalSocketServer*>(ss);
}
bool LinuxDeviceWatcher::Start() {
@@ -369,7 +369,7 @@
}
uint32 LinuxDeviceWatcher::GetRequestedEvents() {
- return talk_base::DE_READ;
+ return rtc::DE_READ;
}
void LinuxDeviceWatcher::OnPreEvent(uint32 ff) {
diff --git a/media/devices/linuxdevicemanager.h b/media/devices/linuxdevicemanager.h
index d8f1665..1eb648f 100644
--- a/media/devices/linuxdevicemanager.h
+++ b/media/devices/linuxdevicemanager.h
@@ -31,10 +31,10 @@
#include <string>
#include <vector>
-#include "talk/base/sigslot.h"
-#include "talk/base/stringencode.h"
#include "talk/media/devices/devicemanager.h"
-#include "talk/sound/soundsystemfactory.h"
+#include "webrtc/sound/soundsystemfactory.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
@@ -47,7 +47,7 @@
private:
virtual bool GetAudioDevices(bool input, std::vector<Device>* devs);
- SoundSystemHandle sound_system_;
+ rtc::SoundSystemHandle sound_system_;
};
} // namespace cricket
diff --git a/media/devices/macdevicemanager.cc b/media/devices/macdevicemanager.cc
index 8055588..8f777b4 100644
--- a/media/devices/macdevicemanager.cc
+++ b/media/devices/macdevicemanager.cc
@@ -30,10 +30,10 @@
#include <CoreAudio/CoreAudio.h>
#include <QuickTime/QuickTime.h>
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
#include "talk/media/base/mediacommon.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
class DeviceWatcherImpl;
@@ -71,7 +71,7 @@
extern DeviceWatcherImpl* CreateDeviceWatcherCallback(
DeviceManagerInterface* dm);
extern void ReleaseDeviceWatcherCallback(DeviceWatcherImpl* impl);
-extern bool GetQTKitVideoDevices(std::vector<Device>* out);
+extern bool GetAVFoundationVideoDevices(std::vector<Device>* out);
static bool GetAudioDeviceIDs(bool inputs, std::vector<AudioDeviceID>* out);
static bool GetAudioDeviceName(AudioDeviceID id, bool input, std::string* out);
@@ -84,7 +84,7 @@
bool MacDeviceManager::GetVideoCaptureDevices(std::vector<Device>* devices) {
devices->clear();
- if (!GetQTKitVideoDevices(devices)) {
+ if (!GetAVFoundationVideoDevices(devices)) {
return false;
}
return FilterDevices(devices, kFilteredVideoDevicesName);
@@ -119,7 +119,7 @@
}
size_t num_devices = propsize / sizeof(AudioDeviceID);
- talk_base::scoped_ptr<AudioDeviceID[]> device_ids(
+ rtc::scoped_ptr<AudioDeviceID[]> device_ids(
new AudioDeviceID[num_devices]);
err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices,
diff --git a/media/devices/macdevicemanager.h b/media/devices/macdevicemanager.h
index 25fe4fc..82e62f9 100644
--- a/media/devices/macdevicemanager.h
+++ b/media/devices/macdevicemanager.h
@@ -31,9 +31,9 @@
#include <string>
#include <vector>
-#include "talk/base/sigslot.h"
-#include "talk/base/stringencode.h"
#include "talk/media/devices/devicemanager.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
diff --git a/media/devices/macdevicemanagermm.mm b/media/devices/macdevicemanagermm.mm
index fdde91f..cfcf5a4 100644
--- a/media/devices/macdevicemanagermm.mm
+++ b/media/devices/macdevicemanagermm.mm
@@ -33,9 +33,14 @@
#include "talk/media/devices/devicemanager.h"
#import <assert.h>
+#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
+#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
+ #import <AVFoundation/AVFoundation.h>
+#endif
+#endif
#import <QTKit/QTKit.h>
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
@interface DeviceWatcherImpl : NSObject {
@private
@@ -136,4 +141,52 @@
return true;
}
+bool GetAVFoundationVideoDevices(std::vector<Device>* devices) {
+#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
+#if __MAC_OS_X_VERSION_MAX_ALLOWED >=1070
+ if (![AVCaptureDevice class]) {
+ // Fallback to using QTKit if AVFoundation is not available
+ return GetQTKitVideoDevices(devices);
+ }
+#if !__has_feature(objc_arc)
+ NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
+#else
+ @autoreleasepool
+#endif
+ {
+ NSArray* capture_devices = [AVCaptureDevice devices];
+ LOG(LS_INFO) << [capture_devices count] << " capture device(s) found:";
+ for (AVCaptureDevice* capture_device in capture_devices) {
+ if ([capture_device hasMediaType:AVMediaTypeVideo] ||
+ [capture_device hasMediaType:AVMediaTypeMuxed]) {
+ static NSString* const kFormat = @"localizedName: \"%@\", "
+ @"modelID: \"%@\", uniqueID \"%@\", isConnected: %d, "
+ @"isInUseByAnotherApplication: %d";
+ NSString* info = [NSString
+ stringWithFormat:kFormat,
+ [capture_device localizedName],
+ [capture_device modelID],
+ [capture_device uniqueID],
+ [capture_device isConnected],
+ [capture_device isInUseByAnotherApplication]];
+ LOG(LS_INFO) << [info UTF8String];
+
+ std::string name([[capture_device localizedName] UTF8String]);
+ devices->push_back(
+ Device(name, [[capture_device uniqueID] UTF8String]));
+ }
+ }
+ }
+#if !__has_feature(objc_arc)
+ [pool drain];
+#endif
+ return true;
+#else // __MAC_OS_X_VERSION_MAX_ALLOWED >=1070
+ return GetQTKitVideoDevices(devices);
+#endif // __MAC_OS_X_VERSION_MAX_ALLOWED >=1070
+#else // __MAC_OS_X_VERSION_MAX_ALLOWED
+ return GetQTKitVideoDevices(devices);
+#endif // __MAC_OS_X_VERSION_MAX_ALLOWED
+}
+
} // namespace cricket
diff --git a/media/devices/mobiledevicemanager.cc b/media/devices/mobiledevicemanager.cc
index a08911b..f9ff35b 100644
--- a/media/devices/mobiledevicemanager.cc
+++ b/media/devices/mobiledevicemanager.cc
@@ -47,7 +47,7 @@
bool MobileDeviceManager::GetVideoCaptureDevices(std::vector<Device>* devs) {
devs->clear();
- talk_base::scoped_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(
+ rtc::scoped_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(
webrtc::VideoCaptureFactory::CreateDeviceInfo(0));
if (!info)
return false;
diff --git a/media/devices/v4llookup.cc b/media/devices/v4llookup.cc
index 76eafa7..5e9ce02 100644
--- a/media/devices/v4llookup.cc
+++ b/media/devices/v4llookup.cc
@@ -14,11 +14,11 @@
#include <linux/videodev2.h>
#include <string.h>
#include <sys/ioctl.h>
-#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/types.h>
#include <unistd.h>
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
namespace cricket {
diff --git a/media/devices/win32devicemanager.cc b/media/devices/win32devicemanager.cc
index 071f111..668270e 100644
--- a/media/devices/win32devicemanager.cc
+++ b/media/devices/win32devicemanager.cc
@@ -38,11 +38,11 @@
#include <functiondiscoverykeys_devpkey.h>
#include <uuids.h>
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/win32.h" // ToUtf8
-#include "talk/base/win32window.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/win32.h" // ToUtf8
+#include "webrtc/base/win32window.h"
#include "talk/media/base/mediacommon.h"
#ifdef HAVE_LOGITECH_HEADERS
#include "third_party/logitech/files/logitechquickcam.h"
@@ -56,7 +56,7 @@
class Win32DeviceWatcher
: public DeviceWatcher,
- public talk_base::Win32Window {
+ public rtc::Win32Window {
public:
explicit Win32DeviceWatcher(Win32DeviceManager* dm);
virtual ~Win32DeviceWatcher();
@@ -151,7 +151,7 @@
std::vector<Device>* devs) {
devs->clear();
- if (talk_base::IsWindowsVistaOrLater()) {
+ if (rtc::IsWindowsVistaOrLater()) {
if (!GetCoreAudioDevices(input, devs))
return false;
} else {
@@ -199,11 +199,11 @@
std::string name_str, path_str;
if (SUCCEEDED(bag->Read(kFriendlyName, &name, 0)) &&
name.vt == VT_BSTR) {
- name_str = talk_base::ToUtf8(name.bstrVal);
+ name_str = rtc::ToUtf8(name.bstrVal);
// Get the device id if one exists.
if (SUCCEEDED(bag->Read(kDevicePath, &path, 0)) &&
path.vt == VT_BSTR) {
- path_str = talk_base::ToUtf8(path.bstrVal);
+ path_str = rtc::ToUtf8(path.bstrVal);
}
devices->push_back(Device(name_str, path_str));
@@ -224,7 +224,7 @@
HRESULT hr = bag->GetValue(key, &var);
if (SUCCEEDED(hr)) {
if (var.pwszVal)
- *out = talk_base::ToUtf8(var.pwszVal);
+ *out = rtc::ToUtf8(var.pwszVal);
else
hr = E_FAIL;
}
@@ -312,8 +312,8 @@
WAVEINCAPS caps;
if (waveInGetDevCaps(i, &caps, sizeof(caps)) == MMSYSERR_NOERROR &&
caps.wChannels > 0) {
- devs->push_back(Device(talk_base::ToUtf8(caps.szPname),
- talk_base::ToString(i)));
+ devs->push_back(Device(rtc::ToUtf8(caps.szPname),
+ rtc::ToString(i)));
}
}
} else {
@@ -322,7 +322,7 @@
WAVEOUTCAPS caps;
if (waveOutGetDevCaps(i, &caps, sizeof(caps)) == MMSYSERR_NOERROR &&
caps.wChannels > 0) {
- devs->push_back(Device(talk_base::ToUtf8(caps.szPname), i));
+ devs->push_back(Device(rtc::ToUtf8(caps.szPname), i));
}
}
}
diff --git a/media/devices/win32devicemanager.h b/media/devices/win32devicemanager.h
index 4854ec0..5f8ba83 100644
--- a/media/devices/win32devicemanager.h
+++ b/media/devices/win32devicemanager.h
@@ -31,9 +31,9 @@
#include <string>
#include <vector>
-#include "talk/base/sigslot.h"
-#include "talk/base/stringencode.h"
#include "talk/media/devices/devicemanager.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
diff --git a/media/devices/yuvframescapturer.cc b/media/devices/yuvframescapturer.cc
index 648094b..0aa3b53 100644
--- a/media/devices/yuvframescapturer.cc
+++ b/media/devices/yuvframescapturer.cc
@@ -1,9 +1,9 @@
#include "talk/media/devices/yuvframescapturer.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
#include "webrtc/system_wrappers/interface/clock.h"
@@ -13,7 +13,7 @@
// frames.
///////////////////////////////////////////////////////////////////////
class YuvFramesCapturer::YuvFramesThread
- : public talk_base::Thread, public talk_base::MessageHandler {
+ : public rtc::Thread, public rtc::MessageHandler {
public:
explicit YuvFramesThread(YuvFramesCapturer* capturer)
: capturer_(capturer),
@@ -35,12 +35,12 @@
Thread::Run();
}
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
finished_ = true;
}
// Override virtual method of parent MessageHandler. Context: Worker Thread.
- virtual void OnMessage(talk_base::Message* /*pmsg*/) {
+ virtual void OnMessage(rtc::Message* /*pmsg*/) {
int waiting_time_ms = 0;
if (capturer_) {
capturer_->ReadFrame(false);
@@ -52,13 +52,13 @@
// Check if Run() is finished.
bool Finished() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return finished_;
}
private:
YuvFramesCapturer* capturer_;
- mutable talk_base::CriticalSection crit_;
+ mutable rtc::CriticalSection crit_;
bool finished_;
DISALLOW_COPY_AND_ASSIGN(YuvFramesThread);
@@ -113,7 +113,7 @@
SetCaptureFormat(&capture_format);
barcode_reference_timestamp_millis_ =
- static_cast<int64>(talk_base::Time()) * 1000;
+ static_cast<int64>(rtc::Time()) * 1000;
// Create a thread to generate frames.
frames_generator_thread = new YuvFramesThread(this);
bool ret = frames_generator_thread->Start();
@@ -166,7 +166,7 @@
frame_index_ % barcode_interval_ != 0) {
return -1;
}
- int64 now_millis = static_cast<int64>(talk_base::Time()) * 1000;
+ int64 now_millis = static_cast<int64>(rtc::Time()) * 1000;
return static_cast<int32>(now_millis - barcode_reference_timestamp_millis_);
}
diff --git a/media/devices/yuvframescapturer.h b/media/devices/yuvframescapturer.h
index 7886525..64c1732 100644
--- a/media/devices/yuvframescapturer.h
+++ b/media/devices/yuvframescapturer.h
@@ -4,13 +4,13 @@
#include <string>
#include <vector>
-#include "talk/base/stream.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/yuvframegenerator.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/stringutils.h"
-namespace talk_base {
+namespace rtc {
class FileStream;
}
@@ -31,7 +31,7 @@
return Device(id.str(), id.str());
}
static bool IsYuvFramesCapturerDevice(const Device& device) {
- return talk_base::starts_with(device.id.c_str(), kYuvFrameDeviceName);
+ return rtc::starts_with(device.id.c_str(), kYuvFrameDeviceName);
}
void Init();
diff --git a/media/other/linphonemediaengine.cc b/media/other/linphonemediaengine.cc
index 3b97c0b..06b6d76 100644
--- a/media/other/linphonemediaengine.cc
+++ b/media/other/linphonemediaengine.cc
@@ -32,18 +32,18 @@
// LinphoneMediaEngine is a Linphone implementation of MediaEngine
extern "C" {
#include <mediastreamer2/mediastream.h>
-#include <mediastreamer2/mssndcard.h>
#include <mediastreamer2/msfilter.h>
+#include <mediastreamer2/mssndcard.h>
}
#include "talk/media/other/linphonemediaengine.h"
-#include "talk/base/buffer.h"
-#include "talk/base/event.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/stream.h"
#include "talk/media/base/rtpdump.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/event.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/stream.h"
#ifndef WIN32
#include <libgen.h>
@@ -137,11 +137,11 @@
ring_stream_(0)
{
- talk_base::Thread *thread = talk_base::ThreadManager::CurrentThread();
- talk_base::SocketServer *ss = thread->socketserver();
+ rtc::Thread *thread = rtc::ThreadManager::CurrentThread();
+ rtc::SocketServer *ss = thread->socketserver();
socket_.reset(ss->CreateAsyncSocket(SOCK_DGRAM));
- socket_->Bind(talk_base::SocketAddress("localhost",3000));
+ socket_->Bind(rtc::SocketAddress("localhost",3000));
socket_->SignalReadEvent.connect(this, &LinphoneVoiceChannel::OnIncomingData);
}
@@ -216,7 +216,7 @@
return true;
}
-void LinphoneVoiceChannel::OnPacketReceived(talk_base::Buffer* packet) {
+void LinphoneVoiceChannel::OnPacketReceived(rtc::Buffer* packet) {
const void* data = packet->data();
int len = packet->length();
uint8 buf[2048];
@@ -227,7 +227,7 @@
*/
int payloadtype = buf[1] & 0x7f;
if (play_ && payloadtype != 13)
- socket_->SendTo(buf, len, talk_base::SocketAddress("localhost",2000));
+ socket_->SendTo(buf, len, rtc::SocketAddress("localhost",2000));
}
void LinphoneVoiceChannel::StartRing(bool bIncomingCall)
@@ -263,12 +263,12 @@
}
}
-void LinphoneVoiceChannel::OnIncomingData(talk_base::AsyncSocket *s)
+void LinphoneVoiceChannel::OnIncomingData(rtc::AsyncSocket *s)
{
char *buf[2048];
int len;
len = s->Recv(buf, sizeof(buf));
- talk_base::Buffer packet(buf, len);
+ rtc::Buffer packet(buf, len);
if (network_interface_ && !mute_)
network_interface_->SendPacket(&packet);
}
diff --git a/media/other/linphonemediaengine.h b/media/other/linphonemediaengine.h
index db3e69f..b4950de 100644
--- a/media/other/linphonemediaengine.h
+++ b/media/other/linphonemediaengine.h
@@ -37,12 +37,12 @@
#include <mediastreamer2/mediastream.h>
}
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediaengine.h"
+#include "webrtc/base/scoped_ptr.h"
-namespace talk_base {
+namespace rtc {
class StreamInterface;
}
@@ -70,7 +70,6 @@
virtual VideoMediaChannel* CreateVideoChannel(VoiceMediaChannel* voice_ch);
virtual SoundclipMedia* CreateSoundclip() { return NULL; }
virtual bool SetAudioOptions(int options) { return true; }
- virtual bool SetVideoOptions(int options) { return true; }
virtual bool SetDefaultVideoEncoderConfig(const VideoEncoderConfig& config) {
return true;
}
@@ -81,7 +80,6 @@
virtual bool SetOutputVolume(int level) { return true; }
virtual int GetInputLevel() { return 0; }
virtual bool SetLocalMonitor(bool enable) { return true; }
- virtual bool SetLocalRenderer(VideoRenderer* renderer) { return true; }
// TODO: control channel send?
virtual bool SetVideoCapture(bool capture) { return true; }
virtual const std::vector<AudioCodec>& audio_codecs() {
@@ -140,8 +138,8 @@
virtual bool GetStats(VoiceMediaInfo* info) { return true; }
// Implement pure virtual methods of MediaChannel.
- virtual void OnPacketReceived(talk_base::Buffer* packet);
- virtual void OnRtcpReceived(talk_base::Buffer* packet) {}
+ virtual void OnPacketReceived(rtc::Buffer* packet);
+ virtual void OnRtcpReceived(rtc::Buffer* packet) {}
virtual void SetSendSsrc(uint32 id) {} // TODO: change RTP packet?
virtual bool SetRtcpCName(const std::string& cname) { return true; }
virtual bool Mute(bool on) { return mute_; }
@@ -163,8 +161,8 @@
AudioStream *audio_stream_;
LinphoneMediaEngine *engine_;
RingStream* ring_stream_;
- talk_base::scoped_ptr<talk_base::AsyncSocket> socket_;
- void OnIncomingData(talk_base::AsyncSocket *s);
+ rtc::scoped_ptr<rtc::AsyncSocket> socket_;
+ void OnIncomingData(rtc::AsyncSocket *s);
DISALLOW_COPY_AND_ASSIGN(LinphoneVoiceChannel);
};
diff --git a/media/sctp/sctpdataengine.cc b/media/sctp/sctpdataengine.cc
index 3647d21..88dade7 100644
--- a/media/sctp/sctpdataengine.cc
+++ b/media/sctp/sctpdataengine.cc
@@ -32,14 +32,14 @@
#include <sstream>
#include <vector>
-#include "talk/base/buffer.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/safe_conversions.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/streamparams.h"
#include "usrsctplib/usrsctp.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/safe_conversions.h"
namespace {
typedef cricket::SctpDataMediaChannel::StreamSet StreamSet;
@@ -102,20 +102,20 @@
} // namespace
namespace cricket {
-typedef talk_base::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
-typedef talk_base::ScopedMessageData<talk_base::Buffer> OutboundPacketMessage;
+typedef rtc::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
+typedef rtc::ScopedMessageData<rtc::Buffer> OutboundPacketMessage;
-// TODO(ldixon): Find where this is defined, and also check is Sctp really
-// respects this.
-static const size_t kSctpMtu = 1280;
+// The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
+// take off 80 bytes for DTLS/TURN/TCP/IP overhead.
+static const size_t kSctpMtu = 1200;
enum {
MSG_SCTPINBOUNDPACKET = 1, // MessageData is SctpInboundPacket
- MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is talk_base:Buffer
+ MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is rtc:Buffer
};
struct SctpInboundPacket {
- talk_base::Buffer buffer;
+ rtc::Buffer buffer;
ReceiveDataParams params;
// The |flags| parameter is used by SCTP to distinguish notification packets
// from other types of packets.
@@ -187,7 +187,7 @@
<< "; set_df: " << std::hex << static_cast<int>(set_df);
// Note: We have to copy the data; the caller will delete it.
OutboundPacketMessage* msg =
- new OutboundPacketMessage(new talk_base::Buffer(data, length));
+ new OutboundPacketMessage(new rtc::Buffer(data, length));
channel->worker_thread()->Post(channel, MSG_SCTPOUTBOUNDPACKET, msg);
return 0;
}
@@ -206,7 +206,7 @@
// memory cleanup. But this does simplify code.
const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
- talk_base::HostToNetwork32(rcv.rcv_ppid));
+ rtc::HostToNetwork32(rcv.rcv_ppid));
cricket::DataMessageType type = cricket::DMT_NONE;
if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
// It's neither a notification nor a recognized data packet. Drop it.
@@ -287,7 +287,7 @@
if (usrsctp_finish() == 0)
return;
- talk_base::Thread::SleepMs(10);
+ rtc::Thread::SleepMs(10);
}
LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
}
@@ -298,10 +298,10 @@
if (data_channel_type != DCT_SCTP) {
return NULL;
}
- return new SctpDataMediaChannel(talk_base::Thread::Current());
+ return new SctpDataMediaChannel(rtc::Thread::Current());
}
-SctpDataMediaChannel::SctpDataMediaChannel(talk_base::Thread* thread)
+SctpDataMediaChannel::SctpDataMediaChannel(rtc::Thread* thread)
: worker_thread_(thread),
local_port_(kSctpDefaultPort),
remote_port_(kSctpDefaultPort),
@@ -322,7 +322,7 @@
sconn.sconn_len = sizeof(sockaddr_conn);
#endif
// Note: conversion from int to uint16_t happens here.
- sconn.sconn_port = talk_base::HostToNetwork16(port);
+ sconn.sconn_port = rtc::HostToNetwork16(port);
sconn.sconn_addr = this;
return sconn;
}
@@ -378,6 +378,18 @@
return false;
}
+ // Disable MTU discovery
+ struct sctp_paddrparams params;
+ params.spp_assoc_id = 0;
+ params.spp_flags = SPP_PMTUD_DISABLE;
+ params.spp_pathmtu = kSctpMtu;
+ if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, ¶ms,
+ sizeof(params))) {
+ LOG_ERRNO(LS_ERROR) << debug_name_
+ << "Failed to set SCTP_PEER_ADDR_PARAMS.";
+ return false;
+ }
+
// Subscribe to SCTP event notifications.
int event_types[] = {SCTP_ASSOC_CHANGE,
SCTP_PEER_ADDR_CHANGE,
@@ -501,7 +513,7 @@
bool SctpDataMediaChannel::SendData(
const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result) {
if (result) {
// Preset |result| to assume an error. If SendData succeeds, we'll
@@ -530,7 +542,7 @@
struct sctp_sendv_spa spa = {0};
spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
spa.sendv_sndinfo.snd_sid = params.ssrc;
- spa.sendv_sndinfo.snd_ppid = talk_base::HostToNetwork32(
+ spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(
GetPpid(params.type));
// Ordered implies reliable.
@@ -551,7 +563,7 @@
send_res = usrsctp_sendv(sock_, payload.data(),
static_cast<size_t>(payload.length()),
NULL, 0, &spa,
- talk_base::checked_cast<socklen_t>(sizeof(spa)),
+ rtc::checked_cast<socklen_t>(sizeof(spa)),
SCTP_SENDV_SPA, 0);
if (send_res < 0) {
if (errno == SCTP_EWOULDBLOCK) {
@@ -573,7 +585,7 @@
// Called by network interface when a packet has been received.
void SctpDataMediaChannel::OnPacketReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): " << " length="
<< packet->length() << ", sending: " << sending_;
// Only give receiving packets to usrsctp after if connected. This enables two
@@ -613,7 +625,7 @@
}
void SctpDataMediaChannel::OnDataFromSctpToChannel(
- const ReceiveDataParams& params, talk_base::Buffer* buffer) {
+ const ReceiveDataParams& params, rtc::Buffer* buffer) {
if (receiving_) {
LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
<< "Posting with length: " << buffer->length()
@@ -682,7 +694,7 @@
return true;
}
-void SctpDataMediaChannel::OnNotificationFromSctp(talk_base::Buffer* buffer) {
+void SctpDataMediaChannel::OnNotificationFromSctp(rtc::Buffer* buffer) {
const sctp_notification& notification =
reinterpret_cast<const sctp_notification&>(*buffer->data());
ASSERT(notification.sn_header.sn_length == buffer->length());
@@ -857,7 +869,7 @@
for (size_t i = 0; i < codecs.size(); ++i) {
if (codecs[i].Matches(match_pattern)) {
if (codecs[i].GetParam(param, &value)) {
- *dest = talk_base::FromString<int>(value);
+ *dest = rtc::FromString<int>(value);
return true;
}
}
@@ -878,7 +890,7 @@
}
void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
- talk_base::Buffer* buffer) {
+ rtc::Buffer* buffer) {
if (buffer->length() > kSctpMtu) {
LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
<< "SCTP seems to have made a packet that is bigger "
@@ -905,7 +917,7 @@
&reset_stream_buf[0]);
resetp->srs_assoc_id = SCTP_ALL_ASSOC;
resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
- resetp->srs_number_streams = talk_base::checked_cast<uint16_t>(num_streams);
+ resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
int result_idx = 0;
for (StreamSet::iterator it = queued_reset_streams_.begin();
it != queued_reset_streams_.end(); ++it) {
@@ -914,7 +926,7 @@
int ret = usrsctp_setsockopt(
sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
- talk_base::checked_cast<socklen_t>(reset_stream_buf.size()));
+ rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
if (ret < 0) {
LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
<< num_streams << " streams";
@@ -927,16 +939,16 @@
return true;
}
-void SctpDataMediaChannel::OnMessage(talk_base::Message* msg) {
+void SctpDataMediaChannel::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_SCTPINBOUNDPACKET: {
- talk_base::scoped_ptr<InboundPacketMessage> pdata(
+ rtc::scoped_ptr<InboundPacketMessage> pdata(
static_cast<InboundPacketMessage*>(msg->pdata));
OnInboundPacketFromSctpToChannel(pdata->data().get());
break;
}
case MSG_SCTPOUTBOUNDPACKET: {
- talk_base::scoped_ptr<OutboundPacketMessage> pdata(
+ rtc::scoped_ptr<OutboundPacketMessage> pdata(
static_cast<OutboundPacketMessage*>(msg->pdata));
OnPacketFromSctpToNetwork(pdata->data().get());
break;
diff --git a/media/sctp/sctpdataengine.h b/media/sctp/sctpdataengine.h
index 2e8beec..4e36d65 100644
--- a/media/sctp/sctpdataengine.h
+++ b/media/sctp/sctpdataengine.h
@@ -41,11 +41,11 @@
};
} // namespace cricket
-#include "talk/base/buffer.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediaengine.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/scoped_ptr.h"
// Defined by "usrsctplib/usrsctp.h"
struct sockaddr_conn;
@@ -107,7 +107,7 @@
struct SctpInboundPacket;
class SctpDataMediaChannel : public DataMediaChannel,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
// DataMessageType is used for the SCTP "Payload Protocol Identifier", as
// defined in http://tools.ietf.org/html/rfc4960#section-14.4
@@ -132,7 +132,7 @@
// Given a thread which will be used to post messages (received data) to this
// SctpDataMediaChannel instance.
- explicit SctpDataMediaChannel(talk_base::Thread* thread);
+ explicit SctpDataMediaChannel(rtc::Thread* thread);
virtual ~SctpDataMediaChannel();
// When SetSend is set to true, connects. When set to false, disconnects.
@@ -149,19 +149,19 @@
// Called when Sctp gets data. The data may be a notification or data for
// OnSctpInboundData. Called from the worker thread.
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
// Send data down this channel (will be wrapped as SCTP packets then given to
// sctp that will then post the network interface by OnMessage).
// Returns true iff successful data somewhere on the send-queue/network.
virtual bool SendData(const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result = NULL);
// A packet is received from the network interface. Posted to OnMessage.
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
// Exposed to allow Post call from c-callbacks.
- talk_base::Thread* worker_thread() const { return worker_thread_; }
+ rtc::Thread* worker_thread() const { return worker_thread_; }
// TODO(ldixon): add a DataOptions class to mediachannel.h
virtual bool SetOptions(int options) { return false; }
@@ -180,8 +180,8 @@
const std::vector<RtpHeaderExtension>& extensions) { return true; }
virtual bool SetSendCodecs(const std::vector<DataCodec>& codecs);
virtual bool SetRecvCodecs(const std::vector<DataCodec>& codecs);
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {}
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {}
virtual void OnReadyToSend(bool ready) {}
// Helper for debugging.
@@ -213,19 +213,19 @@
bool ResetStream(uint32 ssrc);
// Called by OnMessage to send packet on the network.
- void OnPacketFromSctpToNetwork(talk_base::Buffer* buffer);
+ void OnPacketFromSctpToNetwork(rtc::Buffer* buffer);
// Called by OnMessage to decide what to do with the packet.
void OnInboundPacketFromSctpToChannel(SctpInboundPacket* packet);
void OnDataFromSctpToChannel(const ReceiveDataParams& params,
- talk_base::Buffer* buffer);
- void OnNotificationFromSctp(talk_base::Buffer* buffer);
+ rtc::Buffer* buffer);
+ void OnNotificationFromSctp(rtc::Buffer* buffer);
void OnNotificationAssocChange(const sctp_assoc_change& change);
void OnStreamResetEvent(const struct sctp_stream_reset_event* evt);
// Responsible for marshalling incoming data to the channels listeners, and
// outgoing data to the network interface.
- talk_base::Thread* worker_thread_;
+ rtc::Thread* worker_thread_;
// The local and remote SCTP port to use. These are passed along the wire
// and the listener and connector must be using the same port. It is not
// related to the ports at the IP level. If set to -1, we default to
diff --git a/media/sctp/sctpdataengine_unittest.cc b/media/sctp/sctpdataengine_unittest.cc
index cf410e5..fb00650 100644
--- a/media/sctp/sctpdataengine_unittest.cc
+++ b/media/sctp/sctpdataengine_unittest.cc
@@ -31,19 +31,24 @@
#include <string>
#include <vector>
-#include "talk/base/bind.h"
-#include "talk/base/buffer.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/thread.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/sctp/sctpdataengine.h"
+#include "webrtc/base/bind.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/thread.h"
+
+#ifdef HAVE_NSS_SSL_H
+// TODO(thorcarpenter): Remove after webrtc switches over to BoringSSL.
+#include "webrtc/base/nssstreamadapter.h"
+#endif // HAVE_NSS_SSL_H
enum {
MSG_PACKET = 1,
@@ -52,9 +57,9 @@
// Fake NetworkInterface that sends/receives sctp packets. The one in
// talk/media/base/fakenetworkinterface.h only works with rtp/rtcp.
class SctpFakeNetworkInterface : public cricket::MediaChannel::NetworkInterface,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
- explicit SctpFakeNetworkInterface(talk_base::Thread* thread)
+ explicit SctpFakeNetworkInterface(rtc::Thread* thread)
: thread_(thread),
dest_(NULL) {
}
@@ -63,15 +68,14 @@
protected:
// Called to send raw packet down the wire (e.g. SCTP an packet).
- virtual bool SendPacket(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
+ virtual bool SendPacket(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
LOG(LS_VERBOSE) << "SctpFakeNetworkInterface::SendPacket";
// TODO(ldixon): Can/should we use Buffer.TransferTo here?
// Note: this assignment does a deep copy of data from packet.
- talk_base::Buffer* buffer = new talk_base::Buffer(packet->data(),
- packet->length());
- thread_->Post(this, MSG_PACKET, talk_base::WrapMessageData(buffer));
+ rtc::Buffer* buffer = new rtc::Buffer(packet->data(), packet->length());
+ thread_->Post(this, MSG_PACKET, rtc::WrapMessageData(buffer));
LOG(LS_VERBOSE) << "SctpFakeNetworkInterface::SendPacket, Posted message.";
return true;
}
@@ -79,13 +83,13 @@
// Called when a raw packet has been recieved. This passes the data to the
// code that will interpret the packet. e.g. to get the content payload from
// an SCTP packet.
- virtual void OnMessage(talk_base::Message* msg) {
+ virtual void OnMessage(rtc::Message* msg) {
LOG(LS_VERBOSE) << "SctpFakeNetworkInterface::OnMessage";
- talk_base::scoped_ptr<talk_base::Buffer> buffer(
- static_cast<talk_base::TypedMessageData<talk_base::Buffer*>*>(
+ rtc::scoped_ptr<rtc::Buffer> buffer(
+ static_cast<rtc::TypedMessageData<rtc::Buffer*>*>(
msg->pdata)->data());
if (dest_) {
- dest_->OnPacketReceived(buffer.get(), talk_base::PacketTime());
+ dest_->OnPacketReceived(buffer.get(), rtc::PacketTime());
}
delete msg->pdata;
}
@@ -93,23 +97,23 @@
// Unsupported functions required to exist by NetworkInterface.
// TODO(ldixon): Refactor parent NetworkInterface class so these are not
// required. They are RTC specific and should be in an appropriate subclass.
- virtual bool SendRtcp(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
+ virtual bool SendRtcp(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
LOG(LS_WARNING) << "Unsupported: SctpFakeNetworkInterface::SendRtcp.";
return false;
}
- virtual int SetOption(SocketType type, talk_base::Socket::Option opt,
+ virtual int SetOption(SocketType type, rtc::Socket::Option opt,
int option) {
LOG(LS_WARNING) << "Unsupported: SctpFakeNetworkInterface::SetOption.";
return 0;
}
- virtual void SetDefaultDSCPCode(talk_base::DiffServCodePoint dscp) {
+ virtual void SetDefaultDSCPCode(rtc::DiffServCodePoint dscp) {
LOG(LS_WARNING) << "Unsupported: SctpFakeNetworkInterface::SetOption.";
}
private:
// Not owned by this class.
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
cricket::DataMediaChannel* dest_;
};
@@ -219,11 +223,17 @@
// usrsctp uses the NSS random number generator on non-Android platforms,
// so we need to initialize SSL.
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+#ifdef HAVE_NSS_SSL_H
+ // TODO(thorcarpenter): Remove after webrtc switches over to BoringSSL.
+ if (!rtc::NSSContext::InitializeSSL(NULL)) {
+ LOG(LS_WARNING) << "Unabled to initialize NSS.";
+ }
+#endif // HAVE_NSS_SSL_H
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
virtual void SetUp() {
@@ -231,8 +241,8 @@
}
void SetupConnectedChannels() {
- net1_.reset(new SctpFakeNetworkInterface(talk_base::Thread::Current()));
- net2_.reset(new SctpFakeNetworkInterface(talk_base::Thread::Current()));
+ net1_.reset(new SctpFakeNetworkInterface(rtc::Thread::Current()));
+ net2_.reset(new SctpFakeNetworkInterface(rtc::Thread::Current()));
recv1_.reset(new SctpFakeDataReceiver());
recv2_.reset(new SctpFakeDataReceiver());
chan1_.reset(CreateChannel(net1_.get(), recv1_.get()));
@@ -266,6 +276,10 @@
virtual void TearDown() {
channel1()->SetSend(false);
channel2()->SetSend(false);
+
+ // Process messages until idle to prevent a sent packet from being dropped
+ // and causing memory leaks (not being deleted by the receiver).
+ ProcessMessagesUntilIdle();
}
void AddStream(int ssrc) {
@@ -294,7 +308,7 @@
cricket::SendDataParams params;
params.ssrc = ssrc;
- return chan->SendData(params, talk_base::Buffer(
+ return chan->SendData(params, rtc::Buffer(
&msg[0], msg.length()), result);
}
@@ -306,10 +320,10 @@
}
bool ProcessMessagesUntilIdle() {
- talk_base::Thread* thread = talk_base::Thread::Current();
+ rtc::Thread* thread = rtc::Thread::Current();
while (!thread->empty()) {
- talk_base::Message msg;
- if (thread->Get(&msg, talk_base::kForever)) {
+ rtc::Message msg;
+ if (thread->Get(&msg, rtc::kForever)) {
thread->Dispatch(&msg);
}
}
@@ -322,13 +336,13 @@
SctpFakeDataReceiver* receiver2() { return recv2_.get(); }
private:
- talk_base::scoped_ptr<cricket::SctpDataEngine> engine_;
- talk_base::scoped_ptr<SctpFakeNetworkInterface> net1_;
- talk_base::scoped_ptr<SctpFakeNetworkInterface> net2_;
- talk_base::scoped_ptr<SctpFakeDataReceiver> recv1_;
- talk_base::scoped_ptr<SctpFakeDataReceiver> recv2_;
- talk_base::scoped_ptr<cricket::SctpDataMediaChannel> chan1_;
- talk_base::scoped_ptr<cricket::SctpDataMediaChannel> chan2_;
+ rtc::scoped_ptr<cricket::SctpDataEngine> engine_;
+ rtc::scoped_ptr<SctpFakeNetworkInterface> net1_;
+ rtc::scoped_ptr<SctpFakeNetworkInterface> net2_;
+ rtc::scoped_ptr<SctpFakeDataReceiver> recv1_;
+ rtc::scoped_ptr<SctpFakeDataReceiver> recv2_;
+ rtc::scoped_ptr<cricket::SctpDataMediaChannel> chan1_;
+ rtc::scoped_ptr<cricket::SctpDataMediaChannel> chan2_;
};
// Verifies that SignalReadyToSend is fired.
@@ -398,7 +412,7 @@
for (size_t i = 0; i < 100; ++i) {
channel1()->SendData(
- params, talk_base::Buffer(&buffer[0], buffer.size()), &result);
+ params, rtc::Buffer(&buffer[0], buffer.size()), &result);
if (result == cricket::SDR_BLOCK)
break;
}
diff --git a/media/testdata/faces.1280x720_P420.yuv b/media/testdata/faces.1280x720_P420.yuv
new file mode 100644
index 0000000..f4844ee
--- /dev/null
+++ b/media/testdata/faces.1280x720_P420.yuv
Binary files differ
diff --git a/media/testdata/faces_I400.jpg b/media/testdata/faces_I400.jpg
new file mode 100644
index 0000000..c928f00
--- /dev/null
+++ b/media/testdata/faces_I400.jpg
Binary files differ
diff --git a/media/testdata/faces_I411.jpg b/media/testdata/faces_I411.jpg
new file mode 100644
index 0000000..600c122
--- /dev/null
+++ b/media/testdata/faces_I411.jpg
Binary files differ
diff --git a/media/testdata/faces_I420.jpg b/media/testdata/faces_I420.jpg
new file mode 100644
index 0000000..10c5332
--- /dev/null
+++ b/media/testdata/faces_I420.jpg
Binary files differ
diff --git a/media/testdata/faces_I422.jpg b/media/testdata/faces_I422.jpg
new file mode 100644
index 0000000..9907aa1
--- /dev/null
+++ b/media/testdata/faces_I422.jpg
Binary files differ
diff --git a/media/testdata/faces_I444.jpg b/media/testdata/faces_I444.jpg
new file mode 100644
index 0000000..3422755
--- /dev/null
+++ b/media/testdata/faces_I444.jpg
Binary files differ
diff --git a/media/webrtc/OWNERS b/media/webrtc/OWNERS
index 9a3546e..aef5939 100644
--- a/media/webrtc/OWNERS
+++ b/media/webrtc/OWNERS
@@ -1,3 +1,3 @@
mflodman@webrtc.org
+pbos@webrtc.org
pthatcher@webrtc.org
-wu@webrtc.org
diff --git a/media/webrtc/constants.h b/media/webrtc/constants.h
new file mode 100755
index 0000000..68f664b
--- /dev/null
+++ b/media/webrtc/constants.h
@@ -0,0 +1,46 @@
+/*
+ * libjingle
+ * Copyright 2014 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef TALK_MEDIA_WEBRTC_CONSTANTS_H_
+#define TALK_MEDIA_WEBRTC_CONSTANTS_H_
+
+namespace cricket {
+
+extern const int kVideoMtu;
+extern const int kVideoRtpBufferSize;
+
+extern const char kVp8CodecName[];
+
+extern const int kDefaultFramerate;
+extern const int kMinVideoBitrate;
+extern const int kStartVideoBitrate;
+extern const int kMaxVideoBitrate;
+
+extern const int kCpuMonitorPeriodMs;
+
+} // namespace cricket
+
+#endif // TALK_MEDIA_WEBRTC_CONSTANTS_H_
diff --git a/media/webrtc/fakewebrtccommon.h b/media/webrtc/fakewebrtccommon.h
index 026ad10..d1c2320 100644
--- a/media/webrtc/fakewebrtccommon.h
+++ b/media/webrtc/fakewebrtccommon.h
@@ -28,7 +28,7 @@
#ifndef TALK_SESSION_PHONE_FAKEWEBRTCCOMMON_H_
#define TALK_SESSION_PHONE_FAKEWEBRTCCOMMON_H_
-#include "talk/base/common.h"
+#include "webrtc/base/common.h"
namespace cricket {
@@ -41,6 +41,11 @@
#define WEBRTC_BOOL_STUB(method, args) \
virtual bool method args OVERRIDE { return true; }
+#ifdef USE_WEBRTC_DEV_BRANCH
+#define WEBRTC_BOOL_STUB_CONST(method, args) \
+ virtual bool method args const OVERRIDE { return true; }
+#endif
+
#define WEBRTC_VOID_STUB(method, args) \
virtual void method args OVERRIDE {}
diff --git a/media/webrtc/fakewebrtcdeviceinfo.h b/media/webrtc/fakewebrtcdeviceinfo.h
index 585f31e..874369b 100644
--- a/media/webrtc/fakewebrtcdeviceinfo.h
+++ b/media/webrtc/fakewebrtcdeviceinfo.h
@@ -28,8 +28,8 @@
#include <vector>
-#include "talk/base/stringutils.h"
#include "talk/media/webrtc/webrtcvideocapturer.h"
+#include "webrtc/base/stringutils.h"
// Fake class for mocking out webrtc::VideoCaptureModule::DeviceInfo.
class FakeWebRtcDeviceInfo : public webrtc::VideoCaptureModule::DeviceInfo {
@@ -64,12 +64,12 @@
uint32_t product_id_len) {
Device* dev = GetDeviceByIndex(device_num);
if (!dev) return -1;
- talk_base::strcpyn(reinterpret_cast<char*>(device_name), device_name_len,
+ rtc::strcpyn(reinterpret_cast<char*>(device_name), device_name_len,
dev->name.c_str());
- talk_base::strcpyn(reinterpret_cast<char*>(device_id), device_id_len,
+ rtc::strcpyn(reinterpret_cast<char*>(device_id), device_id_len,
dev->id.c_str());
if (product_id) {
- talk_base::strcpyn(reinterpret_cast<char*>(product_id), product_id_len,
+ rtc::strcpyn(reinterpret_cast<char*>(product_id), product_id_len,
dev->product.c_str());
}
return 0;
diff --git a/media/webrtc/fakewebrtcvideocapturemodule.h b/media/webrtc/fakewebrtcvideocapturemodule.h
index 347e4b7..82b5cdd 100644
--- a/media/webrtc/fakewebrtcvideocapturemodule.h
+++ b/media/webrtc/fakewebrtcvideocapturemodule.h
@@ -44,76 +44,72 @@
running_(false),
delay_(0) {
}
- virtual int32_t Version(char* version,
- uint32_t& remaining_buffer_in_bytes,
- uint32_t& position) const {
+ virtual int32_t TimeUntilNextProcess() OVERRIDE {
return 0;
}
- virtual int32_t TimeUntilNextProcess() {
+ virtual int32_t Process() OVERRIDE {
return 0;
}
- virtual int32_t Process() {
- return 0;
- }
- virtual int32_t ChangeUniqueId(const int32_t id) {
+ virtual int32_t ChangeUniqueId(const int32_t id) OVERRIDE {
id_ = id;
return 0;
}
virtual void RegisterCaptureDataCallback(
- webrtc::VideoCaptureDataCallback& callback) {
+ webrtc::VideoCaptureDataCallback& callback) OVERRIDE {
callback_ = &callback;
}
- virtual void DeRegisterCaptureDataCallback() { callback_ = NULL; }
- virtual void RegisterCaptureCallback(webrtc::VideoCaptureFeedBack& callback) {
+ virtual void DeRegisterCaptureDataCallback() OVERRIDE { callback_ = NULL; }
+ virtual void RegisterCaptureCallback(
+ webrtc::VideoCaptureFeedBack& callback) OVERRIDE {
// Not implemented.
}
- virtual void DeRegisterCaptureCallback() {
+ virtual void DeRegisterCaptureCallback() OVERRIDE {
// Not implemented.
}
- virtual void SetCaptureDelay(int32_t delay) { delay_ = delay; }
- virtual int32_t CaptureDelay() { return delay_; }
- virtual void EnableFrameRateCallback(const bool enable) {
+ virtual void SetCaptureDelay(int32_t delay) OVERRIDE { delay_ = delay; }
+ virtual int32_t CaptureDelay() OVERRIDE { return delay_; }
+ virtual void EnableFrameRateCallback(const bool enable) OVERRIDE {
// not implemented
}
- virtual void EnableNoPictureAlarm(const bool enable) {
+ virtual void EnableNoPictureAlarm(const bool enable) OVERRIDE {
// not implemented
}
virtual int32_t StartCapture(
- const webrtc::VideoCaptureCapability& cap) {
+ const webrtc::VideoCaptureCapability& cap) OVERRIDE {
if (running_) return -1;
cap_ = cap;
running_ = true;
return 0;
}
- virtual int32_t StopCapture() {
+ virtual int32_t StopCapture() OVERRIDE {
running_ = false;
return 0;
}
- virtual const char* CurrentDeviceName() const {
+ virtual const char* CurrentDeviceName() const OVERRIDE {
return NULL; // not implemented
}
- virtual bool CaptureStarted() {
+ virtual bool CaptureStarted() OVERRIDE {
return running_;
}
virtual int32_t CaptureSettings(
- webrtc::VideoCaptureCapability& settings) {
+ webrtc::VideoCaptureCapability& settings) OVERRIDE {
if (!running_) return -1;
settings = cap_;
return 0;
}
virtual int32_t SetCaptureRotation(
- webrtc::VideoCaptureRotation rotation) {
+ webrtc::VideoCaptureRotation rotation) OVERRIDE {
return -1; // not implemented
}
virtual VideoCaptureEncodeInterface* GetEncodeInterface(
- const webrtc::VideoCodec& codec) {
+ const webrtc::VideoCodec& codec) OVERRIDE {
return NULL; // not implemented
}
- virtual int32_t AddRef() {
+ virtual int32_t AddRef() OVERRIDE {
return 0;
}
- virtual int32_t Release() {
+ virtual int32_t Release() OVERRIDE {
delete this;
return 0;
}
diff --git a/media/webrtc/fakewebrtcvideoengine.h b/media/webrtc/fakewebrtcvideoengine.h
index 85c59d8..ec4b9c6 100644
--- a/media/webrtc/fakewebrtcvideoengine.h
+++ b/media/webrtc/fakewebrtcvideoengine.h
@@ -32,14 +32,14 @@
#include <set>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/gunit.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/codec.h"
#include "talk/media/webrtc/fakewebrtccommon.h"
#include "talk/media/webrtc/webrtcvideodecoderfactory.h"
#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
#include "talk/media/webrtc/webrtcvie.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
@@ -335,6 +335,7 @@
unsigned int send_nack_bitrate_;
unsigned int send_bandwidth_;
unsigned int receive_bandwidth_;
+ // Bandwidth to deduct from estimated uplink capacity.
unsigned int reserved_transmit_bitrate_bps_;
bool suspend_below_min_bitrate_;
webrtc::CpuOveruseObserver* overuse_observer_;
@@ -548,13 +549,21 @@
WEBRTC_ASSERT_CHANNEL(channel);
return channels_.find(channel)->second->overuse_options_;
}
- int GetRtxSsrc(int channel, int simulcast_idx) const {
+ int GetSsrc(int channel, int idx) const {
WEBRTC_ASSERT_CHANNEL(channel);
- if (channels_.find(channel)->second->rtx_ssrcs_.find(simulcast_idx) ==
+ if (channels_.find(channel)->second->ssrcs_.find(idx) ==
+ channels_.find(channel)->second->ssrcs_.end()) {
+ return -1;
+ }
+ return channels_.find(channel)->second->ssrcs_[idx];
+ }
+ int GetRtxSsrc(int channel, int idx) const {
+ WEBRTC_ASSERT_CHANNEL(channel);
+ if (channels_.find(channel)->second->rtx_ssrcs_.find(idx) ==
channels_.find(channel)->second->rtx_ssrcs_.end()) {
return -1;
}
- return channels_.find(channel)->second->rtx_ssrcs_[simulcast_idx];
+ return channels_.find(channel)->second->rtx_ssrcs_[idx];
}
bool ReceiveCodecRegistered(int channel,
const webrtc::VideoCodec& codec) const {
@@ -684,7 +693,11 @@
channels_[channel]->overuse_observer_ = observer;
return 0;
}
+#ifdef USE_WEBRTC_DEV_BRANCH
+ WEBRTC_STUB(GetCpuOveruseMetrics, (int, webrtc::CpuOveruseMetrics*));
+#else
WEBRTC_STUB(CpuOveruseMeasures, (int, int*, int*, int*, int*));
+#endif
WEBRTC_FUNC(SetCpuOveruseOptions,
(int channel, const webrtc::CpuOveruseOptions& options)) {
WEBRTC_CHECK_CHANNEL(channel);
@@ -738,7 +751,7 @@
} else {
out_codec.codecType = webrtc::kVideoCodecUnknown;
}
- talk_base::strcpyn(out_codec.plName, sizeof(out_codec.plName),
+ rtc::strcpyn(out_codec.plName, sizeof(out_codec.plName),
c.name.c_str());
out_codec.plType = c.id;
out_codec.width = c.width;
@@ -896,6 +909,9 @@
WEBRTC_STUB(SetMTU, (int, unsigned int));
WEBRTC_STUB(ReceivedBWEPacket, (const int, int64_t, int,
const webrtc::RTPHeader&));
+ virtual bool SetBandwidthEstimationConfig(int, const webrtc::Config&) {
+ return true;
+ }
// webrtc::ViERender
WEBRTC_STUB(RegisterVideoRenderModule, (webrtc::VideoRender&));
@@ -1028,7 +1044,7 @@
WEBRTC_FUNC_CONST(GetRTCPCName, (const int channel,
char rtcp_cname[KMaxRTCPCNameLength])) {
WEBRTC_CHECK_CHANNEL(channel);
- talk_base::strcpyn(rtcp_cname, KMaxRTCPCNameLength,
+ rtc::strcpyn(rtcp_cname, KMaxRTCPCNameLength,
channels_.find(channel)->second->cname_.c_str());
return 0;
}
diff --git a/media/webrtc/fakewebrtcvoiceengine.h b/media/webrtc/fakewebrtcvoiceengine.h
index 25c952d..52a50ff 100644
--- a/media/webrtc/fakewebrtcvoiceengine.h
+++ b/media/webrtc/fakewebrtcvoiceengine.h
@@ -32,18 +32,18 @@
#include <map>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/gunit.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/base/voiceprocessor.h"
#include "talk/media/webrtc/fakewebrtccommon.h"
#include "talk/media/webrtc/webrtcvoe.h"
-
-namespace webrtc {
-class ViENetwork;
-}
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/stringutils.h"
+#ifdef USE_WEBRTC_DEV_BRANCH
+#include "webrtc/modules/audio_processing/include/audio_processing.h"
+#endif
+#include "webrtc/video_engine/include/vie_network.h"
namespace cricket {
@@ -61,6 +61,12 @@
static const int kFakeDeviceId = 1;
#endif
+static const int kOpusBandwidthNb = 4000;
+static const int kOpusBandwidthMb = 6000;
+static const int kOpusBandwidthWb = 8000;
+static const int kOpusBandwidthSwb = 12000;
+static const int kOpusBandwidthFb = 20000;
+
// Verify the header extension ID, if enabled, is within the bounds specified in
// [RFC5285]: 1-14 inclusive.
#define WEBRTC_CHECK_HEADER_EXTENSION_ID(enable, id) \
@@ -70,6 +76,88 @@
} \
} while (0);
+#ifdef USE_WEBRTC_DEV_BRANCH
+class FakeAudioProcessing : public webrtc::AudioProcessing {
+ public:
+ FakeAudioProcessing() : experimental_ns_enabled_(false) {}
+
+ WEBRTC_STUB(Initialize, ())
+ WEBRTC_STUB(Initialize, (
+ int input_sample_rate_hz,
+ int output_sample_rate_hz,
+ int reverse_sample_rate_hz,
+ webrtc::AudioProcessing::ChannelLayout input_layout,
+ webrtc::AudioProcessing::ChannelLayout output_layout,
+ webrtc::AudioProcessing::ChannelLayout reverse_layout));
+
+ WEBRTC_VOID_FUNC(SetExtraOptions, (const webrtc::Config& config)) {
+ experimental_ns_enabled_ = config.Get<webrtc::ExperimentalNs>().enabled;
+ }
+
+ WEBRTC_STUB(set_sample_rate_hz, (int rate));
+ WEBRTC_STUB_CONST(input_sample_rate_hz, ());
+ WEBRTC_STUB_CONST(sample_rate_hz, ());
+ WEBRTC_STUB_CONST(proc_sample_rate_hz, ());
+ WEBRTC_STUB_CONST(proc_split_sample_rate_hz, ());
+ WEBRTC_STUB_CONST(num_input_channels, ());
+ WEBRTC_STUB_CONST(num_output_channels, ());
+ WEBRTC_STUB_CONST(num_reverse_channels, ());
+ WEBRTC_VOID_STUB(set_output_will_be_muted, (bool muted));
+ WEBRTC_BOOL_STUB_CONST(output_will_be_muted, ());
+ WEBRTC_STUB(ProcessStream, (webrtc::AudioFrame* frame));
+ WEBRTC_STUB(ProcessStream, (
+ const float* const* src,
+ int samples_per_channel,
+ int input_sample_rate_hz,
+ webrtc::AudioProcessing::ChannelLayout input_layout,
+ int output_sample_rate_hz,
+ webrtc::AudioProcessing::ChannelLayout output_layout,
+ float* const* dest));
+ WEBRTC_STUB(AnalyzeReverseStream, (webrtc::AudioFrame* frame));
+ WEBRTC_STUB(AnalyzeReverseStream, (
+ const float* const* data,
+ int samples_per_channel,
+ int sample_rate_hz,
+ webrtc::AudioProcessing::ChannelLayout layout));
+ WEBRTC_STUB(set_stream_delay_ms, (int delay));
+ WEBRTC_STUB_CONST(stream_delay_ms, ());
+ WEBRTC_BOOL_STUB_CONST(was_stream_delay_set, ());
+ WEBRTC_VOID_STUB(set_stream_key_pressed, (bool key_pressed));
+ WEBRTC_BOOL_STUB_CONST(stream_key_pressed, ());
+ WEBRTC_VOID_STUB(set_delay_offset_ms, (int offset));
+ WEBRTC_STUB_CONST(delay_offset_ms, ());
+ WEBRTC_STUB(StartDebugRecording, (const char filename[kMaxFilenameSize]));
+ WEBRTC_STUB(StartDebugRecording, (FILE* handle));
+ WEBRTC_STUB(StopDebugRecording, ());
+ virtual webrtc::EchoCancellation* echo_cancellation() const OVERRIDE {
+ return NULL;
+ }
+ virtual webrtc::EchoControlMobile* echo_control_mobile() const OVERRIDE {
+ return NULL;
+ }
+ virtual webrtc::GainControl* gain_control() const OVERRIDE { return NULL; }
+ virtual webrtc::HighPassFilter* high_pass_filter() const OVERRIDE {
+ return NULL;
+ }
+ virtual webrtc::LevelEstimator* level_estimator() const OVERRIDE {
+ return NULL;
+ }
+ virtual webrtc::NoiseSuppression* noise_suppression() const OVERRIDE {
+ return NULL;
+ }
+ virtual webrtc::VoiceDetection* voice_detection() const OVERRIDE {
+ return NULL;
+ }
+
+ bool experimental_ns_enabled() {
+ return experimental_ns_enabled_;
+ }
+
+ private:
+ bool experimental_ns_enabled_;
+};
+#endif
+
class FakeWebRtcVoiceEngine
: public webrtc::VoEAudioProcessing,
public webrtc::VoEBase, public webrtc::VoECodec, public webrtc::VoEDtmf,
@@ -98,6 +186,7 @@
file(false),
vad(false),
codec_fec(false),
+ max_encoding_bandwidth(0),
red(false),
nack(false),
media_processor_registered(false),
@@ -127,6 +216,7 @@
bool file;
bool vad;
bool codec_fec;
+ int max_encoding_bandwidth;
bool red;
bool nack;
bool media_processor_registered;
@@ -223,6 +313,9 @@
bool GetCodecFEC(int channel) {
return channels_[channel]->codec_fec;
}
+ int GetMaxEncodingBandwidth(int channel) {
+ return channels_[channel]->max_encoding_bandwidth;
+ }
bool GetNACK(int channel) {
return channels_[channel]->nack;
}
@@ -231,6 +324,8 @@
}
webrtc::ViENetwork* GetViENetwork(int channel) {
WEBRTC_ASSERT_CHANNEL(channel);
+ // WARNING: This pointer is for verification purposes only. Calling
+ // functions on it may result in undefined behavior!
return channels_[channel]->vie_network;
}
int GetVideoChannel(int channel) {
@@ -347,7 +442,11 @@
return 0;
}
virtual webrtc::AudioProcessing* audio_processing() OVERRIDE {
+#ifdef USE_WEBRTC_DEV_BRANCH
+ return &audio_processing_;
+#else
return NULL;
+#endif
}
WEBRTC_FUNC(CreateChannel, ()) {
return AddChannel();
@@ -399,8 +498,6 @@
WEBRTC_STUB(LastError, ());
WEBRTC_STUB(SetOnHoldStatus, (int, bool, webrtc::OnHoldModes));
WEBRTC_STUB(GetOnHoldStatus, (int, bool&, webrtc::OnHoldModes&));
- WEBRTC_STUB(SetNetEQPlayoutMode, (int, webrtc::NetEqModes));
- WEBRTC_STUB(GetNetEQPlayoutMode, (int, webrtc::NetEqModes&));
// webrtc::VoECodec
WEBRTC_FUNC(NumOfCodecs, ()) {
@@ -412,7 +509,7 @@
}
const cricket::AudioCodec& c(*codecs_[index]);
codec.pltype = c.id;
- talk_base::strcpyn(codec.plname, sizeof(codec.plname), c.name.c_str());
+ rtc::strcpyn(codec.plname, sizeof(codec.plname), c.name.c_str());
codec.plfreq = c.clockrate;
codec.pacsize = 0;
codec.channels = c.channels;
@@ -536,9 +633,15 @@
}
WEBRTC_STUB(GetVADStatus, (int channel, bool& enabled,
webrtc::VadModes& mode, bool& disabledDTX));
+
#ifdef USE_WEBRTC_DEV_BRANCH
WEBRTC_FUNC(SetFECStatus, (int channel, bool enable)) {
WEBRTC_CHECK_CHANNEL(channel);
+ if (_stricmp(channels_[channel]->send_codec.plname, "opus") != 0) {
+ // Return -1 if current send codec is not Opus.
+ // TODO(minyue): Excludes other codecs if they support inband FEC.
+ return -1;
+ }
channels_[channel]->codec_fec = enable;
return 0;
}
@@ -547,6 +650,25 @@
enable = channels_[channel]->codec_fec;
return 0;
}
+
+ WEBRTC_FUNC(SetOpusMaxPlaybackRate, (int channel, int frequency_hz)) {
+ WEBRTC_CHECK_CHANNEL(channel);
+ if (_stricmp(channels_[channel]->send_codec.plname, "opus") != 0) {
+ // Return -1 if current send codec is not Opus.
+ return -1;
+ }
+ if (frequency_hz <= 8000)
+ channels_[channel]->max_encoding_bandwidth = kOpusBandwidthNb;
+ else if (frequency_hz <= 12000)
+ channels_[channel]->max_encoding_bandwidth = kOpusBandwidthMb;
+ else if (frequency_hz <= 16000)
+ channels_[channel]->max_encoding_bandwidth = kOpusBandwidthWb;
+ else if (frequency_hz <= 24000)
+ channels_[channel]->max_encoding_bandwidth = kOpusBandwidthSwb;
+ else
+ channels_[channel]->max_encoding_bandwidth = kOpusBandwidthFb;
+ return 0;
+ }
#endif // USE_WEBRTC_DEV_BRANCH
// webrtc::VoEDtmf
@@ -784,7 +906,6 @@
channels_[channel]->send_audio_level_ext_ = (enable) ? id : -1;
return 0;
}
-#ifdef USE_WEBRTC_DEV_BRANCH
WEBRTC_FUNC(SetReceiveAudioLevelIndicationStatus, (int channel, bool enable,
unsigned char id)) {
WEBRTC_CHECK_CHANNEL(channel);
@@ -792,7 +913,6 @@
channels_[channel]->receive_audio_level_ext_ = (enable) ? id : -1;
return 0;
}
-#endif // USE_WEBRTC_DEV_BRANCH
WEBRTC_FUNC(SetSendAbsoluteSenderTimeStatus, (int channel, bool enable,
unsigned char id)) {
WEBRTC_CHECK_CHANNEL(channel);
@@ -862,9 +982,12 @@
}
#ifdef USE_WEBRTC_DEV_BRANCH
WEBRTC_FUNC(SetREDStatus, (int channel, bool enable, int redPayloadtype)) {
-#else
+ return SetFECStatus(channel, enable, redPayloadtype);
+ }
+#endif
+ // TODO(minyue): remove the below function when transition to SetREDStatus
+ // is finished.
WEBRTC_FUNC(SetFECStatus, (int channel, bool enable, int redPayloadtype)) {
-#endif // USE_WEBRTC_DEV_BRANCH
WEBRTC_CHECK_CHANNEL(channel);
channels_[channel]->red = enable;
channels_[channel]->red_type = redPayloadtype;
@@ -872,9 +995,12 @@
}
#ifdef USE_WEBRTC_DEV_BRANCH
WEBRTC_FUNC(GetREDStatus, (int channel, bool& enable, int& redPayloadtype)) {
-#else
+ return GetFECStatus(channel, enable, redPayloadtype);
+ }
+#endif
+ // TODO(minyue): remove the below function when transition to GetREDStatus
+ // is finished.
WEBRTC_FUNC(GetFECStatus, (int channel, bool& enable, int& redPayloadtype)) {
-#endif // USE_WEBRTC_DEV_BRANCH
WEBRTC_CHECK_CHANNEL(channel);
enable = channels_[channel]->red;
redPayloadtype = channels_[channel]->red_type;
@@ -901,6 +1027,11 @@
WEBRTC_CHECK_CHANNEL(channel);
channels_[channel]->vie_network = vie_network;
channels_[channel]->video_channel = video_channel;
+ if (vie_network) {
+ // The interface is released here to avoid leaks. A test should not
+ // attempt to call functions on the interface stored in the channel.
+ vie_network->Release();
+ }
return 0;
}
@@ -1188,6 +1319,9 @@
int playout_sample_rate_;
DtmfInfo dtmf_info_;
webrtc::VoEMediaProcess* media_processor_;
+#ifdef USE_WEBRTC_DEV_BRANCH
+ FakeAudioProcessing audio_processing_;
+#endif
};
#undef WEBRTC_CHECK_HEADER_EXTENSION_ID
diff --git a/media/webrtc/webrtcexport.h b/media/webrtc/webrtcexport.h
index 71ebe4e..b00b0cb 100644
--- a/media/webrtc/webrtcexport.h
+++ b/media/webrtc/webrtcexport.h
@@ -27,6 +27,9 @@
#ifndef TALK_MEDIA_WEBRTC_WEBRTCEXPORT_H_
#define TALK_MEDIA_WEBRTC_WEBRTCEXPORT_H_
+// When building for Chrome a part of the code can be built into
+// a shared library, which is controlled by these macros.
+// For all other builds, we always build a static library.
#if !defined(GOOGLE_CHROME_BUILD) && !defined(CHROMIUM_BUILD)
#define LIBPEERCONNECTION_LIB 1
#endif
diff --git a/media/webrtc/webrtcmediaengine.cc b/media/webrtc/webrtcmediaengine.cc
index 445564c..cf0fcdf 100644
--- a/media/webrtc/webrtcmediaengine.cc
+++ b/media/webrtc/webrtcmediaengine.cc
@@ -25,8 +25,53 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#if defined(LIBPEERCONNECTION_LIB) || \
+ defined(LIBPEERCONNECTION_IMPLEMENTATION)
+
#include "talk/media/webrtc/webrtcmediaengine.h"
+#include "talk/media/webrtc/webrtcvideoengine.h"
+#ifdef WEBRTC_CHROMIUM_BUILD
+#include "talk/media/webrtc/webrtcvideoengine2.h"
+#endif
+#include "talk/media/webrtc/webrtcvoiceengine.h"
+#ifdef WEBRTC_CHROMIUM_BUILD
#include "webrtc/system_wrappers/interface/field_trial.h"
+#endif
+
+namespace cricket {
+
+class WebRtcMediaEngine :
+ public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine> {
+ public:
+ WebRtcMediaEngine() {}
+ WebRtcMediaEngine(webrtc::AudioDeviceModule* adm,
+ webrtc::AudioDeviceModule* adm_sc,
+ WebRtcVideoEncoderFactory* encoder_factory,
+ WebRtcVideoDecoderFactory* decoder_factory) {
+ voice_.SetAudioDeviceModule(adm, adm_sc);
+ video_.SetVoiceEngine(&voice_);
+ video_.SetExternalEncoderFactory(encoder_factory);
+ video_.SetExternalDecoderFactory(decoder_factory);
+ }
+};
+
+#ifdef WEBRTC_CHROMIUM_BUILD
+class WebRtcMediaEngine2 :
+ public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine2> {
+ public:
+ WebRtcMediaEngine2(webrtc::AudioDeviceModule* adm,
+ webrtc::AudioDeviceModule* adm_sc,
+ WebRtcVideoEncoderFactory* encoder_factory,
+ WebRtcVideoDecoderFactory* decoder_factory) {
+ voice_.SetAudioDeviceModule(adm, adm_sc);
+ video_.SetExternalDecoderFactory(decoder_factory);
+ video_.SetExternalEncoderFactory(encoder_factory);
+ video_.SetVoiceEngine(&voice_);
+ }
+};
+#endif // WEBRTC_CHROMIUM_BUILD
+
+} // namespace cricket
WRME_EXPORT
cricket::MediaEngineInterface* CreateWebRtcMediaEngine(
@@ -46,13 +91,28 @@
WRME_EXPORT
void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) {
-#ifdef WEBRTC_CHROMIUM_BUILD
- if (webrtc::field_trial::FindFullName("WebRTC-NewVideoAPI") == "Enabled") {
- delete static_cast<cricket::WebRtcMediaEngine2*>(media_engine);
- } else {
-#endif // WEBRTC_CHROMIUM_BUILD
- delete static_cast<cricket::WebRtcMediaEngine*>(media_engine);
-#ifdef WEBRTC_CHROMIUM_BUILD
- }
-#endif // WEBRTC_CHROMIUM_BUILD
+ delete media_engine;
}
+
+namespace cricket {
+
+// Used by ChannelManager when no media engine is passed in to it
+// explicitly (acts as a default).
+MediaEngineInterface* WebRtcMediaEngineFactory::Create() {
+ return new cricket::WebRtcMediaEngine();
+}
+
+// Used by PeerConnectionFactory to create a media engine passed into
+// ChannelManager.
+MediaEngineInterface* WebRtcMediaEngineFactory::Create(
+ webrtc::AudioDeviceModule* adm,
+ webrtc::AudioDeviceModule* adm_sc,
+ WebRtcVideoEncoderFactory* encoder_factory,
+ WebRtcVideoDecoderFactory* decoder_factory) {
+ return CreateWebRtcMediaEngine(adm, adm_sc, encoder_factory, decoder_factory);
+}
+
+} // namespace cricket
+
+#endif // defined(LIBPEERCONNECTION_LIB) ||
+ // defined(LIBPEERCONNECTION_IMPLEMENTATION)
diff --git a/media/webrtc/webrtcmediaengine.h b/media/webrtc/webrtcmediaengine.h
index 6ca39e7..df517ee 100644
--- a/media/webrtc/webrtcmediaengine.h
+++ b/media/webrtc/webrtcmediaengine.h
@@ -40,7 +40,6 @@
class WebRtcVideoEncoderFactory;
}
-
#if !defined(LIBPEERCONNECTION_LIB) && \
!defined(LIBPEERCONNECTION_IMPLEMENTATION)
@@ -53,22 +52,52 @@
WRME_EXPORT
void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine);
+#endif // !defined(LIBPEERCONNECTION_LIB) &&
+ // !defined(LIBPEERCONNECTION_IMPLEMENTATION)
+
namespace cricket {
-class WebRtcMediaEngine : public cricket::MediaEngineInterface {
+class WebRtcMediaEngineFactory {
public:
- WebRtcMediaEngine(
+#if !defined(LIBPEERCONNECTION_LIB) && \
+ !defined(LIBPEERCONNECTION_IMPLEMENTATION)
+// A bare Create() isn't supported when using the delegating media
+// engine.
+#else
+ static MediaEngineInterface* Create();
+#endif // !defined(LIBPEERCONNECTION_LIB) &&
+ // !defined(LIBPEERCONNECTION_IMPLEMENTATION)
+ static MediaEngineInterface* Create(
webrtc::AudioDeviceModule* adm,
webrtc::AudioDeviceModule* adm_sc,
- cricket::WebRtcVideoEncoderFactory* encoder_factory,
- cricket::WebRtcVideoDecoderFactory* decoder_factory)
+ WebRtcVideoEncoderFactory* encoder_factory,
+ WebRtcVideoDecoderFactory* decoder_factory);
+};
+
+} // namespace cricket
+
+
+#if !defined(LIBPEERCONNECTION_LIB) && \
+ !defined(LIBPEERCONNECTION_IMPLEMENTATION)
+
+namespace cricket {
+
+// TODO(pthacther): Move this code into webrtcmediaengine.cc once
+// Chrome compiles it. Right now it relies on only the .h file.
+class DelegatingWebRtcMediaEngine : public cricket::MediaEngineInterface {
+ public:
+ DelegatingWebRtcMediaEngine(
+ webrtc::AudioDeviceModule* adm,
+ webrtc::AudioDeviceModule* adm_sc,
+ WebRtcVideoEncoderFactory* encoder_factory,
+ WebRtcVideoDecoderFactory* decoder_factory)
: delegate_(CreateWebRtcMediaEngine(
adm, adm_sc, encoder_factory, decoder_factory)) {
}
- virtual ~WebRtcMediaEngine() {
+ virtual ~DelegatingWebRtcMediaEngine() {
DestroyWebRtcMediaEngine(delegate_);
}
- virtual bool Init(talk_base::Thread* worker_thread) OVERRIDE {
+ virtual bool Init(rtc::Thread* worker_thread) OVERRIDE {
return delegate_->Init(worker_thread);
}
virtual void Terminate() OVERRIDE {
@@ -93,9 +122,6 @@
virtual bool SetAudioOptions(const AudioOptions& options) OVERRIDE {
return delegate_->SetAudioOptions(options);
}
- virtual bool SetVideoOptions(const VideoOptions& options) OVERRIDE {
- return delegate_->SetVideoOptions(options);
- }
virtual bool SetAudioDelayOffset(int offset) OVERRIDE {
return delegate_->SetAudioDelayOffset(offset);
}
@@ -122,9 +148,6 @@
virtual bool SetLocalMonitor(bool enable) OVERRIDE {
return delegate_->SetLocalMonitor(enable);
}
- virtual bool SetLocalRenderer(VideoRenderer* renderer) OVERRIDE {
- return delegate_->SetLocalRenderer(renderer);
- }
virtual const std::vector<AudioCodec>& audio_codecs() OVERRIDE {
return delegate_->audio_codecs();
}
@@ -145,7 +168,7 @@
virtual void SetVideoLogging(int min_sev, const char* filter) OVERRIDE {
delegate_->SetVideoLogging(min_sev, filter);
}
- virtual bool StartAecDump(talk_base::PlatformFile file) OVERRIDE {
+ virtual bool StartAecDump(rtc::PlatformFile file) OVERRIDE {
return delegate_->StartAecDump(file);
}
virtual bool RegisterVoiceProcessor(
@@ -171,49 +194,16 @@
cricket::MediaEngineInterface* delegate_;
};
-} // namespace cricket
-#else
-
-#include "talk/media/webrtc/webrtcvideoengine.h"
-#ifdef WEBRTC_CHROMIUM_BUILD
-#include "talk/media/webrtc/webrtcvideoengine2.h"
-#endif
-#include "talk/media/webrtc/webrtcvoiceengine.h"
-
-namespace cricket {
-typedef CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine>
- WebRtcCompositeMediaEngine;
-
-class WebRtcMediaEngine : public WebRtcCompositeMediaEngine {
- public:
- WebRtcMediaEngine(webrtc::AudioDeviceModule* adm,
- webrtc::AudioDeviceModule* adm_sc,
- WebRtcVideoEncoderFactory* encoder_factory,
- WebRtcVideoDecoderFactory* decoder_factory) {
- voice_.SetAudioDeviceModule(adm, adm_sc);
- video_.SetVoiceEngine(&voice_);
- video_.EnableTimedRender();
- video_.SetExternalEncoderFactory(encoder_factory);
- video_.SetExternalDecoderFactory(decoder_factory);
- }
-};
-
-#ifdef WEBRTC_CHROMIUM_BUILD
-typedef CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine2>
- WebRtcCompositeMediaEngine2;
-
-class WebRtcMediaEngine2 : public WebRtcCompositeMediaEngine2 {
- public:
- WebRtcMediaEngine2(webrtc::AudioDeviceModule* adm,
- webrtc::AudioDeviceModule* adm_sc,
- WebRtcVideoEncoderFactory* encoder_factory,
- WebRtcVideoDecoderFactory* decoder_factory) {
- voice_.SetAudioDeviceModule(adm, adm_sc);
- video_.SetVoiceEngine(&voice_);
- video_.EnableTimedRender();
- }
-};
-#endif
+// Used by PeerConnectionFactory to create a media engine passed into
+// ChannelManager.
+MediaEngineInterface* WebRtcMediaEngineFactory::Create(
+ webrtc::AudioDeviceModule* adm,
+ webrtc::AudioDeviceModule* adm_sc,
+ WebRtcVideoEncoderFactory* encoder_factory,
+ WebRtcVideoDecoderFactory* decoder_factory) {
+ return new cricket::DelegatingWebRtcMediaEngine(
+ adm, adm_sc, encoder_factory, decoder_factory);
+}
} // namespace cricket
diff --git a/media/webrtc/webrtcpassthroughrender.cc b/media/webrtc/webrtcpassthroughrender.cc
index b4e78b4..0c6029d 100644
--- a/media/webrtc/webrtcpassthroughrender.cc
+++ b/media/webrtc/webrtcpassthroughrender.cc
@@ -27,8 +27,8 @@
#include "talk/media/webrtc/webrtcpassthroughrender.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -45,7 +45,7 @@
}
virtual int32_t RenderFrame(const uint32_t stream_id,
webrtc::I420VideoFrame& videoFrame) {
- talk_base::CritScope cs(&stream_critical_);
+ rtc::CritScope cs(&stream_critical_);
// Send frame for rendering directly
if (running_ && renderer_) {
renderer_->RenderFrame(stream_id, videoFrame);
@@ -53,19 +53,19 @@
return 0;
}
int32_t SetRenderer(VideoRenderCallback* renderer) {
- talk_base::CritScope cs(&stream_critical_);
+ rtc::CritScope cs(&stream_critical_);
renderer_ = renderer;
return 0;
}
int32_t StartRender() {
- talk_base::CritScope cs(&stream_critical_);
+ rtc::CritScope cs(&stream_critical_);
running_ = true;
return 0;
}
int32_t StopRender() {
- talk_base::CritScope cs(&stream_critical_);
+ rtc::CritScope cs(&stream_critical_);
running_ = false;
return 0;
}
@@ -73,7 +73,7 @@
private:
uint32_t stream_id_;
VideoRenderCallback* renderer_;
- talk_base::CriticalSection stream_critical_;
+ rtc::CriticalSection stream_critical_;
bool running_;
};
@@ -94,7 +94,7 @@
const uint32_t zOrder,
const float left, const float top,
const float right, const float bottom) {
- talk_base::CritScope cs(&render_critical_);
+ rtc::CritScope cs(&render_critical_);
// Stream already exist.
if (FindStream(stream_id) != NULL) {
LOG(LS_ERROR) << "AddIncomingRenderStream - Stream already exists: "
@@ -110,7 +110,7 @@
int32_t WebRtcPassthroughRender::DeleteIncomingRenderStream(
const uint32_t stream_id) {
- talk_base::CritScope cs(&render_critical_);
+ rtc::CritScope cs(&render_critical_);
PassthroughStream* stream = FindStream(stream_id);
if (stream == NULL) {
LOG_FIND_STREAM_ERROR("DeleteIncomingRenderStream", stream_id);
@@ -124,7 +124,7 @@
int32_t WebRtcPassthroughRender::AddExternalRenderCallback(
const uint32_t stream_id,
webrtc::VideoRenderCallback* render_object) {
- talk_base::CritScope cs(&render_critical_);
+ rtc::CritScope cs(&render_critical_);
PassthroughStream* stream = FindStream(stream_id);
if (stream == NULL) {
LOG_FIND_STREAM_ERROR("AddExternalRenderCallback", stream_id);
@@ -143,7 +143,7 @@
}
int32_t WebRtcPassthroughRender::StartRender(const uint32_t stream_id) {
- talk_base::CritScope cs(&render_critical_);
+ rtc::CritScope cs(&render_critical_);
PassthroughStream* stream = FindStream(stream_id);
if (stream == NULL) {
LOG_FIND_STREAM_ERROR("StartRender", stream_id);
@@ -153,7 +153,7 @@
}
int32_t WebRtcPassthroughRender::StopRender(const uint32_t stream_id) {
- talk_base::CritScope cs(&render_critical_);
+ rtc::CritScope cs(&render_critical_);
PassthroughStream* stream = FindStream(stream_id);
if (stream == NULL) {
LOG_FIND_STREAM_ERROR("StopRender", stream_id);
diff --git a/media/webrtc/webrtcpassthroughrender.h b/media/webrtc/webrtcpassthroughrender.h
index e09182f..8d8c488 100644
--- a/media/webrtc/webrtcpassthroughrender.h
+++ b/media/webrtc/webrtcpassthroughrender.h
@@ -30,7 +30,7 @@
#include <map>
-#include "talk/base/criticalsection.h"
+#include "webrtc/base/criticalsection.h"
#include "webrtc/modules/video_render/include/video_render.h"
namespace cricket {
@@ -41,27 +41,21 @@
WebRtcPassthroughRender();
virtual ~WebRtcPassthroughRender();
- virtual int32_t Version(int8_t* version,
- uint32_t& remainingBufferInBytes,
- uint32_t& position) const {
+ virtual int32_t ChangeUniqueId(const int32_t id) OVERRIDE {
return 0;
}
- virtual int32_t ChangeUniqueId(const int32_t id) {
- return 0;
- }
+ virtual int32_t TimeUntilNextProcess() OVERRIDE { return 0; }
- virtual int32_t TimeUntilNextProcess() { return 0; }
+ virtual int32_t Process() OVERRIDE { return 0; }
- virtual int32_t Process() { return 0; }
-
- virtual void* Window() {
- talk_base::CritScope cs(&render_critical_);
+ virtual void* Window() OVERRIDE {
+ rtc::CritScope cs(&render_critical_);
return window_;
}
- virtual int32_t ChangeWindow(void* window) {
- talk_base::CritScope cs(&render_critical_);
+ virtual int32_t ChangeWindow(void* window) OVERRIDE {
+ rtc::CritScope cs(&render_critical_);
window_ = window;
return 0;
}
@@ -70,64 +64,60 @@
const uint32_t stream_id,
const uint32_t zOrder,
const float left, const float top,
- const float right, const float bottom);
+ const float right, const float bottom) OVERRIDE;
- virtual int32_t DeleteIncomingRenderStream(const uint32_t stream_id);
+ virtual int32_t DeleteIncomingRenderStream(const uint32_t stream_id) OVERRIDE;
virtual int32_t AddExternalRenderCallback(
const uint32_t stream_id,
- webrtc::VideoRenderCallback* render_object);
+ webrtc::VideoRenderCallback* render_object) OVERRIDE;
virtual int32_t GetIncomingRenderStreamProperties(
const uint32_t stream_id,
uint32_t& zOrder,
float& left, float& top,
- float& right, float& bottom) const {
+ float& right, float& bottom) const OVERRIDE {
return -1;
}
- virtual uint32_t GetIncomingFrameRate(
- const uint32_t stream_id) {
+ virtual uint32_t GetIncomingFrameRate(const uint32_t stream_id) OVERRIDE {
return 0;
}
- virtual uint32_t GetNumIncomingRenderStreams() const {
+ virtual uint32_t GetNumIncomingRenderStreams() const OVERRIDE {
return static_cast<uint32_t>(stream_render_map_.size());
}
- virtual bool HasIncomingRenderStream(const uint32_t stream_id) const;
+ virtual bool HasIncomingRenderStream(const uint32_t stream_id) const OVERRIDE;
virtual int32_t RegisterRawFrameCallback(
const uint32_t stream_id,
- webrtc::VideoRenderCallback* callback_obj) {
+ webrtc::VideoRenderCallback* callback_obj) OVERRIDE {
return -1;
}
virtual int32_t GetLastRenderedFrame(
const uint32_t stream_id,
- webrtc::I420VideoFrame &frame) const {
+ webrtc::I420VideoFrame &frame) const OVERRIDE {
return -1;
}
- virtual int32_t StartRender(
- const uint32_t stream_id);
+ virtual int32_t StartRender(const uint32_t stream_id) OVERRIDE;
- virtual int32_t StopRender(
- const uint32_t stream_id);
+ virtual int32_t StopRender(const uint32_t stream_id) OVERRIDE;
- virtual int32_t ResetRender() { return 0; }
+ virtual int32_t ResetRender() OVERRIDE { return 0; }
- virtual webrtc::RawVideoType PreferredVideoType() const;
+ virtual webrtc::RawVideoType PreferredVideoType() const OVERRIDE;
- virtual bool IsFullScreen() { return false; }
+ virtual bool IsFullScreen() OVERRIDE { return false; }
virtual int32_t GetScreenResolution(uint32_t& screenWidth,
- uint32_t& screenHeight) const {
+ uint32_t& screenHeight) const OVERRIDE {
return -1;
}
- virtual uint32_t RenderFrameRate(
- const uint32_t stream_id) {
+ virtual uint32_t RenderFrameRate(const uint32_t stream_id) OVERRIDE {
return 0;
}
@@ -135,11 +125,12 @@
const uint32_t stream_id,
const float left, const float top,
const float right,
- const float bottom) {
+ const float bottom) OVERRIDE {
return -1;
}
- virtual int32_t SetExpectedRenderDelay(uint32_t stream_id, int32_t delay_ms) {
+ virtual int32_t SetExpectedRenderDelay(uint32_t stream_id,
+ int32_t delay_ms) OVERRIDE {
return -1;
}
@@ -148,22 +139,22 @@
const unsigned int zOrder,
const float left, const float top,
const float right,
- const float bottom) {
+ const float bottom) OVERRIDE {
return -1;
}
- virtual int32_t SetTransparentBackground(const bool enable) {
+ virtual int32_t SetTransparentBackground(const bool enable) OVERRIDE {
return -1;
}
- virtual int32_t FullScreenRender(void* window, const bool enable) {
+ virtual int32_t FullScreenRender(void* window, const bool enable) OVERRIDE {
return -1;
}
virtual int32_t SetBitmap(const void* bitMap,
const uint8_t pictureId, const void* colorKey,
const float left, const float top,
- const float right, const float bottom) {
+ const float right, const float bottom) OVERRIDE {
return -1;
}
@@ -173,27 +164,27 @@
const uint32_t textColorRef,
const uint32_t backgroundColorRef,
const float left, const float top,
- const float right, const float bottom) {
+ const float right, const float bottom) OVERRIDE {
return -1;
}
virtual int32_t SetStartImage(
const uint32_t stream_id,
- const webrtc::I420VideoFrame& videoFrame) {
+ const webrtc::I420VideoFrame& videoFrame) OVERRIDE {
return -1;
}
virtual int32_t SetTimeoutImage(
const uint32_t stream_id,
const webrtc::I420VideoFrame& videoFrame,
- const uint32_t timeout) {
+ const uint32_t timeout) OVERRIDE {
return -1;
}
virtual int32_t MirrorRenderStream(const int renderId,
const bool enable,
const bool mirrorXAxis,
- const bool mirrorYAxis) {
+ const bool mirrorYAxis) OVERRIDE {
return -1;
}
@@ -204,7 +195,7 @@
void* window_;
StreamMap stream_render_map_;
- talk_base::CriticalSection render_critical_;
+ rtc::CriticalSection render_critical_;
};
} // namespace cricket
diff --git a/media/webrtc/webrtcpassthroughrender_unittest.cc b/media/webrtc/webrtcpassthroughrender_unittest.cc
index 4eb2892..ce45c04 100644
--- a/media/webrtc/webrtcpassthroughrender_unittest.cc
+++ b/media/webrtc/webrtcpassthroughrender_unittest.cc
@@ -4,9 +4,9 @@
#include <string>
-#include "talk/base/gunit.h"
#include "talk/media/base/testutils.h"
#include "talk/media/webrtc/webrtcpassthroughrender.h"
+#include "webrtc/base/gunit.h"
class WebRtcPassthroughRenderTest : public testing::Test {
public:
@@ -67,7 +67,7 @@
}
private:
- talk_base::scoped_ptr<cricket::WebRtcPassthroughRender> renderer_;
+ rtc::scoped_ptr<cricket::WebRtcPassthroughRender> renderer_;
};
TEST_F(WebRtcPassthroughRenderTest, Streams) {
diff --git a/media/webrtc/webrtctexturevideoframe.cc b/media/webrtc/webrtctexturevideoframe.cc
index 08f63a5..ba7cf5e 100644
--- a/media/webrtc/webrtctexturevideoframe.cc
+++ b/media/webrtc/webrtctexturevideoframe.cc
@@ -27,9 +27,9 @@
#include "talk/media/webrtc/webrtctexturevideoframe.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/stream.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stream.h"
#define UNIMPLEMENTED \
LOG(LS_ERROR) << "Call to unimplemented function "<< __FUNCTION__; \
@@ -137,10 +137,10 @@
UNIMPLEMENTED;
}
-talk_base::StreamResult WebRtcTextureVideoFrame::Write(
- talk_base::StreamInterface* stream, int* error) {
+rtc::StreamResult WebRtcTextureVideoFrame::Write(
+ rtc::StreamInterface* stream, int* error) {
UNIMPLEMENTED;
- return talk_base::SR_ERROR;
+ return rtc::SR_ERROR;
}
void WebRtcTextureVideoFrame::StretchToPlanes(
uint8* dst_y, uint8* dst_u, uint8* dst_v, int32 dst_pitch_y,
diff --git a/media/webrtc/webrtctexturevideoframe.h b/media/webrtc/webrtctexturevideoframe.h
index 691c814..cd4d47b 100644
--- a/media/webrtc/webrtctexturevideoframe.h
+++ b/media/webrtc/webrtctexturevideoframe.h
@@ -28,9 +28,9 @@
#ifndef TALK_MEDIA_WEBRTC_WEBRTCTEXTUREVIDEOFRAME_H_
#define TALK_MEDIA_WEBRTC_WEBRTCTEXTUREVIDEOFRAME_H_
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ref_ptr.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/refcount.h"
+#include "webrtc/base/scoped_ref_ptr.h"
#include "webrtc/common_video/interface/native_handle.h"
namespace cricket {
@@ -81,7 +81,7 @@
uint8* dst_y, uint8* dst_u, uint8* dst_v,
int32 dst_pitch_y, int32 dst_pitch_u, int32 dst_pitch_v) const;
virtual void CopyToFrame(VideoFrame* target) const;
- virtual talk_base::StreamResult Write(talk_base::StreamInterface* stream,
+ virtual rtc::StreamResult Write(rtc::StreamInterface* stream,
int* error);
virtual void StretchToPlanes(
uint8* y, uint8* u, uint8* v, int32 pitchY, int32 pitchU, int32 pitchV,
@@ -101,7 +101,7 @@
private:
// The handle of the underlying video frame.
- talk_base::scoped_refptr<webrtc::NativeHandle> handle_;
+ rtc::scoped_refptr<webrtc::NativeHandle> handle_;
int width_;
int height_;
int64 elapsed_time_;
diff --git a/media/webrtc/webrtctexturevideoframe_unittest.cc b/media/webrtc/webrtctexturevideoframe_unittest.cc
index 9ac16da..2aa4818 100644
--- a/media/webrtc/webrtctexturevideoframe_unittest.cc
+++ b/media/webrtc/webrtctexturevideoframe_unittest.cc
@@ -27,8 +27,8 @@
#include "talk/media/webrtc/webrtctexturevideoframe.h"
-#include "talk/base/gunit.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/gunit.h"
class NativeHandleImpl : public webrtc::NativeHandle {
public:
diff --git a/media/webrtc/webrtcvideocapturer.cc b/media/webrtc/webrtcvideocapturer.cc
index d7fc1b2..ea8b61a 100644
--- a/media/webrtc/webrtcvideocapturer.cc
+++ b/media/webrtc/webrtcvideocapturer.cc
@@ -32,13 +32,14 @@
#endif
#ifdef HAVE_WEBRTC_VIDEO
-#include "talk/base/criticalsection.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
+#include "talk/media/webrtc/webrtcvideoframefactory.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timeutils.h"
-#include "talk/base/win32.h" // Need this to #include the impl files.
+#include "webrtc/base/win32.h" // Need this to #include the impl files.
#include "webrtc/modules/video_capture/include/video_capture_factory.h"
namespace cricket {
@@ -53,10 +54,10 @@
static kVideoFourCCEntry kSupportedFourCCs[] = {
{ FOURCC_I420, webrtc::kVideoI420 }, // 12 bpp, no conversion.
{ FOURCC_YV12, webrtc::kVideoYV12 }, // 12 bpp, no conversion.
- { FOURCC_NV12, webrtc::kVideoNV12 }, // 12 bpp, fast conversion.
- { FOURCC_NV21, webrtc::kVideoNV21 }, // 12 bpp, fast conversion.
{ FOURCC_YUY2, webrtc::kVideoYUY2 }, // 16 bpp, fast conversion.
{ FOURCC_UYVY, webrtc::kVideoUYVY }, // 16 bpp, fast conversion.
+ { FOURCC_NV12, webrtc::kVideoNV12 }, // 12 bpp, fast conversion.
+ { FOURCC_NV21, webrtc::kVideoNV21 }, // 12 bpp, fast conversion.
{ FOURCC_MJPG, webrtc::kVideoMJPEG }, // compressed, slow conversion.
{ FOURCC_ARGB, webrtc::kVideoARGB }, // 32 bpp, slow conversion.
{ FOURCC_24BG, webrtc::kVideoRGB24 }, // 24 bpp, slow conversion.
@@ -126,12 +127,14 @@
: factory_(new WebRtcVcmFactory),
module_(NULL),
captured_frames_(0) {
+ set_frame_factory(new WebRtcVideoFrameFactory());
}
WebRtcVideoCapturer::WebRtcVideoCapturer(WebRtcVcmFactoryInterface* factory)
: factory_(factory),
module_(NULL),
captured_frames_(0) {
+ set_frame_factory(new WebRtcVideoFrameFactory());
}
WebRtcVideoCapturer::~WebRtcVideoCapturer() {
@@ -252,7 +255,7 @@
return CS_NO_DEVICE;
}
- talk_base::CritScope cs(&critical_section_stopping_);
+ rtc::CritScope cs(&critical_section_stopping_);
// TODO(hellner): weird to return failure when it is in fact actually running.
if (IsRunning()) {
LOG(LS_ERROR) << "The capturer is already running";
@@ -268,7 +271,7 @@
}
std::string camera_id(GetId());
- uint32 start = talk_base::Time();
+ uint32 start = rtc::Time();
module_->RegisterCaptureDataCallback(*this);
if (module_->StartCapture(cap) != 0) {
LOG(LS_ERROR) << "Camera '" << camera_id << "' failed to start";
@@ -277,7 +280,7 @@
LOG(LS_INFO) << "Camera '" << camera_id << "' started with format "
<< capture_format.ToString() << ", elapsed time "
- << talk_base::TimeSince(start) << " ms";
+ << rtc::TimeSince(start) << " ms";
captured_frames_ = 0;
SetCaptureState(CS_RUNNING);
@@ -290,9 +293,9 @@
// controlling the camera is reversed: system frame -> OnIncomingCapturedFrame;
// Stop -> system stop camera).
void WebRtcVideoCapturer::Stop() {
- talk_base::CritScope cs(&critical_section_stopping_);
+ rtc::CritScope cs(&critical_section_stopping_);
if (IsRunning()) {
- talk_base::Thread::Current()->Clear(this);
+ rtc::Thread::Current()->Clear(this);
module_->StopCapture();
module_->DeRegisterCaptureDataCallback();
@@ -331,7 +334,7 @@
// the same lock. Due to the reversed order, we have to try-lock in order to
// avoid a potential deadlock. Besides, if we can't enter because we're
// stopping, we may as well drop the frame.
- talk_base::TryCritScope cs(&critical_section_stopping_);
+ rtc::TryCritScope cs(&critical_section_stopping_);
if (!cs.locked() || !IsRunning()) {
// Capturer has been stopped or is in the process of stopping.
return;
@@ -373,7 +376,7 @@
pixel_width = 1;
pixel_height = 1;
// Convert units from VideoFrame RenderTimeMs to CapturedFrame (nanoseconds).
- elapsed_time = sample.render_time_ms() * talk_base::kNumNanosecsPerMillisec;
+ elapsed_time = sample.render_time_ms() * rtc::kNumNanosecsPerMillisec;
time_stamp = elapsed_time;
data_size = length;
data = buffer;
diff --git a/media/webrtc/webrtcvideocapturer.h b/media/webrtc/webrtcvideocapturer.h
index cefad56..39a71f8 100644
--- a/media/webrtc/webrtcvideocapturer.h
+++ b/media/webrtc/webrtcvideocapturer.h
@@ -31,10 +31,10 @@
#include <string>
#include <vector>
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagehandler.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/messagehandler.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/modules/video_capture/include/video_capture.h"
@@ -86,13 +86,13 @@
virtual void OnCaptureDelayChanged(const int32_t id,
const int32_t delay);
- talk_base::scoped_ptr<WebRtcVcmFactoryInterface> factory_;
+ rtc::scoped_ptr<WebRtcVcmFactoryInterface> factory_;
webrtc::VideoCaptureModule* module_;
int captured_frames_;
std::vector<uint8_t> capture_buffer_;
// Critical section to avoid Stop during an OnIncomingCapturedFrame callback.
- talk_base::CriticalSection critical_section_stopping_;
+ rtc::CriticalSection critical_section_stopping_;
};
struct WebRtcCapturedFrame : public CapturedFrame {
diff --git a/media/webrtc/webrtcvideocapturer_unittest.cc b/media/webrtc/webrtcvideocapturer_unittest.cc
index 226aa4b..a99b70b 100644
--- a/media/webrtc/webrtcvideocapturer_unittest.cc
+++ b/media/webrtc/webrtcvideocapturer_unittest.cc
@@ -25,14 +25,14 @@
#include <stdio.h>
#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
#include "talk/media/base/testutils.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/webrtc/fakewebrtcvcmfactory.h"
#include "talk/media/webrtc/webrtcvideocapturer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
using cricket::VideoFormat;
@@ -59,7 +59,7 @@
protected:
FakeWebRtcVcmFactory* factory_; // owned by capturer_
- talk_base::scoped_ptr<cricket::WebRtcVideoCapturer> capturer_;
+ rtc::scoped_ptr<cricket::WebRtcVideoCapturer> capturer_;
cricket::VideoCapturerListener listener_;
};
diff --git a/media/webrtc/webrtcvideocapturerfactory.cc b/media/webrtc/webrtcvideocapturerfactory.cc
new file mode 100755
index 0000000..9f542bd
--- /dev/null
+++ b/media/webrtc/webrtcvideocapturerfactory.cc
@@ -0,0 +1,43 @@
+/*
+ * libjingle
+ * Copyright 2014 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "talk/media/webrtc/webrtcvideocapturer.h"
+#include "talk/media/webrtc/webrtcvideocapturerfactory.h"
+#include "webrtc/base/scoped_ptr.h"
+
+namespace cricket {
+
+VideoCapturer* WebRtcVideoDeviceCapturerFactory::Create(const Device& device) {
+ rtc::scoped_ptr<WebRtcVideoCapturer> capturer(
+ new WebRtcVideoCapturer());
+ if (!capturer->Init(device)) {
+ return NULL;
+ }
+ return capturer.release();
+}
+
+} // namespace cricket
diff --git a/media/webrtc/webrtcvideocapturerfactory.h b/media/webrtc/webrtcvideocapturerfactory.h
new file mode 100755
index 0000000..091b072
--- /dev/null
+++ b/media/webrtc/webrtcvideocapturerfactory.h
@@ -0,0 +1,43 @@
+// libjingle
+// Copyright 2014 Google Inc.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+
+// TODO(pthatcher): Reneme file to match class name.
+#ifndef TALK_MEDIA_WEBRTC_WEBRTCVIDEOCAPTURERFACTORY_H_
+#define TALK_MEDIA_WEBRTC_WEBRTCVIDEOCAPTURERFACTORY_H_
+
+#include "talk/media/base/videocapturerfactory.h"
+
+namespace cricket {
+
+// Creates instances of cricket::WebRtcVideoCapturer.
+class WebRtcVideoDeviceCapturerFactory : public VideoDeviceCapturerFactory {
+ public:
+ virtual VideoCapturer* Create(const Device& device);
+};
+
+} // namespace cricket
+
+#endif // TALK_MEDIA_WEBRTC_WEBRTCVIDEOCAPTURERFACTORY_H_
diff --git a/media/webrtc/webrtcvideodecoderfactory.h b/media/webrtc/webrtcvideodecoderfactory.h
index 483bca7..ce26f0e 100644
--- a/media/webrtc/webrtcvideodecoderfactory.h
+++ b/media/webrtc/webrtcvideodecoderfactory.h
@@ -28,7 +28,7 @@
#ifndef TALK_MEDIA_WEBRTC_WEBRTCVIDEODECODERFACTORY_H_
#define TALK_MEDIA_WEBRTC_WEBRTCVIDEODECODERFACTORY_H_
-#include "talk/base/refcount.h"
+#include "webrtc/base/refcount.h"
#include "webrtc/common_types.h"
namespace webrtc {
diff --git a/media/webrtc/webrtcvideoencoderfactory.h b/media/webrtc/webrtcvideoencoderfactory.h
index a844309..3f9294d 100644
--- a/media/webrtc/webrtcvideoencoderfactory.h
+++ b/media/webrtc/webrtcvideoencoderfactory.h
@@ -28,8 +28,8 @@
#ifndef TALK_MEDIA_WEBRTC_WEBRTCVIDEOENCODERFACTORY_H_
#define TALK_MEDIA_WEBRTC_WEBRTCVIDEOENCODERFACTORY_H_
-#include "talk/base/refcount.h"
#include "talk/media/base/codec.h"
+#include "webrtc/base/refcount.h"
#include "webrtc/common_types.h"
namespace webrtc {
diff --git a/media/webrtc/webrtcvideoengine.cc b/media/webrtc/webrtcvideoengine.cc
index fd609e9..b2533b3 100644
--- a/media/webrtc/webrtcvideoengine.cc
+++ b/media/webrtc/webrtcvideoengine.cc
@@ -35,15 +35,6 @@
#include <math.h>
#include <set>
-#include "talk/base/basictypes.h"
-#include "talk/base/buffer.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/cpumonitor.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/base/streamparams.h"
@@ -51,6 +42,7 @@
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videorenderer.h"
#include "talk/media/devices/filevideocapturer.h"
+#include "talk/media/webrtc/constants.h"
#include "talk/media/webrtc/webrtcpassthroughrender.h"
#include "talk/media/webrtc/webrtctexturevideoframe.h"
#include "talk/media/webrtc/webrtcvideocapturer.h"
@@ -60,34 +52,65 @@
#include "talk/media/webrtc/webrtcvie.h"
#include "talk/media/webrtc/webrtcvoe.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/cpumonitor.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timeutils.h"
#include "webrtc/experiments.h"
#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
+namespace {
+
+template <class T>
+bool Changed(cricket::Settable<T> proposed,
+ cricket::Settable<T> original) {
+ return proposed.IsSet() && proposed != original;
+}
+
+template <class T>
+bool Changed(cricket::Settable<T> proposed,
+ cricket::Settable<T> original,
+ T* value) {
+ return proposed.Get(value) && proposed != original;
+}
+
+} // namespace
namespace cricket {
+// Constants defined in talk/media/webrtc/constants.h
+// TODO(pbos): Move these to a separate constants.cc file.
+const int kVideoMtu = 1200;
+const int kVideoRtpBufferSize = 65536;
-static const int kDefaultLogSeverity = talk_base::LS_WARNING;
+const char kVp8CodecName[] = "VP8";
-static const int kMinVideoBitrate = 50;
-static const int kStartVideoBitrate = 300;
-static const int kMaxVideoBitrate = 2000;
+const int kDefaultFramerate = 30;
+const int kMinVideoBitrate = 30;
+const int kStartVideoBitrate = 300;
+const int kMaxVideoBitrate = 2000;
-// Controlled by exp, try a super low minimum bitrate for poor connections.
-static const int kLowerMinBitrate = 30;
+const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
-static const int kVideoMtu = 1200;
+// TODO(pthatcher): Figure out what the proper value here is, or if we
+// can just remove this altogether.
+static const int kDefaultRenderDelayMs = 100;
-static const int kVideoRtpBufferSize = 65536;
-
-static const char kVp8PayloadName[] = "VP8";
-static const char kRedPayloadName[] = "red";
-static const char kFecPayloadName[] = "ulpfec";
+static const int kDefaultLogSeverity = rtc::LS_WARNING;
static const int kDefaultNumberOfTemporalLayers = 1; // 1:1
static const int kExternalVideoPayloadTypeBase = 120;
+static const int kChannelIdUnset = -1;
+static const uint32 kDefaultChannelSsrcKey = 0;
+static const uint32 kSsrcUnset = 0;
+
static bool BitrateIsSet(int value) {
return value > kAutoBandwidth;
}
@@ -105,7 +128,7 @@
return kExternalVideoPayloadTypeBase + index;
}
-static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
+static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
const char* delim = "\r\n";
// TODO(fbarchard): Fix strtok lint warning.
for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
@@ -117,27 +140,25 @@
static int SeverityToFilter(int severity) {
int filter = webrtc::kTraceNone;
switch (severity) {
- case talk_base::LS_VERBOSE:
+ case rtc::LS_VERBOSE:
filter |= webrtc::kTraceAll;
- case talk_base::LS_INFO:
+ case rtc::LS_INFO:
filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
- case talk_base::LS_WARNING:
+ case rtc::LS_WARNING:
filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
- case talk_base::LS_ERROR:
+ case rtc::LS_ERROR:
filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
}
return filter;
}
-static const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
-
static const bool kNotSending = false;
// Default video dscp value.
// See http://tools.ietf.org/html/rfc2474 for details
// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
-static const talk_base::DiffServCodePoint kVideoDscpValue =
- talk_base::DSCP_AF41;
+static const rtc::DiffServCodePoint kVideoDscpValue =
+ rtc::DSCP_AF41;
static bool IsNackEnabled(const VideoCodec& codec) {
return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
@@ -150,7 +171,7 @@
kParamValueEmpty));
}
-struct FlushBlackFrameData : public talk_base::MessageData {
+struct FlushBlackFrameData : public rtc::MessageData {
FlushBlackFrameData(uint32 s, int64 t) : ssrc(s), timestamp(t) {
}
uint32 ssrc;
@@ -172,14 +193,14 @@
}
void SetRenderer(VideoRenderer* renderer) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
renderer_ = renderer;
// FrameSizeChange may have already been called when renderer was not set.
// If so we should call SetSize here.
// TODO(ronghuawu): Add unit test for this case. Didn't do it now
// because the WebRtcRenderAdapter is currently hiding in cc file. No
// good way to get access to it from the unit test.
- if (width_ > 0 && height_ > 0 && renderer_ != NULL) {
+ if (width_ > 0 && height_ > 0 && renderer_) {
if (!renderer_->SetSize(width_, height_, 0)) {
LOG(LS_ERROR)
<< "WebRtcRenderAdapter (channel " << channel_id_
@@ -192,13 +213,13 @@
// Implementation of webrtc::ExternalRenderer.
virtual int FrameSizeChange(unsigned int width, unsigned int height,
unsigned int /*number_of_streams*/) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
width_ = width;
height_ = height;
LOG(LS_INFO) << "WebRtcRenderAdapter (channel " << channel_id_
<< ") frame size changed to: "
<< width << "x" << height;
- if (renderer_ == NULL) {
+ if (!renderer_) {
LOG(LS_VERBOSE) << "WebRtcRenderAdapter (channel " << channel_id_
<< ") the renderer has not been set. "
<< "SetSize will be called later in SetRenderer.";
@@ -210,12 +231,10 @@
virtual int DeliverFrame(unsigned char* buffer,
int buffer_size,
uint32_t rtp_time_stamp,
-#ifdef USE_WEBRTC_DEV_BRANCH
int64_t ntp_time_ms,
-#endif
int64_t render_time,
void* handle) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
if (capture_start_rtp_time_stamp_ < 0) {
capture_start_rtp_time_stamp_ = rtp_time_stamp;
}
@@ -225,25 +244,23 @@
int64 elapsed_time_ms =
(rtp_ts_wraparound_handler_.Unwrap(rtp_time_stamp) -
capture_start_rtp_time_stamp_) / kVideoCodecClockratekHz;
-#ifdef USE_WEBRTC_DEV_BRANCH
if (ntp_time_ms > 0) {
capture_start_ntp_time_ms_ = ntp_time_ms - elapsed_time_ms;
}
-#endif
frame_rate_tracker_.Update(1);
- if (renderer_ == NULL) {
+ if (!renderer_) {
return 0;
}
// Convert elapsed_time_ms to ns timestamp.
int64 elapsed_time_ns =
- elapsed_time_ms * talk_base::kNumNanosecsPerMillisec;
+ elapsed_time_ms * rtc::kNumNanosecsPerMillisec;
// Convert milisecond render time to ns timestamp.
int64 render_time_ns = render_time *
- talk_base::kNumNanosecsPerMillisec;
+ rtc::kNumNanosecsPerMillisec;
// Note that here we send the |elapsed_time_ns| to renderer as the
// cricket::VideoFrame's elapsed_time_ and the |render_time_ns| as the
// cricket::VideoFrame's time_stamp_.
- if (handle == NULL) {
+ if (!handle) {
return DeliverBufferFrame(buffer, buffer_size, render_time_ns,
elapsed_time_ns);
} else {
@@ -279,46 +296,46 @@
}
unsigned int width() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return width_;
}
unsigned int height() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return height_;
}
int framerate() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return static_cast<int>(frame_rate_tracker_.units_second());
}
VideoRenderer* renderer() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return renderer_;
}
int64 capture_start_ntp_time_ms() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return capture_start_ntp_time_ms_;
}
private:
- talk_base::CriticalSection crit_;
+ rtc::CriticalSection crit_;
VideoRenderer* renderer_;
int channel_id_;
unsigned int width_;
unsigned int height_;
- talk_base::RateTracker frame_rate_tracker_;
- talk_base::TimestampWrapAroundHandler rtp_ts_wraparound_handler_;
+ rtc::RateTracker frame_rate_tracker_;
+ rtc::TimestampWrapAroundHandler rtp_ts_wraparound_handler_;
int64 capture_start_rtp_time_stamp_;
int64 capture_start_ntp_time_ms_;
};
class WebRtcDecoderObserver : public webrtc::ViEDecoderObserver {
public:
- explicit WebRtcDecoderObserver(int video_channel)
- : video_channel_(video_channel),
+ explicit WebRtcDecoderObserver(int video_channel_id)
+ : video_channel_id_(video_channel_id),
framerate_(0),
bitrate_(0),
decode_ms_(0),
@@ -331,13 +348,13 @@
}
// virtual functions from VieDecoderObserver.
- virtual void IncomingCodecChanged(const int videoChannel,
+ virtual void IncomingCodecChanged(const int video_channel_id,
const webrtc::VideoCodec& videoCodec) {}
- virtual void IncomingRate(const int videoChannel,
+ virtual void IncomingRate(const int video_channel_id,
const unsigned int framerate,
const unsigned int bitrate) {
- talk_base::CritScope cs(&crit_);
- ASSERT(video_channel_ == videoChannel);
+ rtc::CritScope cs(&crit_);
+ ASSERT(video_channel_id_ == video_channel_id);
framerate_ = framerate;
bitrate_ = bitrate;
}
@@ -349,7 +366,7 @@
int jitter_buffer_ms,
int min_playout_delay_ms,
int render_delay_ms) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
decode_ms_ = decode_ms;
max_decode_ms_ = max_decode_ms;
current_delay_ms_ = current_delay_ms;
@@ -359,11 +376,11 @@
render_delay_ms_ = render_delay_ms;
}
- virtual void RequestNewKeyFrame(const int videoChannel) {}
+ virtual void RequestNewKeyFrame(const int video_channel_id) {}
// Populate |rinfo| based on previously-set data in |*this|.
void ExportTo(VideoReceiverInfo* rinfo) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
rinfo->framerate_rcvd = framerate_;
rinfo->decode_ms = decode_ms_;
rinfo->max_decode_ms = max_decode_ms_;
@@ -375,8 +392,8 @@
}
private:
- mutable talk_base::CriticalSection crit_;
- int video_channel_;
+ mutable rtc::CriticalSection crit_;
+ int video_channel_id_;
int framerate_;
int bitrate_;
int decode_ms_;
@@ -390,45 +407,45 @@
class WebRtcEncoderObserver : public webrtc::ViEEncoderObserver {
public:
- explicit WebRtcEncoderObserver(int video_channel)
- : video_channel_(video_channel),
+ explicit WebRtcEncoderObserver(int video_channel_id)
+ : video_channel_id_(video_channel_id),
framerate_(0),
bitrate_(0),
suspended_(false) {
}
// virtual functions from VieEncoderObserver.
- virtual void OutgoingRate(const int videoChannel,
+ virtual void OutgoingRate(const int video_channel_id,
const unsigned int framerate,
const unsigned int bitrate) {
- talk_base::CritScope cs(&crit_);
- ASSERT(video_channel_ == videoChannel);
+ rtc::CritScope cs(&crit_);
+ ASSERT(video_channel_id_ == video_channel_id);
framerate_ = framerate;
bitrate_ = bitrate;
}
- virtual void SuspendChange(int video_channel, bool is_suspended) {
- talk_base::CritScope cs(&crit_);
- ASSERT(video_channel_ == video_channel);
+ virtual void SuspendChange(int video_channel_id, bool is_suspended) {
+ rtc::CritScope cs(&crit_);
+ ASSERT(video_channel_id_ == video_channel_id);
suspended_ = is_suspended;
}
int framerate() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return framerate_;
}
int bitrate() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return bitrate_;
}
bool suspended() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return suspended_;
}
private:
- mutable talk_base::CriticalSection crit_;
- int video_channel_;
+ mutable rtc::CriticalSection crit_;
+ int video_channel_id_;
int framerate_;
int bitrate_;
bool suspended_;
@@ -439,35 +456,35 @@
WebRtcLocalStreamInfo()
: width_(0), height_(0), elapsed_time_(-1), time_stamp_(-1) {}
size_t width() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return width_;
}
size_t height() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return height_;
}
int64 elapsed_time() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return elapsed_time_;
}
int64 time_stamp() const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return time_stamp_;
}
int framerate() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return static_cast<int>(rate_tracker_.units_second());
}
void GetLastFrameInfo(
size_t* width, size_t* height, int64* elapsed_time) const {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
*width = width_;
*height = height_;
*elapsed_time = elapsed_time_;
}
void UpdateFrame(const VideoFrame* frame) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
width_ = frame->GetWidth();
height_ = frame->GetHeight();
@@ -478,12 +495,12 @@
}
private:
- mutable talk_base::CriticalSection crit_;
+ mutable rtc::CriticalSection crit_;
size_t width_;
size_t height_;
int64 elapsed_time_;
int64 time_stamp_;
- talk_base::RateTracker rate_tracker_;
+ rtc::RateTracker rate_tracker_;
DISALLOW_COPY_AND_ASSIGN(WebRtcLocalStreamInfo);
};
@@ -540,7 +557,7 @@
// adapter know what resolution the request is based on. Helps eliminate stale
// data, race conditions.
virtual void OveruseDetected() OVERRIDE {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
if (!enabled_) {
return;
}
@@ -549,7 +566,7 @@
}
virtual void NormalUsage() OVERRIDE {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
if (!enabled_) {
return;
}
@@ -559,7 +576,7 @@
void Enable(bool enable) {
LOG(LS_INFO) << "WebRtcOveruseObserver enable: " << enable;
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
enabled_ = enable;
}
@@ -568,7 +585,7 @@
private:
CoordinatedVideoAdapter* video_adapter_;
bool enabled_;
- talk_base::CriticalSection crit_;
+ rtc::CriticalSection crit_;
};
@@ -577,7 +594,7 @@
typedef std::map<int, webrtc::VideoEncoder*> EncoderMap; // key: payload type
WebRtcVideoChannelSendInfo(int channel_id, int capture_id,
webrtc::ViEExternalCapture* external_capture,
- talk_base::CpuMonitor* cpu_monitor)
+ rtc::CpuMonitor* cpu_monitor)
: channel_id_(channel_id),
capture_id_(capture_id),
sending_(false),
@@ -585,9 +602,9 @@
video_capturer_(NULL),
encoder_observer_(channel_id),
external_capture_(external_capture),
- capturer_updated_(false),
interval_(0),
- cpu_monitor_(cpu_monitor) {
+ cpu_monitor_(cpu_monitor),
+ old_adaptation_changes_(0) {
}
int channel_id() const { return channel_id_; }
@@ -624,12 +641,17 @@
int64 interval() { return interval_; }
int CurrentAdaptReason() const {
- const CoordinatedVideoAdapter* adapter = video_adapter();
- if (!adapter) {
+ if (!video_adapter()) {
return CoordinatedVideoAdapter::ADAPTREASON_NONE;
}
return video_adapter()->adapt_reason();
}
+ int AdaptChanges() const {
+ if (!video_adapter()) {
+ return old_adaptation_changes_;
+ }
+ return old_adaptation_changes_ + video_adapter()->adaptation_changes();
+ }
StreamParams* stream_params() { return stream_params_.get(); }
void set_stream_params(const StreamParams& sp) {
@@ -654,6 +676,8 @@
CoordinatedVideoAdapter* old_video_adapter = video_adapter();
if (old_video_adapter) {
+ // Get adaptation changes from old video adapter.
+ old_adaptation_changes_ += old_video_adapter->adaptation_changes();
// Disconnect signals from old video adapter.
SignalCpuAdaptationUnable.disconnect(old_video_adapter);
if (cpu_monitor_) {
@@ -661,7 +685,6 @@
}
}
- capturer_updated_ = true;
video_capturer_ = video_capturer;
vie_wrapper->base()->RegisterCpuOveruseObserver(channel_id_, NULL);
@@ -812,58 +835,35 @@
VideoFormat video_format_;
- talk_base::scoped_ptr<StreamParams> stream_params_;
+ rtc::scoped_ptr<StreamParams> stream_params_;
WebRtcLocalStreamInfo local_stream_info_;
- bool capturer_updated_;
-
int64 interval_;
- talk_base::CpuMonitor* cpu_monitor_;
- talk_base::scoped_ptr<WebRtcOveruseObserver> overuse_observer_;
+ rtc::CpuMonitor* cpu_monitor_;
+ rtc::scoped_ptr<WebRtcOveruseObserver> overuse_observer_;
+
+ int old_adaptation_changes_;
VideoOptions video_options_;
};
const WebRtcVideoEngine::VideoCodecPref
WebRtcVideoEngine::kVideoCodecPrefs[] = {
- {kVp8PayloadName, 100, -1, 0},
- {kRedPayloadName, 116, -1, 1},
- {kFecPayloadName, 117, -1, 2},
+ {kVp8CodecName, 100, -1, 0},
+ {kRedCodecName, 116, -1, 1},
+ {kUlpfecCodecName, 117, -1, 2},
{kRtxCodecName, 96, 100, 3},
};
-// The formats are sorted by the descending order of width. We use the order to
-// find the next format for CPU and bandwidth adaptation.
-const VideoFormatPod WebRtcVideoEngine::kVideoFormats[] = {
- {1280, 800, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {1280, 720, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {960, 600, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {960, 540, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {640, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {640, 480, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {480, 300, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {480, 270, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {480, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {320, 200, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {320, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {320, 240, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {240, 150, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {240, 135, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {240, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {160, 100, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {160, 90, FPS_TO_INTERVAL(30), FOURCC_ANY},
- {160, 120, FPS_TO_INTERVAL(30), FOURCC_ANY},
-};
-
-const VideoFormatPod WebRtcVideoEngine::kDefaultVideoFormat =
+const VideoFormatPod WebRtcVideoEngine::kDefaultMaxVideoFormat =
{640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY};
+// TODO(ronghuawu): Change to 640x360.
static void UpdateVideoCodec(const cricket::VideoFormat& video_format,
webrtc::VideoCodec* target_codec) {
- if ((target_codec == NULL) || (video_format == cricket::VideoFormat())) {
+ if ((!target_codec) || (video_format == cricket::VideoFormat())) {
return;
}
target_codec->width = video_format.width;
@@ -916,26 +916,26 @@
WebRtcVideoEngine::WebRtcVideoEngine() {
Construct(new ViEWrapper(), new ViETraceWrapper(), NULL,
- new talk_base::CpuMonitor(NULL));
+ new rtc::CpuMonitor(NULL));
}
WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
ViEWrapper* vie_wrapper,
- talk_base::CpuMonitor* cpu_monitor) {
+ rtc::CpuMonitor* cpu_monitor) {
Construct(vie_wrapper, new ViETraceWrapper(), voice_engine, cpu_monitor);
}
WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
ViEWrapper* vie_wrapper,
ViETraceWrapper* tracing,
- talk_base::CpuMonitor* cpu_monitor) {
+ rtc::CpuMonitor* cpu_monitor) {
Construct(vie_wrapper, tracing, voice_engine, cpu_monitor);
}
void WebRtcVideoEngine::Construct(ViEWrapper* vie_wrapper,
ViETraceWrapper* tracing,
WebRtcVoiceEngine* voice_engine,
- talk_base::CpuMonitor* cpu_monitor) {
+ rtc::CpuMonitor* cpu_monitor) {
LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine";
worker_thread_ = NULL;
vie_wrapper_.reset(vie_wrapper);
@@ -945,8 +945,6 @@
initialized_ = false;
SetTraceFilter(SeverityToFilter(kDefaultLogSeverity));
render_module_.reset(new WebRtcPassthroughRender());
- local_renderer_w_ = local_renderer_h_ = 0;
- local_renderer_ = NULL;
capture_started_ = false;
decoder_factory_ = NULL;
encoder_factory_ = NULL;
@@ -963,14 +961,18 @@
// by the server with a jec in response to our reported system info.
VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
kVideoCodecPrefs[0].name,
- kDefaultVideoFormat.width,
- kDefaultVideoFormat.height,
- VideoFormat::IntervalToFps(kDefaultVideoFormat.interval),
+ kDefaultMaxVideoFormat.width,
+ kDefaultMaxVideoFormat.height,
+ VideoFormat::IntervalToFps(
+ kDefaultMaxVideoFormat.interval),
0);
if (!SetDefaultCodec(max_codec)) {
LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
}
+ // Consider jitter, packet loss, etc when rendering. This will
+ // theoretically make rendering more smooth.
+ EnableTimedRender();
// Load our RTP Header extensions.
rtp_header_extensions_.push_back(
@@ -994,7 +996,7 @@
ASSERT(SignalMediaFrame.is_empty());
}
-bool WebRtcVideoEngine::Init(talk_base::Thread* worker_thread) {
+bool WebRtcVideoEngine::Init(rtc::Thread* worker_thread) {
LOG(LS_INFO) << "WebRtcVideoEngine::Init";
worker_thread_ = worker_thread;
ASSERT(worker_thread_ != NULL);
@@ -1035,7 +1037,7 @@
}
LOG(LS_INFO) << "WebRtc VideoEngine Version:";
- LogMultiline(talk_base::LS_INFO, buffer);
+ LogMultiline(rtc::LS_INFO, buffer);
// Hook up to VoiceEngine for sync purposes, if supplied.
if (!voice_engine_) {
@@ -1077,10 +1079,6 @@
return VIDEO_RECV | VIDEO_SEND;
}
-bool WebRtcVideoEngine::SetOptions(const VideoOptions &options) {
- return true;
-}
-
bool WebRtcVideoEngine::SetDefaultEncoderConfig(
const VideoEncoderConfig& config) {
return SetDefaultCodec(config.max_codec);
@@ -1127,12 +1125,6 @@
return channel;
}
-bool WebRtcVideoEngine::SetLocalRenderer(VideoRenderer* renderer) {
- local_renderer_w_ = local_renderer_h_ = 0;
- local_renderer_ = renderer;
- return true;
-}
-
const std::vector<VideoCodec>& WebRtcVideoEngine::codecs() const {
return video_codecs_;
}
@@ -1156,37 +1148,31 @@
// Checks to see whether we comprehend and could receive a particular codec
bool WebRtcVideoEngine::FindCodec(const VideoCodec& in) {
- for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
- const VideoFormat fmt(kVideoFormats[i]);
- if ((in.width == 0 && in.height == 0) ||
- (fmt.width == in.width && fmt.height == in.height)) {
- if (encoder_factory_) {
- const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
- encoder_factory_->codecs();
- for (size_t j = 0; j < codecs.size(); ++j) {
- VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
- codecs[j].name, 0, 0, 0, 0);
- if (codec.Matches(in))
- return true;
- }
- }
- for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
- VideoCodec codec(kVideoCodecPrefs[j].payload_type,
- kVideoCodecPrefs[j].name, 0, 0, 0, 0);
- if (codec.Matches(in)) {
- return true;
- }
- }
+ if (encoder_factory_) {
+ const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
+ encoder_factory_->codecs();
+ for (size_t j = 0; j < codecs.size(); ++j) {
+ VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
+ codecs[j].name, 0, 0, 0, 0);
+ if (codec.Matches(in))
+ return true;
+ }
+ }
+ for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
+ VideoCodec codec(kVideoCodecPrefs[j].payload_type,
+ kVideoCodecPrefs[j].name, 0, 0, 0, 0);
+ if (codec.Matches(in)) {
+ return true;
}
}
return false;
}
// Given the requested codec, returns true if we can send that codec type and
-// updates out with the best quality we could send for that codec. If current is
-// not empty, we constrain out so that its aspect ratio matches current's.
+// updates out with the best quality we could send for that codec.
+// TODO(ronghuawu): Remove |current| from the interface.
bool WebRtcVideoEngine::CanSendCodec(const VideoCodec& requested,
- const VideoCodec& current,
+ const VideoCodec& /* current */,
VideoCodec* out) {
if (!out) {
return false;
@@ -1205,7 +1191,7 @@
out->name = requested.name;
out->preference = requested.preference;
out->params = requested.params;
- out->framerate = talk_base::_min(requested.framerate, local_max->framerate);
+ out->framerate = rtc::_min(requested.framerate, local_max->framerate);
out->width = 0;
out->height = 0;
out->params = requested.params;
@@ -1219,44 +1205,16 @@
return false;
}
- // Pick the best quality that is within their and our bounds and has the
- // correct aspect ratio.
- for (int j = 0; j < ARRAY_SIZE(kVideoFormats); ++j) {
- const VideoFormat format(kVideoFormats[j]);
-
- // Skip any format that is larger than the local or remote maximums, or
- // smaller than the current best match
- if (format.width > requested.width || format.height > requested.height ||
- format.width > local_max->width ||
- (format.width < out->width && format.height < out->height)) {
- continue;
- }
-
- bool better = false;
-
- // Check any further constraints on this prospective format
- if (!out->width || !out->height) {
- // If we don't have any matches yet, this is the best so far.
- better = true;
- } else if (current.width && current.height) {
- // current is set so format must match its ratio exactly.
- better =
- (format.width * current.height == format.height * current.width);
- } else {
- // Prefer closer aspect ratios i.e
- // format.aspect - requested.aspect < out.aspect - requested.aspect
- better = abs(format.width * requested.height * out->height -
- requested.width * format.height * out->height) <
- abs(out->width * format.height * requested.height -
- requested.width * format.height * out->height);
- }
-
- if (better) {
- out->width = format.width;
- out->height = format.height;
- }
+ // Reduce the requested size by /= 2 until it's width under
+ // |local_max->width|.
+ out->width = requested.width;
+ out->height = requested.height;
+ while (out->width > local_max->width) {
+ out->width /= 2;
+ out->height /= 2;
}
- if (out->width > 0) {
+
+ if (out->width > 0 && out->height > 0) {
return true;
}
}
@@ -1304,7 +1262,7 @@
if (_stricmp(in_codec.name.c_str(), codecs[i].name.c_str()) == 0) {
out_codec->codecType = codecs[i].type;
out_codec->plType = GetExternalVideoPayloadType(static_cast<int>(i));
- talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
+ rtc::strcpyn(out_codec->plName, sizeof(out_codec->plName),
codecs[i].name.c_str(), codecs[i].name.length());
found = true;
break;
@@ -1315,7 +1273,7 @@
// Is this an RTX codec? Handled separately here since webrtc doesn't handle
// them as webrtc::VideoCodec internally.
if (!found && _stricmp(in_codec.name.c_str(), kRtxCodecName) == 0) {
- talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
+ rtc::strcpyn(out_codec->plName, sizeof(out_codec->plName),
in_codec.name.c_str(), in_codec.name.length());
out_codec->plType = in_codec.id;
found = true;
@@ -1364,12 +1322,12 @@
}
void WebRtcVideoEngine::RegisterChannel(WebRtcVideoMediaChannel *channel) {
- talk_base::CritScope cs(&channels_crit_);
+ rtc::CritScope cs(&channels_crit_);
channels_.push_back(channel);
}
void WebRtcVideoEngine::UnregisterChannel(WebRtcVideoMediaChannel *channel) {
- talk_base::CritScope cs(&channels_crit_);
+ rtc::CritScope cs(&channels_crit_);
channels_.erase(std::remove(channels_.begin(), channels_.end(), channel),
channels_.end());
}
@@ -1403,7 +1361,7 @@
void WebRtcVideoEngine::SetTraceOptions(const std::string& options) {
// Set WebRTC trace file.
std::vector<std::string> opts;
- talk_base::tokenize(options, ' ', '"', '"', &opts);
+ rtc::tokenize(options, ' ', '"', '"', &opts);
std::vector<std::string>::iterator tracefile =
std::find(opts.begin(), opts.end(), "tracefile");
if (tracefile != opts.end() && ++tracefile != opts.end()) {
@@ -1444,7 +1402,7 @@
VideoCodec codec(pref.payload_type, pref.name,
in_codec.width, in_codec.height, in_codec.framerate,
static_cast<int>(ARRAY_SIZE(kVideoCodecPrefs) - i));
- if (_stricmp(kVp8PayloadName, codec.name.c_str()) == 0) {
+ if (_stricmp(kVp8CodecName, codec.name.c_str()) == 0) {
AddDefaultFeedbackParams(&codec);
}
if (pref.associated_payload_type != -1) {
@@ -1497,21 +1455,21 @@
}
int WebRtcVideoEngine::GetNumOfChannels() {
- talk_base::CritScope cs(&channels_crit_);
+ rtc::CritScope cs(&channels_crit_);
return static_cast<int>(channels_.size());
}
void WebRtcVideoEngine::Print(webrtc::TraceLevel level, const char* trace,
int length) {
- talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
+ rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
- sev = talk_base::LS_ERROR;
+ sev = rtc::LS_ERROR;
else if (level == webrtc::kTraceWarning)
- sev = talk_base::LS_WARNING;
+ sev = rtc::LS_WARNING;
else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
- sev = talk_base::LS_INFO;
+ sev = rtc::LS_INFO;
else if (level == webrtc::kTraceTerseInfo)
- sev = talk_base::LS_INFO;
+ sev = rtc::LS_INFO;
// Skip past boilerplate prefix text
if (length < 72) {
@@ -1529,7 +1487,7 @@
webrtc::VideoDecoder* WebRtcVideoEngine::CreateExternalDecoder(
webrtc::VideoCodecType type) {
- if (decoder_factory_ == NULL) {
+ if (!decoder_factory_) {
return NULL;
}
return decoder_factory_->CreateVideoDecoder(type);
@@ -1537,14 +1495,14 @@
void WebRtcVideoEngine::DestroyExternalDecoder(webrtc::VideoDecoder* decoder) {
ASSERT(decoder_factory_ != NULL);
- if (decoder_factory_ == NULL)
+ if (!decoder_factory_)
return;
decoder_factory_->DestroyVideoDecoder(decoder);
}
webrtc::VideoEncoder* WebRtcVideoEngine::CreateExternalEncoder(
webrtc::VideoCodecType type) {
- if (encoder_factory_ == NULL) {
+ if (!encoder_factory_) {
return NULL;
}
return encoder_factory_->CreateVideoEncoder(type);
@@ -1552,7 +1510,7 @@
void WebRtcVideoEngine::DestroyExternalEncoder(webrtc::VideoEncoder* encoder) {
ASSERT(encoder_factory_ != NULL);
- if (encoder_factory_ == NULL)
+ if (!encoder_factory_)
return;
encoder_factory_->DestroyVideoEncoder(encoder);
}
@@ -1615,11 +1573,12 @@
VoiceMediaChannel* channel)
: engine_(engine),
voice_channel_(channel),
- vie_channel_(-1),
+ default_channel_id_(kChannelIdUnset),
nack_enabled_(true),
remb_enabled_(false),
render_started_(false),
- first_receive_ssrc_(0),
+ first_receive_ssrc_(kSsrcUnset),
+ receiver_report_ssrc_(kSsrcUnset),
num_unsignalled_recv_channels_(0),
send_rtx_type_(-1),
send_red_type_(-1),
@@ -1632,7 +1591,19 @@
bool WebRtcVideoMediaChannel::Init() {
const uint32 ssrc_key = 0;
- return CreateChannel(ssrc_key, MD_SENDRECV, &vie_channel_);
+ bool result = CreateChannel(ssrc_key, MD_SENDRECV, &default_channel_id_);
+ if (!result) {
+ return false;
+ }
+ if (voice_channel_) {
+ WebRtcVoiceMediaChannel* voice_channel =
+ static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
+ if (!voice_channel->SetupSharedBandwidthEstimation(
+ engine()->vie()->engine(), default_channel_id_)) {
+ return false;
+ }
+ }
+ return true;
}
WebRtcVideoMediaChannel::~WebRtcVideoMediaChannel() {
@@ -1696,18 +1667,15 @@
// Match with local video codec list.
std::vector<webrtc::VideoCodec> send_codecs;
VideoCodec checked_codec;
- VideoCodec current; // defaults to 0x0
- if (sending_) {
- ConvertToCricketVideoCodec(*send_codec_, ¤t);
- }
+ VideoCodec dummy_current; // Will be ignored by CanSendCodec.
std::map<int, int> primary_rtx_pt_mapping;
bool nack_enabled = nack_enabled_;
bool remb_enabled = remb_enabled_;
for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
iter != codecs.end(); ++iter) {
- if (_stricmp(iter->name.c_str(), kRedPayloadName) == 0) {
+ if (_stricmp(iter->name.c_str(), kRedCodecName) == 0) {
send_red_type_ = iter->id;
- } else if (_stricmp(iter->name.c_str(), kFecPayloadName) == 0) {
+ } else if (_stricmp(iter->name.c_str(), kUlpfecCodecName) == 0) {
send_fec_type_ = iter->id;
} else if (_stricmp(iter->name.c_str(), kRtxCodecName) == 0) {
int rtx_type = iter->id;
@@ -1715,7 +1683,7 @@
if (iter->GetParam(kCodecParamAssociatedPayloadType, &rtx_primary_type)) {
primary_rtx_pt_mapping[rtx_primary_type] = rtx_type;
}
- } else if (engine()->CanSendCodec(*iter, current, &checked_codec)) {
+ } else if (engine()->CanSendCodec(*iter, dummy_current, &checked_codec)) {
webrtc::VideoCodec wcodec;
if (engine()->ConvertFromCricketVideoCodec(checked_codec, &wcodec)) {
if (send_codecs.empty()) {
@@ -1807,6 +1775,35 @@
return true;
}
+bool WebRtcVideoMediaChannel::MaybeRegisterExternalEncoder(
+ WebRtcVideoChannelSendInfo* send_channel,
+ const webrtc::VideoCodec& codec) {
+ // Codec type not supported or encoder already registered, so
+ // nothing to do.
+ if (!engine()->IsExternalEncoderCodecType(codec.codecType)
+ || send_channel->IsEncoderRegistered(codec.plType)) {
+ return true;
+ }
+
+ webrtc::VideoEncoder* encoder =
+ engine()->CreateExternalEncoder(codec.codecType);
+ if (!encoder) {
+ // No encoder factor, so nothing to do.
+ return true;
+ }
+
+ const int channel_id = send_channel->channel_id();
+ if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
+ channel_id, codec.plType, encoder, false) != 0) {
+ LOG_RTCERR2(RegisterExternalSendCodec, channel_id, codec.plName);
+ engine()->DestroyExternalEncoder(encoder);
+ return false;
+ }
+
+ send_channel->RegisterEncoder(codec.plType, encoder);
+ return true;
+}
+
bool WebRtcVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
if (!send_codec_) {
return false;
@@ -1817,7 +1814,7 @@
bool WebRtcVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
const VideoFormat& format) {
- WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrc(ssrc);
if (!send_channel) {
LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
return false;
@@ -1899,34 +1896,26 @@
}
uint32 ssrc_key;
- if (!CreateSendChannelKey(sp.first_ssrc(), &ssrc_key)) {
+ if (!CreateSendChannelSsrcKey(sp.first_ssrc(), &ssrc_key)) {
LOG(LS_ERROR) << "Trying to register duplicate ssrc: " << sp.first_ssrc();
return false;
}
// If the default channel is already used for sending create a new channel
// otherwise use the default channel for sending.
- int channel_id = -1;
- if (send_channels_[0]->stream_params() == NULL) {
- channel_id = vie_channel_;
+ int channel_id = kChannelIdUnset;
+ if (!DefaultSendChannelInUse()) {
+ channel_id = default_channel_id_;
} else {
if (!CreateChannel(ssrc_key, MD_SEND, &channel_id)) {
LOG(LS_ERROR) << "AddSendStream: unable to create channel";
return false;
}
}
- WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
- // Set the send (local) SSRC.
+
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrcKey(ssrc_key);
// If there are multiple send SSRCs, we can only set the first one here, and
// the rest of the SSRC(s) need to be set after SetSendCodec has been called
- // (with a codec requires multiple SSRC(s)).
- if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
- sp.first_ssrc()) != 0) {
- LOG_RTCERR2(SetLocalSSRC, channel_id, sp.first_ssrc());
- return false;
- }
-
- // Set the corresponding RTX SSRC.
- if (!SetLocalRtxSsrc(channel_id, sp, sp.first_ssrc(), 0)) {
+ if (!SetLimitedNumberOfSendSsrcs(channel_id, sp, 1)) {
return false;
}
@@ -1937,21 +1926,9 @@
return false;
}
- // At this point the channel's local SSRC has been updated. If the channel is
- // the default channel make sure that all the receive channels are updated as
- // well. Receive channels have to have the same SSRC as the default channel in
- // order to send receiver reports with this SSRC.
- if (IsDefaultChannel(channel_id)) {
- for (RecvChannelMap::const_iterator it = recv_channels_.begin();
- it != recv_channels_.end(); ++it) {
- WebRtcVideoChannelRecvInfo* info = it->second;
- int channel_id = info->channel_id();
- if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
- sp.first_ssrc()) != 0) {
- LOG_RTCERR1(SetLocalSSRC, it->first);
- return false;
- }
- }
+ // Use the SSRC of the default channel in the RTCP receiver reports.
+ if (IsDefaultChannelId(channel_id)) {
+ SetReceiverReportSsrc(sp.first_ssrc());
}
send_channel->set_stream_params(sp);
@@ -1977,14 +1954,14 @@
}
uint32 ssrc_key;
- if (!GetSendChannelKey(ssrc, &ssrc_key)) {
+ if (!GetSendChannelSsrcKey(ssrc, &ssrc_key)) {
LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
<< " which doesn't exist.";
return false;
}
- WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrcKey(ssrc_key);
int channel_id = send_channel->channel_id();
- if (IsDefaultChannel(channel_id) && (send_channel->stream_params() == NULL)) {
+ if (IsDefaultChannelId(channel_id) && !send_channel->stream_params()) {
// Default channel will still exist. However, if stream_params() is NULL
// there is no stream to remove.
return false;
@@ -2006,8 +1983,8 @@
send_channel->ClearRegisteredEncoders();
// The receive channels depend on the default channel, recycle it instead.
- if (IsDefaultChannel(channel_id)) {
- SetCapturer(GetDefaultChannelSsrc(), NULL);
+ if (IsDefaultChannelId(channel_id)) {
+ SetCapturer(GetDefaultSendChannelSsrc(), NULL);
send_channel->ClearStreamParams();
} else {
return DeleteSendChannel(ssrc_key);
@@ -2024,27 +2001,26 @@
// TODO(zhurunz) Remove this once BWE works properly across different send
// and receive channels.
// Reuse default channel for recv stream in 1:1 call.
- if (!InConferenceMode() && first_receive_ssrc_ == 0) {
+ if (!InConferenceMode() && first_receive_ssrc_ == kSsrcUnset) {
LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
<< " reuse default channel #"
- << vie_channel_;
+ << default_channel_id_;
first_receive_ssrc_ = sp.first_ssrc();
- if (!MaybeSetRtxSsrc(sp, vie_channel_)) {
+ if (!MaybeSetRtxSsrc(sp, default_channel_id_)) {
return false;
}
if (render_started_) {
- if (engine()->vie()->render()->StartRender(vie_channel_) !=0) {
- LOG_RTCERR1(StartRender, vie_channel_);
+ if (engine()->vie()->render()->StartRender(default_channel_id_) !=0) {
+ LOG_RTCERR1(StartRender, default_channel_id_);
}
}
return true;
}
- int channel_id = -1;
- RecvChannelMap::iterator channel_iterator =
- recv_channels_.find(sp.first_ssrc());
- if (channel_iterator == recv_channels_.end() &&
- first_receive_ssrc_ != sp.first_ssrc()) {
+ int channel_id = kChannelIdUnset;
+ uint32 ssrc = sp.first_ssrc();
+ WebRtcVideoChannelRecvInfo* recv_channel = GetRecvChannelBySsrc(ssrc);
+ if (!recv_channel && first_receive_ssrc_ != ssrc) {
// TODO(perkj): Implement recv media from multiple media SSRCs per stream.
// NOTE: We have two SSRCs per stream when RTX is enabled.
if (!IsOneSsrcStream(sp)) {
@@ -2062,41 +2038,21 @@
}
} else {
// Already exists.
- if (first_receive_ssrc_ == sp.first_ssrc()) {
+ if (first_receive_ssrc_ == ssrc) {
return false;
}
// Early receive added channel.
- channel_id = (*channel_iterator).second->channel_id();
+ channel_id = recv_channel->channel_id();
}
- channel_iterator = recv_channels_.find(sp.first_ssrc());
if (!MaybeSetRtxSsrc(sp, channel_id)) {
return false;
}
- // Get the default renderer.
- VideoRenderer* default_renderer = NULL;
- if (InConferenceMode()) {
- // The recv_channels_ size start out being 1, so if it is two here this
- // is the first receive channel created (vie_channel_ is not used for
- // receiving in a conference call). This means that the renderer stored
- // inside vie_channel_ should be used for the just created channel.
- if (recv_channels_.size() == 2 &&
- recv_channels_.find(0) != recv_channels_.end()) {
- GetRenderer(0, &default_renderer);
- }
- }
-
- // The first recv stream reuses the default renderer (if a default renderer
- // has been set).
- if (default_renderer) {
- SetRenderer(sp.first_ssrc(), default_renderer);
- }
-
LOG(LS_INFO) << "New video stream " << sp.first_ssrc()
<< " registered to VideoEngine channel #"
- << channel_id << " and connected to channel #" << vie_channel_;
-
+ << channel_id << " and connected to channel #"
+ << default_channel_id_;
return true;
}
@@ -2127,26 +2083,25 @@
}
bool WebRtcVideoMediaChannel::RemoveRecvStreamInternal(uint32 ssrc) {
- RecvChannelMap::iterator it = recv_channels_.find(ssrc);
- if (it == recv_channels_.end()) {
+ WebRtcVideoChannelRecvInfo* recv_channel = GetRecvChannelBySsrc(ssrc);
+ if (!recv_channel) {
// TODO(perkj): Remove this once BWE works properly across different send
// and receive channels.
// The default channel is reused for recv stream in 1:1 call.
if (first_receive_ssrc_ == ssrc) {
- first_receive_ssrc_ = 0;
+ first_receive_ssrc_ = kSsrcUnset;
// Need to stop the renderer and remove it since the render window can be
// deleted after this.
if (render_started_) {
- if (engine()->vie()->render()->StopRender(vie_channel_) !=0) {
- LOG_RTCERR1(StopRender, it->second->channel_id());
+ if (engine()->vie()->render()->StopRender(default_channel_id_) !=0) {
+ LOG_RTCERR1(StopRender, recv_channel->channel_id());
}
}
- recv_channels_[0]->SetRenderer(NULL);
+ GetDefaultRecvChannel()->SetRenderer(NULL);
return true;
}
return false;
}
- WebRtcVideoChannelRecvInfo* info = it->second;
// Remove any RTX SSRC mappings to this stream.
SsrcMap::iterator rtx_it = rtx_to_primary_ssrc_.begin();
@@ -2158,7 +2113,7 @@
}
}
- int channel_id = info->channel_id();
+ int channel_id = recv_channel->channel_id();
if (engine()->vie()->render()->RemoveRenderer(channel_id) != 0) {
LOG_RTCERR1(RemoveRenderer, channel_id);
}
@@ -2173,7 +2128,7 @@
}
const WebRtcVideoChannelRecvInfo::DecoderMap& decoder_map =
- info->registered_decoders();
+ recv_channel->registered_decoders();
for (WebRtcVideoChannelRecvInfo::DecoderMap::const_iterator it =
decoder_map.begin(); it != decoder_map.end(); ++it) {
if (engine()->vie()->ext_codec()->DeRegisterExternalReceiveCodec(
@@ -2182,7 +2137,7 @@
}
engine()->DestroyExternalDecoder(it->second);
}
- info->ClearRegisteredDecoders();
+ recv_channel->ClearRegisteredDecoders();
LOG(LS_INFO) << "Removing video stream " << ssrc
<< " with VideoEngine channel #"
@@ -2193,8 +2148,8 @@
ret = false;
}
// Delete the WebRtcVideoChannelRecvInfo pointed to by it->second.
- delete info;
- recv_channels_.erase(it);
+ delete recv_channel;
+ recv_channels_.erase(ssrc);
return ret;
}
@@ -2262,67 +2217,89 @@
bool WebRtcVideoMediaChannel::HasReadySendChannels() {
return !send_channels_.empty() &&
- ((send_channels_.size() > 1) ||
- (send_channels_[0]->stream_params() != NULL));
+ ((send_channels_.size() > 1) || DefaultSendChannelInUse());
}
-bool WebRtcVideoMediaChannel::GetSendChannelKey(uint32 local_ssrc,
- uint32* key) {
- *key = 0;
+bool WebRtcVideoMediaChannel::DefaultSendChannelInUse() {
+ return GetDefaultSendChannel() && GetDefaultSendChannel()->stream_params();
+}
+
+bool WebRtcVideoMediaChannel::GetSendChannelSsrcKey(uint32 local_ssrc,
+ uint32* ssrc_key) {
+ *ssrc_key = kDefaultChannelSsrcKey;
// If a send channel is not ready to send it will not have local_ssrc
// registered to it.
if (!HasReadySendChannels()) {
return false;
}
- // The default channel is stored with key 0. The key therefore does not match
- // the SSRC associated with the default channel. Check if the SSRC provided
- // corresponds to the default channel's SSRC.
- if (local_ssrc == GetDefaultChannelSsrc()) {
+ // The default channel is stored with ssrc key
+ // kDefaultChannelSsrcKey. The ssrc key therefore does not match the
+ // SSRC associated with the default channel. Check if the SSRC
+ // provided corresponds to the default channel's SSRC.
+ if (local_ssrc == GetDefaultSendChannelSsrc()) {
return true;
}
- if (send_channels_.find(local_ssrc) == send_channels_.end()) {
+ if (!GetSendChannelBySsrcKey(local_ssrc)) {
+ // If a stream has multiple ssrcs, the local_ssrc could be any of
+ // them, but we use the first one (StreamParams::first_ssrc()) as
+ // the key.
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
if (send_channel->has_ssrc(local_ssrc)) {
- *key = iter->first;
+ *ssrc_key = iter->first;
return true;
}
}
return false;
}
- // The key was found in the above std::map::find call. This means that the
- // ssrc is the key.
- *key = local_ssrc;
+ // The ssrc key was found in the above std::map::find call. This
+ // means that the ssrc is the ssrc key.
+ *ssrc_key = local_ssrc;
return true;
}
-WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
- uint32 local_ssrc) {
- uint32 key;
- if (!GetSendChannelKey(local_ssrc, &key)) {
- return NULL;
- }
- return send_channels_[key];
+WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetDefaultSendChannel() {
+ return GetSendChannelBySsrcKey(kDefaultChannelSsrcKey);
}
-bool WebRtcVideoMediaChannel::CreateSendChannelKey(uint32 local_ssrc,
- uint32* key) {
- if (GetSendChannelKey(local_ssrc, key)) {
- // If there is a key corresponding to |local_ssrc|, the SSRC is already in
- // use. SSRCs need to be unique in a session and at this point a duplicate
- // SSRC has been detected.
+WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannelBySsrcKey(
+ uint32 ssrc_key) {
+ std::map<uint32, WebRtcVideoChannelSendInfo *>::iterator iter =
+ send_channels_.find(ssrc_key);
+ if (iter == send_channels_.end()) {
+ return NULL;
+ }
+ return iter->second;
+}
+
+WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannelBySsrc(
+ uint32 local_ssrc) {
+ uint32 ssrc_key;
+ if (!GetSendChannelSsrcKey(local_ssrc, &ssrc_key)) {
+ return NULL;
+ }
+ return send_channels_[ssrc_key];
+}
+
+bool WebRtcVideoMediaChannel::CreateSendChannelSsrcKey(uint32 local_ssrc,
+ uint32* ssrc_key) {
+ if (GetSendChannelSsrcKey(local_ssrc, ssrc_key)) {
+ // If there is an ssrc key corresponding to |local_ssrc|, the SSRC
+ // is already in use. SSRCs need to be unique in a session and at
+ // this point a duplicate SSRC has been detected.
return false;
}
- if (send_channels_[0]->stream_params() == NULL) {
- // key should be 0 here as the default channel should be re-used whenever it
- // is not used.
- *key = 0;
+ if (!DefaultSendChannelInUse()) {
+ // |ssrc_key| should be kDefaultChannelSsrcKey here as the default
+ // channel should be re-used whenever it is not used.
+ *ssrc_key = kDefaultChannelSsrcKey;
return true;
}
- // SSRC is currently not in use and the default channel is already in use. Use
- // the SSRC as key since it is supposed to be unique in a session.
- *key = local_ssrc;
+ // SSRC is currently not in use and the default channel is already
+ // in use. Use the SSRC as ssrc_key since it is supposed to be
+ // unique in a session.
+ *ssrc_key = local_ssrc;
return true;
}
@@ -2338,21 +2315,18 @@
return num;
}
-uint32 WebRtcVideoMediaChannel::GetDefaultChannelSsrc() {
- WebRtcVideoChannelSendInfo* send_channel = send_channels_[0];
- const StreamParams* sp = send_channel->stream_params();
- if (sp == NULL) {
- // This happens if no send stream is currently registered.
+uint32 WebRtcVideoMediaChannel::GetDefaultSendChannelSsrc() {
+ if (!DefaultSendChannelInUse()) {
return 0;
}
- return sp->first_ssrc();
+ return GetDefaultSendChannel()->stream_params()->first_ssrc();
}
bool WebRtcVideoMediaChannel::DeleteSendChannel(uint32 ssrc_key) {
- if (send_channels_.find(ssrc_key) == send_channels_.end()) {
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrcKey(ssrc_key);
+ if (!send_channel) {
return false;
}
- WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
MaybeDisconnectCapturer(send_channel->video_capturer());
send_channel->set_video_capturer(NULL, engine()->vie());
@@ -2376,7 +2350,7 @@
// The default channel is stored in both |send_channels_| and
// |recv_channels_|. To make sure it is only deleted once from vie let the
// delete call happen when tearing down |recv_channels_| and not here.
- if (!IsDefaultChannel(channel_id)) {
+ if (!IsDefaultChannelId(channel_id)) {
engine_->vie()->base()->DeleteChannel(channel_id);
}
delete send_channel;
@@ -2384,13 +2358,25 @@
return true;
}
+WebRtcVideoChannelRecvInfo* WebRtcVideoMediaChannel::GetDefaultRecvChannel() {
+ return GetRecvChannelBySsrc(kDefaultChannelSsrcKey);
+}
+
+WebRtcVideoChannelRecvInfo* WebRtcVideoMediaChannel::GetRecvChannelBySsrc(
+ uint32 ssrc) {
+ if (recv_channels_.find(ssrc) == recv_channels_.end()) {
+ return NULL;
+ }
+ return recv_channels_[ssrc];
+}
+
bool WebRtcVideoMediaChannel::RemoveCapturer(uint32 ssrc) {
- WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrc(ssrc);
if (!send_channel) {
return false;
}
VideoCapturer* capturer = send_channel->video_capturer();
- if (capturer == NULL) {
+ if (!capturer) {
return false;
}
MaybeDisconnectCapturer(capturer);
@@ -2404,22 +2390,22 @@
bool WebRtcVideoMediaChannel::SetRenderer(uint32 ssrc,
VideoRenderer* renderer) {
- if (recv_channels_.find(ssrc) == recv_channels_.end()) {
+ WebRtcVideoChannelRecvInfo* recv_channel = GetRecvChannelBySsrc(ssrc);
+ if (!recv_channel) {
// TODO(perkj): Remove this once BWE works properly across different send
// and receive channels.
// The default channel is reused for recv stream in 1:1 call.
- if (first_receive_ssrc_ == ssrc &&
- recv_channels_.find(0) != recv_channels_.end()) {
+ if (first_receive_ssrc_ == ssrc && GetDefaultRecvChannel()) {
LOG(LS_INFO) << "SetRenderer " << ssrc
<< " reuse default channel #"
- << vie_channel_;
- recv_channels_[0]->SetRenderer(renderer);
+ << default_channel_id_;
+ GetDefaultRecvChannel()->SetRenderer(renderer);
return true;
}
return false;
}
- recv_channels_[ssrc]->SetRenderer(renderer);
+ recv_channel->SetRenderer(renderer);
return true;
}
@@ -2439,21 +2425,21 @@
const int channel_id = send_channel->channel_id();
VideoSenderInfo sinfo;
const StreamParams* send_params = send_channel->stream_params();
- if (send_params == NULL) {
+ if (!send_params) {
// This should only happen if the default vie channel is not in use.
// This can happen if no streams have ever been added or the stream
// corresponding to the default channel has been removed. Note that
// there may be non-default vie channels in use when this happen so
// asserting send_channels_.size() == 1 is not correct and neither is
// breaking out of the loop.
- ASSERT(channel_id == vie_channel_);
+ ASSERT(channel_id == default_channel_id_);
continue;
}
unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
if (engine_->vie()->rtp()->GetRTPStatistics(channel_id, bytes_sent,
packets_sent, bytes_recv,
packets_recv) != 0) {
- LOG_RTCERR1(GetRTPStatistics, vie_channel_);
+ LOG_RTCERR1(GetRTPStatistics, default_channel_id_);
continue;
}
WebRtcLocalStreamInfo* channel_stream_info =
@@ -2505,6 +2491,7 @@
send_codec_->maxBitrate, kMaxVideoBitrate);
}
sinfo.adapt_reason = send_channel->CurrentAdaptReason();
+ sinfo.adapt_changes = send_channel->AdaptChanges();
#ifdef USE_WEBRTC_DEV_BRANCH
webrtc::CpuOveruseMetrics metrics;
@@ -2696,7 +2683,7 @@
// Only call for the default channel because the returned stats are
// collected for all the channels using the same estimator.
if (engine_->vie()->rtp()->GetReceiveBandwidthEstimatorStats(
- recv_channels_[0]->channel_id(), &additional_stats) == 0) {
+ GetDefaultRecvChannel()->channel_id(), &additional_stats) == 0) {
bwe.total_received_propagation_delta_ms =
additional_stats.total_propagation_time_delta_ms;
bwe.recent_received_propagation_delta_ms.swap(
@@ -2707,7 +2694,7 @@
}
engine_->vie()->rtp()->GetPacerQueuingDelayMs(
- recv_channels_[0]->channel_id(), &bwe.bucket_delay);
+ GetDefaultRecvChannel()->channel_id(), &bwe.bucket_delay);
// Calculations done above per send/receive stream.
bwe.actual_enc_bitrate = video_bitrate_sent;
@@ -2728,7 +2715,7 @@
if (!capturer) {
return RemoveCapturer(ssrc);
}
- WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrc(ssrc);
if (!send_channel) {
return false;
}
@@ -2754,20 +2741,20 @@
}
void WebRtcVideoMediaChannel::OnPacketReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
// Pick which channel to send this packet to. If this packet doesn't match
// any multiplexed streams, just send it to the default channel. Otherwise,
// send it to the specific decoder instance for that stream.
uint32 ssrc = 0;
if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc))
return;
- int processing_channel = GetRecvChannelNum(ssrc);
- if (processing_channel == -1) {
+ int processing_channel_id = GetRecvChannelId(ssrc);
+ if (processing_channel_id == kChannelIdUnset) {
// Allocate an unsignalled recv channel for processing in conference mode.
if (!InConferenceMode()) {
// If we can't find or allocate one, use the default.
- processing_channel = video_channel();
- } else if (!CreateUnsignalledRecvChannel(ssrc, &processing_channel)) {
+ processing_channel_id = default_channel_id_;
+ } else if (!CreateUnsignalledRecvChannel(ssrc, &processing_channel_id)) {
// If we can't create an unsignalled recv channel, drop the packet in
// conference mode.
return;
@@ -2775,14 +2762,14 @@
}
engine()->vie()->network()->ReceivedRTPPacket(
- processing_channel,
+ processing_channel_id,
packet->data(),
static_cast<int>(packet->length()),
webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
}
void WebRtcVideoMediaChannel::OnRtcpReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
// Sending channels need all RTCP packets with feedback information.
// Even sender reports can contain attached report blocks.
// Receiving channels need sender reports in order to create
@@ -2801,10 +2788,10 @@
// If it is a sender report, find the channel that is listening.
if (type == kRtcpTypeSR) {
- int which_channel = GetRecvChannelNum(ssrc);
- if (which_channel != -1 && !IsDefaultChannel(which_channel)) {
+ int recv_channel_id = GetRecvChannelId(ssrc);
+ if (recv_channel_id != kChannelIdUnset && !IsDefaultChannelId(recv_channel_id)) {
engine_->vie()->network()->ReceivedRTCPPacket(
- which_channel,
+ recv_channel_id,
packet->data(),
static_cast<int>(packet->length()));
}
@@ -2828,7 +2815,7 @@
}
bool WebRtcVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
- WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrc(ssrc);
if (!send_channel) {
LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
return false;
@@ -2900,7 +2887,7 @@
// Extension closer to the network, @ socket level before sending.
// Pushing the extension id to socket layer.
MediaChannel::SetOption(NetworkInterface::ST_RTP,
- talk_base::Socket::OPT_RTP_SENDTIME_EXTN_ID,
+ rtc::Socket::OPT_RTP_SENDTIME_EXTN_ID,
send_time_extension->id);
}
@@ -2926,7 +2913,7 @@
}
// On success, SetSendCodec() will reset |send_start_bitrate_| to |bps/1000|,
- // by calling MaybeChangeBitrates. That method will also clamp the
+ // by calling SanitizeBitrates. That method will also clamp the
// start bitrate between min and max, consistent with the override behavior
// in SetMaxSendBandwidth.
webrtc::VideoCodec new_codec = *send_codec_;
@@ -2962,44 +2949,10 @@
return true;
}
- // Trigger SetSendCodec to set correct noise reduction state if the option has
- // changed.
- bool denoiser_changed = options.video_noise_reduction.IsSet() &&
- (options_.video_noise_reduction != options.video_noise_reduction);
-
- bool leaky_bucket_changed = options.video_leaky_bucket.IsSet() &&
- (options_.video_leaky_bucket != options.video_leaky_bucket);
-
- bool buffer_latency_changed = options.buffered_mode_latency.IsSet() &&
- (options_.buffered_mode_latency != options.buffered_mode_latency);
-
- bool dscp_option_changed = (options_.dscp != options.dscp);
-
- bool suspend_below_min_bitrate_changed =
- options.suspend_below_min_bitrate.IsSet() &&
- (options_.suspend_below_min_bitrate != options.suspend_below_min_bitrate);
-
- bool conference_mode_turned_off = false;
- if (options_.conference_mode.IsSet() && options.conference_mode.IsSet() &&
- options_.conference_mode.GetWithDefaultIfUnset(false) &&
- !options.conference_mode.GetWithDefaultIfUnset(false)) {
- conference_mode_turned_off = true;
- }
-
- bool improved_wifi_bwe_changed =
- options.use_improved_wifi_bandwidth_estimator.IsSet() &&
- options_.use_improved_wifi_bandwidth_estimator !=
- options.use_improved_wifi_bandwidth_estimator;
-
-#ifdef USE_WEBRTC_DEV_BRANCH
- bool payload_padding_changed = options.use_payload_padding.IsSet() &&
- options_.use_payload_padding != options.use_payload_padding;
-#endif
-
-
// Save the options, to be interpreted where appropriate.
// Use options_.SetAll() instead of assignment so that unset value in options
// will not overwrite the previous option value.
+ VideoOptions original = options_;
options_.SetAll(options);
// Set CPU options for all send channels.
@@ -3010,45 +2963,36 @@
}
if (send_codec_) {
- bool reset_send_codec_needed = denoiser_changed;
webrtc::VideoCodec new_codec = *send_codec_;
- // TODO(pthatcher): Remove this. We don't need 4 ways to set bitrates.
- bool lower_min_bitrate;
- if (options.lower_min_bitrate.Get(&lower_min_bitrate)) {
- new_codec.minBitrate = kLowerMinBitrate;
- reset_send_codec_needed = true;
- }
-
+ bool conference_mode_turned_off = (
+ original.conference_mode.IsSet() &&
+ options.conference_mode.IsSet() &&
+ original.conference_mode.GetWithDefaultIfUnset(false) &&
+ !options.conference_mode.GetWithDefaultIfUnset(false));
if (conference_mode_turned_off) {
// This is a special case for turning conference mode off.
// Max bitrate should go back to the default maximum value instead
// of the current maximum.
new_codec.maxBitrate = kAutoBandwidth;
- reset_send_codec_needed = true;
}
// TODO(pthatcher): Remove this. We don't need 4 ways to set bitrates.
int new_start_bitrate;
if (options.video_start_bitrate.Get(&new_start_bitrate)) {
new_codec.startBitrate = new_start_bitrate;
- reset_send_codec_needed = true;
}
-
- LOG(LS_INFO) << "Reset send codec needed is enabled? "
- << reset_send_codec_needed;
- if (reset_send_codec_needed) {
- if (!SetSendCodec(new_codec)) {
- return false;
- }
- LogSendCodecChange("SetOptions()");
+ if (!SetSendCodec(new_codec)) {
+ return false;
}
+ LogSendCodecChange("SetOptions()");
}
- if (leaky_bucket_changed) {
- bool enable_leaky_bucket =
- options_.video_leaky_bucket.GetWithDefaultIfUnset(true);
+ bool enable_leaky_bucket;
+ if (Changed(options.video_leaky_bucket,
+ original.video_leaky_bucket,
+ &enable_leaky_bucket)) {
LOG(LS_INFO) << "Leaky bucket is enabled? " << enable_leaky_bucket;
for (SendChannelMap::iterator it = send_channels_.begin();
it != send_channels_.end(); ++it) {
@@ -3062,10 +3006,11 @@
}
}
}
- if (buffer_latency_changed) {
- int buffer_latency =
- options_.buffered_mode_latency.GetWithDefaultIfUnset(
- cricket::kBufferedModeDisabled);
+
+ int buffer_latency;
+ if (Changed(options.buffered_mode_latency,
+ original.buffered_mode_latency,
+ &buffer_latency)) {
LOG(LS_INFO) << "Buffer latency is " << buffer_latency;
for (SendChannelMap::iterator it = send_channels_.begin();
it != send_channels_.end(); ++it) {
@@ -3084,17 +3029,24 @@
}
}
}
- if (dscp_option_changed) {
- talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
- if (options_.dscp.GetWithDefaultIfUnset(false))
+
+ bool dscp_enabled;
+ if (Changed(options.dscp, original.dscp, &dscp_enabled)) {
+ rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
+ if (dscp_enabled) {
dscp = kVideoDscpValue;
+ }
LOG(LS_INFO) << "DSCP is " << dscp;
if (MediaChannel::SetDscp(dscp) != 0) {
LOG(LS_WARNING) << "Failed to set DSCP settings for video channel";
}
}
- if (suspend_below_min_bitrate_changed) {
- if (options_.suspend_below_min_bitrate.GetWithDefaultIfUnset(false)) {
+
+ bool suspend_below_min_bitrate;
+ if (Changed(options.suspend_below_min_bitrate,
+ original.suspend_below_min_bitrate,
+ &suspend_below_min_bitrate)) {
+ if (suspend_below_min_bitrate) {
LOG(LS_INFO) << "Suspend below min bitrate enabled.";
for (SendChannelMap::iterator it = send_channels_.begin();
it != send_channels_.end(); ++it) {
@@ -3105,26 +3057,17 @@
LOG(LS_WARNING) << "Cannot disable video suspension once it is enabled";
}
}
- if (improved_wifi_bwe_changed) {
- LOG(LS_INFO) << "Improved WIFI BWE called.";
- webrtc::Config config;
- config.Set(new webrtc::AimdRemoteRateControl(
- options_.use_improved_wifi_bandwidth_estimator
- .GetWithDefaultIfUnset(false)));
- for (SendChannelMap::iterator it = send_channels_.begin();
- it != send_channels_.end(); ++it) {
- engine()->vie()->network()->SetBandwidthEstimationConfig(
- it->second->channel_id(), config);
- }
- }
+
#ifdef USE_WEBRTC_DEV_BRANCH
- if (payload_padding_changed) {
+ bool use_payload_padding;
+ if (Changed(options.use_payload_padding,
+ original.use_payload_padding,
+ &use_payload_padding)) {
LOG(LS_INFO) << "Payload-based padding called.";
for (SendChannelMap::iterator it = send_channels_.begin();
it != send_channels_.end(); ++it) {
engine()->vie()->rtp()->SetPadWithRedundantPayloads(
- it->second->channel_id(),
- options_.use_payload_padding.GetWithDefaultIfUnset(false));
+ it->second->channel_id(), use_payload_padding);
}
}
#endif
@@ -3145,14 +3088,14 @@
MediaChannel::SetInterface(iface);
// Set the RTP recv/send buffer to a bigger size
MediaChannel::SetOption(NetworkInterface::ST_RTP,
- talk_base::Socket::OPT_RCVBUF,
+ rtc::Socket::OPT_RCVBUF,
kVideoRtpBufferSize);
// TODO(sriniv): Remove or re-enable this.
// As part of b/8030474, send-buffer is size now controlled through
// portallocator flags.
// network_interface_->SetOption(NetworkInterface::ST_RTP,
- // talk_base::Socket::OPT_SNDBUF,
+ // rtc::Socket::OPT_SNDBUF,
// kVideoRtpBufferSize);
}
@@ -3175,30 +3118,29 @@
bool WebRtcVideoMediaChannel::GetRenderer(uint32 ssrc,
VideoRenderer** renderer) {
- RecvChannelMap::const_iterator it = recv_channels_.find(ssrc);
- if (it == recv_channels_.end()) {
- if (first_receive_ssrc_ == ssrc &&
- recv_channels_.find(0) != recv_channels_.end()) {
+ WebRtcVideoChannelRecvInfo* recv_channel = GetRecvChannelBySsrc(ssrc);
+ if (!recv_channel) {
+ if (first_receive_ssrc_ == ssrc && GetDefaultRecvChannel()) {
LOG(LS_INFO) << " GetRenderer " << ssrc
<< " reuse default renderer #"
- << vie_channel_;
- *renderer = recv_channels_[0]->render_adapter()->renderer();
+ << default_channel_id_;
+ *renderer = GetDefaultRecvChannel()->render_adapter()->renderer();
return true;
}
return false;
}
- *renderer = it->second->render_adapter()->renderer();
+ *renderer = recv_channel->render_adapter()->renderer();
return true;
}
bool WebRtcVideoMediaChannel::GetVideoAdapter(
uint32 ssrc, CoordinatedVideoAdapter** video_adapter) {
- SendChannelMap::iterator it = send_channels_.find(ssrc);
- if (it == send_channels_.end()) {
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrc(ssrc);
+ if (!send_channel) {
return false;
}
- *video_adapter = it->second->video_adapter();
+ *video_adapter = send_channel->video_adapter();
return true;
}
@@ -3224,7 +3166,7 @@
for (SendChannelMap::iterator iter = send_channels_.begin();
iter != send_channels_.end(); ++iter) {
WebRtcVideoChannelSendInfo* send_channel = iter->second;
- if (send_channel->video_capturer() == NULL) {
+ if (!send_channel->video_capturer()) {
SendFrame(send_channel, frame, capturer->IsScreencast());
}
}
@@ -3259,8 +3201,8 @@
return false;
}
const VideoFrame* frame_out = frame;
- talk_base::scoped_ptr<VideoFrame> processed_frame;
- // Disable muting for screencast.
+ rtc::scoped_ptr<VideoFrame> processed_frame;
+ // TODO(hellner): Remove the need for disabling mute when screencasting.
const bool mute = (send_channel->muted() && !is_screencast);
send_channel->ProcessFrame(*frame_out, mute, processed_frame.use());
if (processed_frame) {
@@ -3288,7 +3230,7 @@
// If the frame timestamp is 0, we will use the deliver time.
const int64 frame_timestamp = frame->GetTimeStamp();
if (frame_timestamp != 0) {
- if (abs(time(NULL) - frame_timestamp / talk_base::kNumNanosecsPerSec) >
+ if (abs(time(NULL) - frame_timestamp / rtc::kNumNanosecsPerSec) >
kTimestampDeltaInSecondsForWarning) {
LOG(LS_WARNING) << "Frame timestamp differs by more than "
<< kTimestampDeltaInSecondsForWarning << " seconds from "
@@ -3296,7 +3238,7 @@
}
timestamp_ntp_ms =
- talk_base::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
+ rtc::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
}
#endif
@@ -3309,32 +3251,33 @@
int* channel_id) {
// There are 3 types of channels. Sending only, receiving only and
// sending and receiving. The sending and receiving channel is the
- // default channel and there is only one. All other channels that are created
- // are associated with the default channel which must exist. The default
- // channel id is stored in |vie_channel_|. All channels need to know about
- // the default channel to properly handle remb which is why there are
- // different ViE create channel calls.
- // For this channel the local and remote ssrc key is 0. However, it may
- // have a non-zero local and/or remote ssrc depending on if it is currently
- // sending and/or receiving.
- if ((vie_channel_ == -1 || direction == MD_SENDRECV) &&
+ // default channel and there is only one. All other channels that
+ // are created are associated with the default channel which must
+ // exist. The default channel id is stored in
+ // |default_channel_id_|. All channels need to know about the
+ // default channel to properly handle remb which is why there are
+ // different ViE create channel calls. For this channel the local
+ // and remote ssrc_key is kDefaultChannelSsrcKey. However, it may
+ // have a non-zero local and/or remote ssrc depending on if it is
+ // currently sending and/or receiving.
+ if ((default_channel_id_ == kChannelIdUnset || direction == MD_SENDRECV) &&
(!send_channels_.empty() || !recv_channels_.empty())) {
ASSERT(false);
return false;
}
- *channel_id = -1;
+ *channel_id = kChannelIdUnset;
if (direction == MD_RECV) {
- // All rec channels are associated with the default channel |vie_channel_|
+ // All rec channels are associated with default_channel_id_.
if (engine_->vie()->base()->CreateReceiveChannel(*channel_id,
- vie_channel_) != 0) {
- LOG_RTCERR2(CreateReceiveChannel, *channel_id, vie_channel_);
+ default_channel_id_) != 0) {
+ LOG_RTCERR2(CreateReceiveChannel, *channel_id, default_channel_id_);
return false;
}
} else if (direction == MD_SEND) {
if (engine_->vie()->base()->CreateChannel(*channel_id,
- vie_channel_) != 0) {
- LOG_RTCERR2(CreateChannel, *channel_id, vie_channel_);
+ default_channel_id_) != 0) {
+ LOG_RTCERR2(CreateChannel, *channel_id, default_channel_id_);
return false;
}
} else {
@@ -3346,7 +3289,7 @@
}
if (!ConfigureChannel(*channel_id, direction, ssrc_key)) {
engine_->vie()->base()->DeleteChannel(*channel_id);
- *channel_id = -1;
+ *channel_id = kChannelIdUnset;
return false;
}
@@ -3428,9 +3371,9 @@
}
bool WebRtcVideoMediaChannel::ConfigureReceiving(int channel_id,
- uint32 remote_ssrc_key) {
- // Make sure that an SSRC/key isn't registered more than once.
- if (recv_channels_.find(remote_ssrc_key) != recv_channels_.end()) {
+ uint32 remote_ssrc) {
+ // Make sure that an SSRC isn't registered more than once.
+ if (GetRecvChannelBySsrc(remote_ssrc)) {
return false;
}
// Connect the voice channel, if there is one.
@@ -3438,11 +3381,11 @@
// know the SSRC of the remote audio channel in order to fetch the correct
// webrtc VoiceEngine channel. For now- only sync the default channel used
// in 1-1 calls.
- if (remote_ssrc_key == 0 && voice_channel_) {
+ if (remote_ssrc == kDefaultChannelSsrcKey && voice_channel_) {
WebRtcVoiceMediaChannel* voice_channel =
static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
if (engine_->vie()->base()->ConnectAudioChannel(
- vie_channel_, voice_channel->voe_channel()) != 0) {
+ default_channel_id_, voice_channel->voe_channel()) != 0) {
LOG_RTCERR2(ConnectAudioChannel, channel_id,
voice_channel->voe_channel());
LOG(LS_WARNING) << "A/V not synchronized";
@@ -3450,7 +3393,7 @@
}
}
- talk_base::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
+ rtc::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
new WebRtcVideoChannelRecvInfo(channel_id));
// Install a render adapter.
@@ -3461,6 +3404,11 @@
return false;
}
+ if (engine()->vie()->render()->SetExpectedRenderDelay(
+ channel_id, kDefaultRenderDelayMs)) {
+ LOG_RTCERR2(SetExpectedRenderDelay,
+ channel_id, kDefaultRenderDelayMs);
+ }
if (engine_->vie()->rtp()->SetRembStatus(channel_id,
kNotSending,
@@ -3479,20 +3427,13 @@
return false;
}
- if (remote_ssrc_key != 0) {
- // Use the same SSRC as our default channel
- // (so the RTCP reports are correct).
- unsigned int send_ssrc = 0;
- webrtc::ViERTP_RTCP* rtp = engine()->vie()->rtp();
- if (rtp->GetLocalSSRC(vie_channel_, send_ssrc) == -1) {
- LOG_RTCERR2(GetLocalSSRC, vie_channel_, send_ssrc);
+ if (receiver_report_ssrc_ != kSsrcUnset) {
+ if (engine()->vie()->rtp()->SetLocalSSRC(
+ channel_id, receiver_report_ssrc_) == -1) {
+ LOG_RTCERR2(SetLocalSSRC, channel_id, receiver_report_ssrc_);
return false;
}
- if (rtp->SetLocalSSRC(channel_id, send_ssrc) == -1) {
- LOG_RTCERR2(SetLocalSSRC, channel_id, send_ssrc);
- return false;
- }
- } // Else this is the the default channel and we don't change the SSRC.
+ }
// Disable color enhancement since it is a bit too aggressive.
if (engine()->vie()->image()->EnableColorEnhancement(channel_id,
@@ -3529,7 +3470,7 @@
return false;
}
- recv_channels_[remote_ssrc_key] = channel_info.release();
+ recv_channels_[remote_ssrc] = channel_info.release();
return true;
}
@@ -3537,12 +3478,12 @@
uint32 local_ssrc_key) {
// The ssrc key can be zero or correspond to an SSRC.
// Make sure the default channel isn't configured more than once.
- if (local_ssrc_key == 0 && send_channels_.find(0) != send_channels_.end()) {
+ if (local_ssrc_key == kDefaultChannelSsrcKey && GetDefaultSendChannel()) {
return false;
}
// Make sure that the SSRC is not already in use.
uint32 dummy_key;
- if (GetSendChannelKey(local_ssrc_key, &dummy_key)) {
+ if (GetSendChannelSsrcKey(local_ssrc_key, &dummy_key)) {
return false;
}
int vie_capture = 0;
@@ -3560,7 +3501,7 @@
LOG_RTCERR2(ConnectCaptureDevice, vie_capture, channel_id);
return false;
}
- talk_base::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
+ rtc::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
new WebRtcVideoChannelSendInfo(channel_id, vie_capture,
external_capture,
engine()->cpu_monitor()));
@@ -3633,6 +3574,16 @@
return false;
}
+ // Enable improved WiFi Bandwidth Estimation
+ {
+ webrtc::Config config;
+ config.Set(new webrtc::AimdRemoteRateControl(true));
+ if (!engine()->vie()->network()->SetBandwidthEstimationConfig(channel_id,
+ config)) {
+ return false;
+ }
+ }
+
send_channels_[local_ssrc_key] = send_channel.release();
return true;
@@ -3711,21 +3662,7 @@
target_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
}
- // Register external encoder if codec type is supported by encoder factory.
- if (engine()->IsExternalEncoderCodecType(codec.codecType) &&
- !send_channel->IsEncoderRegistered(target_codec.plType)) {
- webrtc::VideoEncoder* encoder =
- engine()->CreateExternalEncoder(codec.codecType);
- if (encoder) {
- if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
- channel_id, target_codec.plType, encoder, false) == 0) {
- send_channel->RegisterEncoder(target_codec.plType, encoder);
- } else {
- LOG_RTCERR2(RegisterExternalSendCodec, channel_id, target_codec.plName);
- engine()->DestroyExternalEncoder(encoder);
- }
- }
- }
+ MaybeRegisterExternalEncoder(send_channel, target_codec);
// Resolution and framerate may vary for different send channels.
const VideoFormat& video_format = send_channel->video_format();
@@ -3736,7 +3673,8 @@
LOG(LS_INFO) << "0x0 resolution selected. Captured frames will be dropped "
<< "for ssrc: " << ssrc << ".";
} else {
- MaybeChangeBitrates(channel_id, &target_codec);
+ StreamParams* send_params = send_channel->stream_params();
+ SanitizeBitrates(channel_id, &target_codec);
webrtc::VideoCodec current_codec;
if (!engine()->vie()->codec()->GetSendCodec(channel_id, current_codec)) {
// Compare against existing configured send codec.
@@ -3751,6 +3689,11 @@
return false;
}
+ if (send_params) {
+ if (!SetSendSsrcs(channel_id, *send_params, target_codec)) {
+ return false;
+ }
+ }
// NOTE: SetRtxSendPayloadType must be called after all simulcast SSRCs
// are configured. Otherwise ssrc's configured after this point will use
// the primary PT for RTX.
@@ -3766,7 +3709,6 @@
return true;
}
-
static std::string ToString(webrtc::VideoCodecComplexity complexity) {
switch (complexity) {
case webrtc::kComplexityNormal:
@@ -3797,8 +3739,8 @@
void WebRtcVideoMediaChannel::LogSendCodecChange(const std::string& reason) {
webrtc::VideoCodec vie_codec;
- if (engine()->vie()->codec()->GetSendCodec(vie_channel_, vie_codec) != 0) {
- LOG_RTCERR1(GetSendCodec, vie_channel_);
+ if (engine()->vie()->codec()->GetSendCodec(default_channel_id_, vie_codec) != 0) {
+ LOG_RTCERR1(GetSendCodec, default_channel_id_);
return;
}
@@ -3852,6 +3794,7 @@
it != receive_codecs_.end(); ++it) {
pt_to_codec[it->plType] = &(*it);
}
+ bool rtx_registered = false;
for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
it != receive_codecs_.end(); ++it) {
if (it->codecType == webrtc::kVideoCodecRED) {
@@ -3862,16 +3805,18 @@
// If this is an RTX codec we have to verify that it is associated with
// a valid video codec which we have RTX support for.
if (_stricmp(it->plName, kRtxCodecName) == 0) {
+ // WebRTC only supports one RTX codec at a time.
+ if (rtx_registered) {
+ LOG(LS_ERROR) << "Only one RTX codec at a time is supported.";
+ return false;
+ }
std::map<int, int>::iterator apt_it = associated_payload_types_.find(
it->plType);
bool valid_apt = false;
if (apt_it != associated_payload_types_.end()) {
std::map<int, webrtc::VideoCodec*>::iterator codec_it =
pt_to_codec.find(apt_it->second);
- // We currently only support RTX associated with VP8 due to limitations
- // in webrtc where only one RTX payload type can be registered.
- valid_apt = codec_it != pt_to_codec.end() &&
- _stricmp(codec_it->second->plName, kVp8PayloadName) == 0;
+ valid_apt = codec_it != pt_to_codec.end();
}
if (!valid_apt) {
LOG(LS_ERROR) << "The RTX codec isn't associated with a known and "
@@ -3883,6 +3828,7 @@
LOG_RTCERR2(SetRtxReceivePayloadType, channel_id, it->plType);
return false;
}
+ rtx_registered = true;
continue;
}
if (engine()->vie()->codec()->SetReceiveCodec(channel_id, *it) != 0) {
@@ -3908,28 +3854,28 @@
return true;
}
-int WebRtcVideoMediaChannel::GetRecvChannelNum(uint32 ssrc) {
+int WebRtcVideoMediaChannel::GetRecvChannelId(uint32 ssrc) {
if (ssrc == first_receive_ssrc_) {
- return vie_channel_;
+ return default_channel_id_;
}
- int recv_channel = -1;
- RecvChannelMap::iterator it = recv_channels_.find(ssrc);
- if (it == recv_channels_.end()) {
+ int recv_channel_id = kChannelIdUnset;
+ WebRtcVideoChannelRecvInfo* recv_channel = GetRecvChannelBySsrc(ssrc);
+ if (!recv_channel) {
// Check if we have an RTX stream registered on this SSRC.
SsrcMap::iterator rtx_it = rtx_to_primary_ssrc_.find(ssrc);
if (rtx_it != rtx_to_primary_ssrc_.end()) {
if (rtx_it->second == first_receive_ssrc_) {
- recv_channel = vie_channel_;
+ recv_channel_id = default_channel_id_;
} else {
- it = recv_channels_.find(rtx_it->second);
- assert(it != recv_channels_.end());
- recv_channel = it->second->channel_id();
+ recv_channel = GetRecvChannelBySsrc(rtx_it->second);
+ ASSERT(recv_channel != NULL);
+ recv_channel_id = recv_channel->channel_id();
}
}
} else {
- recv_channel = it->second->channel_id();
+ recv_channel_id = recv_channel->channel_id();
}
- return recv_channel;
+ return recv_channel_id;
}
// If the new frame size is different from the send codec size we set on vie,
@@ -3991,11 +3937,15 @@
int screencast_min_bitrate =
options_.screencast_min_bitrate.GetWithDefaultIfUnset(0);
bool leaky_bucket = options_.video_leaky_bucket.GetWithDefaultIfUnset(true);
+ StreamParams* send_params = send_channel->stream_params();
bool reset_send_codec =
- target_width != cur_width || target_height != cur_height ||
+ target_width != cur_width || target_height != cur_height;
+ if (vie_codec.codecType == webrtc::kVideoCodecVP8) {
+ reset_send_codec = reset_send_codec ||
automatic_resize != vie_codec.codecSpecific.VP8.automaticResizeOn ||
enable_denoising != vie_codec.codecSpecific.VP8.denoisingOn ||
vp8_frame_dropping != vie_codec.codecSpecific.VP8.frameDroppingOn;
+ }
if (reset_send_codec) {
// Set the new codec on vie.
@@ -4006,10 +3956,12 @@
vie_codec.minBitrate = target_codec.minBitrate;
vie_codec.maxBitrate = target_codec.maxBitrate;
vie_codec.targetBitrate = 0;
- vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
- vie_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
- vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
- MaybeChangeBitrates(channel_id, &vie_codec);
+ if (vie_codec.codecType == webrtc::kVideoCodecVP8) {
+ vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
+ vie_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
+ vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
+ }
+ SanitizeBitrates(channel_id, &vie_codec);
if (engine()->vie()->codec()->SetSendCodec(channel_id, vie_codec) != 0) {
LOG_RTCERR1(SetSendCodec, channel_id);
@@ -4031,6 +3983,13 @@
engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
leaky_bucket);
}
+ // TODO(sriniv): SetSendCodec already sets ssrc's like below.
+ // Consider removing.
+ if (send_params) {
+ if (!SetSendSsrcs(channel_id, *send_params, target_codec)) {
+ return false;
+ }
+ }
if (reset) {
*reset = true;
}
@@ -4040,7 +3999,7 @@
return true;
}
-void WebRtcVideoMediaChannel::MaybeChangeBitrates(
+void WebRtcVideoMediaChannel::SanitizeBitrates(
int channel_id, webrtc::VideoCodec* codec) {
codec->minBitrate = GetBitrate(codec->minBitrate, kMinVideoBitrate);
codec->startBitrate = GetBitrate(codec->startBitrate, kStartVideoBitrate);
@@ -4079,7 +4038,7 @@
}
}
-void WebRtcVideoMediaChannel::OnMessage(talk_base::Message* msg) {
+void WebRtcVideoMediaChannel::OnMessage(rtc::Message* msg) {
FlushBlackFrameData* black_frame_data =
static_cast<FlushBlackFrameData*>(msg->pdata);
FlushBlackFrame(black_frame_data->ssrc, black_frame_data->timestamp);
@@ -4088,14 +4047,14 @@
int WebRtcVideoMediaChannel::SendPacket(int channel, const void* data,
int len) {
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return MediaChannel::SendPacket(&packet) ? len : -1;
}
int WebRtcVideoMediaChannel::SendRTCPPacket(int channel,
const void* data,
int len) {
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return MediaChannel::SendRtcp(&packet) ? len : -1;
}
@@ -4107,17 +4066,17 @@
timestamp);
const int delay_ms = static_cast<int>(
2 * cricket::VideoFormat::FpsToInterval(framerate) *
- talk_base::kNumMillisecsPerSec / talk_base::kNumNanosecsPerSec);
+ rtc::kNumMillisecsPerSec / rtc::kNumNanosecsPerSec);
worker_thread()->PostDelayed(delay_ms, this, 0, black_frame_data);
}
}
void WebRtcVideoMediaChannel::FlushBlackFrame(uint32 ssrc, int64 timestamp) {
- WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
+ WebRtcVideoChannelSendInfo* send_channel = GetSendChannelBySsrc(ssrc);
if (!send_channel) {
return;
}
- talk_base::scoped_ptr<const VideoFrame> black_frame_ptr;
+ rtc::scoped_ptr<const VideoFrame> black_frame_ptr;
const WebRtcLocalStreamInfo* channel_stream_info =
send_channel->local_stream_info();
@@ -4185,34 +4144,80 @@
return SetHeaderExtension(setter, channel_id, extension);
}
-bool WebRtcVideoMediaChannel::SetLocalRtxSsrc(int channel_id,
- const StreamParams& send_params,
- uint32 primary_ssrc,
- int stream_idx) {
- uint32 rtx_ssrc = 0;
- bool has_rtx = send_params.GetFidSsrc(primary_ssrc, &rtx_ssrc);
- if (has_rtx && engine()->vie()->rtp()->SetLocalSSRC(
- channel_id, rtx_ssrc, webrtc::kViEStreamTypeRtx, stream_idx) != 0) {
- LOG_RTCERR4(SetLocalSSRC, channel_id, rtx_ssrc,
- webrtc::kViEStreamTypeRtx, stream_idx);
+bool WebRtcVideoMediaChannel::SetPrimaryAndRtxSsrcs(
+ int channel_id, int idx, uint32 primary_ssrc,
+ const StreamParams& send_params) {
+ LOG(LS_INFO) << "Set primary ssrc " << primary_ssrc
+ << " on channel " << channel_id << " idx " << idx;
+ if (engine()->vie()->rtp()->SetLocalSSRC(
+ channel_id, primary_ssrc, webrtc::kViEStreamTypeNormal, idx) != 0) {
+ LOG_RTCERR4(SetLocalSSRC,
+ channel_id, primary_ssrc, webrtc::kViEStreamTypeNormal, idx);
return false;
}
+
+ uint32 rtx_ssrc = 0;
+ if (send_params.GetFidSsrc(primary_ssrc, &rtx_ssrc)) {
+ LOG(LS_INFO) << "Set rtx ssrc " << rtx_ssrc
+ << " on channel " << channel_id << " idx " << idx;
+ if (engine()->vie()->rtp()->SetLocalSSRC(
+ channel_id, rtx_ssrc, webrtc::kViEStreamTypeRtx, idx) != 0) {
+ LOG_RTCERR4(SetLocalSSRC,
+ channel_id, rtx_ssrc, webrtc::kViEStreamTypeRtx, idx);
+ return false;
+ }
+ }
return true;
}
+bool WebRtcVideoMediaChannel::SetLimitedNumberOfSendSsrcs(
+ int channel_id, const StreamParams& sp, size_t limit) {
+ const SsrcGroup* sim_group = sp.get_ssrc_group(kSimSsrcGroupSemantics);
+ if (!sim_group || limit == 1) {
+ return SetPrimaryAndRtxSsrcs(channel_id, 0, sp.first_ssrc(), sp);
+ }
+
+ std::vector<uint32> ssrcs = sim_group->ssrcs;
+ for (size_t i = 0; i < ssrcs.size() && i < limit; ++i) {
+ if (!SetPrimaryAndRtxSsrcs(channel_id, static_cast<int>(i), ssrcs[i], sp)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool WebRtcVideoMediaChannel::SetSendSsrcs(
+ int channel_id, const StreamParams& sp,
+ const webrtc::VideoCodec& codec) {
+ // TODO(pthatcher): Support more than one primary SSRC per stream.
+ return SetLimitedNumberOfSendSsrcs(channel_id, sp, 1);
+}
+
void WebRtcVideoMediaChannel::MaybeConnectCapturer(VideoCapturer* capturer) {
- if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
+ if (capturer && GetSendChannelNum(capturer) == 1) {
capturer->SignalVideoFrame.connect(this,
&WebRtcVideoMediaChannel::SendFrame);
}
}
void WebRtcVideoMediaChannel::MaybeDisconnectCapturer(VideoCapturer* capturer) {
- if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
+ if (capturer && GetSendChannelNum(capturer) == 1) {
capturer->SignalVideoFrame.disconnect(this);
}
}
+void WebRtcVideoMediaChannel::SetReceiverReportSsrc(uint32 ssrc) {
+ for (RecvChannelMap::const_iterator it = recv_channels_.begin();
+ it != recv_channels_.end(); ++it) {
+ int channel_id = it->second->channel_id();
+ if (engine()->vie()->rtp()->SetLocalSSRC(channel_id, ssrc) != 0) {
+ LOG_RTCERR2(SetLocalSSRC, channel_id, ssrc);
+ ASSERT(false);
+ }
+ }
+ receiver_report_ssrc_ = ssrc;
+}
+
} // namespace cricket
#endif // HAVE_WEBRTC_VIDEO
diff --git a/media/webrtc/webrtcvideoengine.h b/media/webrtc/webrtcvideoengine.h
index 775f4e4..6f939d2 100644
--- a/media/webrtc/webrtcvideoengine.h
+++ b/media/webrtc/webrtcvideoengine.h
@@ -31,21 +31,23 @@
#include <map>
#include <vector>
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/videocommon.h"
#include "talk/media/webrtc/webrtccommon.h"
#include "talk/media/webrtc/webrtcexport.h"
#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
#include "talk/session/media/channel.h"
+#include "webrtc/base/scoped_ptr.h"
#include "webrtc/video_engine/include/vie_base.h"
#if !defined(LIBPEERCONNECTION_LIB) && \
!defined(LIBPEERCONNECTION_IMPLEMENTATION)
+// If you hit this, then you've tried to include this header from outside
+// a shared library. An instance of this class must only be created from
+// within the library that actually implements it.
#error "Bogus include."
#endif
-
namespace webrtc {
class VideoCaptureModule;
class VideoDecoder;
@@ -55,9 +57,9 @@
class ViERTP_RTCP;
}
-namespace talk_base {
+namespace rtc {
class CpuMonitor;
-} // namespace talk_base
+} // namespace rtc
namespace cricket {
@@ -94,29 +96,28 @@
// TODO(juberti): Remove the 3-arg ctor once fake tracing is implemented.
WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
ViEWrapper* vie_wrapper,
- talk_base::CpuMonitor* cpu_monitor);
+ rtc::CpuMonitor* cpu_monitor);
WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
ViEWrapper* vie_wrapper,
ViETraceWrapper* tracing,
- talk_base::CpuMonitor* cpu_monitor);
- ~WebRtcVideoEngine();
+ rtc::CpuMonitor* cpu_monitor);
+ virtual ~WebRtcVideoEngine();
// Basic video engine implementation.
- bool Init(talk_base::Thread* worker_thread);
+ bool Init(rtc::Thread* worker_thread);
void Terminate();
int GetCapabilities();
- bool SetOptions(const VideoOptions &options);
bool SetDefaultEncoderConfig(const VideoEncoderConfig& config);
VideoEncoderConfig GetDefaultEncoderConfig() const;
- WebRtcVideoMediaChannel* CreateChannel(VoiceMediaChannel* voice_channel);
+ virtual WebRtcVideoMediaChannel* CreateChannel(
+ VoiceMediaChannel* voice_channel);
const std::vector<VideoCodec>& codecs() const;
const std::vector<RtpHeaderExtension>& rtp_header_extensions() const;
void SetLogging(int min_sev, const char* filter);
- bool SetLocalRenderer(VideoRenderer* renderer);
sigslot::repeater2<VideoCapturer*, CaptureState> SignalCaptureStateChange;
// Set the VoiceEngine for A/V sync. This can only be called before Init.
@@ -128,7 +129,8 @@
// Set a WebRtcVideoEncoderFactory for external encoding. Video engine does
// not take the ownership of |encoder_factory|. The caller needs to make sure
// that |encoder_factory| outlives the video engine.
- void SetExternalEncoderFactory(WebRtcVideoEncoderFactory* encoder_factory);
+ virtual void SetExternalEncoderFactory(
+ WebRtcVideoEncoderFactory* encoder_factory);
// Enable the render module with timing control.
bool EnableTimedRender();
@@ -150,7 +152,7 @@
bool IsExternalEncoderCodecType(webrtc::VideoCodecType type) const;
// Functions called by WebRtcVideoMediaChannel.
- talk_base::Thread* worker_thread() { return worker_thread_; }
+ rtc::Thread* worker_thread() { return worker_thread_; }
ViEWrapper* vie() { return vie_wrapper_.get(); }
const VideoFormat& default_codec_format() const {
return default_codec_format_;
@@ -169,7 +171,7 @@
VideoFormat GetStartCaptureFormat() const { return default_codec_format_; }
- talk_base::CpuMonitor* cpu_monitor() { return cpu_monitor_.get(); }
+ rtc::CpuMonitor* cpu_monitor() { return cpu_monitor_.get(); }
protected:
// When a video processor registers with the engine.
@@ -190,12 +192,12 @@
static const VideoCodecPref kVideoCodecPrefs[];
static const VideoFormatPod kVideoFormats[];
- static const VideoFormatPod kDefaultVideoFormat;
+ static const VideoFormatPod kDefaultMaxVideoFormat;
void Construct(ViEWrapper* vie_wrapper,
ViETraceWrapper* tracing,
WebRtcVoiceEngine* voice_engine,
- talk_base::CpuMonitor* cpu_monitor);
+ rtc::CpuMonitor* cpu_monitor);
bool SetDefaultCodec(const VideoCodec& codec);
bool RebuildCodecList(const VideoCodec& max_codec);
void SetTraceFilter(int filter);
@@ -209,12 +211,12 @@
// WebRtcVideoEncoderFactory::Observer implementation.
virtual void OnCodecsAvailable();
- talk_base::Thread* worker_thread_;
- talk_base::scoped_ptr<ViEWrapper> vie_wrapper_;
+ rtc::Thread* worker_thread_;
+ rtc::scoped_ptr<ViEWrapper> vie_wrapper_;
bool vie_wrapper_base_initialized_;
- talk_base::scoped_ptr<ViETraceWrapper> tracing_;
+ rtc::scoped_ptr<ViETraceWrapper> tracing_;
WebRtcVoiceEngine* voice_engine_;
- talk_base::scoped_ptr<webrtc::VideoRender> render_module_;
+ rtc::scoped_ptr<webrtc::VideoRender> render_module_;
WebRtcVideoEncoderFactory* encoder_factory_;
WebRtcVideoDecoderFactory* decoder_factory_;
std::vector<VideoCodec> video_codecs_;
@@ -222,33 +224,30 @@
VideoFormat default_codec_format_;
bool initialized_;
- talk_base::CriticalSection channels_crit_;
+ rtc::CriticalSection channels_crit_;
VideoChannels channels_;
bool capture_started_;
- int local_renderer_w_;
- int local_renderer_h_;
- VideoRenderer* local_renderer_;
- talk_base::scoped_ptr<talk_base::CpuMonitor> cpu_monitor_;
+ rtc::scoped_ptr<rtc::CpuMonitor> cpu_monitor_;
};
-class WebRtcVideoMediaChannel : public talk_base::MessageHandler,
+class WebRtcVideoMediaChannel : public rtc::MessageHandler,
public VideoMediaChannel,
public webrtc::Transport {
public:
WebRtcVideoMediaChannel(WebRtcVideoEngine* engine,
VoiceMediaChannel* voice_channel);
- ~WebRtcVideoMediaChannel();
+ virtual ~WebRtcVideoMediaChannel();
bool Init();
WebRtcVideoEngine* engine() { return engine_; }
VoiceMediaChannel* voice_channel() { return voice_channel_; }
- int video_channel() const { return vie_channel_; }
bool sending() const { return sending_; }
// Public for testing purpose.
- uint32 GetDefaultChannelSsrc();
+ uint32 GetDefaultSendChannelSsrc();
+ int GetDefaultChannelId() const { return default_channel_id_; }
// VideoMediaChannel implementation
virtual bool SetRecvCodecs(const std::vector<VideoCodec> &codecs);
@@ -268,10 +267,10 @@
virtual bool SendIntraFrame();
virtual bool RequestIntraFrame();
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
virtual void OnReadyToSend(bool ready);
virtual bool MuteStream(uint32 ssrc, bool on);
virtual bool SetRecvRtpHeaderExtensions(
@@ -304,13 +303,27 @@
void OnLocalFrameFormat(VideoCapturer* capturer, const VideoFormat* format) {
}
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
protected:
int GetLastEngineError() { return engine()->GetLastEngineError(); }
virtual int SendPacket(int channel, const void* data, int len);
virtual int SendRTCPPacket(int channel, const void* data, int len);
+ // Checks the current bitrate estimate and modifies the bitrates
+ // accordingly, including converting kAutoBandwidth to the correct defaults.
+ virtual void SanitizeBitrates(
+ int channel_id, webrtc::VideoCodec* video_codec);
+ virtual void LogSendCodecChange(const std::string& reason);
+ bool SetPrimaryAndRtxSsrcs(
+ int channel_id, int idx, uint32 primary_ssrc,
+ const StreamParams& send_params);
+ bool SetLimitedNumberOfSendSsrcs(
+ int channel_id, const StreamParams& send_params, size_t limit);
+ virtual bool SetSendSsrcs(
+ int channel_id, const StreamParams& send_params,
+ const webrtc::VideoCodec& codec);
+
private:
typedef std::map<uint32, WebRtcVideoChannelRecvInfo*> RecvChannelMap;
typedef std::map<uint32, WebRtcVideoChannelSendInfo*> SendChannelMap;
@@ -319,14 +332,15 @@
enum MediaDirection { MD_RECV, MD_SEND, MD_SENDRECV };
- // Creates and initializes a ViE channel. When successful |channel_id| will
- // contain the new channel's ID. If |receiving| is true |ssrc| is the
- // remote ssrc. If |sending| is true the ssrc is local ssrc. If both
- // |receiving| and |sending| is true the ssrc must be 0 and the channel will
- // be created as a default channel. The ssrc must be different for receive
- // channels and it must be different for send channels. If the same SSRC is
- // being used for creating channel more than once, this function will fail
- // returning false.
+ // Creates and initializes a ViE channel. When successful
+ // |channel_id| will contain the new channel's ID. If |receiving| is
+ // true |ssrc| is the remote ssrc. If |sending| is true the ssrc is
+ // local ssrc. If both |receiving| and |sending| is true the ssrc
+ // must be kDefaultChannelSsrcKey and the channel will be created as
+ // a default channel. The ssrc must be different for receive
+ // channels and it must be different for send channels. If the same
+ // SSRC is being used for creating channel more than once, this
+ // function will fail returning false.
bool CreateChannel(uint32 ssrc_key, MediaDirection direction,
int* channel_id);
bool CreateUnsignalledRecvChannel(uint32 ssrc_key, int* channel_id);
@@ -339,22 +353,23 @@
bool SetSendCodec(const webrtc::VideoCodec& codec);
bool SetSendCodec(WebRtcVideoChannelSendInfo* send_channel,
const webrtc::VideoCodec& codec);
- void LogSendCodecChange(const std::string& reason);
// Prepares the channel with channel id |info->channel_id()| to receive all
// codecs in |receive_codecs_| and start receive packets.
bool SetReceiveCodecs(WebRtcVideoChannelRecvInfo* info);
- // Returns the channel number that receives the stream with SSRC |ssrc|.
- int GetRecvChannelNum(uint32 ssrc);
+ // Returns the channel ID that receives the stream with SSRC |ssrc|.
+ int GetRecvChannelId(uint32 ssrc);
bool MaybeSetRtxSsrc(const StreamParams& sp, int channel_id);
+ // Create and register an external endcoder if it's possible to do
+ // so and one isn't already registered.
+ bool MaybeRegisterExternalEncoder(
+ WebRtcVideoChannelSendInfo* send_channel,
+ const webrtc::VideoCodec& codec);
// Given captured video frame size, checks if we need to reset vie send codec.
// |reset| is set to whether resetting has happened on vie or not.
// Returns false on error.
bool MaybeResetVieSendCodec(WebRtcVideoChannelSendInfo* send_channel,
int new_width, int new_height, bool is_screencast,
bool* reset);
- // Checks the current bitrate estimate and modifies the bitrates
- // accordingly, including converting kAutoBandwidth to the correct defaults.
- void MaybeChangeBitrates(int channel_id, webrtc::VideoCodec* video_codec);
// Helper function for starting the sending of media on all channels or
// |channel_id|. Note that these two function do not change |sending_|.
bool StartSend();
@@ -366,32 +381,39 @@
bool SendIntraFrame(int channel_id);
bool HasReadySendChannels();
+ bool DefaultSendChannelInUse();
- // Send channel key returns the key corresponding to the provided local SSRC
- // in |key|. The return value is true upon success.
- // If the local ssrc correspond to that of the default channel the key is 0.
- // For all other channels the returned key will be the same as the local ssrc.
- bool GetSendChannelKey(uint32 local_ssrc, uint32* key);
- WebRtcVideoChannelSendInfo* GetSendChannel(uint32 local_ssrc);
- // Creates a new unique key that can be used for inserting a new send channel
- // into |send_channels_|
- bool CreateSendChannelKey(uint32 local_ssrc, uint32* key);
+ // Returns the ssrc key corresponding to the provided local SSRC in
+ // |ssrc_key|. The return value is true upon success. If the local
+ // ssrc correspond to that of the default channel the key is
+ // kDefaultChannelSsrcKey. For all other channels the returned ssrc
+ // key will be the same as the local ssrc. If a stream has more
+ // than one ssrc, the first (corresponding to
+ // StreamParams::first_ssrc()) is used as the key.
+ bool GetSendChannelSsrcKey(uint32 local_ssrc, uint32* ssrc_key);
+ WebRtcVideoChannelSendInfo* GetDefaultSendChannel();
+ WebRtcVideoChannelSendInfo* GetSendChannelBySsrcKey(uint32 ssrc_key);
+ WebRtcVideoChannelSendInfo* GetSendChannelBySsrc(uint32 local_ssrc);
+ // Creates a new unique ssrc key that can be used for inserting a
+ // new send channel into |send_channels_|
+ bool CreateSendChannelSsrcKey(uint32 local_ssrc, uint32* ssrc_key);
// Get the number of the send channels |capturer| registered with.
int GetSendChannelNum(VideoCapturer* capturer);
- bool IsDefaultChannel(int channel_id) const {
- return channel_id == vie_channel_;
+ bool IsDefaultChannelId(int channel_id) const {
+ return channel_id == default_channel_id_;
}
-
bool DeleteSendChannel(uint32 ssrc_key);
+ WebRtcVideoChannelRecvInfo* GetDefaultRecvChannel();
+ WebRtcVideoChannelRecvInfo* GetRecvChannelBySsrc(uint32 ssrc);
+
bool InConferenceMode() const {
return options_.conference_mode.GetWithDefaultIfUnset(false);
}
bool RemoveCapturer(uint32 ssrc);
-
- talk_base::MessageQueue* worker_thread() { return engine_->worker_thread(); }
+ rtc::MessageQueue* worker_thread() { return engine_->worker_thread(); }
void QueueBlackFrame(uint32 ssrc, int64 timestamp, int framerate);
void FlushBlackFrame(uint32 ssrc, int64 timestamp);
@@ -406,10 +428,6 @@
// Signal when cpu adaptation has no further scope to adapt.
void OnCpuAdaptationUnable();
- // Set the local (send-side) RTX SSRC corresponding to primary_ssrc.
- bool SetLocalRtxSsrc(int channel_id, const StreamParams& send_params,
- uint32 primary_ssrc, int stream_idx);
-
// Connect |capturer| to WebRtcVideoMediaChannel if it is only registered
// to one send channel, i.e. the first send channel.
void MaybeConnectCapturer(VideoCapturer* capturer);
@@ -419,20 +437,23 @@
bool RemoveRecvStreamInternal(uint32 ssrc);
+ // Set the ssrc to use for RTCP receiver reports.
+ void SetReceiverReportSsrc(uint32 ssrc);
+
// Global state.
WebRtcVideoEngine* engine_;
VoiceMediaChannel* voice_channel_;
- int vie_channel_;
+ int default_channel_id_;
bool nack_enabled_;
// Receiver Estimated Max Bitrate
bool remb_enabled_;
VideoOptions options_;
// Global recv side state.
- // Note the default channel (vie_channel_), i.e. the send channel
+ // Note the default channel (default_channel_id_), i.e. the send channel
// corresponding to all the receive channels (this must be done for REMB to
// work properly), resides in both recv_channels_ and send_channels_ with the
- // ssrc key 0.
+ // ssrc key kDefaultChannelSsrcKey.
RecvChannelMap recv_channels_; // Contains all receive channels.
// A map from the SSRCs on which RTX packets are received to the media SSRCs
// the RTX packets are associated with. RTX packets will be delivered to the
@@ -446,12 +467,13 @@
std::map<int, int> associated_payload_types_;
bool render_started_;
uint32 first_receive_ssrc_;
+ uint32 receiver_report_ssrc_;
std::vector<RtpHeaderExtension> receive_extensions_;
int num_unsignalled_recv_channels_;
// Global send side state.
SendChannelMap send_channels_;
- talk_base::scoped_ptr<webrtc::VideoCodec> send_codec_;
+ rtc::scoped_ptr<webrtc::VideoCodec> send_codec_;
int send_rtx_type_;
int send_red_type_;
int send_fec_type_;
diff --git a/media/webrtc/webrtcvideoengine2.cc b/media/webrtc/webrtcvideoengine2.cc
index 716c5a8..26e3079 100644
--- a/media/webrtc/webrtcvideoengine2.cc
+++ b/media/webrtc/webrtcvideoengine2.cc
@@ -28,26 +28,21 @@
#ifdef HAVE_WEBRTC_VIDEO
#include "talk/media/webrtc/webrtcvideoengine2.h"
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <math.h>
-
+#include <set>
#include <string>
#include "libyuv/convert_from.h"
-#include "talk/base/buffer.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videorenderer.h"
+#include "talk/media/webrtc/constants.h"
#include "talk/media/webrtc/webrtcvideocapturer.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringutils.h"
#include "webrtc/call.h"
-// TODO(pbos): Move codecs out of modules (webrtc:3070).
-#include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h"
+#include "webrtc/video_encoder.h"
#define UNIMPLEMENTED \
LOG(LS_ERROR) << "Call to unimplemented function " << __FUNCTION__; \
@@ -55,56 +50,24 @@
namespace cricket {
-static const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
-
// This constant is really an on/off, lower-level configurable NACK history
// duration hasn't been implemented.
static const int kNackHistoryMs = 1000;
-static const int kDefaultFramerate = 30;
-static const int kMinVideoBitrate = 50;
-static const int kMaxVideoBitrate = 2000;
-
-static const int kVideoMtu = 1200;
-static const int kVideoRtpBufferSize = 65536;
-
-static const char kVp8PayloadName[] = "VP8";
+static const int kDefaultQpMax = 56;
static const int kDefaultRtcpReceiverReportSsrc = 1;
struct VideoCodecPref {
int payload_type;
+ int width;
+ int height;
const char* name;
int rtx_payload_type;
-} kDefaultVideoCodecPref = {100, kVp8PayloadName, 96};
+} kDefaultVideoCodecPref = {100, 640, 400, kVp8CodecName, 96};
-VideoCodecPref kRedPref = {116, kRedCodecName, -1};
-VideoCodecPref kUlpfecPref = {117, kUlpfecCodecName, -1};
-
-// The formats are sorted by the descending order of width. We use the order to
-// find the next format for CPU and bandwidth adaptation.
-const VideoFormatPod kDefaultVideoFormat = {
- 640, 400, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY};
-const VideoFormatPod kVideoFormats[] = {
- {1280, 800, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {1280, 720, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {960, 600, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {960, 540, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- kDefaultVideoFormat,
- {640, 360, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {640, 480, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {480, 300, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {480, 270, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {480, 360, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {320, 200, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {320, 180, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {320, 240, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {240, 150, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {240, 135, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {240, 180, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {160, 100, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {160, 90, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
- {160, 120, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY}, };
+VideoCodecPref kRedPref = {116, -1, -1, kRedCodecName, -1};
+VideoCodecPref kUlpfecPref = {117, -1, -1, kUlpfecCodecName, -1};
static bool FindFirstMatchingCodec(const std::vector<VideoCodec>& codecs,
const VideoCodec& requested_codec,
@@ -117,49 +80,6 @@
}
return false;
}
-static bool FindBestVideoFormat(int max_width,
- int max_height,
- int aspect_width,
- int aspect_height,
- VideoFormat* video_format) {
- assert(max_width > 0);
- assert(max_height > 0);
- assert(aspect_width > 0);
- assert(aspect_height > 0);
- VideoFormat best_format;
- for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
- const VideoFormat format(kVideoFormats[i]);
-
- // Skip any format that is larger than the local or remote maximums, or
- // smaller than the current best match
- if (format.width > max_width || format.height > max_height ||
- (format.width < best_format.width &&
- format.height < best_format.height)) {
- continue;
- }
-
- // If we don't have any matches yet, this is the best so far.
- if (best_format.width == 0) {
- best_format = format;
- continue;
- }
-
- // Prefer closer aspect ratios i.e:
- // |format| aspect - requested aspect <
- // |best_format| aspect - requested aspect
- if (abs(format.width * aspect_height * best_format.height -
- aspect_width * format.height * best_format.height) <
- abs(best_format.width * aspect_height * format.height -
- aspect_width * format.height * best_format.height)) {
- best_format = format;
- }
- }
- if (best_format.width != 0) {
- *video_format = best_format;
- return true;
- }
- return false;
-}
static void AddDefaultFeedbackParams(VideoCodec* codec) {
const FeedbackParam kFir(kRtcpFbParamCcm, kRtcpFbCcmParamFir);
@@ -177,11 +97,16 @@
FeedbackParam(kRtcpFbParamNack, kParamValueEmpty));
}
+static bool IsRembEnabled(const VideoCodec& codec) {
+ return codec.HasFeedbackParam(
+ FeedbackParam(kRtcpFbParamRemb, kParamValueEmpty));
+}
+
static VideoCodec DefaultVideoCodec() {
VideoCodec default_codec(kDefaultVideoCodecPref.payload_type,
kDefaultVideoCodecPref.name,
- kDefaultVideoFormat.width,
- kDefaultVideoFormat.height,
+ kDefaultVideoCodecPref.width,
+ kDefaultVideoCodecPref.height,
kDefaultFramerate,
0);
AddDefaultFeedbackParams(&default_codec);
@@ -209,6 +134,34 @@
return codecs;
}
+static bool ValidateRtpHeaderExtensionIds(
+ const std::vector<RtpHeaderExtension>& extensions) {
+ std::set<int> extensions_used;
+ for (size_t i = 0; i < extensions.size(); ++i) {
+ if (extensions[i].id < 0 || extensions[i].id >= 15 ||
+ !extensions_used.insert(extensions[i].id).second) {
+ LOG(LS_ERROR) << "RTP extensions are with incorrect or duplicate ids.";
+ return false;
+ }
+ }
+ return true;
+}
+
+static std::vector<webrtc::RtpExtension> FilterRtpExtensions(
+ const std::vector<RtpHeaderExtension>& extensions) {
+ std::vector<webrtc::RtpExtension> webrtc_extensions;
+ for (size_t i = 0; i < extensions.size(); ++i) {
+ // Unsupported extensions will be ignored.
+ if (webrtc::RtpExtension::IsSupported(extensions[i].uri)) {
+ webrtc_extensions.push_back(webrtc::RtpExtension(
+ extensions[i].uri, extensions[i].id));
+ } else {
+ LOG(LS_WARNING) << "Unsupported RTP extension: " << extensions[i].uri;
+ }
+ }
+ return webrtc_extensions;
+}
+
WebRtcVideoEncoderFactory2::~WebRtcVideoEncoderFactory2() {
}
@@ -235,7 +188,7 @@
stream.min_bitrate_bps = min_bitrate * 1000;
stream.target_bitrate_bps = stream.max_bitrate_bps = max_bitrate * 1000;
- int max_qp = 56;
+ int max_qp = kDefaultQpMax;
codec.GetParam(kCodecParamMaxQuantization, &max_qp);
stream.max_qp = max_qp;
std::vector<webrtc::VideoStream> streams;
@@ -247,38 +200,94 @@
const VideoCodec& codec,
const VideoOptions& options) {
assert(SupportsCodec(codec));
- return webrtc::VP8Encoder::Create();
+ if (_stricmp(codec.name.c_str(), kVp8CodecName) == 0) {
+ return webrtc::VideoEncoder::Create(webrtc::VideoEncoder::kVp8);
+ }
+ // This shouldn't happen, we should be able to create encoders for all codecs
+ // we support.
+ assert(false);
+ return NULL;
+}
+
+void* WebRtcVideoEncoderFactory2::CreateVideoEncoderSettings(
+ const VideoCodec& codec,
+ const VideoOptions& options) {
+ assert(SupportsCodec(codec));
+ if (_stricmp(codec.name.c_str(), kVp8CodecName) == 0) {
+ webrtc::VideoCodecVP8* settings = new webrtc::VideoCodecVP8(
+ webrtc::VideoEncoder::GetDefaultVp8Settings());
+ options.video_noise_reduction.Get(&settings->denoisingOn);
+ return settings;
+ }
+ return NULL;
+}
+
+void WebRtcVideoEncoderFactory2::DestroyVideoEncoderSettings(
+ const VideoCodec& codec,
+ void* encoder_settings) {
+ assert(SupportsCodec(codec));
+ if (encoder_settings == NULL) {
+ return;
+ }
+ if (_stricmp(codec.name.c_str(), kVp8CodecName) == 0) {
+ delete reinterpret_cast<webrtc::VideoCodecVP8*>(encoder_settings);
+ }
}
bool WebRtcVideoEncoderFactory2::SupportsCodec(const VideoCodec& codec) {
- return _stricmp(codec.name.c_str(), kVp8PayloadName) == 0;
+ return _stricmp(codec.name.c_str(), kVp8CodecName) == 0;
}
-WebRtcVideoEngine2::WebRtcVideoEngine2() {
- // Construct without a factory or voice engine.
- Construct(NULL, NULL, new talk_base::CpuMonitor(NULL));
+DefaultUnsignalledSsrcHandler::DefaultUnsignalledSsrcHandler()
+ : default_recv_ssrc_(0), default_renderer_(NULL) {}
+
+UnsignalledSsrcHandler::Action DefaultUnsignalledSsrcHandler::OnUnsignalledSsrc(
+ VideoMediaChannel* channel,
+ uint32_t ssrc) {
+ if (default_recv_ssrc_ != 0) { // Already one default stream.
+ LOG(LS_WARNING) << "Unknown SSRC, but default receive stream already set.";
+ return kDropPacket;
+ }
+
+ StreamParams sp;
+ sp.ssrcs.push_back(ssrc);
+ LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
+ if (!channel->AddRecvStream(sp)) {
+ LOG(LS_WARNING) << "Could not create default receive stream.";
+ }
+
+ channel->SetRenderer(ssrc, default_renderer_);
+ default_recv_ssrc_ = ssrc;
+ return kDeliverPacket;
}
-WebRtcVideoEngine2::WebRtcVideoEngine2(
- WebRtcVideoChannelFactory* channel_factory) {
- // Construct without a voice engine.
- Construct(channel_factory, NULL, new talk_base::CpuMonitor(NULL));
+VideoRenderer* DefaultUnsignalledSsrcHandler::GetDefaultRenderer() const {
+ return default_renderer_;
}
-void WebRtcVideoEngine2::Construct(WebRtcVideoChannelFactory* channel_factory,
- WebRtcVoiceEngine* voice_engine,
- talk_base::CpuMonitor* cpu_monitor) {
- LOG(LS_INFO) << "WebRtcVideoEngine2::WebRtcVideoEngine2";
- worker_thread_ = NULL;
- voice_engine_ = voice_engine;
- initialized_ = false;
- capture_started_ = false;
- cpu_monitor_.reset(cpu_monitor);
- channel_factory_ = channel_factory;
+void DefaultUnsignalledSsrcHandler::SetDefaultRenderer(
+ VideoMediaChannel* channel,
+ VideoRenderer* renderer) {
+ default_renderer_ = renderer;
+ if (default_recv_ssrc_ != 0) {
+ channel->SetRenderer(default_recv_ssrc_, default_renderer_);
+ }
+}
- video_codecs_ = DefaultVideoCodecs();
- default_codec_format_ = VideoFormat(kDefaultVideoFormat);
-
+WebRtcVideoEngine2::WebRtcVideoEngine2()
+ : worker_thread_(NULL),
+ voice_engine_(NULL),
+ video_codecs_(DefaultVideoCodecs()),
+ default_codec_format_(kDefaultVideoCodecPref.width,
+ kDefaultVideoCodecPref.height,
+ FPS_TO_INTERVAL(kDefaultFramerate),
+ FOURCC_ANY),
+ initialized_(false),
+ cpu_monitor_(new rtc::CpuMonitor(NULL)),
+ channel_factory_(NULL),
+ external_decoder_factory_(NULL),
+ external_encoder_factory_(NULL) {
+ LOG(LS_INFO) << "WebRtcVideoEngine2::WebRtcVideoEngine2()";
rtp_header_extensions_.push_back(
RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
kRtpTimestampOffsetHeaderExtensionDefaultId));
@@ -287,6 +296,11 @@
kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
}
+void WebRtcVideoEngine2::SetChannelFactory(
+ WebRtcVideoChannelFactory* channel_factory) {
+ channel_factory_ = channel_factory;
+}
+
WebRtcVideoEngine2::~WebRtcVideoEngine2() {
LOG(LS_INFO) << "WebRtcVideoEngine2::~WebRtcVideoEngine2";
@@ -295,7 +309,7 @@
}
}
-bool WebRtcVideoEngine2::Init(talk_base::Thread* worker_thread) {
+bool WebRtcVideoEngine2::Init(rtc::Thread* worker_thread) {
LOG(LS_INFO) << "WebRtcVideoEngine2::Init";
worker_thread_ = worker_thread;
ASSERT(worker_thread_ != NULL);
@@ -320,18 +334,23 @@
int WebRtcVideoEngine2::GetCapabilities() { return VIDEO_RECV | VIDEO_SEND; }
-bool WebRtcVideoEngine2::SetOptions(const VideoOptions& options) {
- // TODO(pbos): Do we need this? This is a no-op in the existing
- // WebRtcVideoEngine implementation.
- LOG(LS_VERBOSE) << "SetOptions: " << options.ToString();
- // options_ = options;
- return true;
-}
-
bool WebRtcVideoEngine2::SetDefaultEncoderConfig(
const VideoEncoderConfig& config) {
- // TODO(pbos): Implement. Should be covered by corresponding unit tests.
- LOG(LS_VERBOSE) << "SetDefaultEncoderConfig()";
+ const VideoCodec& codec = config.max_codec;
+ // TODO(pbos): Make use of external encoder factory.
+ if (!GetVideoEncoderFactory()->SupportsCodec(codec)) {
+ LOG(LS_ERROR) << "SetDefaultEncoderConfig, codec not supported:"
+ << codec.ToString();
+ return false;
+ }
+
+ default_codec_format_ =
+ VideoFormat(codec.width,
+ codec.height,
+ VideoFormat::FpsToInterval(codec.framerate),
+ FOURCC_ANY);
+ video_codecs_.clear();
+ video_codecs_.push_back(codec);
return true;
}
@@ -376,14 +395,32 @@
}
}
-bool WebRtcVideoEngine2::EnableTimedRender() {
- // TODO(pbos): Figure out whether this can be removed.
- return true;
+void WebRtcVideoEngine2::SetExternalDecoderFactory(
+ WebRtcVideoDecoderFactory* decoder_factory) {
+ external_decoder_factory_ = decoder_factory;
}
-bool WebRtcVideoEngine2::SetLocalRenderer(VideoRenderer* renderer) {
- // TODO(pbos): Implement or remove. Unclear which stream should be rendered
- // locally even.
+void WebRtcVideoEngine2::SetExternalEncoderFactory(
+ WebRtcVideoEncoderFactory* encoder_factory) {
+ if (external_encoder_factory_ == encoder_factory) {
+ return;
+ }
+ if (external_encoder_factory_) {
+ external_encoder_factory_->RemoveObserver(this);
+ }
+ external_encoder_factory_ = encoder_factory;
+ if (external_encoder_factory_) {
+ external_encoder_factory_->AddObserver(this);
+ }
+
+ // Invoke OnCodecAvailable() here in case the list of codecs is already
+ // available when the encoder factory is installed. If not the encoder
+ // factory will invoke the callback later when the codecs become available.
+ OnCodecsAvailable();
+}
+
+bool WebRtcVideoEngine2::EnableTimedRender() {
+ // TODO(pbos): Figure out whether this can be removed.
return true;
}
@@ -392,17 +429,10 @@
// TODO(pbos): Probe encoder factory to figure out that the codec is supported
// if supported by the encoder factory. Add a corresponding test that fails
// with this code (that doesn't ask the factory).
- for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
- const VideoFormat fmt(kVideoFormats[i]);
- if ((in.width != 0 || in.height != 0) &&
- (fmt.width != in.width || fmt.height != in.height)) {
- continue;
- }
- for (size_t j = 0; j < video_codecs_.size(); ++j) {
- VideoCodec codec(video_codecs_[j].id, video_codecs_[j].name, 0, 0, 0, 0);
- if (codec.Matches(in)) {
- return true;
- }
+ for (size_t j = 0; j < video_codecs_.size(); ++j) {
+ VideoCodec codec(video_codecs_[j].id, video_codecs_[j].name, 0, 0, 0, 0);
+ if (codec.Matches(in)) {
+ return true;
}
}
return false;
@@ -416,7 +446,6 @@
const VideoCodec& current,
VideoCodec* out) {
assert(out != NULL);
- // TODO(pbos): Implement.
if (requested.width != requested.height &&
(requested.height == 0 || requested.width == 0)) {
@@ -430,37 +459,26 @@
return false;
}
- // Pick the best quality that is within their and our bounds and has the
- // correct aspect ratio.
- VideoFormat format;
- if (requested.width == 0 && requested.height == 0) {
- // Special case with resolution 0. The channel should not send frames.
- } else {
- int max_width = talk_base::_min(requested.width, matching_codec.width);
- int max_height = talk_base::_min(requested.height, matching_codec.height);
- int aspect_width = max_width;
- int aspect_height = max_height;
- if (current.width > 0 && current.height > 0) {
- aspect_width = current.width;
- aspect_height = current.height;
- }
- if (!FindBestVideoFormat(
- max_width, max_height, aspect_width, aspect_height, &format)) {
- return false;
- }
- }
-
out->id = requested.id;
out->name = requested.name;
out->preference = requested.preference;
out->params = requested.params;
out->framerate =
- talk_base::_min(requested.framerate, matching_codec.framerate);
- out->width = format.width;
- out->height = format.height;
+ rtc::_min(requested.framerate, matching_codec.framerate);
out->params = requested.params;
out->feedback_params = requested.feedback_params;
- return true;
+ out->width = requested.width;
+ out->height = requested.height;
+ if (requested.width == 0 && requested.height == 0) {
+ return true;
+ }
+
+ while (out->width > matching_codec.width) {
+ out->width /= 2;
+ out->height /= 2;
+ }
+
+ return out->width > 0 && out->height > 0;
}
bool WebRtcVideoEngine2::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
@@ -488,6 +506,9 @@
return &default_video_encoder_factory_;
}
+void WebRtcVideoEngine2::OnCodecsAvailable() {
+ // TODO(pbos): Implement.
+}
// Thin map between VideoFrame and an existing webrtc::I420VideoFrame
// to avoid having to copy the rendered VideoFrame prematurely.
// This implementation is only safe to use in a const context and should never
@@ -570,11 +591,11 @@
virtual int64 GetElapsedTime() const OVERRIDE {
// Convert millisecond render time to ns timestamp.
- return frame_->render_time_ms() * talk_base::kNumNanosecsPerMillisec;
+ return frame_->render_time_ms() * rtc::kNumNanosecsPerMillisec;
}
virtual int64 GetTimeStamp() const OVERRIDE {
// Convert 90K rtp timestamp to ns timestamp.
- return (frame_->timestamp() / 90) * talk_base::kNumNanosecsPerMillisec;
+ return (frame_->timestamp() / 90) * rtc::kNumNanosecsPerMillisec;
}
virtual void SetElapsedTime(int64 elapsed_time) OVERRIDE { UNIMPLEMENTED; }
virtual void SetTimeStamp(int64 time_stamp) OVERRIDE { UNIMPLEMENTED; }
@@ -636,8 +657,6 @@
size_t pixel_height,
int64 elapsed_time,
int64 time_stamp) const OVERRIDE {
- // TODO(pbos): Remove WebRtcVideoFrame dependency, and have a non-const
- // version of I420VideoFrame wrapped.
WebRtcVideoFrame* frame = new WebRtcVideoFrame();
frame->InitToBlack(
w, h, pixel_width, pixel_height, elapsed_time, time_stamp);
@@ -648,57 +667,12 @@
const webrtc::I420VideoFrame* const frame_;
};
-WebRtcVideoRenderer::WebRtcVideoRenderer()
- : last_width_(-1), last_height_(-1), renderer_(NULL) {}
-
-void WebRtcVideoRenderer::RenderFrame(const webrtc::I420VideoFrame& frame,
- int time_to_render_ms) {
- talk_base::CritScope crit(&lock_);
- if (renderer_ == NULL) {
- LOG(LS_WARNING) << "VideoReceiveStream not connected to a VideoRenderer.";
- return;
- }
-
- if (frame.width() != last_width_ || frame.height() != last_height_) {
- SetSize(frame.width(), frame.height());
- }
-
- LOG(LS_VERBOSE) << "RenderFrame: (" << frame.width() << "x" << frame.height()
- << ")";
-
- const WebRtcVideoRenderFrame render_frame(&frame);
- renderer_->RenderFrame(&render_frame);
-}
-
-void WebRtcVideoRenderer::SetRenderer(cricket::VideoRenderer* renderer) {
- talk_base::CritScope crit(&lock_);
- renderer_ = renderer;
- if (renderer_ != NULL && last_width_ != -1) {
- SetSize(last_width_, last_height_);
- }
-}
-
-VideoRenderer* WebRtcVideoRenderer::GetRenderer() {
- talk_base::CritScope crit(&lock_);
- return renderer_;
-}
-
-void WebRtcVideoRenderer::SetSize(int width, int height) {
- talk_base::CritScope crit(&lock_);
- if (!renderer_->SetSize(width, height, 0)) {
- LOG(LS_ERROR) << "Could not set renderer size.";
- }
- last_width_ = width;
- last_height_ = height;
-}
-
-// WebRtcVideoChannel2
-
WebRtcVideoChannel2::WebRtcVideoChannel2(
WebRtcVideoEngine2* engine,
VoiceMediaChannel* voice_channel,
WebRtcVideoEncoderFactory2* encoder_factory)
- : encoder_factory_(encoder_factory) {
+ : unsignalled_ssrc_handler_(&default_unsignalled_ssrc_handler_),
+ encoder_factory_(encoder_factory) {
// TODO(pbos): Connect the video and audio with |voice_channel|.
webrtc::Call::Config config(this);
Construct(webrtc::Call::Create(config), engine);
@@ -708,7 +682,8 @@
webrtc::Call* call,
WebRtcVideoEngine2* engine,
WebRtcVideoEncoderFactory2* encoder_factory)
- : encoder_factory_(encoder_factory) {
+ : unsignalled_ssrc_handler_(&default_unsignalled_ssrc_handler_),
+ encoder_factory_(encoder_factory) {
Construct(call, engine);
}
@@ -717,9 +692,15 @@
rtcp_receiver_report_ssrc_ = kDefaultRtcpReceiverReportSsrc;
sending_ = false;
call_.reset(call);
- default_renderer_ = NULL;
default_send_ssrc_ = 0;
- default_recv_ssrc_ = 0;
+
+ SetDefaultOptions();
+}
+
+void WebRtcVideoChannel2::SetDefaultOptions() {
+ options_.video_noise_reduction.Set(true);
+ options_.use_payload_padding.Set(false);
+ options_.suspend_below_min_bitrate.Set(false);
}
WebRtcVideoChannel2::~WebRtcVideoChannel2() {
@@ -730,18 +711,10 @@
delete it->second;
}
- for (std::map<uint32, webrtc::VideoReceiveStream*>::iterator it =
+ for (std::map<uint32, WebRtcVideoReceiveStream*>::iterator it =
receive_streams_.begin();
it != receive_streams_.end();
++it) {
- assert(it->second != NULL);
- call_->DestroyVideoReceiveStream(it->second);
- }
-
- for (std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.begin();
- it != renderers_.end();
- ++it) {
- assert(it->second != NULL);
delete it->second;
}
}
@@ -798,8 +771,6 @@
} // namespace
bool WebRtcVideoChannel2::SetRecvCodecs(const std::vector<VideoCodec>& codecs) {
- // TODO(pbos): Must these receive codecs propagate to existing receive
- // streams?
LOG(LS_INFO) << "SetRecvCodecs: " << CodecVectorToString(codecs);
if (!ValidateCodecFormats(codecs)) {
return false;
@@ -814,7 +785,7 @@
// TODO(pbos): Add a decoder factory which controls supported codecs.
// Blocked on webrtc:2854.
for (size_t i = 0; i < mapped_codecs.size(); ++i) {
- if (_stricmp(mapped_codecs[i].codec.name.c_str(), kVp8PayloadName) != 0) {
+ if (_stricmp(mapped_codecs[i].codec.name.c_str(), kVp8CodecName) != 0) {
LOG(LS_ERROR) << "SetRecvCodecs called with unsupported codec: '"
<< mapped_codecs[i].codec.name << "'";
return false;
@@ -822,6 +793,14 @@
}
recv_codecs_ = mapped_codecs;
+
+ for (std::map<uint32, WebRtcVideoReceiveStream*>::iterator it =
+ receive_streams_.begin();
+ it != receive_streams_.end();
+ ++it) {
+ it->second->SetRecvCodecs(recv_codecs_);
+ }
+
return true;
}
@@ -842,7 +821,13 @@
send_codec_.Set(supported_codecs.front());
LOG(LS_INFO) << "Using codec: " << supported_codecs.front().codec.ToString();
- SetCodecForAllSendStreams(supported_codecs.front());
+ for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
+ send_streams_.begin();
+ it != send_streams_.end();
+ ++it) {
+ assert(it->second != NULL);
+ it->second->SetCodec(supported_codecs.front());
+ }
return true;
}
@@ -888,52 +873,6 @@
return true;
}
-static bool ConfigureSendSsrcs(webrtc::VideoSendStream::Config* config,
- const StreamParams& sp) {
- if (!sp.has_ssrc_groups()) {
- config->rtp.ssrcs = sp.ssrcs;
- return true;
- }
-
- if (sp.get_ssrc_group(kFecSsrcGroupSemantics) != NULL) {
- LOG(LS_ERROR) << "Standalone FEC SSRCs not supported.";
- return false;
- }
-
- // Map RTX SSRCs.
- std::vector<uint32_t> ssrcs;
- std::vector<uint32_t> rtx_ssrcs;
- const SsrcGroup* sim_group = sp.get_ssrc_group(kSimSsrcGroupSemantics);
- if (sim_group == NULL) {
- ssrcs.push_back(sp.first_ssrc());
- uint32_t rtx_ssrc;
- if (!sp.GetFidSsrc(sp.first_ssrc(), &rtx_ssrc)) {
- LOG(LS_ERROR) << "Could not find FID ssrc for primary SSRC '"
- << sp.first_ssrc() << "':" << sp.ToString();
- return false;
- }
- rtx_ssrcs.push_back(rtx_ssrc);
- } else {
- ssrcs = sim_group->ssrcs;
- for (size_t i = 0; i < sim_group->ssrcs.size(); ++i) {
- uint32_t rtx_ssrc;
- if (!sp.GetFidSsrc(sim_group->ssrcs[i], &rtx_ssrc)) {
- continue;
- }
- rtx_ssrcs.push_back(rtx_ssrc);
- }
- }
- if (!rtx_ssrcs.empty() && ssrcs.size() != rtx_ssrcs.size()) {
- LOG(LS_ERROR)
- << "RTX SSRCs exist, but don't cover all SSRCs (unsupported): "
- << sp.ToString();
- return false;
- }
- config->rtp.rtx.ssrcs = rtx_ssrcs;
- config->rtp.ssrcs = ssrcs;
- return true;
-}
-
bool WebRtcVideoChannel2::AddSendStream(const StreamParams& sp) {
LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
if (sp.ssrcs.empty()) {
@@ -950,58 +889,25 @@
return false;
}
- webrtc::VideoSendStream::Config config = call_->GetDefaultSendConfig();
-
- if (!ConfigureSendSsrcs(&config, sp)) {
+ std::vector<uint32> primary_ssrcs;
+ sp.GetPrimarySsrcs(&primary_ssrcs);
+ std::vector<uint32> rtx_ssrcs;
+ sp.GetFidSsrcs(primary_ssrcs, &rtx_ssrcs);
+ if (!rtx_ssrcs.empty() && primary_ssrcs.size() != rtx_ssrcs.size()) {
+ LOG(LS_ERROR)
+ << "RTX SSRCs exist, but don't cover all SSRCs (unsupported): "
+ << sp.ToString();
return false;
}
- VideoCodecSettings codec_settings;
- if (!send_codec_.Get(&codec_settings)) {
- // TODO(pbos): Set up a temporary fake encoder for VideoSendStream instead
- // of setting default codecs not to break CreateEncoderSettings.
- SetSendCodecs(DefaultVideoCodecs());
- assert(send_codec_.IsSet());
- send_codec_.Get(&codec_settings);
- // This is only to bring up defaults to make VideoSendStream setup easier
- // and avoid complexity. We still don't want to allow sending with the
- // default codec.
- send_codec_.Clear();
- }
-
- // CreateEncoderSettings will allocate a suitable VideoEncoder instance
- // matching current settings.
- std::vector<webrtc::VideoStream> video_streams =
- encoder_factory_->CreateVideoStreams(
- codec_settings.codec, options_, config.rtp.ssrcs.size());
- if (video_streams.empty()) {
- return false;
- }
-
- config.encoder_settings.encoder =
- encoder_factory_->CreateVideoEncoder(codec_settings.codec, options_);
- config.encoder_settings.payload_name = codec_settings.codec.name;
- config.encoder_settings.payload_type = codec_settings.codec.id;
- config.rtp.c_name = sp.cname;
- config.rtp.fec = codec_settings.fec;
- if (!config.rtp.rtx.ssrcs.empty()) {
- config.rtp.rtx.payload_type = codec_settings.rtx_payload_type;
- }
-
- config.rtp.extensions = send_rtp_extensions_;
-
- if (IsNackEnabled(codec_settings.codec)) {
- config.rtp.nack.rtp_history_ms = kNackHistoryMs;
- }
- config.rtp.max_packet_size = kVideoMtu;
-
WebRtcVideoSendStream* stream =
new WebRtcVideoSendStream(call_.get(),
- config,
+ encoder_factory_,
options_,
- codec_settings.codec,
- video_streams,
- encoder_factory_);
+ send_codec_,
+ sp,
+ send_rtp_extensions_);
+
send_streams_[ssrc] = stream;
if (rtcp_receiver_report_ssrc_ == kDefaultRtcpReceiverReportSsrc) {
@@ -1052,9 +958,6 @@
uint32 ssrc = sp.first_ssrc();
assert(ssrc != 0); // TODO(pbos): Is this ever valid?
- if (default_recv_ssrc_ == 0) {
- default_recv_ssrc_ = ssrc;
- }
// TODO(pbos): Check if any of the SSRCs overlap.
if (receive_streams_.find(ssrc) != receive_streams_.end()) {
@@ -1062,130 +965,83 @@
return false;
}
- webrtc::VideoReceiveStream::Config config = call_->GetDefaultReceiveConfig();
- config.rtp.remote_ssrc = ssrc;
- config.rtp.local_ssrc = rtcp_receiver_report_ssrc_;
+ webrtc::VideoReceiveStream::Config config;
+ ConfigureReceiverRtp(&config, sp);
+ receive_streams_[ssrc] =
+ new WebRtcVideoReceiveStream(call_.get(), config, recv_codecs_);
- if (IsNackEnabled(recv_codecs_.begin()->codec)) {
- config.rtp.nack.rtp_history_ms = kNackHistoryMs;
- }
- config.rtp.remb = true;
- config.rtp.extensions = recv_rtp_extensions_;
+ return true;
+}
+
+void WebRtcVideoChannel2::ConfigureReceiverRtp(
+ webrtc::VideoReceiveStream::Config* config,
+ const StreamParams& sp) const {
+ uint32 ssrc = sp.first_ssrc();
+
+ config->rtp.remote_ssrc = ssrc;
+ config->rtp.local_ssrc = rtcp_receiver_report_ssrc_;
+
+ config->rtp.extensions = recv_rtp_extensions_;
+
// TODO(pbos): This protection is against setting the same local ssrc as
// remote which is not permitted by the lower-level API. RTCP requires a
// corresponding sender SSRC. Figure out what to do when we don't have
// (receive-only) or know a good local SSRC.
- if (config.rtp.remote_ssrc == config.rtp.local_ssrc) {
- if (config.rtp.local_ssrc != kDefaultRtcpReceiverReportSsrc) {
- config.rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc;
+ if (config->rtp.remote_ssrc == config->rtp.local_ssrc) {
+ if (config->rtp.local_ssrc != kDefaultRtcpReceiverReportSsrc) {
+ config->rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc;
} else {
- config.rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc + 1;
+ config->rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc + 1;
}
}
- bool default_renderer_used = false;
- for (std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.begin();
- it != renderers_.end();
- ++it) {
- if (it->second->GetRenderer() == default_renderer_) {
- default_renderer_used = true;
+
+ for (size_t i = 0; i < recv_codecs_.size(); ++i) {
+ if (recv_codecs_[i].codec.id == kDefaultVideoCodecPref.payload_type) {
+ config->rtp.fec = recv_codecs_[i].fec;
+ uint32 rtx_ssrc;
+ if (recv_codecs_[i].rtx_payload_type != -1 &&
+ sp.GetFidSsrc(ssrc, &rtx_ssrc)) {
+ config->rtp.rtx[kDefaultVideoCodecPref.payload_type].ssrc = rtx_ssrc;
+ config->rtp.rtx[kDefaultVideoCodecPref.payload_type].payload_type =
+ recv_codecs_[i].rtx_payload_type;
+ }
break;
}
}
- assert(renderers_[ssrc] == NULL);
- renderers_[ssrc] = new WebRtcVideoRenderer();
- if (!default_renderer_used) {
- renderers_[ssrc]->SetRenderer(default_renderer_);
- }
- config.renderer = renderers_[ssrc];
-
- {
- // TODO(pbos): Base receive codecs off recv_codecs_ and set up using a
- // DecoderFactory similar to send side. Pending webrtc:2854.
- // Also set up default codecs if there's nothing in recv_codecs_.
- webrtc::VideoCodec codec;
- memset(&codec, 0, sizeof(codec));
-
- codec.plType = kDefaultVideoCodecPref.payload_type;
- strcpy(codec.plName, kDefaultVideoCodecPref.name);
- codec.codecType = webrtc::kVideoCodecVP8;
- codec.codecSpecific.VP8.resilience = webrtc::kResilientStream;
- codec.codecSpecific.VP8.numberOfTemporalLayers = 1;
- codec.codecSpecific.VP8.denoisingOn = true;
- codec.codecSpecific.VP8.errorConcealmentOn = false;
- codec.codecSpecific.VP8.automaticResizeOn = false;
- codec.codecSpecific.VP8.frameDroppingOn = true;
- codec.codecSpecific.VP8.keyFrameInterval = 3000;
- // Bitrates don't matter and are ignored for the receiver. This is put in to
- // have the current underlying implementation accept the VideoCodec.
- codec.minBitrate = codec.startBitrate = codec.maxBitrate = 300;
- config.codecs.push_back(codec);
- for (size_t i = 0; i < recv_codecs_.size(); ++i) {
- if (recv_codecs_[i].codec.id == codec.plType) {
- config.rtp.fec = recv_codecs_[i].fec;
- uint32 rtx_ssrc;
- if (recv_codecs_[i].rtx_payload_type != -1 &&
- sp.GetFidSsrc(ssrc, &rtx_ssrc)) {
- config.rtp.rtx[codec.plType].ssrc = rtx_ssrc;
- config.rtp.rtx[codec.plType].payload_type =
- recv_codecs_[i].rtx_payload_type;
- }
- break;
- }
- }
- }
-
- webrtc::VideoReceiveStream* receive_stream =
- call_->CreateVideoReceiveStream(config);
- assert(receive_stream != NULL);
-
- receive_streams_[ssrc] = receive_stream;
- receive_stream->Start();
-
- return true;
}
bool WebRtcVideoChannel2::RemoveRecvStream(uint32 ssrc) {
LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
if (ssrc == 0) {
- ssrc = default_recv_ssrc_;
+ LOG(LS_ERROR) << "RemoveRecvStream with 0 ssrc is not supported.";
+ return false;
}
- std::map<uint32, webrtc::VideoReceiveStream*>::iterator stream =
+ std::map<uint32, WebRtcVideoReceiveStream*>::iterator stream =
receive_streams_.find(ssrc);
if (stream == receive_streams_.end()) {
LOG(LS_ERROR) << "Stream not found for ssrc: " << ssrc;
return false;
}
- call_->DestroyVideoReceiveStream(stream->second);
+ delete stream->second;
receive_streams_.erase(stream);
- std::map<uint32, WebRtcVideoRenderer*>::iterator renderer =
- renderers_.find(ssrc);
- assert(renderer != renderers_.end());
- delete renderer->second;
- renderers_.erase(renderer);
-
- if (ssrc == default_recv_ssrc_) {
- default_recv_ssrc_ = 0;
- }
-
return true;
}
bool WebRtcVideoChannel2::SetRenderer(uint32 ssrc, VideoRenderer* renderer) {
LOG(LS_INFO) << "SetRenderer: ssrc:" << ssrc << " "
<< (renderer ? "(ptr)" : "NULL");
- bool is_default_ssrc = false;
if (ssrc == 0) {
- is_default_ssrc = true;
- ssrc = default_recv_ssrc_;
- default_renderer_ = renderer;
+ default_unsignalled_ssrc_handler_.SetDefaultRenderer(this, renderer);
+ return true;
}
- std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.find(ssrc);
- if (it == renderers_.end()) {
- return is_default_ssrc;
+ std::map<uint32, WebRtcVideoReceiveStream*>::iterator it =
+ receive_streams_.find(ssrc);
+ if (it == receive_streams_.end()) {
+ return false;
}
it->second->SetRenderer(renderer);
@@ -1194,15 +1050,13 @@
bool WebRtcVideoChannel2::GetRenderer(uint32 ssrc, VideoRenderer** renderer) {
if (ssrc == 0) {
- if (default_renderer_ == NULL) {
- return false;
- }
- *renderer = default_renderer_;
- return true;
+ *renderer = default_unsignalled_ssrc_handler_.GetDefaultRenderer();
+ return *renderer != NULL;
}
- std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.find(ssrc);
- if (it == renderers_.end()) {
+ std::map<uint32, WebRtcVideoReceiveStream*>::iterator it =
+ receive_streams_.find(ssrc);
+ if (it == receive_streams_.end()) {
return false;
}
*renderer = it->second->GetRenderer();
@@ -1211,10 +1065,36 @@
bool WebRtcVideoChannel2::GetStats(const StatsOptions& options,
VideoMediaInfo* info) {
- // TODO(pbos): Implement.
+ info->Clear();
+ FillSenderStats(info);
+ FillReceiverStats(info);
+ FillBandwidthEstimationStats(info);
return true;
}
+void WebRtcVideoChannel2::FillSenderStats(VideoMediaInfo* video_media_info) {
+ for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
+ send_streams_.begin();
+ it != send_streams_.end();
+ ++it) {
+ video_media_info->senders.push_back(it->second->GetVideoSenderInfo());
+ }
+}
+
+void WebRtcVideoChannel2::FillReceiverStats(VideoMediaInfo* video_media_info) {
+ for (std::map<uint32, WebRtcVideoReceiveStream*>::iterator it =
+ receive_streams_.begin();
+ it != receive_streams_.end();
+ ++it) {
+ video_media_info->receivers.push_back(it->second->GetVideoReceiverInfo());
+ }
+}
+
+void WebRtcVideoChannel2::FillBandwidthEstimationStats(
+ VideoMediaInfo* video_media_info) {
+ // TODO(pbos): Implement.
+}
+
bool WebRtcVideoChannel2::SetCapturer(uint32 ssrc, VideoCapturer* capturer) {
LOG(LS_INFO) << "SetCapturer: " << ssrc << " -> "
<< (capturer != NULL ? "(capturer)" : "NULL");
@@ -1239,8 +1119,8 @@
}
void WebRtcVideoChannel2::OnPacketReceived(
- talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {
const webrtc::PacketReceiver::DeliveryStatus delivery_result =
call_->Receiver()->DeliverPacket(
reinterpret_cast<const uint8_t*>(packet->data()), packet->length());
@@ -1254,32 +1134,30 @@
}
uint32 ssrc = 0;
- if (default_recv_ssrc_ != 0) { // Already one default stream.
- LOG(LS_WARNING) << "Unknown SSRC, but default receive stream already set.";
- return;
- }
-
if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc)) {
return;
}
- StreamParams sp;
- sp.ssrcs.push_back(ssrc);
- LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
- AddRecvStream(sp);
+ // TODO(pbos): Make sure that the unsignalled SSRC uses the video payload.
+ // Also figure out whether RTX needs to be handled.
+ switch (unsignalled_ssrc_handler_->OnUnsignalledSsrc(this, ssrc)) {
+ case UnsignalledSsrcHandler::kDropPacket:
+ return;
+ case UnsignalledSsrcHandler::kDeliverPacket:
+ break;
+ }
if (call_->Receiver()->DeliverPacket(
reinterpret_cast<const uint8_t*>(packet->data()), packet->length()) !=
webrtc::PacketReceiver::DELIVERY_OK) {
- LOG(LS_WARNING) << "Failed to deliver RTP packet after creating default "
- "receiver.";
+ LOG(LS_WARNING) << "Failed to deliver RTP packet on re-delivery.";
return;
}
}
void WebRtcVideoChannel2::OnRtcpReceived(
- talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {
if (call_->Receiver()->DeliverPacket(
reinterpret_cast<const uint8_t*>(packet->data()), packet->length()) !=
webrtc::PacketReceiver::DELIVERY_OK) {
@@ -1288,7 +1166,9 @@
}
void WebRtcVideoChannel2::OnReadyToSend(bool ready) {
- LOG(LS_VERBOSE) << "OnReadySend: " << (ready ? "Ready." : "Not ready.");
+ LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
+ call_->SignalNetworkState(ready ? webrtc::Call::kNetworkUp
+ : webrtc::Call::kNetworkDown);
}
bool WebRtcVideoChannel2::MuteStream(uint32 ssrc, bool mute) {
@@ -1299,21 +1179,25 @@
LOG(LS_ERROR) << "No sending stream on ssrc " << ssrc;
return false;
}
- return send_streams_[ssrc]->MuteStream(mute);
+
+ send_streams_[ssrc]->MuteStream(mute);
+ return true;
}
bool WebRtcVideoChannel2::SetRecvRtpHeaderExtensions(
const std::vector<RtpHeaderExtension>& extensions) {
LOG(LS_INFO) << "SetRecvRtpHeaderExtensions: "
<< RtpExtensionsToString(extensions);
- std::vector<webrtc::RtpExtension> webrtc_extensions;
- for (size_t i = 0; i < extensions.size(); ++i) {
- // TODO(pbos): Make sure we don't pass unsupported extensions!
- webrtc::RtpExtension webrtc_extension(extensions[i].uri.c_str(),
- extensions[i].id);
- webrtc_extensions.push_back(webrtc_extension);
+ if (!ValidateRtpHeaderExtensionIds(extensions))
+ return false;
+
+ recv_rtp_extensions_ = FilterRtpExtensions(extensions);
+ for (std::map<uint32, WebRtcVideoReceiveStream*>::iterator it =
+ receive_streams_.begin();
+ it != receive_streams_.end();
+ ++it) {
+ it->second->SetRtpExtensions(recv_rtp_extensions_);
}
- recv_rtp_extensions_ = webrtc_extensions;
return true;
}
@@ -1321,14 +1205,16 @@
const std::vector<RtpHeaderExtension>& extensions) {
LOG(LS_INFO) << "SetSendRtpHeaderExtensions: "
<< RtpExtensionsToString(extensions);
- std::vector<webrtc::RtpExtension> webrtc_extensions;
- for (size_t i = 0; i < extensions.size(); ++i) {
- // TODO(pbos): Make sure we don't pass unsupported extensions!
- webrtc::RtpExtension webrtc_extension(extensions[i].uri.c_str(),
- extensions[i].id);
- webrtc_extensions.push_back(webrtc_extension);
+ if (!ValidateRtpHeaderExtensionIds(extensions))
+ return false;
+
+ send_rtp_extensions_ = FilterRtpExtensions(extensions);
+ for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
+ send_streams_.begin();
+ it != send_streams_.end();
+ ++it) {
+ it->second->SetRtpExtensions(send_rtp_extensions_);
}
- send_rtp_extensions_ = webrtc_extensions;
return true;
}
@@ -1347,6 +1233,12 @@
bool WebRtcVideoChannel2::SetOptions(const VideoOptions& options) {
LOG(LS_VERBOSE) << "SetOptions: " << options.ToString();
options_.SetAll(options);
+ for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
+ send_streams_.begin();
+ it != send_streams_.end();
+ ++it) {
+ it->second->SetOptions(options_);
+ }
return true;
}
@@ -1354,14 +1246,14 @@
MediaChannel::SetInterface(iface);
// Set the RTP recv/send buffer to a bigger size
MediaChannel::SetOption(NetworkInterface::ST_RTP,
- talk_base::Socket::OPT_RCVBUF,
+ rtc::Socket::OPT_RCVBUF,
kVideoRtpBufferSize);
// TODO(sriniv): Remove or re-enable this.
// As part of b/8030474, send-buffer is size now controlled through
// portallocator flags.
// network_interface_->SetOption(NetworkInterface::ST_RTP,
- // talk_base::Socket::OPT_SNDBUF,
+ // rtc::Socket::OPT_SNDBUF,
// kVideoRtpBufferSize);
}
@@ -1369,17 +1261,17 @@
// TODO(pbos): Implement.
}
-void WebRtcVideoChannel2::OnMessage(talk_base::Message* msg) {
+void WebRtcVideoChannel2::OnMessage(rtc::Message* msg) {
// Ignored.
}
bool WebRtcVideoChannel2::SendRtp(const uint8_t* data, size_t len) {
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return MediaChannel::SendPacket(&packet);
}
bool WebRtcVideoChannel2::SendRtcp(const uint8_t* data, size_t len) {
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return MediaChannel::SendRtcp(&packet);
}
@@ -1401,53 +1293,47 @@
}
}
-void WebRtcVideoChannel2::SetCodecForAllSendStreams(
- const WebRtcVideoChannel2::VideoCodecSettings& codec) {
- for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
- send_streams_.begin();
- it != send_streams_.end();
- ++it) {
- assert(it->second != NULL);
- it->second->SetCodec(options_, codec);
- }
-}
-
WebRtcVideoChannel2::WebRtcVideoSendStream::VideoSendStreamParameters::
VideoSendStreamParameters(
const webrtc::VideoSendStream::Config& config,
const VideoOptions& options,
- const VideoCodec& codec,
- const std::vector<webrtc::VideoStream>& video_streams)
- : config(config),
- options(options),
- codec(codec),
- video_streams(video_streams) {
+ const Settable<VideoCodecSettings>& codec_settings)
+ : config(config), options(options), codec_settings(codec_settings) {
}
WebRtcVideoChannel2::WebRtcVideoSendStream::WebRtcVideoSendStream(
webrtc::Call* call,
- const webrtc::VideoSendStream::Config& config,
+ WebRtcVideoEncoderFactory2* encoder_factory,
const VideoOptions& options,
- const VideoCodec& codec,
- const std::vector<webrtc::VideoStream>& video_streams,
- WebRtcVideoEncoderFactory2* encoder_factory)
+ const Settable<VideoCodecSettings>& codec_settings,
+ const StreamParams& sp,
+ const std::vector<webrtc::RtpExtension>& rtp_extensions)
: call_(call),
- parameters_(config, options, codec, video_streams),
encoder_factory_(encoder_factory),
- capturer_(NULL),
stream_(NULL),
+ parameters_(webrtc::VideoSendStream::Config(), options, codec_settings),
+ capturer_(NULL),
sending_(false),
- muted_(false),
- format_(static_cast<int>(video_streams.back().height),
- static_cast<int>(video_streams.back().width),
- VideoFormat::FpsToInterval(video_streams.back().max_framerate),
- FOURCC_I420) {
- RecreateWebRtcStream();
+ muted_(false) {
+ parameters_.config.rtp.max_packet_size = kVideoMtu;
+
+ sp.GetPrimarySsrcs(¶meters_.config.rtp.ssrcs);
+ sp.GetFidSsrcs(parameters_.config.rtp.ssrcs,
+ ¶meters_.config.rtp.rtx.ssrcs);
+ parameters_.config.rtp.c_name = sp.cname;
+ parameters_.config.rtp.extensions = rtp_extensions;
+
+ VideoCodecSettings params;
+ if (codec_settings.Get(¶ms)) {
+ SetCodec(params);
+ }
}
WebRtcVideoChannel2::WebRtcVideoSendStream::~WebRtcVideoSendStream() {
DisconnectCapturer();
- call_->DestroyVideoSendStream(stream_);
+ if (stream_ != NULL) {
+ call_->DestroyVideoSendStream(stream_);
+ }
delete parameters_.config.encoder_settings.encoder;
}
@@ -1493,30 +1379,35 @@
const VideoFrame* frame) {
LOG(LS_VERBOSE) << "InputFrame: " << frame->GetWidth() << "x"
<< frame->GetHeight();
- bool is_screencast = capturer->IsScreencast();
// Lock before copying, can be called concurrently when swapping input source.
- talk_base::CritScope frame_cs(&frame_lock_);
- if (!muted_) {
- ConvertToI420VideoFrame(*frame, &video_frame_);
- } else {
- // Create a tiny black frame to transmit instead.
- CreateBlackFrame(&video_frame_, 1, 1);
- is_screencast = false;
+ rtc::CritScope frame_cs(&frame_lock_);
+ ConvertToI420VideoFrame(*frame, &video_frame_);
+
+ rtc::CritScope cs(&lock_);
+ if (stream_ == NULL) {
+ LOG(LS_WARNING) << "Capturer inputting frames before send codecs are "
+ "configured, dropping.";
+ return;
}
- talk_base::CritScope cs(&lock_);
if (format_.width == 0) { // Dropping frames.
assert(format_.height == 0);
LOG(LS_VERBOSE) << "VideoFormat 0x0 set, Dropping frame.";
return;
}
- // Reconfigure codec if necessary.
- if (is_screencast) {
- SetDimensions(video_frame_.width(), video_frame_.height());
+ if (muted_) {
+ // Create a black frame to transmit instead.
+ CreateBlackFrame(&video_frame_,
+ static_cast<int>(frame->GetWidth()),
+ static_cast<int>(frame->GetHeight()));
}
+ // Reconfigure codec if necessary.
+ SetDimensions(
+ video_frame_.width(), video_frame_.height(), capturer->IsScreencast());
+
LOG(LS_VERBOSE) << "SwapFrame: " << video_frame_.width() << "x"
<< video_frame_.height() << " -> (codec) "
- << parameters_.video_streams.back().width << "x"
- << parameters_.video_streams.back().height;
+ << parameters_.encoder_config.streams.back().width << "x"
+ << parameters_.encoder_config.streams.back().height;
stream_->Input()->SwapFrame(&video_frame_);
}
@@ -1527,20 +1418,22 @@
}
{
- talk_base::CritScope cs(&lock_);
+ rtc::CritScope cs(&lock_);
if (capturer == NULL) {
- LOG(LS_VERBOSE) << "Disabling capturer, sending black frame.";
- webrtc::I420VideoFrame black_frame;
+ if (stream_ != NULL) {
+ LOG(LS_VERBOSE) << "Disabling capturer, sending black frame.";
+ webrtc::I420VideoFrame black_frame;
- int width = format_.width;
- int height = format_.height;
- int half_width = (width + 1) / 2;
- black_frame.CreateEmptyFrame(
- width, height, width, half_width, half_width);
- SetWebRtcFrameToBlack(&black_frame);
- SetDimensions(width, height);
- stream_->Input()->SwapFrame(&black_frame);
+ int width = format_.width;
+ int height = format_.height;
+ int half_width = (width + 1) / 2;
+ black_frame.CreateEmptyFrame(
+ width, height, width, half_width, half_width);
+ SetWebRtcFrameToBlack(&black_frame);
+ SetDimensions(width, height, false);
+ stream_->Input()->SwapFrame(&black_frame);
+ }
capturer_ = NULL;
return true;
@@ -1563,31 +1456,29 @@
return false;
}
- talk_base::CritScope cs(&lock_);
+ rtc::CritScope cs(&lock_);
if (format.width == 0 && format.height == 0) {
LOG(LS_INFO)
<< "0x0 resolution selected. Captured frames will be dropped for ssrc: "
<< parameters_.config.rtp.ssrcs[0] << ".";
} else {
// TODO(pbos): Fix me, this only affects the last stream!
- parameters_.video_streams.back().max_framerate =
+ parameters_.encoder_config.streams.back().max_framerate =
VideoFormat::IntervalToFps(format.interval);
- SetDimensions(format.width, format.height);
+ SetDimensions(format.width, format.height, false);
}
format_ = format;
return true;
}
-bool WebRtcVideoChannel2::WebRtcVideoSendStream::MuteStream(bool mute) {
- talk_base::CritScope cs(&lock_);
- bool was_muted = muted_;
+void WebRtcVideoChannel2::WebRtcVideoSendStream::MuteStream(bool mute) {
+ rtc::CritScope cs(&lock_);
muted_ = mute;
- return was_muted != mute;
}
bool WebRtcVideoChannel2::WebRtcVideoSendStream::DisconnectCapturer() {
- talk_base::CritScope cs(&lock_);
+ rtc::CritScope cs(&lock_);
if (capturer_ == NULL) {
return false;
}
@@ -1596,81 +1487,358 @@
return true;
}
+void WebRtcVideoChannel2::WebRtcVideoSendStream::SetOptions(
+ const VideoOptions& options) {
+ rtc::CritScope cs(&lock_);
+ VideoCodecSettings codec_settings;
+ if (parameters_.codec_settings.Get(&codec_settings)) {
+ SetCodecAndOptions(codec_settings, options);
+ } else {
+ parameters_.options = options;
+ }
+}
void WebRtcVideoChannel2::WebRtcVideoSendStream::SetCodec(
- const VideoOptions& options,
- const VideoCodecSettings& codec) {
- talk_base::CritScope cs(&lock_);
-
+ const VideoCodecSettings& codec_settings) {
+ rtc::CritScope cs(&lock_);
+ SetCodecAndOptions(codec_settings, parameters_.options);
+}
+void WebRtcVideoChannel2::WebRtcVideoSendStream::SetCodecAndOptions(
+ const VideoCodecSettings& codec_settings,
+ const VideoOptions& options) {
std::vector<webrtc::VideoStream> video_streams =
encoder_factory_->CreateVideoStreams(
- codec.codec, options, parameters_.video_streams.size());
+ codec_settings.codec, options, parameters_.config.rtp.ssrcs.size());
if (video_streams.empty()) {
return;
}
- parameters_.video_streams = video_streams;
- format_ = VideoFormat(codec.codec.width,
- codec.codec.height,
+ parameters_.encoder_config.streams = video_streams;
+ format_ = VideoFormat(codec_settings.codec.width,
+ codec_settings.codec.height,
VideoFormat::FpsToInterval(30),
FOURCC_I420);
webrtc::VideoEncoder* old_encoder =
parameters_.config.encoder_settings.encoder;
parameters_.config.encoder_settings.encoder =
- encoder_factory_->CreateVideoEncoder(codec.codec, options);
- parameters_.config.rtp.fec = codec.fec;
- // TODO(pbos): Should changing RTX payload type be allowed?
- parameters_.codec = codec.codec;
+ encoder_factory_->CreateVideoEncoder(codec_settings.codec, options);
+ parameters_.config.encoder_settings.payload_name = codec_settings.codec.name;
+ parameters_.config.encoder_settings.payload_type = codec_settings.codec.id;
+ parameters_.config.rtp.fec = codec_settings.fec;
+
+ // Set RTX payload type if RTX is enabled.
+ if (!parameters_.config.rtp.rtx.ssrcs.empty()) {
+ parameters_.config.rtp.rtx.payload_type = codec_settings.rtx_payload_type;
+
+ options.use_payload_padding.Get(
+ ¶meters_.config.rtp.rtx.pad_with_redundant_payloads);
+ }
+
+ if (IsNackEnabled(codec_settings.codec)) {
+ parameters_.config.rtp.nack.rtp_history_ms = kNackHistoryMs;
+ }
+
+ options.suspend_below_min_bitrate.Get(
+ ¶meters_.config.suspend_below_min_bitrate);
+
+ parameters_.codec_settings.Set(codec_settings);
parameters_.options = options;
+
RecreateWebRtcStream();
delete old_encoder;
}
-void WebRtcVideoChannel2::WebRtcVideoSendStream::SetDimensions(int width,
- int height) {
- assert(!parameters_.video_streams.empty());
+void WebRtcVideoChannel2::WebRtcVideoSendStream::SetRtpExtensions(
+ const std::vector<webrtc::RtpExtension>& rtp_extensions) {
+ rtc::CritScope cs(&lock_);
+ parameters_.config.rtp.extensions = rtp_extensions;
+ RecreateWebRtcStream();
+}
+
+void WebRtcVideoChannel2::WebRtcVideoSendStream::SetDimensions(
+ int width,
+ int height,
+ bool override_max) {
+ assert(!parameters_.encoder_config.streams.empty());
LOG(LS_VERBOSE) << "SetDimensions: " << width << "x" << height;
- if (parameters_.video_streams.back().width == width &&
- parameters_.video_streams.back().height == height) {
+
+ VideoCodecSettings codec_settings;
+ parameters_.codec_settings.Get(&codec_settings);
+ // Restrict dimensions according to codec max.
+ if (!override_max) {
+ if (codec_settings.codec.width < width)
+ width = codec_settings.codec.width;
+ if (codec_settings.codec.height < height)
+ height = codec_settings.codec.height;
+ }
+
+ if (parameters_.encoder_config.streams.back().width == width &&
+ parameters_.encoder_config.streams.back().height == height) {
return;
}
- // TODO(pbos): Fix me, this only affects the last stream!
- parameters_.video_streams.back().width = width;
- parameters_.video_streams.back().height = height;
+ webrtc::VideoEncoderConfig encoder_config = parameters_.encoder_config;
+ encoder_config.encoder_specific_settings =
+ encoder_factory_->CreateVideoEncoderSettings(codec_settings.codec,
+ parameters_.options);
- // TODO(pbos): Wire up encoder_parameters, webrtc:3424.
- if (!stream_->ReconfigureVideoEncoder(parameters_.video_streams, NULL)) {
+ VideoCodec codec = codec_settings.codec;
+ codec.width = width;
+ codec.height = height;
+
+ encoder_config.streams = encoder_factory_->CreateVideoStreams(
+ codec, parameters_.options, parameters_.config.rtp.ssrcs.size());
+
+ bool stream_reconfigured = stream_->ReconfigureVideoEncoder(encoder_config);
+
+ encoder_factory_->DestroyVideoEncoderSettings(
+ codec_settings.codec,
+ encoder_config.encoder_specific_settings);
+
+ encoder_config.encoder_specific_settings = NULL;
+
+ if (!stream_reconfigured) {
LOG(LS_WARNING) << "Failed to reconfigure video encoder for dimensions: "
<< width << "x" << height;
return;
}
+
+ parameters_.encoder_config = encoder_config;
}
void WebRtcVideoChannel2::WebRtcVideoSendStream::Start() {
- talk_base::CritScope cs(&lock_);
+ rtc::CritScope cs(&lock_);
+ assert(stream_ != NULL);
stream_->Start();
sending_ = true;
}
void WebRtcVideoChannel2::WebRtcVideoSendStream::Stop() {
- talk_base::CritScope cs(&lock_);
- stream_->Stop();
+ rtc::CritScope cs(&lock_);
+ if (stream_ != NULL) {
+ stream_->Stop();
+ }
sending_ = false;
}
+VideoSenderInfo
+WebRtcVideoChannel2::WebRtcVideoSendStream::GetVideoSenderInfo() {
+ VideoSenderInfo info;
+ rtc::CritScope cs(&lock_);
+ for (size_t i = 0; i < parameters_.config.rtp.ssrcs.size(); ++i) {
+ info.add_ssrc(parameters_.config.rtp.ssrcs[i]);
+ }
+
+ if (stream_ == NULL) {
+ return info;
+ }
+
+ webrtc::VideoSendStream::Stats stats = stream_->GetStats();
+ info.framerate_input = stats.input_frame_rate;
+ info.framerate_sent = stats.encode_frame_rate;
+
+ for (std::map<uint32_t, webrtc::StreamStats>::iterator it =
+ stats.substreams.begin();
+ it != stats.substreams.end();
+ ++it) {
+ // TODO(pbos): Wire up additional stats, such as padding bytes.
+ webrtc::StreamStats stream_stats = it->second;
+ info.bytes_sent += stream_stats.rtp_stats.bytes +
+ stream_stats.rtp_stats.header_bytes +
+ stream_stats.rtp_stats.padding_bytes;
+ info.packets_sent += stream_stats.rtp_stats.packets;
+ info.packets_lost += stream_stats.rtcp_stats.cumulative_lost;
+ }
+
+ if (!stats.substreams.empty()) {
+ // TODO(pbos): Report fraction lost per SSRC.
+ webrtc::StreamStats first_stream_stats = stats.substreams.begin()->second;
+ info.fraction_lost =
+ static_cast<float>(first_stream_stats.rtcp_stats.fraction_lost) /
+ (1 << 8);
+ }
+
+ if (capturer_ != NULL && !capturer_->IsMuted()) {
+ VideoFormat last_captured_frame_format;
+ capturer_->GetStats(&info.adapt_frame_drops,
+ &info.effects_frame_drops,
+ &info.capturer_frame_time,
+ &last_captured_frame_format);
+ info.input_frame_width = last_captured_frame_format.width;
+ info.input_frame_height = last_captured_frame_format.height;
+ info.send_frame_width =
+ static_cast<int>(parameters_.encoder_config.streams.front().width);
+ info.send_frame_height =
+ static_cast<int>(parameters_.encoder_config.streams.front().height);
+ }
+
+ // TODO(pbos): Support or remove the following stats.
+ info.packets_cached = -1;
+ info.rtt_ms = -1;
+
+ return info;
+}
+
void WebRtcVideoChannel2::WebRtcVideoSendStream::RecreateWebRtcStream() {
if (stream_ != NULL) {
call_->DestroyVideoSendStream(stream_);
}
- // TODO(pbos): Wire up encoder_parameters, webrtc:3424.
- stream_ = call_->CreateVideoSendStream(
- parameters_.config, parameters_.video_streams, NULL);
+ VideoCodecSettings codec_settings;
+ parameters_.codec_settings.Get(&codec_settings);
+ parameters_.encoder_config.encoder_specific_settings =
+ encoder_factory_->CreateVideoEncoderSettings(codec_settings.codec,
+ parameters_.options);
+
+ stream_ = call_->CreateVideoSendStream(parameters_.config,
+ parameters_.encoder_config);
+
+ encoder_factory_->DestroyVideoEncoderSettings(
+ codec_settings.codec,
+ parameters_.encoder_config.encoder_specific_settings);
+
+ parameters_.encoder_config.encoder_specific_settings = NULL;
+
if (sending_) {
stream_->Start();
}
}
+WebRtcVideoChannel2::WebRtcVideoReceiveStream::WebRtcVideoReceiveStream(
+ webrtc::Call* call,
+ const webrtc::VideoReceiveStream::Config& config,
+ const std::vector<VideoCodecSettings>& recv_codecs)
+ : call_(call),
+ stream_(NULL),
+ config_(config),
+ renderer_(NULL),
+ last_width_(-1),
+ last_height_(-1) {
+ config_.renderer = this;
+ // SetRecvCodecs will also reset (start) the VideoReceiveStream.
+ SetRecvCodecs(recv_codecs);
+}
+
+WebRtcVideoChannel2::WebRtcVideoReceiveStream::~WebRtcVideoReceiveStream() {
+ call_->DestroyVideoReceiveStream(stream_);
+}
+
+void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetRecvCodecs(
+ const std::vector<VideoCodecSettings>& recv_codecs) {
+ // TODO(pbos): Reconfigure RTX based on incoming recv_codecs.
+ // TODO(pbos): Base receive codecs off recv_codecs_ and set up using a
+ // DecoderFactory similar to send side. Pending webrtc:2854.
+ // Also set up default codecs if there's nothing in recv_codecs_.
+ webrtc::VideoCodec codec;
+ memset(&codec, 0, sizeof(codec));
+
+ codec.plType = kDefaultVideoCodecPref.payload_type;
+ strcpy(codec.plName, kDefaultVideoCodecPref.name);
+ codec.codecType = webrtc::kVideoCodecVP8;
+ codec.codecSpecific.VP8.resilience = webrtc::kResilientStream;
+ codec.codecSpecific.VP8.numberOfTemporalLayers = 1;
+ codec.codecSpecific.VP8.denoisingOn = true;
+ codec.codecSpecific.VP8.errorConcealmentOn = false;
+ codec.codecSpecific.VP8.automaticResizeOn = false;
+ codec.codecSpecific.VP8.frameDroppingOn = true;
+ codec.codecSpecific.VP8.keyFrameInterval = 3000;
+ // Bitrates don't matter and are ignored for the receiver. This is put in to
+ // have the current underlying implementation accept the VideoCodec.
+ codec.minBitrate = codec.startBitrate = codec.maxBitrate = 300;
+ config_.codecs.clear();
+ config_.codecs.push_back(codec);
+
+ config_.rtp.fec = recv_codecs.front().fec;
+
+ config_.rtp.nack.rtp_history_ms =
+ IsNackEnabled(recv_codecs.begin()->codec) ? kNackHistoryMs : 0;
+ config_.rtp.remb = IsRembEnabled(recv_codecs.begin()->codec);
+
+ RecreateWebRtcStream();
+}
+
+void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetRtpExtensions(
+ const std::vector<webrtc::RtpExtension>& extensions) {
+ config_.rtp.extensions = extensions;
+ RecreateWebRtcStream();
+}
+
+void WebRtcVideoChannel2::WebRtcVideoReceiveStream::RecreateWebRtcStream() {
+ if (stream_ != NULL) {
+ call_->DestroyVideoReceiveStream(stream_);
+ }
+ stream_ = call_->CreateVideoReceiveStream(config_);
+ stream_->Start();
+}
+
+void WebRtcVideoChannel2::WebRtcVideoReceiveStream::RenderFrame(
+ const webrtc::I420VideoFrame& frame,
+ int time_to_render_ms) {
+ rtc::CritScope crit(&renderer_lock_);
+ if (renderer_ == NULL) {
+ LOG(LS_WARNING) << "VideoReceiveStream not connected to a VideoRenderer.";
+ return;
+ }
+
+ if (frame.width() != last_width_ || frame.height() != last_height_) {
+ SetSize(frame.width(), frame.height());
+ }
+
+ LOG(LS_VERBOSE) << "RenderFrame: (" << frame.width() << "x" << frame.height()
+ << ")";
+
+ const WebRtcVideoRenderFrame render_frame(&frame);
+ renderer_->RenderFrame(&render_frame);
+}
+
+void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetRenderer(
+ cricket::VideoRenderer* renderer) {
+ rtc::CritScope crit(&renderer_lock_);
+ renderer_ = renderer;
+ if (renderer_ != NULL && last_width_ != -1) {
+ SetSize(last_width_, last_height_);
+ }
+}
+
+VideoRenderer* WebRtcVideoChannel2::WebRtcVideoReceiveStream::GetRenderer() {
+ // TODO(pbos): Remove GetRenderer and all uses of it, it's thread-unsafe by
+ // design.
+ rtc::CritScope crit(&renderer_lock_);
+ return renderer_;
+}
+
+void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetSize(int width,
+ int height) {
+ rtc::CritScope crit(&renderer_lock_);
+ if (!renderer_->SetSize(width, height, 0)) {
+ LOG(LS_ERROR) << "Could not set renderer size.";
+ }
+ last_width_ = width;
+ last_height_ = height;
+}
+
+VideoReceiverInfo
+WebRtcVideoChannel2::WebRtcVideoReceiveStream::GetVideoReceiverInfo() {
+ VideoReceiverInfo info;
+ info.add_ssrc(config_.rtp.remote_ssrc);
+ webrtc::VideoReceiveStream::Stats stats = stream_->GetStats();
+ info.bytes_rcvd = stats.rtp_stats.bytes + stats.rtp_stats.header_bytes +
+ stats.rtp_stats.padding_bytes;
+ info.packets_rcvd = stats.rtp_stats.packets;
+
+ info.framerate_rcvd = stats.network_frame_rate;
+ info.framerate_decoded = stats.decode_frame_rate;
+ info.framerate_output = stats.render_frame_rate;
+
+ rtc::CritScope frame_cs(&renderer_lock_);
+ info.frame_width = last_width_;
+ info.frame_height = last_height_;
+
+ // TODO(pbos): Support or remove the following stats.
+ info.packets_concealed = -1;
+
+ return info;
+}
+
WebRtcVideoChannel2::VideoCodecSettings::VideoCodecSettings()
: rtx_payload_type(-1) {}
diff --git a/media/webrtc/webrtcvideoengine2.h b/media/webrtc/webrtcvideoengine2.h
index 81466eb..18a80d7 100644
--- a/media/webrtc/webrtcvideoengine2.h
+++ b/media/webrtc/webrtcvideoengine2.h
@@ -29,16 +29,19 @@
#define TALK_MEDIA_WEBRTC_WEBRTCVIDEOENGINE2_H_
#include <map>
-#include <vector>
#include <string>
+#include <vector>
-#include "talk/base/cpumonitor.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/mediaengine.h"
#include "talk/media/webrtc/webrtcvideochannelfactory.h"
+#include "talk/media/webrtc/webrtcvideodecoderfactory.h"
+#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
+#include "webrtc/base/cpumonitor.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread_annotations.h"
#include "webrtc/common_video/interface/i420_video_frame.h"
-#include "webrtc/system_wrappers/interface/thread_annotations.h"
#include "webrtc/transport.h"
+#include "webrtc/video_receive_stream.h"
#include "webrtc/video_renderer.h"
#include "webrtc/video_send_stream.h"
@@ -52,10 +55,10 @@
class VideoReceiveStream;
}
-namespace talk_base {
+namespace rtc {
class CpuMonitor;
class Thread;
-} // namespace talk_base
+} // namespace rtc
namespace cricket {
@@ -64,14 +67,13 @@
class VideoProcessor;
class VideoRenderer;
class VoiceMediaChannel;
-class WebRtcVideoChannel2;
class WebRtcDecoderObserver;
class WebRtcEncoderObserver;
class WebRtcLocalStreamInfo;
class WebRtcRenderAdapter;
+class WebRtcVideoChannel2;
class WebRtcVideoChannelRecvInfo;
class WebRtcVideoChannelSendInfo;
-class WebRtcVideoDecoderFactory;
class WebRtcVoiceEngine;
struct CapturedFrame;
@@ -79,6 +81,32 @@
class WebRtcVideoEngine2;
class WebRtcVideoChannel2;
+class WebRtcVideoRenderer;
+
+class UnsignalledSsrcHandler {
+ public:
+ enum Action {
+ kDropPacket,
+ kDeliverPacket,
+ };
+ virtual Action OnUnsignalledSsrc(VideoMediaChannel* engine,
+ uint32_t ssrc) = 0;
+};
+
+// TODO(pbos): Remove, use external handlers only.
+class DefaultUnsignalledSsrcHandler : public UnsignalledSsrcHandler {
+ public:
+ DefaultUnsignalledSsrcHandler();
+ virtual Action OnUnsignalledSsrc(VideoMediaChannel* engine,
+ uint32_t ssrc) OVERRIDE;
+
+ VideoRenderer* GetDefaultRenderer() const;
+ void SetDefaultRenderer(VideoMediaChannel* channel, VideoRenderer* renderer);
+
+ private:
+ uint32_t default_recv_ssrc_;
+ VideoRenderer* default_renderer_;
+};
class WebRtcVideoEncoderFactory2 {
public:
@@ -92,24 +120,31 @@
const VideoCodec& codec,
const VideoOptions& options);
+ virtual void* CreateVideoEncoderSettings(const VideoCodec& codec,
+ const VideoOptions& options);
+
+ virtual void DestroyVideoEncoderSettings(const VideoCodec& codec,
+ void* encoder_settings);
+
virtual bool SupportsCodec(const cricket::VideoCodec& codec);
};
// WebRtcVideoEngine2 is used for the new native WebRTC Video API (webrtc:1667).
-class WebRtcVideoEngine2 : public sigslot::has_slots<> {
+class WebRtcVideoEngine2 : public sigslot::has_slots<>,
+ public WebRtcVideoEncoderFactory::Observer {
public:
// Creates the WebRtcVideoEngine2 with internal VideoCaptureModule.
WebRtcVideoEngine2();
- // Custom WebRtcVideoChannelFactory for testing purposes.
- explicit WebRtcVideoEngine2(WebRtcVideoChannelFactory* channel_factory);
- ~WebRtcVideoEngine2();
+ virtual ~WebRtcVideoEngine2();
+
+ // Use a custom WebRtcVideoChannelFactory (for testing purposes).
+ void SetChannelFactory(WebRtcVideoChannelFactory* channel_factory);
// Basic video engine implementation.
- bool Init(talk_base::Thread* worker_thread);
+ bool Init(rtc::Thread* worker_thread);
void Terminate();
int GetCapabilities();
- bool SetOptions(const VideoOptions& options);
bool SetDefaultEncoderConfig(const VideoEncoderConfig& config);
VideoEncoderConfig GetDefaultEncoderConfig() const;
@@ -119,20 +154,23 @@
const std::vector<RtpHeaderExtension>& rtp_header_extensions() const;
void SetLogging(int min_sev, const char* filter);
+ // Set a WebRtcVideoDecoderFactory for external decoding. Video engine does
+ // not take the ownership of |decoder_factory|. The caller needs to make sure
+ // that |decoder_factory| outlives the video engine.
+ void SetExternalDecoderFactory(WebRtcVideoDecoderFactory* decoder_factory);
+ // Set a WebRtcVideoEncoderFactory for external encoding. Video engine does
+ // not take the ownership of |encoder_factory|. The caller needs to make sure
+ // that |encoder_factory| outlives the video engine.
+ virtual void SetExternalEncoderFactory(
+ WebRtcVideoEncoderFactory* encoder_factory);
+
bool EnableTimedRender();
- // No-op, never used.
- bool SetLocalRenderer(VideoRenderer* renderer);
// This is currently ignored.
sigslot::repeater2<VideoCapturer*, CaptureState> SignalCaptureStateChange;
// Set the VoiceEngine for A/V sync. This can only be called before Init.
bool SetVoiceEngine(WebRtcVoiceEngine* voice_engine);
- // Functions called by WebRtcVideoChannel2.
- const VideoFormat& default_codec_format() const {
- return default_codec_format_;
- }
-
bool FindCodec(const VideoCodec& in);
bool CanSendCodec(const VideoCodec& in,
const VideoCodec& current,
@@ -142,16 +180,14 @@
VideoFormat GetStartCaptureFormat() const { return default_codec_format_; }
- talk_base::CpuMonitor* cpu_monitor() { return cpu_monitor_.get(); }
+ rtc::CpuMonitor* cpu_monitor() { return cpu_monitor_.get(); }
virtual WebRtcVideoEncoderFactory2* GetVideoEncoderFactory();
private:
- void Construct(WebRtcVideoChannelFactory* channel_factory,
- WebRtcVoiceEngine* voice_engine,
- talk_base::CpuMonitor* cpu_monitor);
+ virtual void OnCodecsAvailable() OVERRIDE;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* worker_thread_;
WebRtcVoiceEngine* voice_engine_;
std::vector<VideoCodec> video_codecs_;
std::vector<RtpHeaderExtension> rtp_header_extensions_;
@@ -159,41 +195,19 @@
bool initialized_;
- bool capture_started_;
-
// Critical section to protect the media processor register/unregister
// while processing a frame
- talk_base::CriticalSection signal_media_critical_;
+ rtc::CriticalSection signal_media_critical_;
- talk_base::scoped_ptr<talk_base::CpuMonitor> cpu_monitor_;
+ rtc::scoped_ptr<rtc::CpuMonitor> cpu_monitor_;
WebRtcVideoChannelFactory* channel_factory_;
WebRtcVideoEncoderFactory2 default_video_encoder_factory_;
+
+ WebRtcVideoDecoderFactory* external_decoder_factory_;
+ WebRtcVideoEncoderFactory* external_encoder_factory_;
};
-// Adapter between webrtc::VideoRenderer and cricket::VideoRenderer.
-// The webrtc::VideoRenderer is set once, whereas the cricket::VideoRenderer can
-// be set after initialization. This adapter will also convert the incoming
-// webrtc::I420VideoFrame to a frame type that cricket::VideoRenderer can
-// render.
-class WebRtcVideoRenderer : public webrtc::VideoRenderer {
- public:
- WebRtcVideoRenderer();
-
- virtual void RenderFrame(const webrtc::I420VideoFrame& frame,
- int time_to_render_ms) OVERRIDE;
-
- void SetRenderer(cricket::VideoRenderer* renderer);
- cricket::VideoRenderer* GetRenderer();
-
- private:
- void SetSize(int width, int height);
- int last_width_;
- int last_height_;
- talk_base::CriticalSection lock_;
- cricket::VideoRenderer* renderer_ GUARDED_BY(lock_);
-};
-
-class WebRtcVideoChannel2 : public talk_base::MessageHandler,
+class WebRtcVideoChannel2 : public rtc::MessageHandler,
public VideoMediaChannel,
public webrtc::newapi::Transport {
public:
@@ -228,11 +242,11 @@
virtual bool SendIntraFrame() OVERRIDE;
virtual bool RequestIntraFrame() OVERRIDE;
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time)
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time)
OVERRIDE;
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time)
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time)
OVERRIDE;
virtual void OnReadyToSend(bool ready) OVERRIDE;
virtual bool MuteStream(uint32 ssrc, bool mute) OVERRIDE;
@@ -253,14 +267,17 @@
virtual void SetInterface(NetworkInterface* iface) OVERRIDE;
virtual void UpdateAspectRatio(int ratio_w, int ratio_h) OVERRIDE;
- virtual void OnMessage(talk_base::Message* msg) OVERRIDE;
+ virtual void OnMessage(rtc::Message* msg) OVERRIDE;
// Implemented for VideoMediaChannelTest.
bool sending() const { return sending_; }
- uint32 GetDefaultChannelSsrc() { return default_send_ssrc_; }
+ uint32 GetDefaultSendChannelSsrc() { return default_send_ssrc_; }
bool GetRenderer(uint32 ssrc, VideoRenderer** renderer);
private:
+ void ConfigureReceiverRtp(webrtc::VideoReceiveStream::Config* config,
+ const StreamParams& sp) const;
+
struct VideoCodecSettings {
VideoCodecSettings();
@@ -269,26 +286,35 @@
int rtx_payload_type;
};
+ // Wrapper for the sender part, this is where the capturer is connected and
+ // frames are then converted from cricket frames to webrtc frames.
class WebRtcVideoSendStream : public sigslot::has_slots<> {
public:
- WebRtcVideoSendStream(webrtc::Call* call,
- const webrtc::VideoSendStream::Config& config,
- const VideoOptions& options,
- const VideoCodec& codec,
- const std::vector<webrtc::VideoStream>& video_streams,
- WebRtcVideoEncoderFactory2* encoder_factory);
+ WebRtcVideoSendStream(
+ webrtc::Call* call,
+ WebRtcVideoEncoderFactory2* encoder_factory,
+ const VideoOptions& options,
+ const Settable<VideoCodecSettings>& codec_settings,
+ const StreamParams& sp,
+ const std::vector<webrtc::RtpExtension>& rtp_extensions);
+
~WebRtcVideoSendStream();
- void SetCodec(const VideoOptions& options, const VideoCodecSettings& codec);
+ void SetOptions(const VideoOptions& options);
+ void SetCodec(const VideoCodecSettings& codec);
+ void SetRtpExtensions(
+ const std::vector<webrtc::RtpExtension>& rtp_extensions);
void InputFrame(VideoCapturer* capturer, const VideoFrame* frame);
bool SetCapturer(VideoCapturer* capturer);
bool SetVideoFormat(const VideoFormat& format);
- bool MuteStream(bool mute);
+ void MuteStream(bool mute);
bool DisconnectCapturer();
void Start();
void Stop();
+ VideoSenderInfo GetVideoSenderInfo();
+
private:
// Parameters needed to reconstruct the underlying stream.
// webrtc::VideoSendStream doesn't support setting a lot of options on the
@@ -298,24 +324,28 @@
VideoSendStreamParameters(
const webrtc::VideoSendStream::Config& config,
const VideoOptions& options,
- const VideoCodec& codec,
- const std::vector<webrtc::VideoStream>& video_streams);
+ const Settable<VideoCodecSettings>& codec_settings);
webrtc::VideoSendStream::Config config;
VideoOptions options;
- VideoCodec codec;
+ Settable<VideoCodecSettings> codec_settings;
// Sent resolutions + bitrates etc. by the underlying VideoSendStream,
// typically changes when setting a new resolution or reconfiguring
// bitrates.
- std::vector<webrtc::VideoStream> video_streams;
+ webrtc::VideoEncoderConfig encoder_config;
};
- void RecreateWebRtcStream();
- void SetDimensions(int width, int height);
+ void SetCodecAndOptions(const VideoCodecSettings& codec,
+ const VideoOptions& options)
+ EXCLUSIVE_LOCKS_REQUIRED(lock_);
+ void RecreateWebRtcStream() EXCLUSIVE_LOCKS_REQUIRED(lock_);
+ // When |override_max| is false constrain width/height to codec dimensions.
+ void SetDimensions(int width, int height, bool override_max)
+ EXCLUSIVE_LOCKS_REQUIRED(lock_);
webrtc::Call* const call_;
WebRtcVideoEncoderFactory2* const encoder_factory_;
- talk_base::CriticalSection lock_;
+ rtc::CriticalSection lock_;
webrtc::VideoSendStream* stream_ GUARDED_BY(lock_);
VideoSendStreamParameters parameters_ GUARDED_BY(lock_);
@@ -324,34 +354,76 @@
bool muted_ GUARDED_BY(lock_);
VideoFormat format_ GUARDED_BY(lock_);
- talk_base::CriticalSection frame_lock_;
+ rtc::CriticalSection frame_lock_;
webrtc::I420VideoFrame video_frame_ GUARDED_BY(frame_lock_);
};
+ // Wrapper for the receiver part, contains configs etc. that are needed to
+ // reconstruct the underlying VideoReceiveStream. Also serves as a wrapper
+ // between webrtc::VideoRenderer and cricket::VideoRenderer.
+ class WebRtcVideoReceiveStream : public webrtc::VideoRenderer {
+ public:
+ WebRtcVideoReceiveStream(
+ webrtc::Call*,
+ const webrtc::VideoReceiveStream::Config& config,
+ const std::vector<VideoCodecSettings>& recv_codecs);
+ ~WebRtcVideoReceiveStream();
+
+ void SetRecvCodecs(const std::vector<VideoCodecSettings>& recv_codecs);
+ void SetRtpExtensions(const std::vector<webrtc::RtpExtension>& extensions);
+
+ virtual void RenderFrame(const webrtc::I420VideoFrame& frame,
+ int time_to_render_ms) OVERRIDE;
+
+ void SetRenderer(cricket::VideoRenderer* renderer);
+ cricket::VideoRenderer* GetRenderer();
+
+ VideoReceiverInfo GetVideoReceiverInfo();
+
+ private:
+ void SetSize(int width, int height);
+ void RecreateWebRtcStream();
+
+ webrtc::Call* const call_;
+
+ webrtc::VideoReceiveStream* stream_;
+ webrtc::VideoReceiveStream::Config config_;
+
+ rtc::CriticalSection renderer_lock_;
+ cricket::VideoRenderer* renderer_ GUARDED_BY(renderer_lock_);
+ int last_width_ GUARDED_BY(renderer_lock_);
+ int last_height_ GUARDED_BY(renderer_lock_);
+ };
+
void Construct(webrtc::Call* call, WebRtcVideoEngine2* engine);
+ void SetDefaultOptions();
virtual bool SendRtp(const uint8_t* data, size_t len) OVERRIDE;
virtual bool SendRtcp(const uint8_t* data, size_t len) OVERRIDE;
void StartAllSendStreams();
void StopAllSendStreams();
- void SetCodecForAllSendStreams(const VideoCodecSettings& codec);
+
static std::vector<VideoCodecSettings> MapCodecs(
const std::vector<VideoCodec>& codecs);
std::vector<VideoCodecSettings> FilterSupportedCodecs(
const std::vector<VideoCodecSettings>& mapped_codecs);
+ void FillSenderStats(VideoMediaInfo* info);
+ void FillReceiverStats(VideoMediaInfo* info);
+ void FillBandwidthEstimationStats(VideoMediaInfo* info);
+
uint32_t rtcp_receiver_report_ssrc_;
bool sending_;
- talk_base::scoped_ptr<webrtc::Call> call_;
- std::map<uint32, WebRtcVideoRenderer*> renderers_;
- VideoRenderer* default_renderer_;
+ rtc::scoped_ptr<webrtc::Call> call_;
uint32_t default_send_ssrc_;
- uint32_t default_recv_ssrc_;
+
+ DefaultUnsignalledSsrcHandler default_unsignalled_ssrc_handler_;
+ UnsignalledSsrcHandler* const unsignalled_ssrc_handler_;
// Using primary-ssrc (first ssrc) as key.
std::map<uint32, WebRtcVideoSendStream*> send_streams_;
- std::map<uint32, webrtc::VideoReceiveStream*> receive_streams_;
+ std::map<uint32, WebRtcVideoReceiveStream*> receive_streams_;
Settable<VideoCodecSettings> send_codec_;
std::vector<webrtc::RtpExtension> send_rtp_extensions_;
diff --git a/media/webrtc/webrtcvideoengine2_unittest.cc b/media/webrtc/webrtcvideoengine2_unittest.cc
index 6886300..6112c50 100644
--- a/media/webrtc/webrtcvideoengine2_unittest.cc
+++ b/media/webrtc/webrtcvideoengine2_unittest.cc
@@ -28,12 +28,13 @@
#include <map>
#include <vector>
-#include "talk/base/gunit.h"
#include "talk/media/base/testutils.h"
#include "talk/media/base/videoengine_unittest.h"
+#include "talk/media/webrtc/webrtcvideochannelfactory.h"
#include "talk/media/webrtc/webrtcvideoengine2.h"
#include "talk/media/webrtc/webrtcvideoengine2_unittest.h"
-#include "talk/media/webrtc/webrtcvideochannelfactory.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/stringutils.h"
namespace {
static const cricket::VideoCodec kVp8Codec720p(100, "VP8", 1280, 720, 30, 0);
@@ -48,6 +49,8 @@
static const uint32 kSsrcs1[] = {1};
static const uint32 kRtxSsrcs1[] = {4};
+static const char kUnsupportedExtensionName[] =
+ "urn:ietf:params:rtp-hdrext:unsupported";
void VerifyCodecHasDefaultFeedbackParams(const cricket::VideoCodec& codec) {
EXPECT_TRUE(codec.HasFeedbackParam(cricket::FeedbackParam(
@@ -65,8 +68,10 @@
namespace cricket {
FakeVideoSendStream::FakeVideoSendStream(
const webrtc::VideoSendStream::Config& config,
- const std::vector<webrtc::VideoStream>& video_streams)
- : sending_(false), config_(config), video_streams_(video_streams) {
+ const webrtc::VideoEncoderConfig& encoder_config)
+ : sending_(false), config_(config), codec_settings_set_(false) {
+ assert(config.encoder_settings.encoder != NULL);
+ ReconfigureVideoEncoder(encoder_config);
}
webrtc::VideoSendStream::Config FakeVideoSendStream::GetConfig() {
@@ -74,21 +79,36 @@
}
std::vector<webrtc::VideoStream> FakeVideoSendStream::GetVideoStreams() {
- return video_streams_;
+ return encoder_config_.streams;
}
-bool FakeVideoSendStream::IsSending() {
+bool FakeVideoSendStream::IsSending() const {
return sending_;
}
+bool FakeVideoSendStream::GetVp8Settings(
+ webrtc::VideoCodecVP8* settings) const {
+ if (!codec_settings_set_) {
+ return false;
+ }
+
+ *settings = vp8_settings_;
+ return true;
+}
+
webrtc::VideoSendStream::Stats FakeVideoSendStream::GetStats() const {
return webrtc::VideoSendStream::Stats();
}
bool FakeVideoSendStream::ReconfigureVideoEncoder(
- const std::vector<webrtc::VideoStream>& streams,
- const void* encoder_specific) {
- video_streams_ = streams;
+ const webrtc::VideoEncoderConfig& config) {
+ encoder_config_ = config;
+ if (config.encoder_specific_settings != NULL) {
+ assert(config_.encoder_settings.payload_name == "VP8");
+ vp8_settings_ = *reinterpret_cast<const webrtc::VideoCodecVP8*>(
+ config.encoder_specific_settings);
+ }
+ codec_settings_set_ = config.encoder_specific_settings != NULL;
return true;
}
@@ -114,6 +134,10 @@
return config_;
}
+bool FakeVideoReceiveStream::IsReceiving() const {
+ return receiving_;
+}
+
webrtc::VideoReceiveStream::Stats FakeVideoReceiveStream::GetStats() const {
return webrtc::VideoReceiveStream::Stats();
}
@@ -121,13 +145,17 @@
void FakeVideoReceiveStream::Start() {
receiving_ = true;
}
+
void FakeVideoReceiveStream::Stop() {
receiving_ = false;
}
+
void FakeVideoReceiveStream::GetCurrentReceiveCodec(webrtc::VideoCodec* codec) {
}
-FakeCall::FakeCall() { SetVideoCodecs(GetDefaultVideoCodecs()); }
+FakeCall::FakeCall() : network_state_(kNetworkUp) {
+ SetVideoCodecs(GetDefaultVideoCodecs());
+}
FakeCall::~FakeCall() {
EXPECT_EQ(0u, video_send_streams_.size());
@@ -162,7 +190,8 @@
webrtc::VideoCodec FakeCall::GetVideoCodecVp8() {
webrtc::VideoCodec vp8_codec = GetEmptyVideoCodec();
vp8_codec.codecType = webrtc::kVideoCodecVP8;
- strcpy(vp8_codec.plName, kVp8Codec.name.c_str());
+ rtc::strcpyn(vp8_codec.plName, ARRAY_SIZE(vp8_codec.plName),
+ kVp8Codec.name.c_str());
vp8_codec.plType = kVp8Codec.id;
return vp8_codec;
@@ -172,7 +201,8 @@
webrtc::VideoCodec vp9_codec = GetEmptyVideoCodec();
// TODO(pbos): Add a correct codecType when webrtc has one.
vp9_codec.codecType = webrtc::kVideoCodecVP8;
- strcpy(vp9_codec.plName, kVp9Codec.name.c_str());
+ rtc::strcpyn(vp9_codec.plName, ARRAY_SIZE(vp9_codec.plName),
+ kVp9Codec.name.c_str());
vp9_codec.plType = kVp9Codec.id;
return vp9_codec;
@@ -186,19 +216,15 @@
return codecs;
}
-webrtc::VideoSendStream::Config FakeCall::GetDefaultSendConfig() {
- webrtc::VideoSendStream::Config config;
- // TODO(pbos): Encoder settings.
- // config.codec = GetVideoCodecVp8();
- return config;
+webrtc::Call::NetworkState FakeCall::GetNetworkState() const {
+ return network_state_;
}
webrtc::VideoSendStream* FakeCall::CreateVideoSendStream(
const webrtc::VideoSendStream::Config& config,
- const std::vector<webrtc::VideoStream>& video_streams,
- const void* encoder_settings) {
+ const webrtc::VideoEncoderConfig& encoder_config) {
FakeVideoSendStream* fake_stream =
- new FakeVideoSendStream(config, video_streams);
+ new FakeVideoSendStream(config, encoder_config);
video_send_streams_.push_back(fake_stream);
return fake_stream;
}
@@ -216,10 +242,6 @@
ADD_FAILURE() << "DestroyVideoSendStream called with unknown paramter.";
}
-webrtc::VideoReceiveStream::Config FakeCall::GetDefaultReceiveConfig() {
- return webrtc::VideoReceiveStream::Config();
-}
-
webrtc::VideoReceiveStream* FakeCall::CreateVideoReceiveStream(
const webrtc::VideoReceiveStream::Config& config) {
video_receive_streams_.push_back(new FakeVideoReceiveStream(config));
@@ -253,6 +275,10 @@
return 0;
}
+void FakeCall::SignalNetworkState(webrtc::Call::NetworkState state) {
+ network_state_ = state;
+}
+
FakeWebRtcVideoChannel2::FakeWebRtcVideoChannel2(
FakeCall* call,
WebRtcVideoEngine2* engine,
@@ -268,6 +294,7 @@
VoiceMediaChannel* FakeWebRtcVideoChannel2::GetVoiceChannel() {
return voice_channel_;
}
+
FakeCall* FakeWebRtcVideoChannel2::GetFakeCall() {
return fake_call_;
}
@@ -288,7 +315,8 @@
class WebRtcVideoEngine2Test : public testing::Test {
public:
- WebRtcVideoEngine2Test() : engine_(&factory_) {
+ WebRtcVideoEngine2Test() {
+ engine_.SetChannelFactory(&factory_);
std::vector<VideoCodec> engine_codecs = engine_.codecs();
assert(!engine_codecs.empty());
bool codec_set = false;
@@ -318,7 +346,7 @@
};
TEST_F(WebRtcVideoEngine2Test, CreateChannel) {
- talk_base::scoped_ptr<VideoMediaChannel> channel(engine_.CreateChannel(NULL));
+ rtc::scoped_ptr<VideoMediaChannel> channel(engine_.CreateChannel(NULL));
ASSERT_TRUE(channel.get() != NULL) << "Could not create channel.";
EXPECT_TRUE(factory_.GetFakeChannel(channel.get()) != NULL)
<< "Channel not created through factory.";
@@ -326,7 +354,7 @@
TEST_F(WebRtcVideoEngine2Test, CreateChannelWithVoiceEngine) {
VoiceMediaChannel* voice_channel = reinterpret_cast<VoiceMediaChannel*>(0x42);
- talk_base::scoped_ptr<VideoMediaChannel> channel(
+ rtc::scoped_ptr<VideoMediaChannel> channel(
engine_.CreateChannel(voice_channel));
ASSERT_TRUE(channel.get() != NULL) << "Could not create channel.";
@@ -358,8 +386,10 @@
vp8_diff_id.id = 97;
EXPECT_TRUE(engine_.FindCodec(vp8_diff_id));
+ // FindCodec ignores the codec size.
+ // Test that FindCodec can accept uncommon codec size.
cricket::VideoCodec vp8_diff_res(104, "VP8", 320, 111, 30, 0);
- EXPECT_FALSE(engine_.FindCodec(vp8_diff_res));
+ EXPECT_TRUE(engine_.FindCodec(vp8_diff_res));
// PeerConnection doesn't negotiate the resolution at this point.
// Test that FindCodec can handle the case when width/height is 0.
@@ -421,6 +451,35 @@
FAIL() << "Absolute Sender Time extension not in header-extension list.";
}
+TEST_F(WebRtcVideoEngine2Test, SetSendFailsBeforeSettingCodecs) {
+ rtc::scoped_ptr<VideoMediaChannel> channel(engine_.CreateChannel(NULL));
+
+ EXPECT_TRUE(channel->AddSendStream(StreamParams::CreateLegacy(123)));
+
+ EXPECT_FALSE(channel->SetSend(true))
+ << "Channel should not start without codecs.";
+ EXPECT_TRUE(channel->SetSend(false))
+ << "Channel should be stoppable even without set codecs.";
+}
+
+TEST_F(WebRtcVideoEngine2Test, GetStatsWithoutSendCodecsSetDoesNotCrash) {
+ rtc::scoped_ptr<VideoMediaChannel> channel(engine_.CreateChannel(NULL));
+ EXPECT_TRUE(channel->AddSendStream(StreamParams::CreateLegacy(123)));
+ VideoMediaInfo info;
+ channel->GetStats(&info);
+}
+
+class WebRtcVideoEngine2BaseTest
+ : public VideoEngineTest<cricket::WebRtcVideoEngine2> {
+ protected:
+ typedef VideoEngineTest<cricket::WebRtcVideoEngine2> Base;
+};
+
+#define WEBRTC_ENGINE_BASE_TEST(test) \
+ TEST_F(WebRtcVideoEngine2BaseTest, test) { Base::test##Body(); }
+
+WEBRTC_ENGINE_BASE_TEST(ConstrainNewCodec2);
+
class WebRtcVideoChannel2BaseTest
: public VideoMediaChannelTest<WebRtcVideoEngine2, WebRtcVideoChannel2> {
protected:
@@ -428,119 +487,87 @@
typedef VideoMediaChannelTest<WebRtcVideoEngine2, WebRtcVideoChannel2> Base;
};
+#define WEBRTC_BASE_TEST(test) \
+ TEST_F(WebRtcVideoChannel2BaseTest, test) { Base::test(); }
+
+#define WEBRTC_DISABLED_BASE_TEST(test) \
+ TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_ ## test) { Base::test(); }
+
// TODO(pbos): Fix WebRtcVideoEngine2BaseTest, where we want CheckCoInitialize.
#if 0
// TODO(juberti): Figure out why ViE is munging the COM refcount.
#ifdef WIN32
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_CheckCoInitialize) {
+WEBRTC_DISABLED_BASE_TEST(CheckCoInitialize) {
Base::CheckCoInitialize();
}
#endif
#endif
-TEST_F(WebRtcVideoChannel2BaseTest, SetSend) { Base::SetSend(); }
+WEBRTC_BASE_TEST(SetSend);
+WEBRTC_BASE_TEST(SetSendWithoutCodecs);
+WEBRTC_BASE_TEST(SetSendSetsTransportBufferSizes);
-TEST_F(WebRtcVideoChannel2BaseTest, SetSendWithoutCodecs) {
- Base::SetSendWithoutCodecs();
-}
+WEBRTC_BASE_TEST(GetStats);
+WEBRTC_BASE_TEST(GetStatsMultipleRecvStreams);
+WEBRTC_BASE_TEST(GetStatsMultipleSendStreams);
-TEST_F(WebRtcVideoChannel2BaseTest, SetSendSetsTransportBufferSizes) {
- Base::SetSendSetsTransportBufferSizes();
-}
+WEBRTC_BASE_TEST(SetSendBandwidth);
-// TODO(juberti): Fix this test to tolerate missing stats.
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_GetStats) { Base::GetStats(); }
+WEBRTC_BASE_TEST(SetSendSsrc);
+WEBRTC_BASE_TEST(SetSendSsrcAfterSetCodecs);
-// TODO(juberti): Fix this test to tolerate missing stats.
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_GetStatsMultipleRecvStreams) {
- Base::GetStatsMultipleRecvStreams();
-}
+WEBRTC_BASE_TEST(SetRenderer);
+WEBRTC_BASE_TEST(AddRemoveRecvStreams);
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_GetStatsMultipleSendStreams) {
- Base::GetStatsMultipleSendStreams();
-}
+WEBRTC_DISABLED_BASE_TEST(AddRemoveRecvStreamAndRender);
-TEST_F(WebRtcVideoChannel2BaseTest, SetSendBandwidth) {
- Base::SetSendBandwidth();
-}
-TEST_F(WebRtcVideoChannel2BaseTest, SetSendSsrc) { Base::SetSendSsrc(); }
-TEST_F(WebRtcVideoChannel2BaseTest, SetSendSsrcAfterSetCodecs) {
- Base::SetSendSsrcAfterSetCodecs();
-}
+WEBRTC_BASE_TEST(AddRemoveRecvStreamsNoConference);
-TEST_F(WebRtcVideoChannel2BaseTest, SetRenderer) { Base::SetRenderer(); }
+WEBRTC_BASE_TEST(AddRemoveSendStreams);
-TEST_F(WebRtcVideoChannel2BaseTest, AddRemoveRecvStreams) {
- Base::AddRemoveRecvStreams();
-}
+WEBRTC_BASE_TEST(SimulateConference);
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_AddRemoveRecvStreamAndRender) {
- Base::AddRemoveRecvStreamAndRender();
-}
+WEBRTC_BASE_TEST(AddRemoveCapturer);
-TEST_F(WebRtcVideoChannel2BaseTest, AddRemoveRecvStreamsNoConference) {
- Base::AddRemoveRecvStreamsNoConference();
-}
+WEBRTC_BASE_TEST(RemoveCapturerWithoutAdd);
-TEST_F(WebRtcVideoChannel2BaseTest, AddRemoveSendStreams) {
- Base::AddRemoveSendStreams();
-}
-
-TEST_F(WebRtcVideoChannel2BaseTest, SimulateConference) {
- Base::SimulateConference();
-}
-
-TEST_F(WebRtcVideoChannel2BaseTest, AddRemoveCapturer) {
- Base::AddRemoveCapturer();
-}
-
-TEST_F(WebRtcVideoChannel2BaseTest, RemoveCapturerWithoutAdd) {
- Base::RemoveCapturerWithoutAdd();
-}
-
-TEST_F(WebRtcVideoChannel2BaseTest, AddRemoveCapturerMultipleSources) {
- Base::AddRemoveCapturerMultipleSources();
-}
+WEBRTC_BASE_TEST(AddRemoveCapturerMultipleSources);
// TODO(pbos): Figure out why this fails so often.
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_HighAspectHighHeightCapturer) {
- Base::HighAspectHighHeightCapturer();
-}
+WEBRTC_DISABLED_BASE_TEST(HighAspectHighHeightCapturer);
-TEST_F(WebRtcVideoChannel2BaseTest, RejectEmptyStreamParams) {
- Base::RejectEmptyStreamParams();
-}
+WEBRTC_BASE_TEST(RejectEmptyStreamParams);
-TEST_F(WebRtcVideoChannel2BaseTest, AdaptResolution16x10) {
- Base::AdaptResolution16x10();
-}
+WEBRTC_BASE_TEST(AdaptResolution16x10);
-TEST_F(WebRtcVideoChannel2BaseTest, AdaptResolution4x3) {
- Base::AdaptResolution4x3();
-}
-
-TEST_F(WebRtcVideoChannel2BaseTest, MuteStream) { Base::MuteStream(); }
-
-TEST_F(WebRtcVideoChannel2BaseTest, MultipleSendStreams) {
- Base::MultipleSendStreams();
-}
+WEBRTC_BASE_TEST(AdaptResolution4x3);
// TODO(juberti): Restore this test once we support sending 0 fps.
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_AdaptDropAllFrames) {
- Base::AdaptDropAllFrames();
-}
+WEBRTC_DISABLED_BASE_TEST(AdaptDropAllFrames);
// TODO(juberti): Understand why we get decode errors on this test.
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_AdaptFramerate) {
- Base::AdaptFramerate();
-}
+WEBRTC_DISABLED_BASE_TEST(AdaptFramerate);
-TEST_F(WebRtcVideoChannel2BaseTest, SetSendStreamFormat0x0) {
- Base::SetSendStreamFormat0x0();
-}
+WEBRTC_BASE_TEST(SendsLowerResolutionOnSmallerFrames);
+
+WEBRTC_BASE_TEST(MuteStream);
+
+WEBRTC_BASE_TEST(MultipleSendStreams);
+
+WEBRTC_BASE_TEST(SetSendStreamFormat0x0);
// TODO(zhurunz): Fix the flakey test.
-TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_SetSendStreamFormat) {
- Base::SetSendStreamFormat();
+WEBRTC_DISABLED_BASE_TEST(SetSendStreamFormat);
+
+TEST_F(WebRtcVideoChannel2BaseTest, SendAndReceiveVp8Vga) {
+ SendAndReceive(cricket::VideoCodec(100, "VP8", 640, 400, 30, 0));
+}
+
+TEST_F(WebRtcVideoChannel2BaseTest, SendAndReceiveVp8Qvga) {
+ SendAndReceive(cricket::VideoCodec(100, "VP8", 320, 200, 30, 0));
+}
+
+TEST_F(WebRtcVideoChannel2BaseTest, SendAndReceiveVp8SvcQqvga) {
+ SendAndReceive(cricket::VideoCodec(100, "VP8", 160, 100, 30, 0));
}
TEST_F(WebRtcVideoChannel2BaseTest, TwoStreamsSendAndReceive) {
@@ -551,6 +578,32 @@
Base::TwoStreamsReUseFirstStream(kVp8Codec);
}
+WEBRTC_BASE_TEST(SendManyResizeOnce);
+
+// TODO(pbos): Enable and figure out why this fails (or should work).
+TEST_F(WebRtcVideoChannel2BaseTest, DISABLED_SendVp8HdAndReceiveAdaptedVp8Vga) {
+ EXPECT_TRUE(channel_->SetCapturer(kSsrc, NULL));
+ EXPECT_TRUE(channel_->SetRenderer(kDefaultReceiveSsrc, &renderer_));
+ channel_->UpdateAspectRatio(1280, 720);
+ video_capturer_.reset(new cricket::FakeVideoCapturer);
+ const std::vector<cricket::VideoFormat>* formats =
+ video_capturer_->GetSupportedFormats();
+ cricket::VideoFormat capture_format_hd = (*formats)[0];
+ EXPECT_EQ(cricket::CS_RUNNING, video_capturer_->Start(capture_format_hd));
+ EXPECT_TRUE(channel_->SetCapturer(kSsrc, video_capturer_.get()));
+
+ // Capture format HD -> adapt (OnOutputFormatRequest VGA) -> VGA.
+ cricket::VideoCodec codec(100, "VP8", 1280, 720, 30, 0);
+ EXPECT_TRUE(SetOneCodec(codec));
+ codec.width /= 2;
+ codec.height /= 2;
+ EXPECT_TRUE(SetSend(true));
+ EXPECT_TRUE(channel_->SetRender(true));
+ EXPECT_EQ(0, renderer_.num_rendered_frames());
+ EXPECT_TRUE(SendFrame());
+ EXPECT_FRAME_WAIT(1, codec.width, codec.height, kTimeout);
+}
+
class WebRtcVideoChannel2Test : public WebRtcVideoEngine2Test {
public:
virtual void SetUp() OVERRIDE {
@@ -559,6 +612,7 @@
last_ssrc_ = 123;
ASSERT_TRUE(fake_channel_ != NULL)
<< "Channel not created through factory.";
+ EXPECT_TRUE(fake_channel_->SetSendCodecs(engine_.codecs()));
}
protected:
@@ -615,17 +669,9 @@
EXPECT_EQ(max_bitrate, codec.params[kCodecParamMaxBitrate]);
}
- void ExpectEqualCodecs(const VideoCodec video_codec,
- const webrtc::VideoCodec& webrtc_codec) {
- EXPECT_STREQ(video_codec.name.c_str(), webrtc_codec.plName);
- EXPECT_EQ(video_codec.id, webrtc_codec.plType);
- EXPECT_EQ(video_codec.width, webrtc_codec.width);
- EXPECT_EQ(video_codec.height, webrtc_codec.height);
- EXPECT_EQ(video_codec.framerate, webrtc_codec.maxFramerate);
- }
-
void TestSetSendRtpHeaderExtensions(const std::string& cricket_ext,
const std::string& webrtc_ext) {
+ FakeCall* call = fake_channel_->GetFakeCall();
// Enable extension.
const int id = 1;
std::vector<cricket::RtpHeaderExtension> extensions;
@@ -647,15 +693,25 @@
->GetConfig()
.rtp.extensions.empty());
- // Remove the extension id, verify that this doesn't reset extensions as
- // they should be set before creating channels.
+ // Verify that existing RTP header extensions can be removed.
std::vector<cricket::RtpHeaderExtension> empty_extensions;
EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(empty_extensions));
- EXPECT_FALSE(send_stream->GetConfig().rtp.extensions.empty());
+ ASSERT_EQ(1u, call->GetVideoSendStreams().size());
+ send_stream = call->GetVideoSendStreams()[0];
+ EXPECT_TRUE(send_stream->GetConfig().rtp.extensions.empty());
+
+ // Verify that adding receive RTP header extensions adds them for existing
+ // streams.
+ EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
+ send_stream = call->GetVideoSendStreams()[0];
+ ASSERT_EQ(1u, send_stream->GetConfig().rtp.extensions.size());
+ EXPECT_EQ(id, send_stream->GetConfig().rtp.extensions[0].id);
+ EXPECT_EQ(webrtc_ext, send_stream->GetConfig().rtp.extensions[0].name);
}
void TestSetRecvRtpHeaderExtensions(const std::string& cricket_ext,
const std::string& webrtc_ext) {
+ FakeCall* call = fake_channel_->GetFakeCall();
// Enable extension.
const int id = 1;
std::vector<cricket::RtpHeaderExtension> extensions;
@@ -671,20 +727,30 @@
EXPECT_EQ(webrtc_ext, recv_stream->GetConfig().rtp.extensions[0].name);
// Verify call with same set of extensions returns true.
EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
+
// Verify that SetRecvRtpHeaderExtensions doesn't implicitly add them for
// senders.
EXPECT_TRUE(AddSendStream(cricket::StreamParams::CreateLegacy(123))
->GetConfig()
.rtp.extensions.empty());
- // Remove the extension id, verify that this doesn't reset extensions as
- // they should be set before creating channels.
+ // Verify that existing RTP header extensions can be removed.
std::vector<cricket::RtpHeaderExtension> empty_extensions;
- EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(empty_extensions));
- EXPECT_FALSE(recv_stream->GetConfig().rtp.extensions.empty());
+ EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(empty_extensions));
+ ASSERT_EQ(1u, call->GetVideoReceiveStreams().size());
+ recv_stream = call->GetVideoReceiveStreams()[0];
+ EXPECT_TRUE(recv_stream->GetConfig().rtp.extensions.empty());
+
+ // Verify that adding receive RTP header extensions adds them for existing
+ // streams.
+ EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
+ recv_stream = call->GetVideoReceiveStreams()[0];
+ ASSERT_EQ(1u, recv_stream->GetConfig().rtp.extensions.size());
+ EXPECT_EQ(id, recv_stream->GetConfig().rtp.extensions[0].id);
+ EXPECT_EQ(webrtc_ext, recv_stream->GetConfig().rtp.extensions[0].name);
}
- talk_base::scoped_ptr<VideoMediaChannel> channel_;
+ rtc::scoped_ptr<VideoMediaChannel> channel_;
FakeWebRtcVideoChannel2* fake_channel_;
uint32 last_ssrc_;
};
@@ -743,24 +809,6 @@
#endif
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_RtcpEnabled) {
- // Note(pbos): This is a receiver-side setting, dumbo.
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
-TEST_F(WebRtcVideoChannel2Test, DISABLED_KeyFrameRequestEnabled) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
-TEST_F(WebRtcVideoChannel2Test, RembIsEnabledByDefault) {
- FakeVideoReceiveStream* stream = AddRecvStream();
- EXPECT_TRUE(stream->GetConfig().rtp.remb);
-}
-
-TEST_F(WebRtcVideoChannel2Test, DISABLED_RembEnabledOnReceiveChannels) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
TEST_F(WebRtcVideoChannel2Test, RecvStreamWithSimAndRtx) {
EXPECT_TRUE(channel_->SetSendCodecs(engine_.codecs()));
EXPECT_TRUE(channel_->SetSend(true));
@@ -839,6 +887,110 @@
webrtc::RtpExtension::kAbsSendTime);
}
+TEST_F(WebRtcVideoChannel2Test,
+ SetSendRtpHeaderExtensionsExcludeUnsupportedExtensions) {
+ const int kUnsupportedId = 1;
+ const int kTOffsetId = 2;
+
+ std::vector<cricket::RtpHeaderExtension> extensions;
+ extensions.push_back(cricket::RtpHeaderExtension(
+ kUnsupportedExtensionName, kUnsupportedId));
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, kTOffsetId));
+ EXPECT_TRUE(channel_->SetSendRtpHeaderExtensions(extensions));
+ FakeVideoSendStream* send_stream =
+ AddSendStream(cricket::StreamParams::CreateLegacy(123));
+
+ // Only timestamp offset extension is set to send stream,
+ // unsupported rtp extension is ignored.
+ ASSERT_EQ(1u, send_stream->GetConfig().rtp.extensions.size());
+ EXPECT_STREQ(webrtc::RtpExtension::kTOffset,
+ send_stream->GetConfig().rtp.extensions[0].name.c_str());
+}
+
+TEST_F(WebRtcVideoChannel2Test,
+ SetRecvRtpHeaderExtensionsExcludeUnsupportedExtensions) {
+ const int kUnsupportedId = 1;
+ const int kTOffsetId = 2;
+
+ std::vector<cricket::RtpHeaderExtension> extensions;
+ extensions.push_back(cricket::RtpHeaderExtension(
+ kUnsupportedExtensionName, kUnsupportedId));
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, kTOffsetId));
+ EXPECT_TRUE(channel_->SetRecvRtpHeaderExtensions(extensions));
+ FakeVideoReceiveStream* recv_stream =
+ AddRecvStream(cricket::StreamParams::CreateLegacy(123));
+
+ // Only timestamp offset extension is set to receive stream,
+ // unsupported rtp extension is ignored.
+ ASSERT_EQ(1u, recv_stream->GetConfig().rtp.extensions.size());
+ EXPECT_STREQ(webrtc::RtpExtension::kTOffset,
+ recv_stream->GetConfig().rtp.extensions[0].name.c_str());
+}
+
+TEST_F(WebRtcVideoChannel2Test,
+ SetSendRtpHeaderExtensionsRejectsIncorrectIds) {
+ const size_t kNumIncorrectIds = 4;
+ const int kIncorrectIds[kNumIncorrectIds] = {-2, -1, 15, 16};
+ for (size_t i = 0; i < kNumIncorrectIds; ++i) {
+ std::vector<cricket::RtpHeaderExtension> extensions;
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, kIncorrectIds[i]));
+ EXPECT_FALSE(channel_->SetSendRtpHeaderExtensions(extensions))
+ << "Bad extension id '" << kIncorrectIds[i] << "' accepted.";
+ }
+}
+
+TEST_F(WebRtcVideoChannel2Test,
+ SetRecvRtpHeaderExtensionsRejectsIncorrectIds) {
+ const size_t kNumIncorrectIds = 4;
+ const int kIncorrectIds[kNumIncorrectIds] = {-2, -1, 15, 16};
+ for (size_t i = 0; i < kNumIncorrectIds; ++i) {
+ std::vector<cricket::RtpHeaderExtension> extensions;
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, kIncorrectIds[i]));
+ EXPECT_FALSE(channel_->SetRecvRtpHeaderExtensions(extensions))
+ << "Bad extension id '" << kIncorrectIds[i] << "' accepted.";
+ }
+}
+
+TEST_F(WebRtcVideoChannel2Test,
+ SetSendRtpHeaderExtensionsRejectsDuplicateIds) {
+ const int id = 1;
+ std::vector<cricket::RtpHeaderExtension> extensions;
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, id));
+ extensions.push_back(cricket::RtpHeaderExtension(
+ kRtpAbsoluteSenderTimeHeaderExtension, id));
+ EXPECT_FALSE(channel_->SetSendRtpHeaderExtensions(extensions));
+
+ // Duplicate entries are also not supported.
+ extensions.clear();
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, id));
+ extensions.push_back(extensions.back());
+ EXPECT_FALSE(channel_->SetSendRtpHeaderExtensions(extensions));
+}
+
+TEST_F(WebRtcVideoChannel2Test,
+ SetRecvRtpHeaderExtensionsRejectsDuplicateIds) {
+ const int id = 1;
+ std::vector<cricket::RtpHeaderExtension> extensions;
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, id));
+ extensions.push_back(cricket::RtpHeaderExtension(
+ kRtpAbsoluteSenderTimeHeaderExtension, id));
+ EXPECT_FALSE(channel_->SetRecvRtpHeaderExtensions(extensions));
+
+ // Duplicate entries are also not supported.
+ extensions.clear();
+ extensions.push_back(cricket::RtpHeaderExtension(
+ webrtc::RtpExtension::kTOffset, id));
+ extensions.push_back(extensions.back());
+ EXPECT_FALSE(channel_->SetRecvRtpHeaderExtensions(extensions));
+}
+
TEST_F(WebRtcVideoChannel2Test, DISABLED_LeakyBucketTest) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
@@ -856,12 +1008,28 @@
EXPECT_EQ(1u, fake_channel_->GetFakeCall()->GetVideoReceiveStreams().size());
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_NoRembChangeAfterAddRecvStream) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+TEST_F(WebRtcVideoChannel2Test, RembIsEnabledByDefault) {
+ FakeVideoReceiveStream* stream = AddRecvStream();
+ EXPECT_TRUE(stream->GetConfig().rtp.remb);
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_RembOnOff) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+TEST_F(WebRtcVideoChannel2Test, RembCanBeEnabledAndDisabled) {
+ FakeVideoReceiveStream* stream = AddRecvStream();
+ EXPECT_TRUE(stream->GetConfig().rtp.remb);
+
+ // Verify that REMB is turned off when codecs without REMB are set.
+ std::vector<VideoCodec> codecs;
+ codecs.push_back(kVp8Codec);
+ EXPECT_TRUE(codecs[0].feedback_params.params().empty());
+ EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
+ stream = fake_channel_->GetFakeCall()->GetVideoReceiveStreams()[0];
+ EXPECT_FALSE(stream->GetConfig().rtp.remb);
+
+ // Verify that REMB is turned on when setting default codecs since the
+ // default codecs have REMB enabled.
+ EXPECT_TRUE(channel_->SetRecvCodecs(engine_.codecs()));
+ stream = fake_channel_->GetFakeCall()->GetVideoReceiveStreams()[0];
+ EXPECT_TRUE(stream->GetConfig().rtp.remb);
}
TEST_F(WebRtcVideoChannel2Test, NackIsEnabledByDefault) {
@@ -951,15 +1119,82 @@
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SetOptionsWithDenoising) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+TEST_F(WebRtcVideoChannel2Test, SuspendBelowMinBitrateDisabledByDefault) {
+ FakeVideoSendStream* stream = AddSendStream();
+ EXPECT_FALSE(stream->GetConfig().suspend_below_min_bitrate);
+}
+
+TEST_F(WebRtcVideoChannel2Test, SetOptionsWithSuspendBelowMinBitrate) {
+ VideoOptions options;
+ options.suspend_below_min_bitrate.Set(true);
+ channel_->SetOptions(options);
+
+ FakeVideoSendStream* stream = AddSendStream();
+ EXPECT_TRUE(stream->GetConfig().suspend_below_min_bitrate);
+
+ options.suspend_below_min_bitrate.Set(false);
+ channel_->SetOptions(options);
+
+ stream = fake_channel_->GetFakeCall()->GetVideoSendStreams()[0];
+ EXPECT_FALSE(stream->GetConfig().suspend_below_min_bitrate);
+}
+
+TEST_F(WebRtcVideoChannel2Test, RedundantPayloadsDisabledByDefault) {
+ const std::vector<uint32> ssrcs = MAKE_VECTOR(kSsrcs1);
+ const std::vector<uint32> rtx_ssrcs = MAKE_VECTOR(kRtxSsrcs1);
+ FakeVideoSendStream* stream = AddSendStream(
+ cricket::CreateSimWithRtxStreamParams("cname", ssrcs, rtx_ssrcs));
+ EXPECT_FALSE(stream->GetConfig().rtp.rtx.pad_with_redundant_payloads);
+}
+
+TEST_F(WebRtcVideoChannel2Test, SetOptionsWithPayloadPadding) {
+ VideoOptions options;
+ options.use_payload_padding.Set(true);
+ channel_->SetOptions(options);
+
+ const std::vector<uint32> ssrcs = MAKE_VECTOR(kSsrcs1);
+ const std::vector<uint32> rtx_ssrcs = MAKE_VECTOR(kRtxSsrcs1);
+ FakeVideoSendStream* stream = AddSendStream(
+ cricket::CreateSimWithRtxStreamParams("cname", ssrcs, rtx_ssrcs));
+ EXPECT_TRUE(stream->GetConfig().rtp.rtx.pad_with_redundant_payloads);
+
+ options.use_payload_padding.Set(false);
+ channel_->SetOptions(options);
+
+ stream = fake_channel_->GetFakeCall()->GetVideoSendStreams()[0];
+ EXPECT_FALSE(stream->GetConfig().rtp.rtx.pad_with_redundant_payloads);
+}
+
+TEST_F(WebRtcVideoChannel2Test, Vp8DenoisingEnabledByDefault) {
+ FakeVideoSendStream* stream = AddSendStream();
+ webrtc::VideoCodecVP8 vp8_settings;
+ ASSERT_TRUE(stream->GetVp8Settings(&vp8_settings)) << "No VP8 config set.";
+ EXPECT_TRUE(vp8_settings.denoisingOn);
+}
+
+TEST_F(WebRtcVideoChannel2Test, SetOptionsWithDenoising) {
+ VideoOptions options;
+ options.video_noise_reduction.Set(false);
+ channel_->SetOptions(options);
+
+ FakeVideoSendStream* stream = AddSendStream();
+ webrtc::VideoCodecVP8 vp8_settings;
+ ASSERT_TRUE(stream->GetVp8Settings(&vp8_settings)) << "No VP8 config set.";
+ EXPECT_FALSE(vp8_settings.denoisingOn);
+
+ options.video_noise_reduction.Set(true);
+ channel_->SetOptions(options);
+
+ stream = fake_channel_->GetFakeCall()->GetVideoSendStreams()[0];
+ ASSERT_TRUE(stream->GetVp8Settings(&vp8_settings)) << "No VP8 config set.";
+ EXPECT_TRUE(vp8_settings.denoisingOn);
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_MultipleSendStreamsWithOneCapturer) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_DISABLED_SendReceiveBitratesStats) {
+TEST_F(WebRtcVideoChannel2Test, DISABLED_SendReceiveBitratesStats) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
@@ -996,16 +1231,14 @@
FakeVideoSendStream* stream = AddSendStream(
cricket::CreateSimWithRtxStreamParams("cname", ssrcs, rtx_ssrcs));
webrtc::VideoSendStream::Config config = stream->GetConfig();
- // TODO(pbos): Replace ExpectEqualCodecs.
- // ExpectEqualCodecs(engine_.codecs()[0], config.codec);
// Make sure NACK and FEC are enabled on the correct payload types.
EXPECT_EQ(1000, config.rtp.nack.rtp_history_ms);
EXPECT_EQ(default_ulpfec_codec_.id, config.rtp.fec.ulpfec_payload_type);
EXPECT_EQ(default_red_codec_.id, config.rtp.fec.red_payload_type);
- // TODO(pbos): Verify that the rtx ssrc is set, correct, not taken by anything
- // else.
- // ASSERT_EQ(1u, config.rtp.rtx.ssrcs.size());
+
+ EXPECT_EQ(1u, config.rtp.rtx.ssrcs.size());
+ EXPECT_EQ(kRtxSsrcs1[0], config.rtp.rtx.ssrcs[0]);
EXPECT_EQ(static_cast<int>(default_rtx_codec_.id),
config.rtp.rtx.payload_type);
// TODO(juberti): Check RTCP, PLI, TMMBR.
@@ -1024,28 +1257,68 @@
}
TEST_F(WebRtcVideoChannel2Test,
- DISABLED_SetSendCodecRejectsRtxWithoutAssociatedPayloadType) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+ SetSendCodecRejectsRtxWithoutAssociatedPayloadType) {
+ std::vector<VideoCodec> codecs;
+ cricket::VideoCodec rtx_codec(96, "rtx", 0, 0, 0, 0);
+ codecs.push_back(rtx_codec);
+ EXPECT_FALSE(channel_->SetSendCodecs(codecs))
+ << "RTX codec without associated payload type should be rejected.";
}
TEST_F(WebRtcVideoChannel2Test,
- DISABLED_SetSendCodecRejectsRtxWithoutMatchingVideoCodec) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+ SetSendCodecRejectsRtxWithoutMatchingVideoCodec) {
+ std::vector<VideoCodec> codecs;
+ cricket::VideoCodec rtx_codec =
+ cricket::VideoCodec::CreateRtxCodec(96, kVp8Codec.id);
+ codecs.push_back(kVp8Codec);
+ codecs.push_back(rtx_codec);
+ ASSERT_TRUE(channel_->SetSendCodecs(codecs));
+
+ cricket::VideoCodec rtx_codec2 =
+ cricket::VideoCodec::CreateRtxCodec(96, kVp8Codec.id + 1);
+ codecs.pop_back();
+ codecs.push_back(rtx_codec2);
+ EXPECT_FALSE(channel_->SetSendCodecs(codecs))
+ << "RTX without matching video codec should be rejected.";
}
-TEST_F(WebRtcVideoChannel2Test,
- DISABLED_SetCodecsWithoutFecDisablesCurrentFec) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+TEST_F(WebRtcVideoChannel2Test, SetSendCodecsWithoutFecDisablesFec) {
+ std::vector<VideoCodec> codecs;
+ codecs.push_back(kVp8Codec);
+ codecs.push_back(kUlpfecCodec);
+ ASSERT_TRUE(channel_->SetSendCodecs(codecs));
+
+ FakeVideoSendStream* stream = AddSendStream();
+ webrtc::VideoSendStream::Config config = stream->GetConfig();
+
+ EXPECT_EQ(kUlpfecCodec.id, config.rtp.fec.ulpfec_payload_type);
+
+ codecs.pop_back();
+ ASSERT_TRUE(channel_->SetSendCodecs(codecs));
+ stream = fake_channel_->GetFakeCall()->GetVideoSendStreams()[0];
+ ASSERT_TRUE(stream != NULL);
+ config = stream->GetConfig();
+ EXPECT_EQ(-1, config.rtp.fec.ulpfec_payload_type)
+ << "SetSendCodec without FEC should disable current FEC.";
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SetSendCodecsChangesExistingStreams) {
- FAIL(); // TODO(pbos): Implement, make sure that it's changing running
- // streams. Should it?
-}
+TEST_F(WebRtcVideoChannel2Test, SetSendCodecsChangesExistingStreams) {
+ std::vector<VideoCodec> codecs;
+ codecs.push_back(kVp8Codec720p);
+ ASSERT_TRUE(channel_->SetSendCodecs(codecs));
-TEST_F(WebRtcVideoChannel2Test,
- DISABLED_ConstrainsSetCodecsAccordingToEncoderConfig) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+ std::vector<webrtc::VideoStream> streams =
+ AddSendStream()->GetVideoStreams();
+ EXPECT_EQ(kVp8Codec720p.width, streams[0].width);
+ EXPECT_EQ(kVp8Codec720p.height, streams[0].height);
+
+ codecs.clear();
+ codecs.push_back(kVp8Codec360p);
+ ASSERT_TRUE(channel_->SetSendCodecs(codecs));
+ streams = fake_channel_->GetFakeCall()->GetVideoSendStreams()[0]
+ ->GetVideoStreams();
+ EXPECT_EQ(kVp8Codec360p.width, streams[0].width);
+ EXPECT_EQ(kVp8Codec360p.height, streams[0].height);
}
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsWithMinMaxBitrate) {
@@ -1158,10 +1431,13 @@
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SetRecvCodecsAcceptDefaultCodecs) {
+TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsAcceptDefaultCodecs) {
EXPECT_TRUE(channel_->SetRecvCodecs(engine_.codecs()));
- // (I've added this one.) Make sure they propagate down to VideoReceiveStream!
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+
+ FakeVideoReceiveStream* stream = AddRecvStream();
+ webrtc::VideoReceiveStream::Config config = stream->GetConfig();
+ EXPECT_STREQ(engine_.codecs()[0].name.c_str(), config.codecs[0].plName);
+ EXPECT_EQ(engine_.codecs()[0].id, config.codecs[0].plType);
}
TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsRejectUnsupportedCodec) {
@@ -1189,6 +1465,26 @@
FAIL(); // TODO(pbos): Verify that the FEC parameters are set for all codecs.
}
+TEST_F(WebRtcVideoChannel2Test, SetRecvCodecsWithoutFecDisablesFec) {
+ std::vector<VideoCodec> codecs;
+ codecs.push_back(kVp8Codec);
+ codecs.push_back(kUlpfecCodec);
+ ASSERT_TRUE(channel_->SetSendCodecs(codecs));
+
+ FakeVideoReceiveStream* stream = AddRecvStream();
+ webrtc::VideoReceiveStream::Config config = stream->GetConfig();
+
+ EXPECT_EQ(kUlpfecCodec.id, config.rtp.fec.ulpfec_payload_type);
+
+ codecs.pop_back();
+ ASSERT_TRUE(channel_->SetRecvCodecs(codecs));
+ stream = fake_channel_->GetFakeCall()->GetVideoReceiveStreams()[0];
+ ASSERT_TRUE(stream != NULL);
+ config = stream->GetConfig();
+ EXPECT_EQ(-1, config.rtp.fec.ulpfec_payload_type)
+ << "SetSendCodec without FEC should disable current FEC.";
+}
+
TEST_F(WebRtcVideoChannel2Test, SetSendCodecsRejectDuplicateFecPayloads) {
std::vector<VideoCodec> codecs;
codecs.push_back(kVp8Codec);
@@ -1218,25 +1514,12 @@
EXPECT_FALSE(AddSendStream()->IsSending());
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_ReceiveStreamReceivingByDefault) {
- // Is this test correct though? Auto-receive? Enable receive on first packet?
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+TEST_F(WebRtcVideoChannel2Test, ReceiveStreamReceivingByDefault) {
+ EXPECT_TRUE(AddRecvStream()->IsReceiving());
}
TEST_F(WebRtcVideoChannel2Test, SetSend) {
- AddSendStream();
- EXPECT_FALSE(channel_->SetSend(true))
- << "Channel should not start without codecs.";
- EXPECT_TRUE(channel_->SetSend(false))
- << "Channel should be stoppable even without set codecs.";
-
- std::vector<cricket::VideoCodec> codecs;
- codecs.push_back(kVp8Codec);
- channel_->SetSendCodecs(codecs);
- std::vector<FakeVideoSendStream*> streams = GetFakeSendStreams();
- ASSERT_EQ(1u, streams.size());
- FakeVideoSendStream* stream = streams.back();
-
+ FakeVideoSendStream* stream = AddSendStream();
EXPECT_FALSE(stream->IsSending());
// false->true
@@ -1258,26 +1541,6 @@
<< "Send stream created after SetSend(true) not sending initially.";
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SendAndReceiveVp8Vga) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SendAndReceiveVp8Qvga) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SendAndReceiveH264SvcQqvga) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SendManyResizeOnce) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
-TEST_F(WebRtcVideoChannel2Test, DISABLED_SendVp8HdAndReceiveAdaptedVp8Vga) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
-}
-
TEST_F(WebRtcVideoChannel2Test, DISABLED_TestSetDscpOptions) {
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
@@ -1357,8 +1620,17 @@
FAIL() << "Not implemented."; // TODO(pbos): Implement.
}
-TEST_F(WebRtcVideoChannel2Test, DISABLED_OnReadyToSend) {
- FAIL() << "Not implemented."; // TODO(pbos): Implement.
+TEST_F(WebRtcVideoChannel2Test, OnReadyToSendSignalsNetworkState) {
+ EXPECT_EQ(webrtc::Call::kNetworkUp,
+ fake_channel_->GetFakeCall()->GetNetworkState());
+
+ channel_->OnReadyToSend(false);
+ EXPECT_EQ(webrtc::Call::kNetworkDown,
+ fake_channel_->GetFakeCall()->GetNetworkState());
+
+ channel_->OnReadyToSend(true);
+ EXPECT_EQ(webrtc::Call::kNetworkUp,
+ fake_channel_->GetFakeCall()->GetNetworkState());
}
TEST_F(WebRtcVideoChannel2Test, DISABLED_CaptureFrameTimestampToNtpTimestamp) {
diff --git a/media/webrtc/webrtcvideoengine2_unittest.h b/media/webrtc/webrtcvideoengine2_unittest.h
index 879b4f4..30f1efb 100644
--- a/media/webrtc/webrtcvideoengine2_unittest.h
+++ b/media/webrtc/webrtcvideoengine2_unittest.h
@@ -39,18 +39,18 @@
class FakeVideoSendStream : public webrtc::VideoSendStream {
public:
FakeVideoSendStream(const webrtc::VideoSendStream::Config& config,
- const std::vector<webrtc::VideoStream>& video_streams);
+ const webrtc::VideoEncoderConfig& encoder_config);
webrtc::VideoSendStream::Config GetConfig();
std::vector<webrtc::VideoStream> GetVideoStreams();
- bool IsSending();
+ bool IsSending() const;
+ bool GetVp8Settings(webrtc::VideoCodecVP8* settings) const;
private:
virtual webrtc::VideoSendStream::Stats GetStats() const OVERRIDE;
virtual bool ReconfigureVideoEncoder(
- const std::vector<webrtc::VideoStream>& streams,
- const void* encoder_specific);
+ const webrtc::VideoEncoderConfig& config) OVERRIDE;
virtual webrtc::VideoSendStreamInput* Input() OVERRIDE;
@@ -59,7 +59,9 @@
bool sending_;
webrtc::VideoSendStream::Config config_;
- std::vector<webrtc::VideoStream> video_streams_;
+ webrtc::VideoEncoderConfig encoder_config_;
+ bool codec_settings_set_;
+ webrtc::VideoCodecVP8 vp8_settings_;
};
class FakeVideoReceiveStream : public webrtc::VideoReceiveStream {
@@ -69,6 +71,8 @@
webrtc::VideoReceiveStream::Config GetConfig();
+ bool IsReceiving() const;
+
private:
virtual webrtc::VideoReceiveStream::Stats GetStats() const OVERRIDE;
@@ -97,19 +101,16 @@
std::vector<webrtc::VideoCodec> GetDefaultVideoCodecs();
- private:
- virtual webrtc::VideoSendStream::Config GetDefaultSendConfig() OVERRIDE;
+ webrtc::Call::NetworkState GetNetworkState() const;
+ private:
virtual webrtc::VideoSendStream* CreateVideoSendStream(
const webrtc::VideoSendStream::Config& config,
- const std::vector<webrtc::VideoStream>& video_streams,
- const void* encoder_settings) OVERRIDE;
+ const webrtc::VideoEncoderConfig& encoder_config) OVERRIDE;
virtual void DestroyVideoSendStream(
webrtc::VideoSendStream* send_stream) OVERRIDE;
- virtual webrtc::VideoReceiveStream::Config GetDefaultReceiveConfig() OVERRIDE;
-
virtual webrtc::VideoReceiveStream* CreateVideoReceiveStream(
const webrtc::VideoReceiveStream::Config& config) OVERRIDE;
@@ -120,6 +121,9 @@
virtual uint32_t SendBitrateEstimate() OVERRIDE;
virtual uint32_t ReceiveBitrateEstimate() OVERRIDE;
+ virtual void SignalNetworkState(webrtc::Call::NetworkState state) OVERRIDE;
+
+ webrtc::Call::NetworkState network_state_;
std::vector<webrtc::VideoCodec> codecs_;
std::vector<FakeVideoSendStream*> video_send_streams_;
std::vector<FakeVideoReceiveStream*> video_receive_streams_;
diff --git a/media/webrtc/webrtcvideoengine_unittest.cc b/media/webrtc/webrtcvideoengine_unittest.cc
index 307e594..35f05e1 100644
--- a/media/webrtc/webrtcvideoengine_unittest.cc
+++ b/media/webrtc/webrtcvideoengine_unittest.cc
@@ -25,23 +25,17 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/fakecpumonitor.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stream.h"
#include "talk/media/base/constants.h"
-#include "talk/media/base/fakemediaprocessor.h"
#include "talk/media/base/fakenetworkinterface.h"
-#include "talk/media/base/fakevideorenderer.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/testutils.h"
-#include "talk/media/base/videoadapter.h"
#include "talk/media/base/videoengine_unittest.h"
-#include "talk/media/webrtc/fakewebrtcvideocapturemodule.h"
#include "talk/media/webrtc/fakewebrtcvideoengine.h"
-#include "talk/media/webrtc/fakewebrtcvoiceengine.h"
-#include "talk/media/webrtc/webrtcvideocapturer.h"
+#include "webrtc/base/fakecpumonitor.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stream.h"
#include "talk/media/webrtc/webrtcvideoengine.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
@@ -54,11 +48,9 @@
using cricket::kRtpAbsoluteSenderTimeHeaderExtension;
static const cricket::VideoCodec kVP8Codec720p(100, "VP8", 1280, 720, 30, 0);
-static const cricket::VideoCodec kVP8Codec360p(100, "VP8", 640, 360, 30, 0);
-static const cricket::VideoCodec kVP8Codec270p(100, "VP8", 480, 270, 30, 0);
-static const cricket::VideoCodec kVP8Codec180p(100, "VP8", 320, 180, 30, 0);
static const cricket::VideoCodec kVP8Codec(100, "VP8", 640, 400, 30, 0);
+static const cricket::VideoCodec kH264Codec(127, "H264", 640, 400, 30, 0);
static const cricket::VideoCodec kRedCodec(101, "red", 0, 0, 0, 0);
static const cricket::VideoCodec kUlpFecCodec(102, "ulpfec", 0, 0, 0, 0);
static const cricket::VideoCodec* const kVideoCodecs[] = {
@@ -68,7 +60,7 @@
};
static const unsigned int kStartBandwidthKbps = 300;
-static const unsigned int kMinBandwidthKbps = 50;
+static const unsigned int kMinBandwidthKbps = 30;
static const unsigned int kMaxBandwidthKbps = 2000;
static const uint32 kSsrcs1[] = {1};
@@ -77,7 +69,6 @@
static const uint32 kRtxSsrcs1[] = {4};
static const uint32 kRtxSsrcs3[] = {4, 5, 6};
-
class FakeViEWrapper : public cricket::ViEWrapper {
public:
explicit FakeViEWrapper(cricket::FakeWebRtcVideoEngine* engine)
@@ -99,8 +90,8 @@
public:
WebRtcVideoEngineTestFake()
: vie_(kVideoCodecs, ARRAY_SIZE(kVideoCodecs)),
- cpu_monitor_(new talk_base::FakeCpuMonitor(
- talk_base::Thread::Current())),
+ cpu_monitor_(new rtc::FakeCpuMonitor(
+ rtc::Thread::Current())),
engine_(NULL, // cricket::WebRtcVoiceEngine
new FakeViEWrapper(&vie_), cpu_monitor_),
channel_(NULL),
@@ -108,7 +99,7 @@
last_error_(cricket::VideoMediaChannel::ERROR_NONE) {
}
bool SetupEngine() {
- bool result = engine_.Init(talk_base::Thread::Current());
+ bool result = engine_.Init(rtc::Thread::Current());
if (result) {
channel_ = engine_.CreateChannel(voice_channel_);
channel_->SignalMediaError.connect(this,
@@ -252,7 +243,7 @@
EXPECT_EQ(100, gcodec.plType);
EXPECT_EQ(width, gcodec.width);
EXPECT_EQ(height, gcodec.height);
- EXPECT_EQ(talk_base::_min(start_bitrate, max_bitrate), gcodec.startBitrate);
+ EXPECT_EQ(rtc::_min(start_bitrate, max_bitrate), gcodec.startBitrate);
EXPECT_EQ(max_bitrate, gcodec.maxBitrate);
EXPECT_EQ(min_bitrate, gcodec.minBitrate);
EXPECT_EQ(fps, gcodec.maxFramerate);
@@ -272,7 +263,7 @@
cricket::FakeWebRtcVideoEngine vie_;
cricket::FakeWebRtcVideoDecoderFactory decoder_factory_;
cricket::FakeWebRtcVideoEncoderFactory encoder_factory_;
- talk_base::FakeCpuMonitor* cpu_monitor_;
+ rtc::FakeCpuMonitor* cpu_monitor_;
cricket::WebRtcVideoEngine engine_;
cricket::WebRtcVideoMediaChannel* channel_;
cricket::WebRtcVoiceMediaChannel* voice_channel_;
@@ -307,7 +298,7 @@
// Tests that our stub library "works".
TEST_F(WebRtcVideoEngineTestFake, StartupShutdown) {
EXPECT_FALSE(vie_.IsInited());
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
EXPECT_TRUE(vie_.IsInited());
engine_.Terminate();
}
@@ -315,16 +306,16 @@
// Tests that webrtc logs are logged when they should be.
TEST_F(WebRtcVideoEngineTest, WebRtcShouldLog) {
const char webrtc_log[] = "WebRtcVideoEngineTest.WebRtcShouldLog";
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
- engine_.SetLogging(talk_base::LS_INFO, "");
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
+ engine_.SetLogging(rtc::LS_INFO, "");
std::string str;
- talk_base::StringStream stream(str);
- talk_base::LogMessage::AddLogToStream(&stream, talk_base::LS_INFO);
- EXPECT_EQ(talk_base::LS_INFO, talk_base::LogMessage::GetLogToStream(&stream));
+ rtc::StringStream stream(str);
+ rtc::LogMessage::AddLogToStream(&stream, rtc::LS_INFO);
+ EXPECT_EQ(rtc::LS_INFO, rtc::LogMessage::GetLogToStream(&stream));
webrtc::Trace::Add(webrtc::kTraceStateInfo, webrtc::kTraceUndefined, 0,
webrtc_log);
- talk_base::Thread::Current()->ProcessMessages(100);
- talk_base::LogMessage::RemoveLogToStream(&stream);
+ rtc::Thread::Current()->ProcessMessages(100);
+ rtc::LogMessage::RemoveLogToStream(&stream);
// Access |str| after LogMessage is done with it to avoid data racing.
EXPECT_NE(std::string::npos, str.find(webrtc_log));
}
@@ -332,25 +323,25 @@
// Tests that webrtc logs are not logged when they should't be.
TEST_F(WebRtcVideoEngineTest, WebRtcShouldNotLog) {
const char webrtc_log[] = "WebRtcVideoEngineTest.WebRtcShouldNotLog";
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
// WebRTC should never be logged lower than LS_INFO.
- engine_.SetLogging(talk_base::LS_WARNING, "");
+ engine_.SetLogging(rtc::LS_WARNING, "");
std::string str;
- talk_base::StringStream stream(str);
+ rtc::StringStream stream(str);
// Make sure that WebRTC is not logged, even at lowest severity
- talk_base::LogMessage::AddLogToStream(&stream, talk_base::LS_SENSITIVE);
- EXPECT_EQ(talk_base::LS_SENSITIVE,
- talk_base::LogMessage::GetLogToStream(&stream));
+ rtc::LogMessage::AddLogToStream(&stream, rtc::LS_SENSITIVE);
+ EXPECT_EQ(rtc::LS_SENSITIVE,
+ rtc::LogMessage::GetLogToStream(&stream));
webrtc::Trace::Add(webrtc::kTraceStateInfo, webrtc::kTraceUndefined, 0,
webrtc_log);
- talk_base::Thread::Current()->ProcessMessages(10);
+ rtc::Thread::Current()->ProcessMessages(10);
EXPECT_EQ(std::string::npos, str.find(webrtc_log));
- talk_base::LogMessage::RemoveLogToStream(&stream);
+ rtc::LogMessage::RemoveLogToStream(&stream);
}
// Tests that we can create and destroy a channel.
TEST_F(WebRtcVideoEngineTestFake, CreateChannel) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel(voice_channel_);
EXPECT_TRUE(channel_ != NULL);
EXPECT_EQ(1, engine_.GetNumOfChannels());
@@ -362,7 +353,7 @@
// Tests that we properly handle failures in CreateChannel.
TEST_F(WebRtcVideoEngineTestFake, CreateChannelFail) {
vie_.set_fail_create_channel(true);
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel(voice_channel_);
EXPECT_TRUE(channel_ == NULL);
}
@@ -370,7 +361,7 @@
// Tests that we properly handle failures in AllocateExternalCaptureDevice.
TEST_F(WebRtcVideoEngineTestFake, AllocateExternalCaptureDeviceFail) {
vie_.set_fail_alloc_capturer(true);
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel(voice_channel_);
EXPECT_TRUE(channel_ == NULL);
}
@@ -430,8 +421,13 @@
codecs[0].params[cricket::kCodecParamStartBitrate] = "450";
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
- VerifyVP8SendCodec(
- channel_num, kVP8Codec.width, kVP8Codec.height, 0, 2000, 50, 450);
+ VerifyVP8SendCodec(channel_num,
+ kVP8Codec.width,
+ kVP8Codec.height,
+ 0,
+ kMaxBandwidthKbps,
+ kMinBandwidthKbps,
+ 450);
cricket::VideoCodec codec;
EXPECT_TRUE(channel_->GetSendCodec(&codec));
@@ -470,11 +466,11 @@
int channel_num = vie_.GetLastChannel();
std::vector<cricket::VideoCodec> codecs(engine_.codecs());
codecs[0].params[cricket::kCodecParamMinBitrate] = "1000";
- codecs[0].params[cricket::kCodecParamMaxBitrate] = "2000";
+ codecs[0].params[cricket::kCodecParamMaxBitrate] = "3000";
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
VerifyVP8SendCodec(
- channel_num, kVP8Codec.width, kVP8Codec.height, 0, 2000, 1000,
+ channel_num, kVP8Codec.width, kVP8Codec.height, 0, 3000, 1000,
1000);
}
@@ -485,9 +481,15 @@
codecs[0].params[cricket::kCodecParamMaxQuantization] = "21";
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
- VerifyVP8SendCodec(
- channel_num, kVP8Codec.width, kVP8Codec.height, 0, 2000, 50, 300,
- 30, 21);
+ VerifyVP8SendCodec(channel_num,
+ kVP8Codec.width,
+ kVP8Codec.height,
+ 0,
+ kMaxBandwidthKbps,
+ kMinBandwidthKbps,
+ 300,
+ 30,
+ 21);
cricket::VideoCodec codec;
EXPECT_TRUE(channel_->GetSendCodec(&codec));
@@ -519,25 +521,6 @@
channel_num, kVP8Codec.width, kVP8Codec.height, 0, 20, 10, 20);
}
-TEST_F(WebRtcVideoEngineTestFake, SetOptionsWithLoweredBitrate) {
- EXPECT_TRUE(SetupEngine());
- int channel_num = vie_.GetLastChannel();
- std::vector<cricket::VideoCodec> codecs(engine_.codecs());
- codecs[0].params[cricket::kCodecParamMinBitrate] = "50";
- codecs[0].params[cricket::kCodecParamMaxBitrate] = "100";
- EXPECT_TRUE(channel_->SetSendCodecs(codecs));
-
- VerifyVP8SendCodec(
- channel_num, kVP8Codec.width, kVP8Codec.height, 0, 100, 50, 100);
-
- // Verify that min bitrate changes after SetOptions().
- cricket::VideoOptions options;
- options.lower_min_bitrate.Set(true);
- EXPECT_TRUE(channel_->SetOptions(options));
- VerifyVP8SendCodec(
- channel_num, kVP8Codec.width, kVP8Codec.height, 0, 100, 30, 100);
-}
-
TEST_F(WebRtcVideoEngineTestFake, MaxBitrateResetWithConferenceMode) {
EXPECT_TRUE(SetupEngine());
int channel_num = vie_.GetLastChannel();
@@ -570,36 +553,33 @@
std::vector<cricket::VideoCodec> codec_list;
codec_list.push_back(codec);
EXPECT_TRUE(channel_->SetSendCodecs(codec_list));
- const unsigned int kVideoMaxSendBitrateKbps = 2000;
- const unsigned int kVideoMinSendBitrateKbps = 50;
- const unsigned int kVideoDefaultStartSendBitrateKbps = 300;
VerifyVP8SendCodec(send_channel, kVP8Codec.width, kVP8Codec.height, 0,
- kVideoMaxSendBitrateKbps, kVideoMinSendBitrateKbps,
- kVideoDefaultStartSendBitrateKbps);
+ kMaxBandwidthKbps, kMinBandwidthKbps,
+ kStartBandwidthKbps);
EXPECT_EQ(0, vie_.StartSend(send_channel));
// Increase the send bitrate and verify it is used as start bitrate.
- const unsigned int kVideoSendBitrateBps = 768000;
- vie_.SetSendBitrates(send_channel, kVideoSendBitrateBps, 0, 0);
+ const unsigned int kIncreasedSendBitrateBps = 768000;
+ vie_.SetSendBitrates(send_channel, kIncreasedSendBitrateBps, 0, 0);
EXPECT_TRUE(channel_->SetSendCodecs(codec_list));
VerifyVP8SendCodec(send_channel, kVP8Codec.width, kVP8Codec.height, 0,
- kVideoMaxSendBitrateKbps, kVideoMinSendBitrateKbps,
- kVideoSendBitrateBps / 1000);
+ kMaxBandwidthKbps, kMinBandwidthKbps,
+ kIncreasedSendBitrateBps / 1000);
// Never set a start bitrate higher than the max bitrate.
- vie_.SetSendBitrates(send_channel, kVideoMaxSendBitrateKbps + 500, 0, 0);
+ vie_.SetSendBitrates(send_channel, kMaxBandwidthKbps + 500, 0, 0);
EXPECT_TRUE(channel_->SetSendCodecs(codec_list));
VerifyVP8SendCodec(send_channel, kVP8Codec.width, kVP8Codec.height, 0,
- kVideoMaxSendBitrateKbps, kVideoMinSendBitrateKbps,
- kVideoDefaultStartSendBitrateKbps);
+ kMaxBandwidthKbps, kMinBandwidthKbps,
+ kStartBandwidthKbps);
// Use the default start bitrate if the send bitrate is lower.
- vie_.SetSendBitrates(send_channel, kVideoDefaultStartSendBitrateKbps - 50, 0,
+ vie_.SetSendBitrates(send_channel, kStartBandwidthKbps - 50, 0,
0);
EXPECT_TRUE(channel_->SetSendCodecs(codec_list));
VerifyVP8SendCodec(send_channel, kVP8Codec.width, kVP8Codec.height, 0,
- kVideoMaxSendBitrateKbps, kVideoMinSendBitrateKbps,
- kVideoDefaultStartSendBitrateKbps);
+ kMaxBandwidthKbps, kMinBandwidthKbps,
+ kStartBandwidthKbps);
}
@@ -778,9 +758,9 @@
memset(data, 0, sizeof(data));
data[0] = 0x80;
data[1] = rtx_codec.id;
- talk_base::SetBE32(&data[8], kRtxSsrcs1[0]);
- talk_base::Buffer packet(data, kDataLength);
- talk_base::PacketTime packet_time;
+ rtc::SetBE32(&data[8], kRtxSsrcs1[0]);
+ rtc::Buffer packet(data, kDataLength);
+ rtc::PacketTime packet_time;
channel_->OnPacketReceived(&packet, packet_time);
EXPECT_EQ(rtx_codec.id, vie_.GetLastRecvdPayloadType(channel_num));
}
@@ -814,9 +794,9 @@
memset(data, 0, sizeof(data));
data[0] = 0x80;
data[1] = rtx_codec.id;
- talk_base::SetBE32(&data[8], kRtxSsrcs3[1]);
- talk_base::Buffer packet(data, kDataLength);
- talk_base::PacketTime packet_time;
+ rtc::SetBE32(&data[8], kRtxSsrcs3[1]);
+ rtc::Buffer packet(data, kDataLength);
+ rtc::PacketTime packet_time;
channel_->OnPacketReceived(&packet, packet_time);
EXPECT_NE(rtx_codec.id, vie_.GetLastRecvdPayloadType(channel_num[0]));
EXPECT_EQ(rtx_codec.id, vie_.GetLastRecvdPayloadType(channel_num[1]));
@@ -1566,7 +1546,6 @@
768, kMinBandwidthKbps, kStartBandwidthKbps);
}
-
// Test that sending screencast frames doesn't change bitrate.
TEST_F(WebRtcVideoEngineTestFake, SetBandwidthScreencast) {
EXPECT_TRUE(SetupEngine());
@@ -1586,7 +1565,6 @@
VerifyVP8SendCodec(channel_num, kVP8Codec.width, kVP8Codec.height, 0, 111);
}
-
// Test SetSendSsrc.
TEST_F(WebRtcVideoEngineTestFake, SetSendSsrcAndCname) {
EXPECT_TRUE(SetupEngine());
@@ -1607,7 +1585,6 @@
EXPECT_STREQ("cname", rtcp_cname);
}
-
// Test that the local SSRC is the same on sending and receiving channels if the
// receive channel is created before the send channel.
TEST_F(WebRtcVideoEngineTestFake, SetSendSsrcAfterCreatingReceiveChannel) {
@@ -1628,7 +1605,6 @@
EXPECT_EQ(1, vie_.GetNumSsrcs(receive_channel_num));
}
-
// Test SetOptions with denoising flag.
TEST_F(WebRtcVideoEngineTestFake, SetOptionsWithDenoising) {
EXPECT_TRUE(SetupEngine());
@@ -1717,7 +1693,6 @@
EXPECT_EQ(-1, vie_.GetIncomingFrameNum(channel1));
}
-
TEST_F(WebRtcVideoEngineTestFake, SendReceiveBitratesStats) {
EXPECT_TRUE(SetupEngine());
cricket::VideoOptions options;
@@ -1849,7 +1824,6 @@
EXPECT_EQ(high, 1.0f);
}
-
TEST_F(WebRtcVideoEngineTestFake, ResetCodecOnScreencast) {
EXPECT_TRUE(SetupEngine());
cricket::VideoOptions options;
@@ -1880,7 +1854,6 @@
EXPECT_FALSE(gcodec.codecSpecific.VP8.denoisingOn);
}
-
TEST_F(WebRtcVideoEngineTestFake, DontRegisterDecoderIfFactoryIsNotGiven) {
engine_.SetExternalDecoderFactory(NULL);
EXPECT_TRUE(SetupEngine());
@@ -2125,6 +2098,144 @@
EXPECT_TRUE(channel_->RemoveSendStream(kSsrc));
}
+#ifdef USE_WEBRTC_DEV_BRANCH
+TEST_F(WebRtcVideoEngineTestFake, SetSendCodecsWithExternalH264) {
+ encoder_factory_.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
+ engine_.SetExternalEncoderFactory(&encoder_factory_);
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = vie_.GetLastChannel();
+
+ std::vector<cricket::VideoCodec> codecs;
+ codecs.push_back(kH264Codec);
+ cricket::VideoCodec rtx_codec(96, "rtx", 0, 0, 0, 0);
+ rtx_codec.SetParam("apt", kH264Codec.id);
+ codecs.push_back(rtx_codec);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+
+ EXPECT_EQ(96, vie_.GetRtxSendPayloadType(channel_num));
+
+ cricket::StreamParams params =
+ cricket::StreamParams::CreateLegacy(kSsrcs1[0]);
+ params.AddFidSsrc(kSsrcs1[0], kRtxSsrcs1[0]);
+ EXPECT_TRUE(channel_->AddSendStream(params));
+
+ EXPECT_EQ(1, vie_.GetNumSsrcs(channel_num));
+ EXPECT_EQ(1, vie_.GetNumRtxSsrcs(channel_num));
+ EXPECT_EQ(static_cast<int>(kRtxSsrcs1[0]), vie_.GetRtxSsrc(channel_num, 0));
+
+ EXPECT_TRUE(vie_.ExternalEncoderRegistered(channel_num, 127));
+ EXPECT_EQ(1, vie_.GetNumExternalEncoderRegistered(channel_num));
+ EXPECT_EQ(1, encoder_factory_.GetNumCreatedEncoders());
+
+ EXPECT_TRUE(channel_->RemoveSendStream(kSsrcs1[0]));
+}
+
+TEST_F(WebRtcVideoEngineTestFake, SetSendCodecsWithVP8AndExternalH264) {
+ encoder_factory_.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
+ engine_.SetExternalEncoderFactory(&encoder_factory_);
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = vie_.GetLastChannel();
+
+ std::vector<cricket::VideoCodec> codecs;
+ codecs.push_back(kH264Codec);
+ cricket::VideoCodec rtx_codec(96, "rtx", 0, 0, 0, 0);
+ rtx_codec.SetParam("apt", kH264Codec.id);
+ codecs.push_back(rtx_codec);
+ codecs.push_back(kVP8Codec);
+ cricket::VideoCodec rtx_codec2(97, "rtx", 0, 0, 0, 0);
+ rtx_codec2.SetParam("apt", kVP8Codec.id);
+ codecs.push_back(rtx_codec2);
+
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+
+ // The first matched codec should be set, i.e., H.264.
+
+ EXPECT_EQ(96, vie_.GetRtxSendPayloadType(channel_num));
+
+ cricket::StreamParams params =
+ cricket::StreamParams::CreateLegacy(kSsrcs1[0]);
+ params.AddFidSsrc(kSsrcs1[0], kRtxSsrcs1[0]);
+ EXPECT_TRUE(channel_->AddSendStream(params));
+
+ EXPECT_EQ(1, vie_.GetNumSsrcs(channel_num));
+ EXPECT_EQ(1, vie_.GetNumRtxSsrcs(channel_num));
+ EXPECT_EQ(static_cast<int>(kRtxSsrcs1[0]), vie_.GetRtxSsrc(channel_num, 0));
+
+ EXPECT_TRUE(vie_.ExternalEncoderRegistered(channel_num, 127));
+ EXPECT_EQ(1, vie_.GetNumExternalEncoderRegistered(channel_num));
+ EXPECT_EQ(1, encoder_factory_.GetNumCreatedEncoders());
+
+ EXPECT_TRUE(channel_->RemoveSendStream(kSsrcs1[0]));
+}
+
+TEST_F(WebRtcVideoEngineTestFake, SetRecvCodecsWithExternalH264) {
+ // WebRtcVideoEngine assumes that if we have encode support for a codec, we
+ // also have decode support. It doesn't support decode only support. Therefore
+ // we here have to register both an encoder and a decoder factory with H264
+ // support, to be able to test the decoder factory.
+ encoder_factory_.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
+ decoder_factory_.AddSupportedVideoCodecType(webrtc::kVideoCodecH264);
+ EXPECT_TRUE(SetupEngine());
+ engine_.SetExternalEncoderFactory(&encoder_factory_);
+ engine_.SetExternalDecoderFactory(&decoder_factory_);
+ int channel_num = vie_.GetLastChannel();
+
+ std::vector<cricket::VideoCodec> codecs;
+ codecs.push_back(kH264Codec);
+ cricket::VideoCodec rtx_codec(96, "rtx", 0, 0, 0, 0);
+ rtx_codec.SetParam("apt", kH264Codec.id);
+ codecs.push_back(rtx_codec);
+ EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
+
+ EXPECT_EQ(96, vie_.GetRtxRecvPayloadType(channel_num));
+
+ cricket::StreamParams params =
+ cricket::StreamParams::CreateLegacy(kSsrcs1[0]);
+ params.AddFidSsrc(kSsrcs1[0], kRtxSsrcs1[0]);
+ EXPECT_TRUE(channel_->AddRecvStream(params));
+
+ EXPECT_EQ(1, vie_.GetNumSsrcs(channel_num));
+ EXPECT_EQ(static_cast<int>(kRtxSsrcs1[0]),
+ vie_.GetRemoteRtxSsrc(channel_num));
+
+ EXPECT_TRUE(vie_.ExternalDecoderRegistered(channel_num, 127));
+ EXPECT_EQ(1, vie_.GetNumExternalDecoderRegistered(channel_num));
+ EXPECT_EQ(1, decoder_factory_.GetNumCreatedDecoders());
+
+ EXPECT_TRUE(channel_->RemoveRecvStream(kSsrcs1[0]));
+}
+
+TEST_F(WebRtcVideoEngineTestFake, SetRecvCodecsWithVP8AndExternalH264) {
+ encoder_factory_.AddSupportedVideoCodecType(webrtc::kVideoCodecH264, "H264");
+ decoder_factory_.AddSupportedVideoCodecType(webrtc::kVideoCodecH264);
+ EXPECT_TRUE(SetupEngine());
+ engine_.SetExternalEncoderFactory(&encoder_factory_);
+ engine_.SetExternalDecoderFactory(&decoder_factory_);
+ int channel_num = vie_.GetLastChannel();
+
+ std::vector<cricket::VideoCodec> codecs;
+ cricket::VideoCodec rtx_codec(97, "rtx", 0, 0, 0, 0);
+ rtx_codec.SetParam("apt", kH264Codec.id);
+ codecs.push_back(kH264Codec);
+ codecs.push_back(rtx_codec);
+
+ cricket::VideoCodec rtx_codec2(96, "rtx", 0, 0, 0, 0);
+ rtx_codec2.SetParam("apt", kVP8Codec.id);
+ codecs.push_back(kVP8Codec);
+ codecs.push_back(rtx_codec);
+ // Should fail since WebRTC only supports one RTX codec at a time.
+ EXPECT_FALSE(channel_->SetRecvCodecs(codecs));
+
+ codecs.pop_back();
+
+ // One RTX codec should be fine.
+ EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
+
+ // The RTX payload type should have been set.
+ EXPECT_EQ(rtx_codec.id, vie_.GetRtxRecvPayloadType(channel_num));
+}
+#endif
+
// Tests that OnReadyToSend will be propagated into ViE.
TEST_F(WebRtcVideoEngineTestFake, OnReadyToSend) {
EXPECT_TRUE(SetupEngine());
@@ -2152,10 +2263,10 @@
EXPECT_TRUE(channel_->SetSendCodecs(codec_list));
EXPECT_TRUE(channel_->SetSend(true));
- int64 timestamp = time(NULL) * talk_base::kNumNanosecsPerSec;
+ int64 timestamp = time(NULL) * rtc::kNumNanosecsPerSec;
SendI420ScreencastFrameWithTimestamp(
kVP8Codec.width, kVP8Codec.height, timestamp);
- EXPECT_EQ(talk_base::UnixTimestampNanosecsToNtpMillisecs(timestamp),
+ EXPECT_EQ(rtc::UnixTimestampNanosecsToNtpMillisecs(timestamp),
vie_.GetCaptureLastTimestamp(capture_id));
SendI420ScreencastFrameWithTimestamp(kVP8Codec.width, kVP8Codec.height, 0);
@@ -2188,7 +2299,9 @@
EXPECT_TRUE(engine_.FindCodec(vp8_diff_id));
cricket::VideoCodec vp8_diff_res(104, "VP8", 320, 111, 30, 0);
- EXPECT_FALSE(engine_.FindCodec(vp8_diff_res));
+ // FindCodec ignores the codec size.
+ // Test that FindCodec can accept uncommon codec size.
+ EXPECT_TRUE(engine_.FindCodec(vp8_diff_res));
// PeerConnection doesn't negotiate the resolution at this point.
// Test that FindCodec can handle the case when width/height is 0.
@@ -2228,15 +2341,12 @@
}
TEST_F(WebRtcVideoEngineTest, StartupShutdown) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
engine_.Terminate();
}
-TEST_PRE_VIDEOENGINE_INIT(WebRtcVideoEngineTest, ConstrainNewCodec)
-TEST_POST_VIDEOENGINE_INIT(WebRtcVideoEngineTest, ConstrainNewCodec)
-
-TEST_PRE_VIDEOENGINE_INIT(WebRtcVideoEngineTest, ConstrainRunningCodec)
-TEST_POST_VIDEOENGINE_INIT(WebRtcVideoEngineTest, ConstrainRunningCodec)
+TEST_PRE_VIDEOENGINE_INIT(WebRtcVideoEngineTest, ConstrainNewCodec2)
+TEST_POST_VIDEOENGINE_INIT(WebRtcVideoEngineTest, ConstrainNewCodec2)
// TODO(juberti): Figure out why ViE is munging the COM refcount.
#ifdef WIN32
@@ -2246,7 +2356,7 @@
#endif
TEST_F(WebRtcVideoEngineTest, CreateChannel) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
cricket::VideoMediaChannel* channel = engine_.CreateChannel(NULL);
EXPECT_TRUE(channel != NULL);
delete channel;
@@ -2395,23 +2505,26 @@
// This test verifies DSCP settings are properly applied on video media channel.
TEST_F(WebRtcVideoMediaChannelTest, TestSetDscpOptions) {
- talk_base::scoped_ptr<cricket::FakeNetworkInterface> network_interface(
+ rtc::scoped_ptr<cricket::FakeNetworkInterface> network_interface(
new cricket::FakeNetworkInterface);
channel_->SetInterface(network_interface.get());
cricket::VideoOptions options;
options.dscp.Set(true);
EXPECT_TRUE(channel_->SetOptions(options));
- EXPECT_EQ(talk_base::DSCP_AF41, network_interface->dscp());
+ EXPECT_EQ(rtc::DSCP_AF41, network_interface->dscp());
// Verify previous value is not modified if dscp option is not set.
cricket::VideoOptions options1;
EXPECT_TRUE(channel_->SetOptions(options1));
- EXPECT_EQ(talk_base::DSCP_AF41, network_interface->dscp());
+ EXPECT_EQ(rtc::DSCP_AF41, network_interface->dscp());
options.dscp.Set(false);
EXPECT_TRUE(channel_->SetOptions(options));
- EXPECT_EQ(talk_base::DSCP_DEFAULT, network_interface->dscp());
+ EXPECT_EQ(rtc::DSCP_DEFAULT, network_interface->dscp());
channel_->SetInterface(NULL);
}
+TEST_F(WebRtcVideoMediaChannelTest, HighAspectHighHeightCapturer) {
+ Base::HighAspectHighHeightCapturer();
+}
TEST_F(WebRtcVideoMediaChannelTest, SetOptionsSucceedsWhenSending) {
cricket::VideoOptions options;
@@ -2440,7 +2553,6 @@
Base::RejectEmptyStreamParams();
}
-
TEST_F(WebRtcVideoMediaChannelTest, AdaptResolution16x10) {
Base::AdaptResolution16x10();
}
@@ -2492,7 +2604,6 @@
TEST_F(WebRtcVideoMediaChannelTest,
TwoStreamsSendAndFailUnsignalledRecv) {
- webrtc::Trace::set_level_filter(webrtc::kTraceAll);
Base::TwoStreamsSendAndFailUnsignalledRecv(
cricket::VideoCodec(100, "VP8", 640, 400, 30, 0));
}
diff --git a/media/webrtc/webrtcvideoframe.cc b/media/webrtc/webrtcvideoframe.cc
index 1cc6fe9..9e4ea06 100644
--- a/media/webrtc/webrtcvideoframe.cc
+++ b/media/webrtc/webrtcvideoframe.cc
@@ -30,9 +30,9 @@
#include "libyuv/convert.h"
#include "libyuv/convert_from.h"
#include "libyuv/planar_functions.h"
-#include "talk/base/logging.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -56,7 +56,7 @@
const webrtc::VideoFrame* frame() const;
private:
- talk_base::scoped_ptr<uint8[]> owned_data_;
+ rtc::scoped_ptr<uint8[]> owned_data_;
webrtc::VideoFrame video_frame_;
};
@@ -157,7 +157,7 @@
void WebRtcVideoFrame::Alias(
uint8* buffer, size_t buffer_size, int w, int h, size_t pixel_width,
size_t pixel_height, int64 elapsed_time, int64 time_stamp, int rotation) {
- talk_base::scoped_refptr<RefCountedBuffer> video_buffer(
+ rtc::scoped_refptr<RefCountedBuffer> video_buffer(
new RefCountedBuffer());
video_buffer->Alias(buffer, buffer_size);
Attach(video_buffer.get(), buffer_size, w, h, pixel_width, pixel_height,
@@ -324,7 +324,7 @@
}
size_t desired_size = SizeOf(new_width, new_height);
- talk_base::scoped_refptr<RefCountedBuffer> video_buffer(
+ rtc::scoped_refptr<RefCountedBuffer> video_buffer(
new RefCountedBuffer(desired_size));
// Since the libyuv::ConvertToI420 will handle the rotation, so the
// new frame's rotation should always be 0.
@@ -368,7 +368,7 @@
size_t pixel_height,
int64 elapsed_time, int64 time_stamp) {
size_t buffer_size = VideoFrame::SizeOf(w, h);
- talk_base::scoped_refptr<RefCountedBuffer> video_buffer(
+ rtc::scoped_refptr<RefCountedBuffer> video_buffer(
new RefCountedBuffer(buffer_size));
Attach(video_buffer.get(), buffer_size, w, h, pixel_width, pixel_height,
elapsed_time, time_stamp, 0);
diff --git a/media/webrtc/webrtcvideoframe.h b/media/webrtc/webrtcvideoframe.h
index 4ba7ab6..c492ff1 100644
--- a/media/webrtc/webrtcvideoframe.h
+++ b/media/webrtc/webrtcvideoframe.h
@@ -28,10 +28,10 @@
#ifndef TALK_MEDIA_WEBRTCVIDEOFRAME_H_
#define TALK_MEDIA_WEBRTCVIDEOFRAME_H_
-#include "talk/base/buffer.h"
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ref_ptr.h"
#include "talk/media/base/videoframe.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/refcount.h"
+#include "webrtc/base/scoped_ref_ptr.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/interface/module_common_types.h"
@@ -108,7 +108,7 @@
private:
class FrameBuffer;
- typedef talk_base::RefCountedObject<FrameBuffer> RefCountedBuffer;
+ typedef rtc::RefCountedObject<FrameBuffer> RefCountedBuffer;
void Attach(RefCountedBuffer* video_buffer, size_t buffer_size, int w, int h,
size_t pixel_width, size_t pixel_height, int64 elapsed_time,
@@ -120,7 +120,7 @@
void InitToEmptyBuffer(int w, int h, size_t pixel_width, size_t pixel_height,
int64 elapsed_time, int64 time_stamp);
- talk_base::scoped_refptr<RefCountedBuffer> video_buffer_;
+ rtc::scoped_refptr<RefCountedBuffer> video_buffer_;
bool is_black_;
size_t pixel_width_;
size_t pixel_height_;
diff --git a/media/webrtc/webrtcvideoframe_unittest.cc b/media/webrtc/webrtcvideoframe_unittest.cc
index e63c5d5..5f65c58 100644
--- a/media/webrtc/webrtcvideoframe_unittest.cc
+++ b/media/webrtc/webrtcvideoframe_unittest.cc
@@ -25,16 +25,12 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/flags.h"
#include "talk/media/base/videoframe_unittest.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
-extern int FLAG_yuvconverter_repeat; // From lmivideoframe_unittest.cc.
-
class WebRtcVideoFrameTest : public VideoFrameTest<cricket::WebRtcVideoFrame> {
public:
WebRtcVideoFrameTest() {
- repeat_ = FLAG_yuvconverter_repeat;
}
void TestInit(int cropped_width, int cropped_height) {
@@ -53,7 +49,7 @@
captured_frame.height = frame_height;
captured_frame.data_size = (frame_width * frame_height) +
((frame_width + 1) / 2) * ((frame_height + 1) / 2) * 2;
- talk_base::scoped_ptr<uint8[]> captured_frame_buffer(
+ rtc::scoped_ptr<uint8[]> captured_frame_buffer(
new uint8[captured_frame.data_size]);
captured_frame.data = captured_frame_buffer.get();
@@ -136,7 +132,7 @@
TEST_WEBRTCVIDEOFRAME(ConstructBlack)
// TODO(fbarchard): Implement Jpeg
// TEST_WEBRTCVIDEOFRAME(ConstructMjpgI420)
-// TEST_WEBRTCVIDEOFRAME(ConstructMjpgI422)
+TEST_WEBRTCVIDEOFRAME(ConstructMjpgI422)
// TEST_WEBRTCVIDEOFRAME(ConstructMjpgI444)
// TEST_WEBRTCVIDEOFRAME(ConstructMjpgI411)
// TEST_WEBRTCVIDEOFRAME(ConstructMjpgI400)
diff --git a/media/webrtc/webrtcvideoframefactory.cc b/media/webrtc/webrtcvideoframefactory.cc
new file mode 100755
index 0000000..07b6663
--- /dev/null
+++ b/media/webrtc/webrtcvideoframefactory.cc
@@ -0,0 +1,47 @@
+/*
+ * libjingle
+ * Copyright 2014 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "talk/media/webrtc/webrtcvideoframe.h"
+#include "talk/media/webrtc/webrtcvideoframefactory.h"
+#include "webrtc/base/logging.h"
+
+namespace cricket {
+
+VideoFrame* WebRtcVideoFrameFactory::CreateAliasedFrame(
+ const CapturedFrame* aliased_frame, int width, int height) const {
+ // TODO(pthatcher): Move Alias logic into the VideoFrameFactory and
+ // out of the VideoFrame.
+ rtc::scoped_ptr<WebRtcVideoFrame> frame(new WebRtcVideoFrame());
+ if (!frame->Alias(aliased_frame, width, height)) {
+ LOG(LS_ERROR) <<
+ "Failed to create WebRtcVideoFrame in CreateAliasedFrame.";
+ return NULL;
+ }
+ return frame.release();
+}
+
+} // namespace cricket
diff --git a/media/webrtc/webrtcvideoframefactory.h b/media/webrtc/webrtcvideoframefactory.h
new file mode 100755
index 0000000..448cdcf
--- /dev/null
+++ b/media/webrtc/webrtcvideoframefactory.h
@@ -0,0 +1,45 @@
+// libjingle
+// Copyright 2014 Google Inc.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+
+#ifndef TALK_MEDIA_WEBRTC_WEBRTCVIDEOFRAMEFACTORY_H_
+#define TALK_MEDIA_WEBRTC_WEBRTCVIDEOFRAMEFACTORY_H_
+
+#include "talk/media/base/videoframefactory.h"
+
+namespace cricket {
+
+struct CapturedFrame;
+
+// Creates instances of cricket::WebRtcVideoFrame.
+class WebRtcVideoFrameFactory : public VideoFrameFactory {
+ public:
+ virtual VideoFrame* CreateAliasedFrame(
+ const CapturedFrame* aliased_frame, int width, int height) const OVERRIDE;
+};
+
+} // namespace cricket
+
+#endif // TALK_MEDIA_WEBRTC_WEBRTCVIDEOFRAMEFACTORY_H_
diff --git a/media/webrtc/webrtcvie.h b/media/webrtc/webrtcvie.h
index 9550962..190ad8b 100644
--- a/media/webrtc/webrtcvie.h
+++ b/media/webrtc/webrtcvie.h
@@ -29,8 +29,8 @@
#ifndef TALK_MEDIA_WEBRTCVIE_H_
#define TALK_MEDIA_WEBRTCVIE_H_
-#include "talk/base/common.h"
#include "talk/media/webrtc/webrtccommon.h"
+#include "webrtc/base/common.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/modules/video_capture/include/video_capture.h"
diff --git a/media/webrtc/webrtcvoe.h b/media/webrtc/webrtcvoe.h
index bc8358d..8624aeb 100644
--- a/media/webrtc/webrtcvoe.h
+++ b/media/webrtc/webrtcvoe.h
@@ -29,8 +29,8 @@
#ifndef TALK_MEDIA_WEBRTCVOE_H_
#define TALK_MEDIA_WEBRTCVOE_H_
-#include "talk/base/common.h"
#include "talk/media/webrtc/webrtccommon.h"
+#include "webrtc/base/common.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/audio_device/include/audio_device.h"
diff --git a/media/webrtc/webrtcvoiceengine.cc b/media/webrtc/webrtcvoiceengine.cc
index f1460a6..a524bad 100644
--- a/media/webrtc/webrtcvoiceengine.cc
+++ b/media/webrtc/webrtcvoiceengine.cc
@@ -38,20 +38,21 @@
#include <string>
#include <vector>
-#include "talk/base/base64.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/audiorenderer.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/streamparams.h"
#include "talk/media/base/voiceprocessor.h"
#include "talk/media/webrtc/webrtcvoe.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
#include "webrtc/common.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
+#include "webrtc/video_engine/include/vie_network.h"
#ifdef WIN32
#include <objbase.h> // NOLINT
@@ -119,10 +120,11 @@
// Opus bitrate should be in the range between 6000 and 510000.
static const int kOpusMinBitrate = 6000;
static const int kOpusMaxBitrate = 510000;
+
// Default audio dscp value.
// See http://tools.ietf.org/html/rfc2474 for details.
// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
-static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
+static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
// Ensure we open the file in a writeable path on ChromeOS and Android. This
// workaround can be removed when it's possible to specify a filename for audio
@@ -155,7 +157,7 @@
return ss.str();
}
-static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
+static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
const char* delim = "\r\n";
for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
LOG_V(sev) << tok;
@@ -166,13 +168,13 @@
static int SeverityToFilter(int severity) {
int filter = webrtc::kTraceNone;
switch (severity) {
- case talk_base::LS_VERBOSE:
+ case rtc::LS_VERBOSE:
filter |= webrtc::kTraceAll;
- case talk_base::LS_INFO:
+ case rtc::LS_INFO:
filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
- case talk_base::LS_WARNING:
+ case rtc::LS_WARNING:
filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
- case talk_base::LS_ERROR:
+ case rtc::LS_ERROR:
filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
}
return filter;
@@ -237,7 +239,6 @@
options.experimental_aec.Set(false);
options.experimental_ns.Set(false);
options.aec_dump.Set(false);
- options.opus_fec.Set(false);
return options;
}
@@ -328,7 +329,7 @@
private:
WebRtcVoiceEngine *engine_;
int webrtc_channel_;
- talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
+ rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
};
WebRtcVoiceEngine::WebRtcVoiceEngine()
@@ -404,6 +405,7 @@
return codec.GetParam(kCodecParamStereo, &value) && value == 1;
}
+// TODO(minyue): Clamp bitrate when invalid.
static bool IsValidOpusBitrate(int bitrate) {
return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
}
@@ -423,19 +425,63 @@
return bitrate;
}
-// Return true params[kCodecParamUseInbandFec] == kParamValueTrue, false
+// Return true if params[kCodecParamUseInbandFec] == "1", false
// otherwise.
static bool IsOpusFecEnabled(const AudioCodec& codec) {
int value;
return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
}
-// Set params[kCodecParamUseInbandFec]. Caller should make sure codec is Opus.
-static void SetOpusFec(AudioCodec *codec, bool opus_fec) {
- if (opus_fec) {
- codec->params[kCodecParamUseInbandFec] = kParamValueTrue;
+// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
+// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
+static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
+ int value;
+ if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
+ return value;
+ }
+ return kOpusDefaultMaxPlaybackRate;
+}
+
+static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
+ bool* enable_codec_fec, int* max_playback_rate) {
+ *enable_codec_fec = IsOpusFecEnabled(codec);
+ *max_playback_rate = GetOpusMaxPlaybackRate(codec);
+
+ // If OPUS, change what we send according to the "stereo" codec
+ // parameter, and not the "channels" parameter. We set
+ // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
+ // the bitrate is not specified, i.e. is zero, we set it to the
+ // appropriate default value for mono or stereo Opus.
+
+ // TODO(minyue): The determination of bit rate might take the maximum playback
+ // rate into account.
+
+ if (IsOpusStereoEnabled(codec)) {
+ voe_codec->channels = 2;
+ if (!IsValidOpusBitrate(codec.bitrate)) {
+ if (codec.bitrate != 0) {
+ LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
+ << codec.bitrate
+ << ") with default opus stereo bitrate: "
+ << kOpusStereoBitrate;
+ }
+ voe_codec->rate = kOpusStereoBitrate;
+ }
} else {
- codec->params.erase(kCodecParamUseInbandFec);
+ voe_codec->channels = 1;
+ if (!IsValidOpusBitrate(codec.bitrate)) {
+ if (codec.bitrate != 0) {
+ LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
+ << codec.bitrate
+ << ") with default opus mono bitrate: "
+ << kOpusMonoBitrate;
+ }
+ voe_codec->rate = kOpusMonoBitrate;
+ }
+ }
+ int bitrate_from_params = GetOpusBitrateFromParams(codec);
+ if (bitrate_from_params != 0) {
+ voe_codec->rate = bitrate_from_params;
}
}
@@ -475,15 +521,14 @@
// Only add fmtp parameters that differ from the spec.
if (kPreferredMinPTime != kOpusDefaultMinPTime) {
codec.params[kCodecParamMinPTime] =
- talk_base::ToString(kPreferredMinPTime);
+ rtc::ToString(kPreferredMinPTime);
}
if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
codec.params[kCodecParamMaxPTime] =
- talk_base::ToString(kPreferredMaxPTime);
+ rtc::ToString(kPreferredMaxPTime);
}
// TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
// when they can be set to values other than the default.
- SetOpusFec(&codec, false);
}
codecs_.push_back(codec);
} else {
@@ -518,7 +563,7 @@
tracing_->SetTraceCallback(NULL);
}
-bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
+bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
bool res = InitInternal();
if (res) {
@@ -533,7 +578,7 @@
bool WebRtcVoiceEngine::InitInternal() {
// Temporarily turn logging level up for the Init call
int old_filter = log_filter_;
- int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
+ int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
SetTraceFilter(extended_filter);
SetTraceOptions("");
@@ -551,7 +596,7 @@
char buffer[1024] = "";
voe_wrapper_->base()->GetVersion(buffer);
LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
- LogMultiline(talk_base::LS_INFO, buffer);
+ LogMultiline(rtc::LS_INFO, buffer);
// Save the default AGC configuration settings. This must happen before
// calling SetOptions or the default will be overwritten.
@@ -816,23 +861,6 @@
}
}
- bool experimental_ns;
- if (options.experimental_ns.Get(&experimental_ns)) {
- webrtc::AudioProcessing* audioproc =
- voe_wrapper_->base()->audio_processing();
- // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
- // returns NULL on audio_processing().
- if (audioproc) {
- if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
- LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
- return false;
- }
- } else {
- LOG(LS_VERBOSE) << "Experimental noise suppression set to "
- << experimental_ns;
- }
- }
-
bool highpass_filter;
if (options.highpass_filter.Get(&highpass_filter)) {
LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
@@ -878,20 +906,50 @@
StopAecDump();
}
+ webrtc::Config config;
+
+ experimental_aec_.SetFrom(options.experimental_aec);
bool experimental_aec;
- if (options.experimental_aec.Get(&experimental_aec)) {
- LOG(LS_INFO) << "Experimental aec is " << experimental_aec;
- webrtc::AudioProcessing* audioproc =
- voe_wrapper_->base()->audio_processing();
+ if (experimental_aec_.Get(&experimental_aec)) {
+ LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
+ config.Set<webrtc::DelayCorrection>(
+ new webrtc::DelayCorrection(experimental_aec));
+ }
+
+#ifdef USE_WEBRTC_DEV_BRANCH
+ experimental_ns_.SetFrom(options.experimental_ns);
+ bool experimental_ns;
+ if (experimental_ns_.Get(&experimental_ns)) {
+ LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
+ config.Set<webrtc::ExperimentalNs>(
+ new webrtc::ExperimentalNs(experimental_ns));
+ }
+#endif
+
+ // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
+ // returns NULL on audio_processing().
+ webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
+ if (audioproc) {
+ audioproc->SetExtraOptions(config);
+ }
+
+#ifndef USE_WEBRTC_DEV_BRANCH
+ bool experimental_ns;
+ if (options.experimental_ns.Get(&experimental_ns)) {
+ LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
// We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
// returns NULL on audio_processing().
if (audioproc) {
- webrtc::Config config;
- config.Set<webrtc::DelayCorrection>(
- new webrtc::DelayCorrection(experimental_aec));
- audioproc->SetExtraOptions(config);
+ if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
+ LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
+ return false;
+ }
+ } else {
+ LOG(LS_VERBOSE) << "Experimental noise suppression set to "
+ << experimental_ns;
}
}
+#endif
uint32 recording_sample_rate;
if (options.recording_sample_rate.Get(&recording_sample_rate)) {
@@ -909,16 +967,6 @@
}
}
- bool opus_fec = false;
- if (options.opus_fec.Get(&opus_fec)) {
- LOG(LS_INFO) << "Opus FEC is enabled? " << opus_fec;
- for (std::vector<AudioCodec>::iterator it = codecs_.begin();
- it != codecs_.end(); ++it) {
- if (IsOpus(*it))
- SetOpusFec(&(*it), opus_fec);
- }
- }
-
return true;
}
@@ -949,9 +997,9 @@
bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
const Device* out_device) {
#if !defined(IOS)
- int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
+ int in_id = in_device ? rtc::FromString<int>(in_device->id) :
kDefaultAudioDeviceId;
- int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
+ int out_id = out_device ? rtc::FromString<int>(out_device->id) :
kDefaultAudioDeviceId;
// The device manager uses -1 as the default device, which was the case for
// VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
@@ -1002,6 +1050,9 @@
LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
ret = false;
}
+ webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
+ if (ap)
+ ap->Initialize();
}
// Find the playout device id in VoiceEngine and set playout device.
@@ -1244,7 +1295,7 @@
void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
// Set encrypted trace file.
std::vector<std::string> opts;
- talk_base::tokenize(options, ' ', '"', '"', &opts);
+ rtc::tokenize(options, ' ', '"', '"', &opts);
std::vector<std::string>::iterator tracefile =
std::find(opts.begin(), opts.end(), "tracefile");
if (tracefile != opts.end() && ++tracefile != opts.end()) {
@@ -1262,7 +1313,7 @@
std::vector<std::string>::iterator tracefilter =
std::find(opts.begin(), opts.end(), "tracefilter");
if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
- if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
+ if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
LOG_RTCERR1(SetTraceFilter, *tracefilter);
}
}
@@ -1309,15 +1360,15 @@
void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
int length) {
- talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
+ rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
- sev = talk_base::LS_ERROR;
+ sev = rtc::LS_ERROR;
else if (level == webrtc::kTraceWarning)
- sev = talk_base::LS_WARNING;
+ sev = rtc::LS_WARNING;
else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
- sev = talk_base::LS_INFO;
+ sev = rtc::LS_INFO;
else if (level == webrtc::kTraceTerseInfo)
- sev = talk_base::LS_INFO;
+ sev = rtc::LS_INFO;
// Skip past boilerplate prefix text
if (length < 72) {
@@ -1333,7 +1384,7 @@
}
void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
- talk_base::CritScope lock(&channels_cs_);
+ rtc::CritScope lock(&channels_cs_);
WebRtcVoiceMediaChannel* channel = NULL;
uint32 ssrc = 0;
LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
@@ -1393,12 +1444,12 @@
}
void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
- talk_base::CritScope lock(&channels_cs_);
+ rtc::CritScope lock(&channels_cs_);
channels_.push_back(channel);
}
void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
- talk_base::CritScope lock(&channels_cs_);
+ rtc::CritScope lock(&channels_cs_);
ChannelList::iterator i = std::find(channels_.begin(),
channels_.end(),
channel);
@@ -1464,11 +1515,11 @@
return true;
}
-bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
- FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
+bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
+ FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
if (!aec_dump_file_stream) {
LOG(LS_ERROR) << "Could not open AEC dump file stream.";
- if (!talk_base::ClosePlatformFile(file))
+ if (!rtc::ClosePlatformFile(file))
LOG(LS_WARNING) << "Could not close file.";
return false;
}
@@ -1500,7 +1551,7 @@
webrtc::ProcessingTypes processing_type;
{
- talk_base::CritScope cs(&signal_media_critical_);
+ rtc::CritScope cs(&signal_media_critical_);
if (direction == MPD_RX) {
processing_type = webrtc::kPlaybackAllChannelsMixed;
if (SignalRxMediaFrame.is_empty()) {
@@ -1565,7 +1616,7 @@
int deregister_id = -1;
{
- talk_base::CritScope cs(&signal_media_critical_);
+ rtc::CritScope cs(&signal_media_critical_);
if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
signal->disconnect(voice_processor);
int channel_id = -1;
@@ -1621,7 +1672,7 @@
int length,
int sampling_freq,
bool is_stereo) {
- talk_base::CritScope cs(&signal_media_critical_);
+ rtc::CritScope cs(&signal_media_critical_);
AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
if (type == webrtc::kPlaybackAllChannelsMixed) {
SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
@@ -1688,7 +1739,7 @@
// This method is called on the libjingle worker thread.
// TODO(xians): Make sure Start() is called only once.
void Start(AudioRenderer* renderer) {
- talk_base::CritScope lock(&lock_);
+ rtc::CritScope lock(&lock_);
ASSERT(renderer != NULL);
if (renderer_ != NULL) {
ASSERT(renderer_ == renderer);
@@ -1706,7 +1757,7 @@
// callback will be received after this method.
// This method is called on the libjingle worker thread.
void Stop() {
- talk_base::CritScope lock(&lock_);
+ rtc::CritScope lock(&lock_);
if (renderer_ == NULL)
return;
@@ -1733,7 +1784,7 @@
// Callback from the |renderer_| when it is going away. In case Start() has
// never been called, this callback won't be triggered.
virtual void OnClose() OVERRIDE {
- talk_base::CritScope lock(&lock_);
+ rtc::CritScope lock(&lock_);
// Set |renderer_| to NULL to make sure no more callback will get into
// the renderer.
renderer_ = NULL;
@@ -1752,7 +1803,7 @@
AudioRenderer* renderer_;
// Protects |renderer_| in Start(), Stop() and OnClose().
- talk_base::CriticalSection lock_;
+ rtc::CriticalSection lock_;
};
// WebRtcVoiceMediaChannel
@@ -1770,6 +1821,8 @@
typing_noise_detected_(false),
desired_send_(SEND_NOTHING),
send_(SEND_NOTHING),
+ shared_bwe_vie_(NULL),
+ shared_bwe_vie_channel_(-1),
default_receive_ssrc_(0) {
engine->RegisterChannel(this);
LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
@@ -1781,6 +1834,7 @@
WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
<< voe_channel();
+ SetupSharedBandwidthEstimation(NULL, -1);
// Remove any remaining send streams, the default channel will be deleted
// later.
@@ -1873,7 +1927,7 @@
}
}
if (dscp_option_changed) {
- talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
+ rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
if (options_.dscp.GetWithDefaultIfUnset(false))
dscp = kAudioDscpValue;
if (MediaChannel::SetDscp(dscp) != 0) {
@@ -1881,6 +1935,12 @@
}
}
+ // Force update of Video Engine BWE forwarding to reflect experiment setting.
+ if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
+ shared_bwe_vie_channel_)) {
+ return false;
+ }
+
LOG(LS_INFO) << "Set voice channel options. Current options: "
<< options_.ToString();
return true;
@@ -1985,6 +2045,11 @@
memset(&send_codec, 0, sizeof(send_codec));
bool nack_enabled = nack_enabled_;
+ bool enable_codec_fec = false;
+
+ // max_playback_rate <= 0 will not trigger setting of maximum encoding
+ // bandwidth.
+ int max_playback_rate = 0;
// Set send codec (the first non-telephone-event/CN codec)
for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
@@ -2002,53 +2067,6 @@
continue;
}
- // If OPUS, change what we send according to the "stereo" codec
- // parameter, and not the "channels" parameter. We set
- // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
- // the bitrate is not specified, i.e. is zero, we set it to the
- // appropriate default value for mono or stereo Opus.
- if (IsOpus(*it)) {
- if (IsOpusStereoEnabled(*it)) {
- voe_codec.channels = 2;
- if (!IsValidOpusBitrate(it->bitrate)) {
- if (it->bitrate != 0) {
- LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
- << it->bitrate
- << ") with default opus stereo bitrate: "
- << kOpusStereoBitrate;
- }
- voe_codec.rate = kOpusStereoBitrate;
- }
- } else {
- voe_codec.channels = 1;
- if (!IsValidOpusBitrate(it->bitrate)) {
- if (it->bitrate != 0) {
- LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
- << it->bitrate
- << ") with default opus mono bitrate: "
- << kOpusMonoBitrate;
- }
- voe_codec.rate = kOpusMonoBitrate;
- }
- }
- int bitrate_from_params = GetOpusBitrateFromParams(*it);
- if (bitrate_from_params != 0) {
- voe_codec.rate = bitrate_from_params;
- }
-
- // For Opus, we also enable inband FEC if it is requested.
- if (IsOpusFecEnabled(*it)) {
- LOG(LS_INFO) << "Enabling Opus FEC on channel " << channel;
-#ifdef USE_WEBRTC_DEV_BRANCH
- if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
- // Enable in-band FEC of the Opus codec. Treat any failure as a fatal
- // internal error.
- LOG_RTCERR2(SetFECStatus, channel, true);
- return false;
- }
-#endif // USE_WEBRTC_DEV_BRANCH
- }
- }
// We'll use the first codec in the list to actually send audio data.
// Be sure to use the payload type requested by the remote side.
@@ -2078,6 +2096,11 @@
} else {
send_codec = voe_codec;
nack_enabled = IsNackEnabled(*it);
+ // For Opus as the send codec, we are to enable inband FEC if requested
+ // and set maximum playback rate.
+ if (IsOpus(*it)) {
+ GetOpusConfig(*it, &send_codec, &enable_codec_fec, &max_playback_rate);
+ }
}
found_send_codec = true;
break;
@@ -2098,6 +2121,34 @@
if (!SetSendCodec(channel, send_codec))
return false;
+ // FEC should be enabled after SetSendCodec.
+ if (enable_codec_fec) {
+ LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
+ << channel;
+#ifdef USE_WEBRTC_DEV_BRANCH
+ if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
+ // Enable codec internal FEC. Treat any failure as fatal internal error.
+ LOG_RTCERR2(SetFECStatus, channel, true);
+ return false;
+ }
+#endif // USE_WEBRTC_DEV_BRANCH
+ }
+
+ // maxplaybackrate should be set after SetSendCodec.
+ if (max_playback_rate > 0) {
+ LOG(LS_INFO) << "Attempt to set maximum playback rate to "
+ << max_playback_rate
+ << " Hz on channel "
+ << channel;
+#ifdef USE_WEBRTC_DEV_BRANCH
+ // (max_playback_rate + 1) >> 1 is to obtain ceil(max_playback_rate / 2.0).
+ if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
+ channel, max_playback_rate) == -1) {
+ LOG(LS_WARNING) << "Could not set maximum playback rate.";
+ }
+#endif
+ }
+
// Always update the |send_codec_| to the currently set send codec.
send_codec_.reset(new webrtc::CodecInst(send_codec));
@@ -2277,7 +2328,6 @@
bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
-#ifdef USE_WEBRTC_DEV_BRANCH
const RtpHeaderExtension* audio_level_extension =
FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
if (!SetHeaderExtension(
@@ -2285,7 +2335,6 @@
audio_level_extension)) {
return false;
}
-#endif // USE_WEBRTC_DEV_BRANCH
const RtpHeaderExtension* send_time_extension =
FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
@@ -2541,8 +2590,8 @@
}
if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
- LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
- return false;
+ LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
+ return false;
}
// Set the current codecs to be used for the new channel.
@@ -2587,7 +2636,7 @@
}
bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
- talk_base::CritScope lock(&receive_channels_cs_);
+ rtc::CritScope lock(&receive_channels_cs_);
if (!VERIFY(sp.ssrcs.size() == 1))
return false;
@@ -2614,6 +2663,9 @@
receive_channels_.insert(std::make_pair(
default_receive_ssrc_,
new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
+ if (!SetupSharedBweOnChannel(voe_channel())) {
+ return false;
+ }
return SetPlayout(voe_channel(), playout_);
}
@@ -2701,11 +2753,16 @@
return false;
}
+ // Set up channel to be able to forward incoming packets to video engine BWE.
+ if (!SetupSharedBweOnChannel(channel)) {
+ return false;
+ }
+
return SetPlayout(channel, playout_);
}
bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
- talk_base::CritScope lock(&receive_channels_cs_);
+ rtc::CritScope lock(&receive_channels_cs_);
ChannelMap::iterator it = receive_channels_.find(ssrc);
if (it == receive_channels_.end()) {
LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
@@ -2823,7 +2880,7 @@
for (ChannelMap::iterator it = receive_channels_.begin();
it != receive_channels_.end(); ++it) {
int level = GetOutputLevel(it->second->channel());
- highest = talk_base::_max(level, highest);
+ highest = rtc::_max(level, highest);
}
return highest;
}
@@ -2855,7 +2912,7 @@
bool WebRtcVoiceMediaChannel::SetOutputScaling(
uint32 ssrc, double left, double right) {
- talk_base::CritScope lock(&receive_channels_cs_);
+ rtc::CritScope lock(&receive_channels_cs_);
// Collect the channels to scale the output volume.
std::vector<int> channels;
if (0 == ssrc) { // Collect all channels, including the default one.
@@ -2878,7 +2935,7 @@
// Scale the output volume for the collected channels. We first normalize to
// scale the volume and then set the left and right pan.
- float scale = static_cast<float>(talk_base::_max(left, right));
+ float scale = static_cast<float>(rtc::_max(left, right));
if (scale > 0.0001f) {
left /= scale;
right /= scale;
@@ -2907,7 +2964,7 @@
uint32 ssrc, double* left, double* right) {
if (!left || !right) return false;
- talk_base::CritScope lock(&receive_channels_cs_);
+ rtc::CritScope lock(&receive_channels_cs_);
// Determine which channel based on ssrc.
int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
if (channel == -1) {
@@ -3040,7 +3097,7 @@
}
void WebRtcVoiceMediaChannel::OnPacketReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
// Pick which channel to send this packet to. If this packet doesn't match
// any multiplexed streams, just send it to the default channel. Otherwise,
// send it to the specific decoder instance for that stream.
@@ -3070,11 +3127,12 @@
engine()->voe()->network()->ReceivedRTPPacket(
which_channel,
packet->data(),
- static_cast<unsigned int>(packet->length()));
+ static_cast<unsigned int>(packet->length()),
+ webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
}
void WebRtcVoiceMediaChannel::OnRtcpReceived(
- talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
+ rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
// Sending channels need all RTCP packets with feedback information.
// Even sender reports can contain attached report blocks.
// Receiving channels need sender reports in order to create
@@ -3128,6 +3186,23 @@
LOG_RTCERR2(SetInputMute, channel, muted);
return false;
}
+ // We set the AGC to mute state only when all the channels are muted.
+ // This implementation is not ideal, instead we should signal the AGC when
+ // the mic channel is muted/unmuted. We can't do it today because there
+ // is no good way to know which stream is mapping to the mic channel.
+ bool all_muted = muted;
+ for (ChannelMap::const_iterator iter = send_channels_.begin();
+ iter != send_channels_.end() && all_muted; ++iter) {
+ if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
+ all_muted)) {
+ LOG_RTCERR1(GetInputMute, iter->second->channel());
+ return false;
+ }
+ }
+
+ webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
+ if (ap)
+ ap->set_output_will_be_muted(all_muted);
return true;
}
@@ -3380,7 +3455,7 @@
}
bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
- talk_base::CritScope lock(&receive_channels_cs_);
+ rtc::CritScope lock(&receive_channels_cs_);
ASSERT(ssrc != NULL);
if (channel_num == -1 && send_ != SEND_NOTHING) {
// Sometimes the VoiceEngine core will throw error with channel_num = -1.
@@ -3447,6 +3522,23 @@
return -1;
}
+bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
+ webrtc::VideoEngine* vie, int vie_channel) {
+ shared_bwe_vie_ = vie;
+ shared_bwe_vie_channel_ = vie_channel;
+
+ if (!SetupSharedBweOnChannel(voe_channel())) {
+ return false;
+ }
+ for (ChannelMap::iterator it = receive_channels_.begin();
+ it != receive_channels_.end(); ++it) {
+ if (!SetupSharedBweOnChannel(it->second->channel())) {
+ return false;
+ }
+ }
+ return true;
+}
+
bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
// Get the RED encodings from the parameter with no name. This may
@@ -3462,9 +3554,9 @@
if (it != red_codec.params.end()) {
red_params = it->second;
std::vector<std::string> red_pts;
- if (talk_base::split(red_params, '/', &red_pts) != 2 ||
+ if (rtc::split(red_params, '/', &red_pts) != 2 ||
red_pts[0] != red_pts[1] ||
- !talk_base::FromString(red_pts[0], &red_pt)) {
+ !rtc::FromString(red_pts[0], &red_pt)) {
LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
return false;
}
@@ -3541,7 +3633,7 @@
size_t ssrc_pos = (!rtcp) ? 8 : 4;
uint32 ssrc = 0;
if (len >= (ssrc_pos + sizeof(ssrc))) {
- ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
+ ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
}
return ssrc;
}
@@ -3596,6 +3688,25 @@
return true;
}
+bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
+ webrtc::ViENetwork* vie_network = NULL;
+ int vie_channel = -1;
+ if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
+ shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
+ vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
+ vie_channel = shared_bwe_vie_channel_;
+ }
+ if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
+ vie_channel) == -1) {
+ LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
+ if (vie_network != NULL) {
+ // Don't fail if we're tearing down.
+ return false;
+ }
+ }
+ return true;
+}
+
int WebRtcSoundclipStream::Read(void *buf, int len) {
size_t res = 0;
mem_.Read(buf, len, &res, NULL);
diff --git a/media/webrtc/webrtcvoiceengine.h b/media/webrtc/webrtcvoiceengine.h
index efc388f..5557af0 100644
--- a/media/webrtc/webrtcvoiceengine.h
+++ b/media/webrtc/webrtcvoiceengine.h
@@ -33,23 +33,31 @@
#include <string>
#include <vector>
-#include "talk/base/buffer.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stream.h"
#include "talk/media/base/rtputils.h"
#include "talk/media/webrtc/webrtccommon.h"
#include "talk/media/webrtc/webrtcexport.h"
#include "talk/media/webrtc/webrtcvoe.h"
#include "talk/session/media/channel.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stream.h"
#include "webrtc/common.h"
#if !defined(LIBPEERCONNECTION_LIB) && \
!defined(LIBPEERCONNECTION_IMPLEMENTATION)
+// If you hit this, then you've tried to include this header from outside
+// the shared library. An instance of this class must only be created from
+// within the library that actually implements it. Otherwise use the
+// WebRtcMediaEngine to construct an instance.
#error "Bogus include."
#endif
+namespace webrtc {
+class VideoEngine;
+}
+
namespace cricket {
// WebRtcSoundclipStream is an adapter object that allows a memory stream to be
@@ -64,7 +72,7 @@
virtual int Rewind();
private:
- talk_base::MemoryStream mem_;
+ rtc::MemoryStream mem_;
bool loop_;
};
@@ -97,7 +105,7 @@
VoEWrapper* voe_wrapper_sc,
VoETraceWrapper* tracing);
~WebRtcVoiceEngine();
- bool Init(talk_base::Thread* worker_thread);
+ bool Init(rtc::Thread* worker_thread);
void Terminate();
int GetCapabilities();
@@ -173,7 +181,7 @@
webrtc::AudioDeviceModule* adm_sc);
// Starts AEC dump using existing file.
- bool StartAecDump(talk_base::PlatformFile file);
+ bool StartAecDump(rtc::PlatformFile file);
// Check whether the supplied trace should be ignored.
bool ShouldIgnoreTrace(const std::string& trace);
@@ -230,14 +238,14 @@
FrameSignal SignalRxMediaFrame;
FrameSignal SignalTxMediaFrame;
- static const int kDefaultLogSeverity = talk_base::LS_WARNING;
+ static const int kDefaultLogSeverity = rtc::LS_WARNING;
// The primary instance of WebRtc VoiceEngine.
- talk_base::scoped_ptr<VoEWrapper> voe_wrapper_;
+ rtc::scoped_ptr<VoEWrapper> voe_wrapper_;
// A secondary instance, for playing out soundclips (on the 'ring' device).
- talk_base::scoped_ptr<VoEWrapper> voe_wrapper_sc_;
+ rtc::scoped_ptr<VoEWrapper> voe_wrapper_sc_;
bool voe_wrapper_sc_initialized_;
- talk_base::scoped_ptr<VoETraceWrapper> tracing_;
+ rtc::scoped_ptr<VoETraceWrapper> tracing_;
// The external audio device manager
webrtc::AudioDeviceModule* adm_;
webrtc::AudioDeviceModule* adm_sc_;
@@ -247,12 +255,12 @@
std::vector<AudioCodec> codecs_;
std::vector<RtpHeaderExtension> rtp_header_extensions_;
bool desired_local_monitor_enable_;
- talk_base::scoped_ptr<WebRtcMonitorStream> monitor_;
+ rtc::scoped_ptr<WebRtcMonitorStream> monitor_;
SoundclipList soundclips_;
ChannelList channels_;
// channels_ can be read from WebRtc callback thread. We need a lock on that
// callback as well as the RegisterChannel/UnregisterChannel.
- talk_base::CriticalSection channels_cs_;
+ rtc::CriticalSection channels_cs_;
webrtc::AgcConfig default_agc_config_;
webrtc::Config voe_config_;
@@ -275,7 +283,14 @@
uint32 tx_processor_ssrc_;
uint32 rx_processor_ssrc_;
- talk_base::CriticalSection signal_media_critical_;
+ rtc::CriticalSection signal_media_critical_;
+
+ // Cache received experimental_aec and experimental_ns values, and apply them
+ // in case they are missing in the audio options. We need to do this because
+ // SetExtraOptions() will revert to defaults for options which are not
+ // provided.
+ Settable<bool> experimental_aec_;
+ Settable<bool> experimental_ns_;
};
// WebRtcMediaChannel is a class that implements the common WebRtc channel
@@ -292,7 +307,7 @@
protected:
// implements Transport interface
virtual int SendPacket(int channel, const void *data, int len) {
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
if (!T::SendPacket(&packet)) {
return -1;
}
@@ -300,7 +315,7 @@
}
virtual int SendRTCPPacket(int channel, const void *data, int len) {
- talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
+ rtc::Buffer packet(data, len, kMaxRtpPacketLen);
return T::SendRtcp(&packet) ? len : -1;
}
@@ -353,10 +368,10 @@
virtual bool CanInsertDtmf();
virtual bool InsertDtmf(uint32 ssrc, int event, int duration, int flags);
- virtual void OnPacketReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
- virtual void OnRtcpReceived(talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
+ virtual void OnPacketReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
+ virtual void OnRtcpReceived(rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
virtual void OnReadyToSend(bool ready) {}
virtual bool MuteStream(uint32 ssrc, bool on);
virtual bool SetStartSendBandwidth(int bps);
@@ -373,6 +388,8 @@
int GetReceiveChannelNum(uint32 ssrc);
int GetSendChannelNum(uint32 ssrc);
+ bool SetupSharedBandwidthEstimation(webrtc::VideoEngine* vie,
+ int vie_channel);
protected:
int GetLastEngineError() { return engine()->GetLastEngineError(); }
int GetOutputLevel(int channel);
@@ -415,6 +432,7 @@
bool SetHeaderExtension(ExtensionSetterFunction setter, int channel_id,
const RtpHeaderExtension* extension);
+ bool SetupSharedBweOnChannel(int voe_channel);
bool SetChannelRecvRtpHeaderExtensions(
int channel_id,
@@ -423,11 +441,11 @@
int channel_id,
const std::vector<RtpHeaderExtension>& extensions);
- talk_base::scoped_ptr<WebRtcSoundclipStream> ringback_tone_;
+ rtc::scoped_ptr<WebRtcSoundclipStream> ringback_tone_;
std::set<int> ringback_channels_; // channels playing ringback
std::vector<AudioCodec> recv_codecs_;
std::vector<AudioCodec> send_codecs_;
- talk_base::scoped_ptr<webrtc::CodecInst> send_codec_;
+ rtc::scoped_ptr<webrtc::CodecInst> send_codec_;
bool send_bw_setting_;
int send_bw_bps_;
AudioOptions options_;
@@ -438,6 +456,11 @@
bool typing_noise_detected_;
SendFlags desired_send_;
SendFlags send_;
+ // shared_bwe_vie_ and shared_bwe_vie_channel_ together identifies a WebRTC
+ // VideoEngine channel that this voice channel should forward incoming packets
+ // to for Bandwidth Estimation purposes.
+ webrtc::VideoEngine* shared_bwe_vie_;
+ int shared_bwe_vie_channel_;
// send_channels_ contains the channels which are being used for sending.
// When the default channel (voe_channel) is used for sending, it is
@@ -456,7 +479,7 @@
std::vector<RtpHeaderExtension> receive_extensions_;
// Do not lock this on the VoE media processor thread; potential for deadlock
// exists.
- mutable talk_base::CriticalSection receive_channels_cs_;
+ mutable rtc::CriticalSection receive_channels_cs_;
};
} // namespace cricket
diff --git a/media/webrtc/webrtcvoiceengine_unittest.cc b/media/webrtc/webrtcvoiceengine_unittest.cc
index 58893b9..b044e92 100644
--- a/media/webrtc/webrtcvoiceengine_unittest.cc
+++ b/media/webrtc/webrtcvoiceengine_unittest.cc
@@ -26,18 +26,19 @@
*/
#ifdef WIN32
-#include "talk/base/win32.h"
+#include "webrtc/base/win32.h"
#include <objbase.h>
#endif
-#include "talk/base/byteorder.h"
-#include "talk/base/gunit.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/gunit.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/fakemediaprocessor.h"
#include "talk/media/base/fakenetworkinterface.h"
#include "talk/media/base/fakertp.h"
#include "talk/media/webrtc/fakewebrtcvoiceengine.h"
+#include "talk/media/webrtc/webrtcvie.h"
#include "talk/media/webrtc/webrtcvoiceengine.h"
#include "talk/p2p/base/fakesession.h"
#include "talk/session/media/channel.h"
@@ -140,7 +141,7 @@
options_adjust_agc_.adjust_agc_delta.Set(-10);
}
bool SetupEngineWithoutStream() {
- if (!engine_.Init(talk_base::Thread::Current())) {
+ if (!engine_.Init(rtc::Thread::Current())) {
return false;
}
channel_ = engine_.CreateChannel();
@@ -166,8 +167,8 @@
EXPECT_EQ(0, voe_.GetLocalSSRC(default_channel_num, default_send_ssrc));
}
void DeliverPacket(const void* data, int len) {
- talk_base::Buffer packet(data, len);
- channel_->OnPacketReceived(&packet, talk_base::PacketTime());
+ rtc::Buffer packet(data, len);
+ channel_->OnPacketReceived(&packet, rtc::PacketTime());
}
virtual void TearDown() {
delete soundclip_;
@@ -176,7 +177,7 @@
}
void TestInsertDtmf(uint32 ssrc, bool caller) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_ != NULL);
if (caller) {
@@ -351,7 +352,7 @@
TEST_F(WebRtcVoiceEngineTestFake, StartupShutdown) {
EXPECT_FALSE(voe_.IsInited());
EXPECT_FALSE(voe_sc_.IsInited());
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
EXPECT_TRUE(voe_.IsInited());
// The soundclip engine is lazily initialized.
EXPECT_FALSE(voe_sc_.IsInited());
@@ -362,7 +363,7 @@
// Tests that we can create and destroy a channel.
TEST_F(WebRtcVoiceEngineTestFake, CreateChannel) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_ != NULL);
}
@@ -370,7 +371,7 @@
// Tests that we properly handle failures in CreateChannel.
TEST_F(WebRtcVoiceEngineTestFake, CreateChannelFail) {
voe_.set_fail_create_channel(true);
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_ == NULL);
}
@@ -439,13 +440,13 @@
codecs[2].id = 126;
EXPECT_TRUE(channel_->SetRecvCodecs(codecs));
webrtc::CodecInst gcodec;
- talk_base::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "ISAC");
+ rtc::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "ISAC");
gcodec.plfreq = 16000;
gcodec.channels = 1;
EXPECT_EQ(0, voe_.GetRecPayloadType(channel_num, gcodec));
EXPECT_EQ(106, gcodec.pltype);
EXPECT_STREQ("ISAC", gcodec.plname);
- talk_base::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname),
+ rtc::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname),
"telephone-event");
gcodec.plfreq = 8000;
EXPECT_EQ(0, voe_.GetRecPayloadType(channel_num, gcodec));
@@ -557,13 +558,13 @@
cricket::StreamParams::CreateLegacy(kSsrc1)));
int channel_num2 = voe_.GetLastChannel();
webrtc::CodecInst gcodec;
- talk_base::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "ISAC");
+ rtc::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "ISAC");
gcodec.plfreq = 16000;
gcodec.channels = 1;
EXPECT_EQ(0, voe_.GetRecPayloadType(channel_num2, gcodec));
EXPECT_EQ(106, gcodec.pltype);
EXPECT_STREQ("ISAC", gcodec.plname);
- talk_base::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname),
+ rtc::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname),
"telephone-event");
gcodec.plfreq = 8000;
gcodec.channels = 1;
@@ -585,7 +586,7 @@
int channel_num2 = voe_.GetLastChannel();
webrtc::CodecInst gcodec;
- talk_base::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "ISAC");
+ rtc::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "ISAC");
gcodec.plfreq = 16000;
gcodec.channels = 1;
EXPECT_EQ(0, voe_.GetRecPayloadType(channel_num2, gcodec));
@@ -686,7 +687,7 @@
}
TEST_F(WebRtcVoiceEngineTestFake, SetMaxSendBandwidthMultiRateAsCallee) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_ != NULL);
EXPECT_TRUE(channel_->SetSendCodecs(engine_.codecs()));
@@ -1048,7 +1049,7 @@
// Test that we can enable NACK with opus as callee.
TEST_F(WebRtcVoiceEngineTestFake, SetSendCodecEnableNackAsCallee) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_ != NULL);
@@ -1151,7 +1152,6 @@
int channel_num = voe_.GetLastChannel();
std::vector<cricket::AudioCodec> codecs;
codecs.push_back(kOpusCodec);
- codecs[0].bitrate = 0;
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
EXPECT_FALSE(voe_.GetCodecFEC(channel_num));
}
@@ -1217,33 +1217,172 @@
EXPECT_TRUE(channel_->SetSendCodecs(codecs));
EXPECT_FALSE(voe_.GetCodecFEC(channel_num));
}
-#endif // USE_WEBRTC_DEV_BRANCH
-// Test AudioOptions controls whether opus FEC is supported in codec list.
-TEST_F(WebRtcVoiceEngineTestFake, OpusFecViaOptions) {
+// Test the with non-Opus, even if useinbandfec=1, FEC is off.
+TEST_F(WebRtcVoiceEngineTestFake, SetSendCodecIsacWithParamNoFec) {
EXPECT_TRUE(SetupEngine());
- std::vector<cricket::AudioCodec> codecs = engine_.codecs();
- int value;
- for (std::vector<cricket::AudioCodec>::const_iterator it = codecs.begin();
- it != codecs.end(); ++it) {
- if (_stricmp(it->name.c_str(), cricket::kOpusCodecName) == 0) {
- EXPECT_FALSE(it->GetParam(cricket::kCodecParamUseInbandFec, &value));
- }
- }
-
- cricket::AudioOptions options;
- options.opus_fec.Set(true);
- EXPECT_TRUE(engine_.SetOptions(options));
- codecs = engine_.codecs();
- for (std::vector<cricket::AudioCodec>::const_iterator it = codecs.begin();
- it != codecs.end(); ++it) {
- if (_stricmp(it->name.c_str(), cricket::kOpusCodecName) == 0) {
- EXPECT_TRUE(it->GetParam(cricket::kCodecParamUseInbandFec, &value));
- EXPECT_EQ(1, value);
- }
- }
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kIsacCodec);
+ codecs[0].params["useinbandfec"] = "1";
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_FALSE(voe_.GetCodecFEC(channel_num));
}
+// Test that Opus FEC status can be changed.
+TEST_F(WebRtcVoiceEngineTestFake, ChangeOpusFecStatus) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_FALSE(voe_.GetCodecFEC(channel_num));
+ codecs[0].params["useinbandfec"] = "1";
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_TRUE(voe_.GetCodecFEC(channel_num));
+}
+
+// Test maxplaybackrate <= 8000 triggers Opus narrow band mode.
+TEST_F(WebRtcVoiceEngineTestFake, SetOpusMaxPlaybackRateNb) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ codecs[0].bitrate = 0;
+ codecs[0].SetParam(cricket::kCodecParamMaxPlaybackRate, 8000);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(cricket::kOpusBandwidthNb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+ webrtc::CodecInst gcodec;
+ EXPECT_EQ(0, voe_.GetSendCodec(channel_num, gcodec));
+ EXPECT_STREQ("opus", gcodec.plname);
+ // TODO(minyue): Default bit rate is not but can in future be affected by
+ // kCodecParamMaxPlaybackRate.
+ EXPECT_EQ(32000, gcodec.rate);
+}
+
+// Test 8000 < maxplaybackrate <= 12000 triggers Opus medium band mode.
+TEST_F(WebRtcVoiceEngineTestFake, SetOpusMaxPlaybackRateMb) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ codecs[0].bitrate = 0;
+ codecs[0].SetParam(cricket::kCodecParamMaxPlaybackRate, 8001);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(cricket::kOpusBandwidthMb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+ webrtc::CodecInst gcodec;
+ EXPECT_EQ(0, voe_.GetSendCodec(channel_num, gcodec));
+ EXPECT_STREQ("opus", gcodec.plname);
+ // TODO(minyue): Default bit rate is not but can in future be affected by
+ // kCodecParamMaxPlaybackRate.
+ EXPECT_EQ(32000, gcodec.rate);
+}
+
+// Test 12000 < maxplaybackrate <= 16000 triggers Opus wide band mode.
+TEST_F(WebRtcVoiceEngineTestFake, SetOpusMaxPlaybackRateWb) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ codecs[0].bitrate = 0;
+ codecs[0].SetParam(cricket::kCodecParamMaxPlaybackRate, 12001);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(cricket::kOpusBandwidthWb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+ webrtc::CodecInst gcodec;
+ EXPECT_EQ(0, voe_.GetSendCodec(channel_num, gcodec));
+ EXPECT_STREQ("opus", gcodec.plname);
+ // TODO(minyue): Default bit rate is not but can in future be affected by
+ // kCodecParamMaxPlaybackRate.
+ EXPECT_EQ(32000, gcodec.rate);
+}
+
+// Test 16000 < maxplaybackrate <= 24000 triggers Opus super wide band mode.
+TEST_F(WebRtcVoiceEngineTestFake, SetOpusMaxPlaybackRateSwb) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ codecs[0].bitrate = 0;
+ codecs[0].SetParam(cricket::kCodecParamMaxPlaybackRate, 16001);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(cricket::kOpusBandwidthSwb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+ webrtc::CodecInst gcodec;
+ EXPECT_EQ(0, voe_.GetSendCodec(channel_num, gcodec));
+ EXPECT_STREQ("opus", gcodec.plname);
+ // TODO(minyue): Default bit rate is not but can in future be affected by
+ // kCodecParamMaxPlaybackRate.
+ EXPECT_EQ(32000, gcodec.rate);
+}
+
+// Test 24000 < maxplaybackrate triggers Opus full band mode.
+TEST_F(WebRtcVoiceEngineTestFake, SetOpusMaxPlaybackRateFb) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ codecs[0].bitrate = 0;
+ codecs[0].SetParam(cricket::kCodecParamMaxPlaybackRate, 24001);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(cricket::kOpusBandwidthFb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+ webrtc::CodecInst gcodec;
+ EXPECT_EQ(0, voe_.GetSendCodec(channel_num, gcodec));
+ EXPECT_STREQ("opus", gcodec.plname);
+ // TODO(minyue): Default bit rate is not but can in future be affected by
+ // kCodecParamMaxPlaybackRate.
+ EXPECT_EQ(32000, gcodec.rate);
+}
+
+// Test Opus that without maxplaybackrate, default playback rate is used.
+TEST_F(WebRtcVoiceEngineTestFake, DefaultOpusMaxPlaybackRate) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(cricket::kOpusBandwidthFb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+}
+
+// Test the with non-Opus, maxplaybackrate has no effect.
+TEST_F(WebRtcVoiceEngineTestFake, SetNonOpusMaxPlaybackRate) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kIsacCodec);
+ codecs[0].SetParam(cricket::kCodecParamMaxPlaybackRate, 32000);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(0, voe_.GetMaxEncodingBandwidth(channel_num));
+}
+
+// Test maxplaybackrate can be set on two streams.
+TEST_F(WebRtcVoiceEngineTestFake, SetOpusMaxPlaybackRateOnTwoStreams) {
+ EXPECT_TRUE(SetupEngine());
+ int channel_num = voe_.GetLastChannel();
+ std::vector<cricket::AudioCodec> codecs;
+ codecs.push_back(kOpusCodec);
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ // Default bandwidth is 24000.
+ EXPECT_EQ(cricket::kOpusBandwidthFb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+
+ codecs[0].SetParam(cricket::kCodecParamMaxPlaybackRate, 8000);
+
+ EXPECT_TRUE(channel_->SetSendCodecs(codecs));
+ EXPECT_EQ(cricket::kOpusBandwidthNb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+
+ channel_->AddSendStream(cricket::StreamParams::CreateLegacy(kSsrc2));
+ channel_num = voe_.GetLastChannel();
+ EXPECT_EQ(cricket::kOpusBandwidthNb,
+ voe_.GetMaxEncodingBandwidth(channel_num));
+}
+#endif // USE_WEBRTC_DEV_BRANCH
+
// Test that we can apply CELT with stereo mode but fail with mono mode.
TEST_F(WebRtcVoiceEngineTestFake, SetSendCodecsCelt) {
EXPECT_TRUE(SetupEngine());
@@ -1423,7 +1562,7 @@
// Test that we set VAD and DTMF types correctly as callee.
TEST_F(WebRtcVoiceEngineTestFake, SetSendCodecsCNandDTMFAsCallee) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_ != NULL);
@@ -1540,7 +1679,7 @@
// Test that we set up RED correctly as callee.
TEST_F(WebRtcVoiceEngineTestFake, SetSendCodecsREDAsCallee) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_ != NULL);
@@ -1681,11 +1820,9 @@
TEST_F(WebRtcVoiceEngineTestFake, SendAudioLevelHeaderExtensions) {
TestSetSendRtpHeaderExtensions(kRtpAudioLevelHeaderExtension);
}
-#ifdef USE_WEBRTC_DEV_BRANCH
TEST_F(WebRtcVoiceEngineTestFake, RecvAudioLevelHeaderExtensions) {
TestSetRecvRtpHeaderExtensions(kRtpAudioLevelHeaderExtension);
}
-#endif // USE_WEBRTC_DEV_BRANCH
// Test support for absolute send time header extension.
TEST_F(WebRtcVoiceEngineTestFake, SendAbsoluteSendTimeHeaderExtensions) {
@@ -2118,7 +2255,7 @@
TEST_F(WebRtcVoiceEngineTestFake, TraceFilterViaTraceOptions) {
EXPECT_TRUE(SetupEngine());
- engine_.SetLogging(talk_base::LS_INFO, "");
+ engine_.SetLogging(rtc::LS_INFO, "");
EXPECT_EQ(
// Info:
webrtc::kTraceStateInfo | webrtc::kTraceInfo |
@@ -2129,8 +2266,8 @@
static_cast<int>(trace_wrapper_->filter_));
// Now set it explicitly
std::string filter =
- "tracefilter " + talk_base::ToString(webrtc::kTraceDefault);
- engine_.SetLogging(talk_base::LS_VERBOSE, filter.c_str());
+ "tracefilter " + rtc::ToString(webrtc::kTraceDefault);
+ engine_.SetLogging(rtc::LS_VERBOSE, filter.c_str());
EXPECT_EQ(static_cast<unsigned int>(webrtc::kTraceDefault),
trace_wrapper_->filter_);
}
@@ -2213,7 +2350,7 @@
// Test that the local SSRC is the same on sending and receiving channels if the
// receive channel is created before the send channel.
TEST_F(WebRtcVoiceEngineTestFake, SetSendSsrcAfterCreatingReceiveChannel) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
channel_ = engine_.CreateChannel();
EXPECT_TRUE(channel_->SetOptions(options_conference_));
@@ -2254,7 +2391,7 @@
char packets[4][sizeof(kPcmuFrame)];
for (size_t i = 0; i < ARRAY_SIZE(packets); ++i) {
memcpy(packets[i], kPcmuFrame, sizeof(kPcmuFrame));
- talk_base::SetBE32(packets[i] + 8, static_cast<uint32>(i));
+ rtc::SetBE32(packets[i] + 8, static_cast<uint32>(i));
}
EXPECT_TRUE(voe_.CheckNoPacket(channel_num1));
EXPECT_TRUE(voe_.CheckNoPacket(channel_num2));
@@ -2318,7 +2455,7 @@
cricket::StreamParams::CreateLegacy(kSsrc1)));
int channel_num2 = voe_.GetLastChannel();
webrtc::CodecInst gcodec;
- talk_base::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "CELT");
+ rtc::strcpyn(gcodec.plname, ARRAY_SIZE(gcodec.plname), "CELT");
gcodec.plfreq = 32000;
gcodec.channels = 2;
EXPECT_EQ(-1, voe_.GetRecPayloadType(channel_num2, gcodec));
@@ -2429,14 +2566,14 @@
// Send a packet with SSRC 2; the tone should stop.
char packet[sizeof(kPcmuFrame)];
memcpy(packet, kPcmuFrame, sizeof(kPcmuFrame));
- talk_base::SetBE32(packet + 8, 2);
+ rtc::SetBE32(packet + 8, 2);
DeliverPacket(packet, sizeof(packet));
EXPECT_EQ(0, voe_.IsPlayingFileLocally(channel_num));
}
// Tests creating soundclips, and make sure they come from the right engine.
TEST_F(WebRtcVoiceEngineTestFake, CreateSoundclip) {
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
EXPECT_FALSE(voe_sc_.IsInited());
soundclip_ = engine_.CreateSoundclip();
EXPECT_TRUE(voe_sc_.IsInited());
@@ -2457,14 +2594,14 @@
// Tests playing out a fake sound.
TEST_F(WebRtcVoiceEngineTestFake, PlaySoundclip) {
static const char kZeroes[16000] = {};
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
soundclip_ = engine_.CreateSoundclip();
ASSERT_TRUE(soundclip_ != NULL);
EXPECT_TRUE(soundclip_->PlaySound(kZeroes, sizeof(kZeroes), 0));
}
TEST_F(WebRtcVoiceEngineTestFake, MediaEngineCallbackOnError) {
- talk_base::scoped_ptr<ChannelErrorListener> listener;
+ rtc::scoped_ptr<ChannelErrorListener> listener;
cricket::WebRtcVoiceMediaChannel* media_channel;
unsigned int ssrc = 0;
@@ -2770,7 +2907,7 @@
set_config.digitalCompressionGaindB = 9;
set_config.limiterEnable = true;
EXPECT_EQ(0, voe_.SetAgcConfig(set_config));
- EXPECT_TRUE(engine_.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine_.Init(rtc::Thread::Current()));
webrtc::AgcConfig config = {0};
EXPECT_EQ(0, voe_.GetAgcConfig(config));
@@ -2782,9 +2919,9 @@
TEST_F(WebRtcVoiceEngineTestFake, SetOptionOverridesViaChannels) {
EXPECT_TRUE(SetupEngine());
- talk_base::scoped_ptr<cricket::VoiceMediaChannel> channel1(
+ rtc::scoped_ptr<cricket::VoiceMediaChannel> channel1(
engine_.CreateChannel());
- talk_base::scoped_ptr<cricket::VoiceMediaChannel> channel2(
+ rtc::scoped_ptr<cricket::VoiceMediaChannel> channel2(
engine_.CreateChannel());
// Have to add a stream to make SetSend work.
@@ -2902,22 +3039,22 @@
// This test verifies DSCP settings are properly applied on voice media channel.
TEST_F(WebRtcVoiceEngineTestFake, TestSetDscpOptions) {
EXPECT_TRUE(SetupEngine());
- talk_base::scoped_ptr<cricket::VoiceMediaChannel> channel(
+ rtc::scoped_ptr<cricket::VoiceMediaChannel> channel(
engine_.CreateChannel());
- talk_base::scoped_ptr<cricket::FakeNetworkInterface> network_interface(
+ rtc::scoped_ptr<cricket::FakeNetworkInterface> network_interface(
new cricket::FakeNetworkInterface);
channel->SetInterface(network_interface.get());
cricket::AudioOptions options;
options.dscp.Set(true);
EXPECT_TRUE(channel->SetOptions(options));
- EXPECT_EQ(talk_base::DSCP_EF, network_interface->dscp());
+ EXPECT_EQ(rtc::DSCP_EF, network_interface->dscp());
// Verify previous value is not modified if dscp option is not set.
cricket::AudioOptions options1;
EXPECT_TRUE(channel->SetOptions(options1));
- EXPECT_EQ(talk_base::DSCP_EF, network_interface->dscp());
+ EXPECT_EQ(rtc::DSCP_EF, network_interface->dscp());
options.dscp.Set(false);
EXPECT_TRUE(channel->SetOptions(options));
- EXPECT_EQ(talk_base::DSCP_DEFAULT, network_interface->dscp());
+ EXPECT_EQ(rtc::DSCP_DEFAULT, network_interface->dscp());
}
TEST(WebRtcVoiceEngineTest, TestDefaultOptionsBeforeInit) {
@@ -2984,31 +3121,31 @@
// Tests that the library initializes and shuts down properly.
TEST(WebRtcVoiceEngineTest, StartupShutdown) {
cricket::WebRtcVoiceEngine engine;
- EXPECT_TRUE(engine.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine.Init(rtc::Thread::Current()));
cricket::VoiceMediaChannel* channel = engine.CreateChannel();
EXPECT_TRUE(channel != NULL);
delete channel;
engine.Terminate();
// Reinit to catch regression where VoiceEngineObserver reference is lost
- EXPECT_TRUE(engine.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine.Init(rtc::Thread::Current()));
engine.Terminate();
}
// Tests that the logging from the library is cleartext.
TEST(WebRtcVoiceEngineTest, DISABLED_HasUnencryptedLogging) {
cricket::WebRtcVoiceEngine engine;
- talk_base::scoped_ptr<talk_base::MemoryStream> stream(
- new talk_base::MemoryStream);
+ rtc::scoped_ptr<rtc::MemoryStream> stream(
+ new rtc::MemoryStream);
size_t size = 0;
bool cleartext = true;
- talk_base::LogMessage::AddLogToStream(stream.get(), talk_base::LS_VERBOSE);
- engine.SetLogging(talk_base::LS_VERBOSE, "");
- EXPECT_TRUE(engine.Init(talk_base::Thread::Current()));
+ rtc::LogMessage::AddLogToStream(stream.get(), rtc::LS_VERBOSE);
+ engine.SetLogging(rtc::LS_VERBOSE, "");
+ EXPECT_TRUE(engine.Init(rtc::Thread::Current()));
EXPECT_TRUE(stream->GetSize(&size));
EXPECT_GT(size, 0U);
engine.Terminate();
- talk_base::LogMessage::RemoveLogToStream(stream.get());
+ rtc::LogMessage::RemoveLogToStream(stream.get());
const char* buf = stream->GetBuffer();
for (size_t i = 0; i < size && cleartext; ++i) {
int ch = static_cast<int>(buf[i]);
@@ -3023,13 +3160,13 @@
// when initiating the engine.
TEST(WebRtcVoiceEngineTest, HasNoMonitorThread) {
cricket::WebRtcVoiceEngine engine;
- talk_base::scoped_ptr<talk_base::MemoryStream> stream(
- new talk_base::MemoryStream);
- talk_base::LogMessage::AddLogToStream(stream.get(), talk_base::LS_VERBOSE);
- engine.SetLogging(talk_base::LS_VERBOSE, "");
- EXPECT_TRUE(engine.Init(talk_base::Thread::Current()));
+ rtc::scoped_ptr<rtc::MemoryStream> stream(
+ new rtc::MemoryStream);
+ rtc::LogMessage::AddLogToStream(stream.get(), rtc::LS_VERBOSE);
+ engine.SetLogging(rtc::LS_VERBOSE, "");
+ EXPECT_TRUE(engine.Init(rtc::Thread::Current()));
engine.Terminate();
- talk_base::LogMessage::RemoveLogToStream(stream.get());
+ rtc::LogMessage::RemoveLogToStream(stream.get());
size_t size = 0;
EXPECT_TRUE(stream->GetSize(&size));
@@ -3119,7 +3256,7 @@
// Tests that VoE supports at least 32 channels
TEST(WebRtcVoiceEngineTest, Has32Channels) {
cricket::WebRtcVoiceEngine engine;
- EXPECT_TRUE(engine.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine.Init(rtc::Thread::Current()));
cricket::VoiceMediaChannel* channels[32];
int num_channels = 0;
@@ -3145,7 +3282,7 @@
// Test that we set our preferred codecs properly.
TEST(WebRtcVoiceEngineTest, SetRecvCodecs) {
cricket::WebRtcVoiceEngine engine;
- EXPECT_TRUE(engine.Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine.Init(rtc::Thread::Current()));
cricket::WebRtcVoiceMediaChannel channel(&engine);
EXPECT_TRUE(channel.SetRecvCodecs(engine.codecs()));
}
@@ -3159,9 +3296,9 @@
EXPECT_EQ(S_OK, CoInitializeEx(NULL, COINIT_MULTITHREADED));
// Engine should start even with COM already inited.
- EXPECT_TRUE(engine->Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine->Init(rtc::Thread::Current()));
engine->Terminate();
- EXPECT_TRUE(engine->Init(talk_base::Thread::Current()));
+ EXPECT_TRUE(engine->Init(rtc::Thread::Current()));
engine->Terminate();
// Refcount after terminate should be 1 (in reality 3); test if it is nonzero.
@@ -3177,3 +3314,112 @@
}
#endif
+TEST_F(WebRtcVoiceEngineTestFake, ChangeCombinedAudioVideoBweOption) {
+ // Test that changing the combined_audio_video_bwe option results in the
+ // expected state changes in VoiceEngine.
+ cricket::ViEWrapper vie;
+ const int kVieCh = 667;
+
+ EXPECT_TRUE(SetupEngine());
+ cricket::WebRtcVoiceMediaChannel* media_channel =
+ static_cast<cricket::WebRtcVoiceMediaChannel*>(channel_);
+ EXPECT_TRUE(media_channel->SetupSharedBandwidthEstimation(vie.engine(),
+ kVieCh));
+ EXPECT_TRUE(media_channel->AddRecvStream(
+ cricket::StreamParams::CreateLegacy(2)));
+ int recv_ch = voe_.GetLastChannel();
+
+ // Combined BWE should not be set up yet.
+ EXPECT_EQ(NULL, voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(-1, voe_.GetVideoChannel(recv_ch));
+
+ // Enable combined BWE option - now it should be set up.
+ cricket::AudioOptions options;
+ options.combined_audio_video_bwe.Set(true);
+ EXPECT_TRUE(media_channel->SetOptions(options));
+ EXPECT_EQ(vie.network(), voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(kVieCh, voe_.GetVideoChannel(recv_ch));
+
+ // Disable combined BWE option - should be disabled again.
+ options.combined_audio_video_bwe.Set(false);
+ EXPECT_TRUE(media_channel->SetOptions(options));
+ EXPECT_EQ(NULL, voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(-1, voe_.GetVideoChannel(recv_ch));
+
+ EXPECT_TRUE(media_channel->SetupSharedBandwidthEstimation(NULL, -1));
+}
+
+TEST_F(WebRtcVoiceEngineTestFake, SetupSharedBandwidthEstimation) {
+ // Test that calling SetupSharedBandwidthEstimation() on the voice media
+ // channel results in the expected state changes in VoiceEngine.
+ cricket::ViEWrapper vie1;
+ cricket::ViEWrapper vie2;
+ const int kVieCh1 = 667;
+ const int kVieCh2 = 70;
+
+ EXPECT_TRUE(SetupEngine());
+ cricket::WebRtcVoiceMediaChannel* media_channel =
+ static_cast<cricket::WebRtcVoiceMediaChannel*>(channel_);
+ cricket::AudioOptions options;
+ options.combined_audio_video_bwe.Set(true);
+ EXPECT_TRUE(media_channel->SetOptions(options));
+ EXPECT_TRUE(media_channel->AddRecvStream(
+ cricket::StreamParams::CreateLegacy(2)));
+ int recv_ch = voe_.GetLastChannel();
+
+ // Combined BWE should not be set up yet.
+ EXPECT_EQ(NULL, voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(-1, voe_.GetVideoChannel(recv_ch));
+
+ // Register - should be enabled.
+ EXPECT_TRUE(media_channel->SetupSharedBandwidthEstimation(vie1.engine(),
+ kVieCh1));
+ EXPECT_EQ(vie1.network(), voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(kVieCh1, voe_.GetVideoChannel(recv_ch));
+
+ // Re-register - should still be enabled.
+ EXPECT_TRUE(media_channel->SetupSharedBandwidthEstimation(vie2.engine(),
+ kVieCh2));
+ EXPECT_EQ(vie2.network(), voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(kVieCh2, voe_.GetVideoChannel(recv_ch));
+
+ // Unregister - should be disabled again.
+ EXPECT_TRUE(media_channel->SetupSharedBandwidthEstimation(NULL, -1));
+ EXPECT_EQ(NULL, voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(-1, voe_.GetVideoChannel(recv_ch));
+}
+
+TEST_F(WebRtcVoiceEngineTestFake, ConfigureCombinedBweForNewRecvStreams) {
+ // Test that adding receive streams after enabling combined bandwidth
+ // estimation will correctly configure each channel.
+ cricket::ViEWrapper vie;
+ const int kVieCh = 667;
+
+ EXPECT_TRUE(SetupEngine());
+ cricket::WebRtcVoiceMediaChannel* media_channel =
+ static_cast<cricket::WebRtcVoiceMediaChannel*>(channel_);
+ EXPECT_TRUE(media_channel->SetupSharedBandwidthEstimation(vie.engine(),
+ kVieCh));
+ cricket::AudioOptions options;
+ options.combined_audio_video_bwe.Set(true);
+ EXPECT_TRUE(media_channel->SetOptions(options));
+
+ static const uint32 kSsrcs[] = {1, 2, 3, 4};
+ int voe_channels[ARRAY_SIZE(kSsrcs)] = {0};
+ for (unsigned int i = 0; i < ARRAY_SIZE(kSsrcs); ++i) {
+ EXPECT_TRUE(media_channel->AddRecvStream(
+ cricket::StreamParams::CreateLegacy(kSsrcs[i])));
+ int recv_ch = media_channel->GetReceiveChannelNum(kSsrcs[i]);
+ EXPECT_NE(-1, recv_ch);
+ voe_channels[i] = recv_ch;
+ EXPECT_EQ(vie.network(), voe_.GetViENetwork(recv_ch));
+ EXPECT_EQ(kVieCh, voe_.GetVideoChannel(recv_ch));
+ }
+
+ EXPECT_TRUE(media_channel->SetupSharedBandwidthEstimation(NULL, -1));
+
+ for (unsigned int i = 0; i < ARRAY_SIZE(voe_channels); ++i) {
+ EXPECT_EQ(NULL, voe_.GetViENetwork(voe_channels[i]));
+ EXPECT_EQ(-1, voe_.GetVideoChannel(voe_channels[i]));
+ }
+}
diff --git a/p2p/base/asyncstuntcpsocket.cc b/p2p/base/asyncstuntcpsocket.cc
index 8bcfa3a..c1aeead 100644
--- a/p2p/base/asyncstuntcpsocket.cc
+++ b/p2p/base/asyncstuntcpsocket.cc
@@ -29,9 +29,9 @@
#include <string.h>
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -53,20 +53,20 @@
// it. Takes ownership of |socket|. Returns NULL if bind() or
// connect() fail (|socket| is destroyed in that case).
AsyncStunTCPSocket* AsyncStunTCPSocket::Create(
- talk_base::AsyncSocket* socket,
- const talk_base::SocketAddress& bind_address,
- const talk_base::SocketAddress& remote_address) {
+ rtc::AsyncSocket* socket,
+ const rtc::SocketAddress& bind_address,
+ const rtc::SocketAddress& remote_address) {
return new AsyncStunTCPSocket(AsyncTCPSocketBase::ConnectSocket(
socket, bind_address, remote_address), false);
}
AsyncStunTCPSocket::AsyncStunTCPSocket(
- talk_base::AsyncSocket* socket, bool listen)
- : talk_base::AsyncTCPSocketBase(socket, listen, kBufSize) {
+ rtc::AsyncSocket* socket, bool listen)
+ : rtc::AsyncTCPSocketBase(socket, listen, kBufSize) {
}
int AsyncStunTCPSocket::Send(const void *pv, size_t cb,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
if (cb > kBufSize || cb < kPacketLenSize + kPacketLenOffset) {
SetError(EMSGSIZE);
return -1;
@@ -101,7 +101,7 @@
}
void AsyncStunTCPSocket::ProcessInput(char* data, size_t* len) {
- talk_base::SocketAddress remote_addr(GetRemoteAddress());
+ rtc::SocketAddress remote_addr(GetRemoteAddress());
// STUN packet - First 4 bytes. Total header size is 20 bytes.
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |0 0| STUN Message Type | Message Length |
@@ -126,7 +126,7 @@
}
SignalReadPacket(this, data, expected_pkt_len, remote_addr,
- talk_base::CreatePacketTime(0));
+ rtc::CreatePacketTime(0));
*len -= actual_length;
if (*len > 0) {
@@ -136,7 +136,7 @@
}
void AsyncStunTCPSocket::HandleIncomingConnection(
- talk_base::AsyncSocket* socket) {
+ rtc::AsyncSocket* socket) {
SignalNewConnection(this, new AsyncStunTCPSocket(socket, false));
}
@@ -144,9 +144,9 @@
int* pad_bytes) {
*pad_bytes = 0;
PacketLength pkt_len =
- talk_base::GetBE16(static_cast<const char*>(data) + kPacketLenOffset);
+ rtc::GetBE16(static_cast<const char*>(data) + kPacketLenOffset);
size_t expected_pkt_len;
- uint16 msg_type = talk_base::GetBE16(data);
+ uint16 msg_type = rtc::GetBE16(data);
if (IsStunMessage(msg_type)) {
// STUN message.
expected_pkt_len = kStunHeaderSize + pkt_len;
diff --git a/p2p/base/asyncstuntcpsocket.h b/p2p/base/asyncstuntcpsocket.h
index bef8e98..136b4df 100644
--- a/p2p/base/asyncstuntcpsocket.h
+++ b/p2p/base/asyncstuntcpsocket.h
@@ -25,32 +25,32 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef TALK_BASE_ASYNCSTUNTCPSOCKET_H_
-#define TALK_BASE_ASYNCSTUNTCPSOCKET_H_
+#ifndef TALK_P2P_BASE_ASYNCSTUNTCPSOCKET_H_
+#define TALK_P2P_BASE_ASYNCSTUNTCPSOCKET_H_
-#include "talk/base/asynctcpsocket.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketfactory.h"
+#include "webrtc/base/asynctcpsocket.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketfactory.h"
namespace cricket {
-class AsyncStunTCPSocket : public talk_base::AsyncTCPSocketBase {
+class AsyncStunTCPSocket : public rtc::AsyncTCPSocketBase {
public:
// Binds and connects |socket| and creates AsyncTCPSocket for
// it. Takes ownership of |socket|. Returns NULL if bind() or
// connect() fail (|socket| is destroyed in that case).
static AsyncStunTCPSocket* Create(
- talk_base::AsyncSocket* socket,
- const talk_base::SocketAddress& bind_address,
- const talk_base::SocketAddress& remote_address);
+ rtc::AsyncSocket* socket,
+ const rtc::SocketAddress& bind_address,
+ const rtc::SocketAddress& remote_address);
- AsyncStunTCPSocket(talk_base::AsyncSocket* socket, bool listen);
+ AsyncStunTCPSocket(rtc::AsyncSocket* socket, bool listen);
virtual ~AsyncStunTCPSocket() {}
virtual int Send(const void* pv, size_t cb,
- const talk_base::PacketOptions& options);
+ const rtc::PacketOptions& options);
virtual void ProcessInput(char* data, size_t* len);
- virtual void HandleIncomingConnection(talk_base::AsyncSocket* socket);
+ virtual void HandleIncomingConnection(rtc::AsyncSocket* socket);
private:
// This method returns the message hdr + length written in the header.
@@ -64,4 +64,4 @@
} // namespace cricket
-#endif // TALK_BASE_ASYNCSTUNTCPSOCKET_H_
+#endif // TALK_P2P_BASE_ASYNCSTUNTCPSOCKET_H_
diff --git a/p2p/base/asyncstuntcpsocket_unittest.cc b/p2p/base/asyncstuntcpsocket_unittest.cc
index f3261df..46e5d63 100644
--- a/p2p/base/asyncstuntcpsocket_unittest.cc
+++ b/p2p/base/asyncstuntcpsocket_unittest.cc
@@ -25,11 +25,11 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/asyncsocket.h"
-#include "talk/base/gunit.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/p2p/base/asyncstuntcpsocket.h"
+#include "webrtc/base/asyncsocket.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/virtualsocketserver.h"
namespace cricket {
@@ -77,14 +77,14 @@
};
-static const talk_base::SocketAddress kClientAddr("11.11.11.11", 0);
-static const talk_base::SocketAddress kServerAddr("22.22.22.22", 0);
+static const rtc::SocketAddress kClientAddr("11.11.11.11", 0);
+static const rtc::SocketAddress kServerAddr("22.22.22.22", 0);
class AsyncStunTCPSocketTest : public testing::Test,
public sigslot::has_slots<> {
protected:
AsyncStunTCPSocketTest()
- : vss_(new talk_base::VirtualSocketServer(NULL)),
+ : vss_(new rtc::VirtualSocketServer(NULL)),
ss_scope_(vss_.get()) {
}
@@ -93,14 +93,14 @@
}
void CreateSockets() {
- talk_base::AsyncSocket* server = vss_->CreateAsyncSocket(
+ rtc::AsyncSocket* server = vss_->CreateAsyncSocket(
kServerAddr.family(), SOCK_STREAM);
server->Bind(kServerAddr);
recv_socket_.reset(new AsyncStunTCPSocket(server, true));
recv_socket_->SignalNewConnection.connect(
this, &AsyncStunTCPSocketTest::OnNewConnection);
- talk_base::AsyncSocket* client = vss_->CreateAsyncSocket(
+ rtc::AsyncSocket* client = vss_->CreateAsyncSocket(
kClientAddr.family(), SOCK_STREAM);
send_socket_.reset(AsyncStunTCPSocket::Create(
client, kClientAddr, recv_socket_->GetLocalAddress()));
@@ -108,21 +108,21 @@
vss_->ProcessMessagesUntilIdle();
}
- void OnReadPacket(talk_base::AsyncPacketSocket* socket, const char* data,
- size_t len, const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ void OnReadPacket(rtc::AsyncPacketSocket* socket, const char* data,
+ size_t len, const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
recv_packets_.push_back(std::string(data, len));
}
- void OnNewConnection(talk_base::AsyncPacketSocket* server,
- talk_base::AsyncPacketSocket* new_socket) {
+ void OnNewConnection(rtc::AsyncPacketSocket* server,
+ rtc::AsyncPacketSocket* new_socket) {
listen_socket_.reset(new_socket);
new_socket->SignalReadPacket.connect(
this, &AsyncStunTCPSocketTest::OnReadPacket);
}
bool Send(const void* data, size_t len) {
- talk_base::PacketOptions options;
+ rtc::PacketOptions options;
size_t ret = send_socket_->Send(
reinterpret_cast<const char*>(data), len, options);
vss_->ProcessMessagesUntilIdle();
@@ -139,11 +139,11 @@
return ret;
}
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> vss_;
- talk_base::SocketServerScope ss_scope_;
- talk_base::scoped_ptr<AsyncStunTCPSocket> send_socket_;
- talk_base::scoped_ptr<AsyncStunTCPSocket> recv_socket_;
- talk_base::scoped_ptr<talk_base::AsyncPacketSocket> listen_socket_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> vss_;
+ rtc::SocketServerScope ss_scope_;
+ rtc::scoped_ptr<AsyncStunTCPSocket> send_socket_;
+ rtc::scoped_ptr<AsyncStunTCPSocket> recv_socket_;
+ rtc::scoped_ptr<rtc::AsyncPacketSocket> listen_socket_;
std::list<std::string> recv_packets_;
};
diff --git a/p2p/base/basicpacketsocketfactory.cc b/p2p/base/basicpacketsocketfactory.cc
index 758d492..2b3b06f 100644
--- a/p2p/base/basicpacketsocketfactory.cc
+++ b/p2p/base/basicpacketsocketfactory.cc
@@ -27,18 +27,19 @@
#include "talk/p2p/base/basicpacketsocketfactory.h"
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/asynctcpsocket.h"
-#include "talk/base/logging.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/asyncstuntcpsocket.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/asynctcpsocket.h"
+#include "webrtc/base/asyncudpsocket.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/nethelpers.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketadapters.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/thread.h"
-namespace talk_base {
+namespace rtc {
BasicPacketSocketFactory::BasicPacketSocketFactory()
: thread_(Thread::Current()),
@@ -62,7 +63,7 @@
AsyncPacketSocket* BasicPacketSocketFactory::CreateUdpSocket(
const SocketAddress& address, int min_port, int max_port) {
// UDP sockets are simple.
- talk_base::AsyncSocket* socket =
+ rtc::AsyncSocket* socket =
socket_factory()->CreateAsyncSocket(
address.family(), SOCK_DGRAM);
if (!socket) {
@@ -74,7 +75,7 @@
delete socket;
return NULL;
}
- return new talk_base::AsyncUDPSocket(socket);
+ return new rtc::AsyncUDPSocket(socket);
}
AsyncPacketSocket* BasicPacketSocketFactory::CreateServerTcpSocket(
@@ -86,7 +87,7 @@
return NULL;
}
- talk_base::AsyncSocket* socket =
+ rtc::AsyncSocket* socket =
socket_factory()->CreateAsyncSocket(local_address.family(),
SOCK_STREAM);
if (!socket) {
@@ -103,30 +104,24 @@
// If using SSLTCP, wrap the TCP socket in a pseudo-SSL socket.
if (opts & PacketSocketFactory::OPT_SSLTCP) {
ASSERT(!(opts & PacketSocketFactory::OPT_TLS));
- socket = new talk_base::AsyncSSLSocket(socket);
+ socket = new rtc::AsyncSSLSocket(socket);
}
// Set TCP_NODELAY (via OPT_NODELAY) for improved performance.
// See http://go/gtalktcpnodelayexperiment
- socket->SetOption(talk_base::Socket::OPT_NODELAY, 1);
+ socket->SetOption(rtc::Socket::OPT_NODELAY, 1);
if (opts & PacketSocketFactory::OPT_STUN)
return new cricket::AsyncStunTCPSocket(socket, true);
- return new talk_base::AsyncTCPSocket(socket, true);
+ return new rtc::AsyncTCPSocket(socket, true);
}
AsyncPacketSocket* BasicPacketSocketFactory::CreateClientTcpSocket(
const SocketAddress& local_address, const SocketAddress& remote_address,
const ProxyInfo& proxy_info, const std::string& user_agent, int opts) {
- // Fail if TLS is required.
- if (opts & PacketSocketFactory::OPT_TLS) {
- LOG(LS_ERROR) << "TLS support currently is not available.";
- return NULL;
- }
-
- talk_base::AsyncSocket* socket =
+ rtc::AsyncSocket* socket =
socket_factory()->CreateAsyncSocket(local_address.family(), SOCK_STREAM);
if (!socket) {
return NULL;
@@ -140,19 +135,35 @@
}
// If using a proxy, wrap the socket in a proxy socket.
- if (proxy_info.type == talk_base::PROXY_SOCKS5) {
- socket = new talk_base::AsyncSocksProxySocket(
+ if (proxy_info.type == rtc::PROXY_SOCKS5) {
+ socket = new rtc::AsyncSocksProxySocket(
socket, proxy_info.address, proxy_info.username, proxy_info.password);
- } else if (proxy_info.type == talk_base::PROXY_HTTPS) {
- socket = new talk_base::AsyncHttpsProxySocket(
+ } else if (proxy_info.type == rtc::PROXY_HTTPS) {
+ socket = new rtc::AsyncHttpsProxySocket(
socket, user_agent, proxy_info.address,
proxy_info.username, proxy_info.password);
}
+ // If using TLS, wrap the socket in an SSL adapter.
+ if (opts & PacketSocketFactory::OPT_TLS) {
+ ASSERT(!(opts & PacketSocketFactory::OPT_SSLTCP));
+
+ rtc::SSLAdapter* ssl_adapter = rtc::SSLAdapter::Create(socket);
+ if (!ssl_adapter) {
+ return NULL;
+ }
+
+ socket = ssl_adapter;
+
+ if (ssl_adapter->StartSSL(remote_address.hostname().c_str(), false) != 0) {
+ delete ssl_adapter;
+ return NULL;
+ }
+
// If using SSLTCP, wrap the TCP socket in a pseudo-SSL socket.
- if (opts & PacketSocketFactory::OPT_SSLTCP) {
+ } else if (opts & PacketSocketFactory::OPT_SSLTCP) {
ASSERT(!(opts & PacketSocketFactory::OPT_TLS));
- socket = new talk_base::AsyncSSLSocket(socket);
+ socket = new rtc::AsyncSSLSocket(socket);
}
if (socket->Connect(remote_address) < 0) {
@@ -167,18 +178,18 @@
if (opts & PacketSocketFactory::OPT_STUN) {
tcp_socket = new cricket::AsyncStunTCPSocket(socket, false);
} else {
- tcp_socket = new talk_base::AsyncTCPSocket(socket, false);
+ tcp_socket = new rtc::AsyncTCPSocket(socket, false);
}
// Set TCP_NODELAY (via OPT_NODELAY) for improved performance.
// See http://go/gtalktcpnodelayexperiment
- tcp_socket->SetOption(talk_base::Socket::OPT_NODELAY, 1);
+ tcp_socket->SetOption(rtc::Socket::OPT_NODELAY, 1);
return tcp_socket;
}
AsyncResolverInterface* BasicPacketSocketFactory::CreateAsyncResolver() {
- return new talk_base::AsyncResolver();
+ return new rtc::AsyncResolver();
}
int BasicPacketSocketFactory::BindSocket(
@@ -191,7 +202,7 @@
} else {
// Otherwise, try to find a port in the provided range.
for (int port = min_port; ret < 0 && port <= max_port; ++port) {
- ret = socket->Bind(talk_base::SocketAddress(local_address.ipaddr(),
+ ret = socket->Bind(rtc::SocketAddress(local_address.ipaddr(),
port));
}
}
@@ -207,4 +218,4 @@
}
}
-} // namespace talk_base
+} // namespace rtc
diff --git a/p2p/base/basicpacketsocketfactory.h b/p2p/base/basicpacketsocketfactory.h
index 27963c9..77b1652 100644
--- a/p2p/base/basicpacketsocketfactory.h
+++ b/p2p/base/basicpacketsocketfactory.h
@@ -25,12 +25,12 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef TALK_BASE_BASICPACKETSOCKETFACTORY_H_
-#define TALK_BASE_BASICPACKETSOCKETFACTORY_H_
+#ifndef TALK_P2P_BASE_BASICPACKETSOCKETFACTORY_H_
+#define TALK_P2P_BASE_BASICPACKETSOCKETFACTORY_H_
#include "talk/p2p/base/packetsocketfactory.h"
-namespace talk_base {
+namespace rtc {
class AsyncSocket;
class SocketFactory;
@@ -63,6 +63,6 @@
SocketFactory* socket_factory_;
};
-} // namespace talk_base
+} // namespace rtc
-#endif // TALK_BASE_BASICPACKETSOCKETFACTORY_H_
+#endif // TALK_P2P_BASE_BASICPACKETSOCKETFACTORY_H_
diff --git a/p2p/base/candidate.h b/p2p/base/candidate.h
index 547725d..cb0b1bc 100644
--- a/p2p/base/candidate.h
+++ b/p2p/base/candidate.h
@@ -31,13 +31,13 @@
#include <limits.h>
#include <math.h>
-#include <string>
-#include <sstream>
#include <iomanip>
+#include <sstream>
+#include <string>
-#include "talk/base/basictypes.h"
-#include "talk/base/socketaddress.h"
#include "talk/p2p/base/constants.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/socketaddress.h"
namespace cricket {
@@ -49,7 +49,7 @@
// candidate-attribute syntax. http://tools.ietf.org/html/rfc5245#section-15.1
Candidate() : component_(0), priority_(0), generation_(0) {}
Candidate(const std::string& id, int component, const std::string& protocol,
- const talk_base::SocketAddress& address, uint32 priority,
+ const rtc::SocketAddress& address, uint32 priority,
const std::string& username, const std::string& password,
const std::string& type, const std::string& network_name,
uint32 generation, const std::string& foundation)
@@ -68,8 +68,8 @@
const std::string & protocol() const { return protocol_; }
void set_protocol(const std::string & protocol) { protocol_ = protocol; }
- const talk_base::SocketAddress & address() const { return address_; }
- void set_address(const talk_base::SocketAddress & address) {
+ const rtc::SocketAddress & address() const { return address_; }
+ void set_address(const rtc::SocketAddress & address) {
address_ = address;
}
@@ -94,7 +94,7 @@
// This can happen for e.g. when preference = 3.
uint64 prio_val = static_cast<uint64>(preference * 127) << 24;
priority_ = static_cast<uint32>(
- talk_base::_min(prio_val, static_cast<uint64>(UINT_MAX)));
+ rtc::_min(prio_val, static_cast<uint64>(UINT_MAX)));
}
const std::string & username() const { return username_; }
@@ -132,13 +132,17 @@
foundation_ = foundation;
}
- const talk_base::SocketAddress & related_address() const {
+ const rtc::SocketAddress & related_address() const {
return related_address_;
}
void set_related_address(
- const talk_base::SocketAddress & related_address) {
+ const rtc::SocketAddress & related_address) {
related_address_ = related_address;
}
+ const std::string& tcptype() const { return tcptype_; }
+ void set_tcptype(const std::string& tcptype){
+ tcptype_ = tcptype;
+ }
// Determines whether this candidate is equivalent to the given one.
bool IsEquivalent(const Candidate& c) const {
@@ -166,7 +170,8 @@
}
uint32 GetPriority(uint32 type_preference,
- int network_adapter_preference) const {
+ int network_adapter_preference,
+ int relay_preference) const {
// RFC 5245 - 4.1.2.1.
// priority = (2^24)*(type preference) +
// (2^8)*(local preference) +
@@ -181,10 +186,11 @@
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// NIC Type - Type of the network adapter e.g. 3G/Wifi/Wired.
// Addr Pref - Address preference value as per RFC 3484.
- // local preference is calculated as - NIC Type << 8 | Addr_Pref.
+ // local preference = (NIC Type << 8 | Addr_Pref) - relay preference.
int addr_pref = IPAddressPrecedence(address_.ipaddr());
- int local_preference = (network_adapter_preference << 8) | addr_pref;
+ int local_preference = ((network_adapter_preference << 8) | addr_pref) +
+ relay_preference;
return (type_preference << 24) |
(local_preference << 8) |
@@ -206,7 +212,7 @@
std::string id_;
int component_;
std::string protocol_;
- talk_base::SocketAddress address_;
+ rtc::SocketAddress address_;
uint32 priority_;
std::string username_;
std::string password_;
@@ -214,7 +220,8 @@
std::string network_name_;
uint32 generation_;
std::string foundation_;
- talk_base::SocketAddress related_address_;
+ rtc::SocketAddress related_address_;
+ std::string tcptype_;
};
} // namespace cricket
diff --git a/p2p/base/common.h b/p2p/base/common.h
index 5a38180..a33e9e0 100644
--- a/p2p/base/common.h
+++ b/p2p/base/common.h
@@ -28,7 +28,7 @@
#ifndef TALK_P2P_BASE_COMMON_H_
#define TALK_P2P_BASE_COMMON_H_
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
// Common log description format for jingle messages
#define LOG_J(sev, obj) LOG(sev) << "Jingle:" << obj->ToString() << ": "
diff --git a/p2p/base/constants.cc b/p2p/base/constants.cc
index 2e57d9d..278a615 100644
--- a/p2p/base/constants.cc
+++ b/p2p/base/constants.cc
@@ -29,7 +29,7 @@
#include <string>
-#include "talk/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/qname.h"
namespace cricket {
diff --git a/p2p/base/constants.h b/p2p/base/constants.h
index 61dd815..4cd1166 100644
--- a/p2p/base/constants.h
+++ b/p2p/base/constants.h
@@ -29,7 +29,7 @@
#define TALK_P2P_BASE_CONSTANTS_H_
#include <string>
-#include "talk/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/qname.h"
// This file contains constants related to signaling that are used in various
// classes in this directory.
diff --git a/p2p/base/dtlstransport.h b/p2p/base/dtlstransport.h
index 6bef185..318c14a 100644
--- a/p2p/base/dtlstransport.h
+++ b/p2p/base/dtlstransport.h
@@ -31,7 +31,7 @@
#include "talk/p2p/base/dtlstransportchannel.h"
#include "talk/p2p/base/transport.h"
-namespace talk_base {
+namespace rtc {
class SSLIdentity;
}
@@ -43,22 +43,23 @@
template<class Base>
class DtlsTransport : public Base {
public:
- DtlsTransport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ DtlsTransport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
PortAllocator* allocator,
- talk_base::SSLIdentity* identity)
+ rtc::SSLIdentity* identity)
: Base(signaling_thread, worker_thread, content_name, allocator),
- identity_(identity) {
+ identity_(identity),
+ secure_role_(rtc::SSL_CLIENT) {
}
~DtlsTransport() {
Base::DestroyAllChannels();
}
- virtual void SetIdentity_w(talk_base::SSLIdentity* identity) {
+ virtual void SetIdentity_w(rtc::SSLIdentity* identity) {
identity_ = identity;
}
- virtual bool GetIdentity_w(talk_base::SSLIdentity** identity) {
+ virtual bool GetIdentity_w(rtc::SSLIdentity** identity) {
if (!identity_)
return false;
@@ -68,14 +69,14 @@
virtual bool ApplyLocalTransportDescription_w(TransportChannelImpl* channel,
std::string* error_desc) {
- talk_base::SSLFingerprint* local_fp =
+ rtc::SSLFingerprint* local_fp =
Base::local_description()->identity_fingerprint.get();
if (local_fp) {
// Sanity check local fingerprint.
if (identity_) {
- talk_base::scoped_ptr<talk_base::SSLFingerprint> local_fp_tmp(
- talk_base::SSLFingerprint::Create(local_fp->algorithm,
+ rtc::scoped_ptr<rtc::SSLFingerprint> local_fp_tmp(
+ rtc::SSLFingerprint::Create(local_fp->algorithm,
identity_));
ASSERT(local_fp_tmp.get() != NULL);
if (!(*local_fp_tmp == *local_fp)) {
@@ -111,13 +112,13 @@
return BadTransportDescription(msg, error_desc);
}
- talk_base::SSLFingerprint* local_fp =
+ rtc::SSLFingerprint* local_fp =
Base::local_description()->identity_fingerprint.get();
- talk_base::SSLFingerprint* remote_fp =
+ rtc::SSLFingerprint* remote_fp =
Base::remote_description()->identity_fingerprint.get();
if (remote_fp && local_fp) {
- remote_fingerprint_.reset(new talk_base::SSLFingerprint(*remote_fp));
+ remote_fingerprint_.reset(new rtc::SSLFingerprint(*remote_fp));
// From RFC 4145, section-4.1, The following are the values that the
// 'setup' attribute can take in an offer/answer exchange:
@@ -187,8 +188,8 @@
// If local is passive, local will act as server.
}
- secure_role_ = is_remote_server ? talk_base::SSL_CLIENT :
- talk_base::SSL_SERVER;
+ secure_role_ = is_remote_server ? rtc::SSL_CLIENT :
+ rtc::SSL_SERVER;
} else if (local_fp && (local_role == CA_ANSWER)) {
return BadTransportDescription(
@@ -196,7 +197,7 @@
error_desc);
} else {
// We are not doing DTLS
- remote_fingerprint_.reset(new talk_base::SSLFingerprint(
+ remote_fingerprint_.reset(new rtc::SSLFingerprint(
"", NULL, 0));
}
@@ -218,7 +219,7 @@
Base::DestroyTransportChannel(base_channel);
}
- virtual bool GetSslRole_w(talk_base::SSLRole* ssl_role) const {
+ virtual bool GetSslRole_w(rtc::SSLRole* ssl_role) const {
ASSERT(ssl_role != NULL);
*ssl_role = secure_role_;
return true;
@@ -246,9 +247,9 @@
return Base::ApplyNegotiatedTransportDescription_w(channel, error_desc);
}
- talk_base::SSLIdentity* identity_;
- talk_base::SSLRole secure_role_;
- talk_base::scoped_ptr<talk_base::SSLFingerprint> remote_fingerprint_;
+ rtc::SSLIdentity* identity_;
+ rtc::SSLRole secure_role_;
+ rtc::scoped_ptr<rtc::SSLFingerprint> remote_fingerprint_;
};
} // namespace cricket
diff --git a/p2p/base/dtlstransportchannel.cc b/p2p/base/dtlstransportchannel.cc
index 416e6e9..e0f4141 100644
--- a/p2p/base/dtlstransportchannel.cc
+++ b/p2p/base/dtlstransportchannel.cc
@@ -28,13 +28,13 @@
#include "talk/p2p/base/dtlstransportchannel.h"
-#include "talk/base/buffer.h"
-#include "talk/base/dscp.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/stream.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/common.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -52,45 +52,45 @@
return (len >= kMinRtpPacketLen && (u[0] & 0xC0) == 0x80);
}
-talk_base::StreamResult StreamInterfaceChannel::Read(void* buffer,
+rtc::StreamResult StreamInterfaceChannel::Read(void* buffer,
size_t buffer_len,
size_t* read,
int* error) {
- if (state_ == talk_base::SS_CLOSED)
- return talk_base::SR_EOS;
- if (state_ == talk_base::SS_OPENING)
- return talk_base::SR_BLOCK;
+ if (state_ == rtc::SS_CLOSED)
+ return rtc::SR_EOS;
+ if (state_ == rtc::SS_OPENING)
+ return rtc::SR_BLOCK;
return fifo_.Read(buffer, buffer_len, read, error);
}
-talk_base::StreamResult StreamInterfaceChannel::Write(const void* data,
+rtc::StreamResult StreamInterfaceChannel::Write(const void* data,
size_t data_len,
size_t* written,
int* error) {
// Always succeeds, since this is an unreliable transport anyway.
// TODO: Should this block if channel_'s temporarily unwritable?
- talk_base::PacketOptions packet_options;
+ rtc::PacketOptions packet_options;
channel_->SendPacket(static_cast<const char*>(data), data_len,
packet_options);
if (written) {
*written = data_len;
}
- return talk_base::SR_SUCCESS;
+ return rtc::SR_SUCCESS;
}
bool StreamInterfaceChannel::OnPacketReceived(const char* data, size_t size) {
// We force a read event here to ensure that we don't overflow our FIFO.
// Under high packet rate this can occur if we wait for the FIFO to post its
// own SE_READ.
- bool ret = (fifo_.WriteAll(data, size, NULL, NULL) == talk_base::SR_SUCCESS);
+ bool ret = (fifo_.WriteAll(data, size, NULL, NULL) == rtc::SR_SUCCESS);
if (ret) {
- SignalEvent(this, talk_base::SE_READ, 0);
+ SignalEvent(this, rtc::SE_READ, 0);
}
return ret;
}
-void StreamInterfaceChannel::OnEvent(talk_base::StreamInterface* stream,
+void StreamInterfaceChannel::OnEvent(rtc::StreamInterface* stream,
int sig, int err) {
SignalEvent(this, sig, err);
}
@@ -100,12 +100,12 @@
TransportChannelImpl* channel)
: TransportChannelImpl(channel->content_name(), channel->component()),
transport_(transport),
- worker_thread_(talk_base::Thread::Current()),
+ worker_thread_(rtc::Thread::Current()),
channel_(channel),
downward_(NULL),
dtls_state_(STATE_NONE),
local_identity_(NULL),
- ssl_role_(talk_base::SSL_CLIENT) {
+ ssl_role_(rtc::SSL_CLIENT) {
channel_->SignalReadableState.connect(this,
&DtlsTransportChannelWrapper::OnReadableState);
channel_->SignalWritableState.connect(this,
@@ -155,7 +155,7 @@
}
bool DtlsTransportChannelWrapper::SetLocalIdentity(
- talk_base::SSLIdentity* identity) {
+ rtc::SSLIdentity* identity) {
if (dtls_state_ != STATE_NONE) {
if (identity == local_identity_) {
// This may happen during renegotiation.
@@ -178,7 +178,7 @@
}
bool DtlsTransportChannelWrapper::GetLocalIdentity(
- talk_base::SSLIdentity** identity) const {
+ rtc::SSLIdentity** identity) const {
if (!local_identity_)
return false;
@@ -186,7 +186,7 @@
return true;
}
-bool DtlsTransportChannelWrapper::SetSslRole(talk_base::SSLRole role) {
+bool DtlsTransportChannelWrapper::SetSslRole(rtc::SSLRole role) {
if (dtls_state_ == STATE_OPEN) {
if (ssl_role_ != role) {
LOG(LS_ERROR) << "SSL Role can't be reversed after the session is setup.";
@@ -199,7 +199,7 @@
return true;
}
-bool DtlsTransportChannelWrapper::GetSslRole(talk_base::SSLRole* role) const {
+bool DtlsTransportChannelWrapper::GetSslRole(rtc::SSLRole* role) const {
*role = ssl_role_;
return true;
}
@@ -209,7 +209,7 @@
const uint8* digest,
size_t digest_len) {
- talk_base::Buffer remote_fingerprint_value(digest, digest_len);
+ rtc::Buffer remote_fingerprint_value(digest, digest_len);
if (dtls_state_ != STATE_NONE &&
remote_fingerprint_value_ == remote_fingerprint_value &&
@@ -247,7 +247,7 @@
}
bool DtlsTransportChannelWrapper::GetRemoteCertificate(
- talk_base::SSLCertificate** cert) const {
+ rtc::SSLCertificate** cert) const {
if (!dtls_)
return false;
@@ -258,7 +258,7 @@
StreamInterfaceChannel* downward =
new StreamInterfaceChannel(worker_thread_, channel_);
- dtls_.reset(talk_base::SSLStreamAdapter::Create(downward));
+ dtls_.reset(rtc::SSLStreamAdapter::Create(downward));
if (!dtls_) {
LOG_J(LS_ERROR, this) << "Failed to create DTLS adapter.";
delete downward;
@@ -268,7 +268,7 @@
downward_ = downward;
dtls_->SetIdentity(local_identity_->GetReference());
- dtls_->SetMode(talk_base::SSL_MODE_DTLS);
+ dtls_->SetMode(rtc::SSL_MODE_DTLS);
dtls_->SetServerRole(ssl_role_);
dtls_->SignalEvent.connect(this, &DtlsTransportChannelWrapper::OnDtlsEvent);
if (!dtls_->SetPeerCertificateDigest(
@@ -298,6 +298,11 @@
if (srtp_ciphers_ == ciphers)
return true;
+ if (dtls_state_ == STATE_STARTED) {
+ LOG(LS_WARNING) << "Ignoring new SRTP ciphers while DTLS is negotiating";
+ return true;
+ }
+
if (dtls_state_ == STATE_OPEN) {
// We don't support DTLS renegotiation currently. If new set of srtp ciphers
// are different than what's being used currently, we will not use it.
@@ -347,7 +352,7 @@
// Called from upper layers to send a media packet.
int DtlsTransportChannelWrapper::SendPacket(
const char* data, size_t size,
- const talk_base::PacketOptions& options, int flags) {
+ const rtc::PacketOptions& options, int flags) {
int result = -1;
switch (dtls_state_) {
@@ -374,7 +379,7 @@
result = channel_->SendPacket(data, size, options);
} else {
result = (dtls_->WriteAll(data, size, NULL, NULL) ==
- talk_base::SR_SUCCESS) ? static_cast<int>(size) : -1;
+ rtc::SR_SUCCESS) ? static_cast<int>(size) : -1;
}
break;
// Not doing DTLS.
@@ -400,7 +405,7 @@
// - Once the DTLS handshake completes, the state is that of the
// impl again
void DtlsTransportChannelWrapper::OnReadableState(TransportChannel* channel) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == channel_);
LOG_J(LS_VERBOSE, this)
<< "DTLSTransportChannelWrapper: channel readable state changed.";
@@ -412,7 +417,7 @@
}
void DtlsTransportChannelWrapper::OnWritableState(TransportChannel* channel) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == channel_);
LOG_J(LS_VERBOSE, this)
<< "DTLSTransportChannelWrapper: channel writable state changed.";
@@ -454,8 +459,8 @@
void DtlsTransportChannelWrapper::OnReadPacket(
TransportChannel* channel, const char* data, size_t size,
- const talk_base::PacketTime& packet_time, int flags) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ const rtc::PacketTime& packet_time, int flags) {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == channel_);
ASSERT(flags == 0);
@@ -521,14 +526,14 @@
}
}
-void DtlsTransportChannelWrapper::OnDtlsEvent(talk_base::StreamInterface* dtls,
+void DtlsTransportChannelWrapper::OnDtlsEvent(rtc::StreamInterface* dtls,
int sig, int err) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(dtls == dtls_.get());
- if (sig & talk_base::SE_OPEN) {
+ if (sig & rtc::SE_OPEN) {
// This is the first time.
LOG_J(LS_INFO, this) << "DTLS handshake complete.";
- if (dtls_->GetState() == talk_base::SS_OPEN) {
+ if (dtls_->GetState() == rtc::SS_OPEN) {
// The check for OPEN shouldn't be necessary but let's make
// sure we don't accidentally frob the state if it's closed.
dtls_state_ = STATE_OPEN;
@@ -537,15 +542,15 @@
set_writable(true);
}
}
- if (sig & talk_base::SE_READ) {
+ if (sig & rtc::SE_READ) {
char buf[kMaxDtlsPacketLen];
size_t read;
- if (dtls_->Read(buf, sizeof(buf), &read, NULL) == talk_base::SR_SUCCESS) {
- SignalReadPacket(this, buf, read, talk_base::CreatePacketTime(0), 0);
+ if (dtls_->Read(buf, sizeof(buf), &read, NULL) == rtc::SR_SUCCESS) {
+ SignalReadPacket(this, buf, read, rtc::CreatePacketTime(0), 0);
}
}
- if (sig & talk_base::SE_CLOSE) {
- ASSERT(sig == talk_base::SE_CLOSE); // SE_CLOSE should be by itself.
+ if (sig & rtc::SE_CLOSE) {
+ ASSERT(sig == rtc::SE_CLOSE); // SE_CLOSE should be by itself.
if (!err) {
LOG_J(LS_INFO, this) << "DTLS channel closed";
} else {
diff --git a/p2p/base/dtlstransportchannel.h b/p2p/base/dtlstransportchannel.h
index 232d400..44769c9 100644
--- a/p2p/base/dtlstransportchannel.h
+++ b/p2p/base/dtlstransportchannel.h
@@ -32,22 +32,22 @@
#include <string>
#include <vector>
-#include "talk/base/buffer.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/base/stream.h"
#include "talk/p2p/base/transportchannelimpl.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/stream.h"
namespace cricket {
// A bridge between a packet-oriented/channel-type interface on
// the bottom and a StreamInterface on the top.
-class StreamInterfaceChannel : public talk_base::StreamInterface,
+class StreamInterfaceChannel : public rtc::StreamInterface,
public sigslot::has_slots<> {
public:
- StreamInterfaceChannel(talk_base::Thread* owner, TransportChannel* channel)
+ StreamInterfaceChannel(rtc::Thread* owner, TransportChannel* channel)
: channel_(channel),
- state_(talk_base::SS_OPEN),
+ state_(rtc::SS_OPEN),
fifo_(kFifoSize, owner) {
fifo_.SignalEvent.connect(this, &StreamInterfaceChannel::OnEvent);
}
@@ -56,22 +56,22 @@
bool OnPacketReceived(const char* data, size_t size);
// Implementations of StreamInterface
- virtual talk_base::StreamState GetState() const { return state_; }
- virtual void Close() { state_ = talk_base::SS_CLOSED; }
- virtual talk_base::StreamResult Read(void* buffer, size_t buffer_len,
+ virtual rtc::StreamState GetState() const { return state_; }
+ virtual void Close() { state_ = rtc::SS_CLOSED; }
+ virtual rtc::StreamResult Read(void* buffer, size_t buffer_len,
size_t* read, int* error);
- virtual talk_base::StreamResult Write(const void* data, size_t data_len,
+ virtual rtc::StreamResult Write(const void* data, size_t data_len,
size_t* written, int* error);
private:
static const size_t kFifoSize = 8192;
// Forward events
- virtual void OnEvent(talk_base::StreamInterface* stream, int sig, int err);
+ virtual void OnEvent(rtc::StreamInterface* stream, int sig, int err);
TransportChannel* channel_; // owned by DtlsTransportChannelWrapper
- talk_base::StreamState state_;
- talk_base::FifoBuffer fifo_;
+ rtc::StreamState state_;
+ rtc::FifoBuffer fifo_;
DISALLOW_COPY_AND_ASSIGN(StreamInterfaceChannel);
};
@@ -130,8 +130,8 @@
virtual size_t GetConnectionCount() const {
return channel_->GetConnectionCount();
}
- virtual bool SetLocalIdentity(talk_base::SSLIdentity *identity);
- virtual bool GetLocalIdentity(talk_base::SSLIdentity** identity) const;
+ virtual bool SetLocalIdentity(rtc::SSLIdentity *identity);
+ virtual bool GetLocalIdentity(rtc::SSLIdentity** identity) const;
virtual bool SetRemoteFingerprint(const std::string& digest_alg,
const uint8* digest,
@@ -140,11 +140,11 @@
// Called to send a packet (via DTLS, if turned on).
virtual int SendPacket(const char* data, size_t size,
- const talk_base::PacketOptions& options,
+ const rtc::PacketOptions& options,
int flags);
// TransportChannel calls that we forward to the wrapped transport.
- virtual int SetOption(talk_base::Socket::Option opt, int value) {
+ virtual int SetOption(rtc::Socket::Option opt, int value) {
return channel_->SetOption(opt, value);
}
virtual int GetError() {
@@ -165,12 +165,12 @@
// Find out which DTLS-SRTP cipher was negotiated
virtual bool GetSrtpCipher(std::string* cipher);
- virtual bool GetSslRole(talk_base::SSLRole* role) const;
- virtual bool SetSslRole(talk_base::SSLRole role);
+ virtual bool GetSslRole(rtc::SSLRole* role) const;
+ virtual bool SetSslRole(rtc::SSLRole role);
// Once DTLS has been established, this method retrieves the certificate in
// use by the remote peer, for use in external identity verification.
- virtual bool GetRemoteCertificate(talk_base::SSLCertificate** cert) const;
+ virtual bool GetRemoteCertificate(rtc::SSLCertificate** cert) const;
// Once DTLS has established (i.e., this channel is writable), this method
// extracts the keys negotiated during the DTLS handshake, for use in external
@@ -231,9 +231,9 @@
void OnReadableState(TransportChannel* channel);
void OnWritableState(TransportChannel* channel);
void OnReadPacket(TransportChannel* channel, const char* data, size_t size,
- const talk_base::PacketTime& packet_time, int flags);
+ const rtc::PacketTime& packet_time, int flags);
void OnReadyToSend(TransportChannel* channel);
- void OnDtlsEvent(talk_base::StreamInterface* stream_, int sig, int err);
+ void OnDtlsEvent(rtc::StreamInterface* stream_, int sig, int err);
bool SetupDtls();
bool MaybeStartDtls();
bool HandleDtlsPacket(const char* data, size_t size);
@@ -245,15 +245,15 @@
void OnConnectionRemoved(TransportChannelImpl* channel);
Transport* transport_; // The transport_ that created us.
- talk_base::Thread* worker_thread_; // Everything should occur on this thread.
+ rtc::Thread* worker_thread_; // Everything should occur on this thread.
TransportChannelImpl* channel_; // Underlying channel, owned by transport_.
- talk_base::scoped_ptr<talk_base::SSLStreamAdapter> dtls_; // The DTLS stream
+ rtc::scoped_ptr<rtc::SSLStreamAdapter> dtls_; // The DTLS stream
StreamInterfaceChannel* downward_; // Wrapper for channel_, owned by dtls_.
std::vector<std::string> srtp_ciphers_; // SRTP ciphers to use with DTLS.
State dtls_state_;
- talk_base::SSLIdentity* local_identity_;
- talk_base::SSLRole ssl_role_;
- talk_base::Buffer remote_fingerprint_value_;
+ rtc::SSLIdentity* local_identity_;
+ rtc::SSLRole ssl_role_;
+ rtc::Buffer remote_fingerprint_value_;
std::string remote_fingerprint_algorithm_;
DISALLOW_COPY_AND_ASSIGN(DtlsTransportChannelWrapper);
diff --git a/p2p/base/dtlstransportchannel_unittest.cc b/p2p/base/dtlstransportchannel_unittest.cc
index 5727ac4..bc1cf27 100644
--- a/p2p/base/dtlstransportchannel_unittest.cc
+++ b/p2p/base/dtlstransportchannel_unittest.cc
@@ -28,21 +28,21 @@
#include <set>
-#include "talk/base/common.h"
-#include "talk/base/dscp.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/p2p/base/fakesession.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslidentity.h"
-#include "talk/base/sslstreamadapter.h"
#include "talk/p2p/base/dtlstransport.h"
+#include "talk/p2p/base/fakesession.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/sslidentity.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
#define MAYBE_SKIP_TEST(feature) \
- if (!(talk_base::SSLStreamAdapter::feature())) { \
+ if (!(rtc::SSLStreamAdapter::feature())) { \
LOG(LS_INFO) << "Feature disabled... skipping"; \
return; \
}
@@ -64,8 +64,8 @@
class DtlsTestClient : public sigslot::has_slots<> {
public:
DtlsTestClient(const std::string& name,
- talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread) :
+ rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread) :
name_(name),
signaling_thread_(signaling_thread),
worker_thread_(worker_thread),
@@ -80,9 +80,9 @@
protocol_ = proto;
}
void CreateIdentity() {
- identity_.reset(talk_base::SSLIdentity::Generate(name_));
+ identity_.reset(rtc::SSLIdentity::Generate(name_));
}
- talk_base::SSLIdentity* identity() { return identity_.get(); }
+ rtc::SSLIdentity* identity() { return identity_.get(); }
void SetupSrtp() {
ASSERT(identity_.get() != NULL);
use_dtls_srtp_ = true;
@@ -135,22 +135,22 @@
}
// Allow any DTLS configuration to be specified (including invalid ones).
- void Negotiate(talk_base::SSLIdentity* local_identity,
- talk_base::SSLIdentity* remote_identity,
+ void Negotiate(rtc::SSLIdentity* local_identity,
+ rtc::SSLIdentity* remote_identity,
cricket::ContentAction action,
ConnectionRole local_role,
ConnectionRole remote_role,
int flags) {
- talk_base::scoped_ptr<talk_base::SSLFingerprint> local_fingerprint;
- talk_base::scoped_ptr<talk_base::SSLFingerprint> remote_fingerprint;
+ rtc::scoped_ptr<rtc::SSLFingerprint> local_fingerprint;
+ rtc::scoped_ptr<rtc::SSLFingerprint> remote_fingerprint;
if (local_identity) {
- local_fingerprint.reset(talk_base::SSLFingerprint::Create(
- talk_base::DIGEST_SHA_1, local_identity));
+ local_fingerprint.reset(rtc::SSLFingerprint::Create(
+ rtc::DIGEST_SHA_1, local_identity));
ASSERT_TRUE(local_fingerprint.get() != NULL);
}
if (remote_identity) {
- remote_fingerprint.reset(talk_base::SSLFingerprint::Create(
- talk_base::DIGEST_SHA_1, remote_identity));
+ remote_fingerprint.reset(rtc::SSLFingerprint::Create(
+ rtc::DIGEST_SHA_1, remote_identity));
ASSERT_TRUE(remote_fingerprint.get() != NULL);
}
@@ -205,8 +205,8 @@
bool writable() const { return transport_->writable(); }
- void CheckRole(talk_base::SSLRole role) {
- if (role == talk_base::SSL_CLIENT) {
+ void CheckRole(rtc::SSLRole role) {
+ if (role == rtc::SSL_CLIENT) {
ASSERT_FALSE(received_dtls_client_hello_);
ASSERT_TRUE(received_dtls_server_hello_);
} else {
@@ -233,19 +233,19 @@
void SendPackets(size_t channel, size_t size, size_t count, bool srtp) {
ASSERT(channel < channels_.size());
- talk_base::scoped_ptr<char[]> packet(new char[size]);
+ rtc::scoped_ptr<char[]> packet(new char[size]);
size_t sent = 0;
do {
// Fill the packet with a known value and a sequence number to check
// against, and make sure that it doesn't look like DTLS.
memset(packet.get(), sent & 0xff, size);
packet[0] = (srtp) ? 0x80 : 0x00;
- talk_base::SetBE32(packet.get() + kPacketNumOffset,
+ rtc::SetBE32(packet.get() + kPacketNumOffset,
static_cast<uint32>(sent));
// Only set the bypass flag if we've activated DTLS.
int flags = (identity_.get() && srtp) ? cricket::PF_SRTP_BYPASS : 0;
- talk_base::PacketOptions packet_options;
+ rtc::PacketOptions packet_options;
int rv = channels_[channel]->SendPacket(
packet.get(), size, packet_options, flags);
ASSERT_GT(rv, 0);
@@ -256,11 +256,11 @@
int SendInvalidSrtpPacket(size_t channel, size_t size) {
ASSERT(channel < channels_.size());
- talk_base::scoped_ptr<char[]> packet(new char[size]);
+ rtc::scoped_ptr<char[]> packet(new char[size]);
// Fill the packet with 0 to form an invalid SRTP packet.
memset(packet.get(), 0, size);
- talk_base::PacketOptions packet_options;
+ rtc::PacketOptions packet_options;
return channels_[channel]->SendPacket(
packet.get(), size, packet_options, cricket::PF_SRTP_BYPASS);
}
@@ -279,7 +279,7 @@
(data[0] != 0 && static_cast<uint8>(data[0]) != 0x80)) {
return false;
}
- uint32 packet_num = talk_base::GetBE32(data + kPacketNumOffset);
+ uint32 packet_num = rtc::GetBE32(data + kPacketNumOffset);
for (size_t i = kPacketHeaderLen; i < size; ++i) {
if (static_cast<uint8>(data[i]) != (packet_num & 0xff)) {
return false;
@@ -296,7 +296,7 @@
if (size <= packet_size_) {
return false;
}
- uint32 packet_num = talk_base::GetBE32(data + kPacketNumOffset);
+ uint32 packet_num = rtc::GetBE32(data + kPacketNumOffset);
int num_matches = 0;
for (size_t i = kPacketNumOffset; i < size; ++i) {
if (static_cast<uint8>(data[i]) == (packet_num & 0xff)) {
@@ -319,7 +319,7 @@
void OnTransportChannelReadPacket(cricket::TransportChannel* channel,
const char* data, size_t size,
- const talk_base::PacketTime& packet_time,
+ const rtc::PacketTime& packet_time,
int flags) {
uint32 packet_num = 0;
ASSERT_TRUE(VerifyPacket(data, size, &packet_num));
@@ -333,7 +333,7 @@
// Hook into the raw packet stream to make sure DTLS packets are encrypted.
void OnFakeTransportChannelReadPacket(cricket::TransportChannel* channel,
const char* data, size_t size,
- const talk_base::PacketTime& time,
+ const rtc::PacketTime& time,
int flags) {
// Flags shouldn't be set on the underlying TransportChannel packets.
ASSERT_EQ(0, flags);
@@ -360,11 +360,11 @@
private:
std::string name_;
- talk_base::Thread* signaling_thread_;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* signaling_thread_;
+ rtc::Thread* worker_thread_;
cricket::TransportProtocol protocol_;
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity_;
- talk_base::scoped_ptr<cricket::FakeTransport> transport_;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity_;
+ rtc::scoped_ptr<cricket::FakeTransport> transport_;
std::vector<cricket::DtlsTransportChannelWrapper*> channels_;
size_t packet_size_;
std::set<int> received_;
@@ -378,18 +378,18 @@
class DtlsTransportChannelTest : public testing::Test {
public:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
DtlsTransportChannelTest() :
- client1_("P1", talk_base::Thread::Current(),
- talk_base::Thread::Current()),
- client2_("P2", talk_base::Thread::Current(),
- talk_base::Thread::Current()),
+ client1_("P1", rtc::Thread::Current(),
+ rtc::Thread::Current()),
+ client2_("P2", rtc::Thread::Current(),
+ rtc::Thread::Current()),
channel_ct_(1),
use_dtls_(false),
use_dtls_srtp_(false) {
@@ -435,17 +435,17 @@
// Check that we used the right roles.
if (use_dtls_) {
- talk_base::SSLRole client1_ssl_role =
+ rtc::SSLRole client1_ssl_role =
(client1_role == cricket::CONNECTIONROLE_ACTIVE ||
(client2_role == cricket::CONNECTIONROLE_PASSIVE &&
client1_role == cricket::CONNECTIONROLE_ACTPASS)) ?
- talk_base::SSL_CLIENT : talk_base::SSL_SERVER;
+ rtc::SSL_CLIENT : rtc::SSL_SERVER;
- talk_base::SSLRole client2_ssl_role =
+ rtc::SSLRole client2_ssl_role =
(client2_role == cricket::CONNECTIONROLE_ACTIVE ||
(client1_role == cricket::CONNECTIONROLE_PASSIVE &&
client2_role == cricket::CONNECTIONROLE_ACTPASS)) ?
- talk_base::SSL_CLIENT : talk_base::SSL_SERVER;
+ rtc::SSL_CLIENT : rtc::SSL_SERVER;
client1_.CheckRole(client1_ssl_role);
client2_.CheckRole(client2_ssl_role);
@@ -701,12 +701,12 @@
MAYBE_SKIP_TEST(HaveDtlsSrtp);
PrepareDtls(true, true);
NegotiateWithLegacy();
- talk_base::SSLRole channel1_role;
- talk_base::SSLRole channel2_role;
+ rtc::SSLRole channel1_role;
+ rtc::SSLRole channel2_role;
EXPECT_TRUE(client1_.transport()->GetSslRole(&channel1_role));
EXPECT_TRUE(client2_.transport()->GetSslRole(&channel2_role));
- EXPECT_EQ(talk_base::SSL_SERVER, channel1_role);
- EXPECT_EQ(talk_base::SSL_CLIENT, channel2_role);
+ EXPECT_EQ(rtc::SSL_SERVER, channel1_role);
+ EXPECT_EQ(rtc::SSL_CLIENT, channel2_role);
}
// Testing re offer/answer after the session is estbalished. Roles will be
@@ -801,10 +801,10 @@
PrepareDtls(true, true);
Negotiate();
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity1;
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity2;
- talk_base::scoped_ptr<talk_base::SSLCertificate> remote_cert1;
- talk_base::scoped_ptr<talk_base::SSLCertificate> remote_cert2;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity1;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity2;
+ rtc::scoped_ptr<rtc::SSLCertificate> remote_cert1;
+ rtc::scoped_ptr<rtc::SSLCertificate> remote_cert2;
// After negotiation, each side has a distinct local certificate, but still no
// remote certificate, because connection has not yet occurred.
@@ -826,10 +826,10 @@
PrepareDtls(true, true);
ASSERT_TRUE(Connect());
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity1;
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity2;
- talk_base::scoped_ptr<talk_base::SSLCertificate> remote_cert1;
- talk_base::scoped_ptr<talk_base::SSLCertificate> remote_cert2;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity1;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity2;
+ rtc::scoped_ptr<rtc::SSLCertificate> remote_cert1;
+ rtc::scoped_ptr<rtc::SSLCertificate> remote_cert2;
// After connection, each side has a distinct local certificate.
ASSERT_TRUE(client1_.transport()->GetIdentity(identity1.accept()));
diff --git a/p2p/base/fakesession.h b/p2p/base/fakesession.h
index f2c5b84..7c99719 100644
--- a/p2p/base/fakesession.h
+++ b/p2p/base/fakesession.h
@@ -32,31 +32,31 @@
#include <string>
#include <vector>
-#include "talk/base/buffer.h"
-#include "talk/base/fakesslidentity.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/sslfingerprint.h"
-#include "talk/base/messagequeue.h"
#include "talk/p2p/base/session.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/transportchannel.h"
#include "talk/p2p/base/transportchannelimpl.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/fakesslidentity.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/sslfingerprint.h"
namespace cricket {
class FakeTransport;
-struct PacketMessageData : public talk_base::MessageData {
+struct PacketMessageData : public rtc::MessageData {
PacketMessageData(const char* data, size_t len) : packet(data, len) {
}
- talk_base::Buffer packet;
+ rtc::Buffer packet;
};
// Fake transport channel class, which can be passed to anything that needs a
// transport channel. Can be informed of another FakeTransportChannel via
// SetDestination.
class FakeTransportChannel : public TransportChannelImpl,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
explicit FakeTransportChannel(Transport* transport,
const std::string& content_name,
@@ -73,7 +73,7 @@
ice_proto_(ICEPROTO_HYBRID),
remote_ice_mode_(ICEMODE_FULL),
dtls_fingerprint_("", NULL, 0),
- ssl_role_(talk_base::SSL_CLIENT),
+ ssl_role_(rtc::SSL_CLIENT),
connection_count_(0) {
}
~FakeTransportChannel() {
@@ -87,7 +87,7 @@
const std::string& ice_pwd() const { return ice_pwd_; }
const std::string& remote_ice_ufrag() const { return remote_ice_ufrag_; }
const std::string& remote_ice_pwd() const { return remote_ice_pwd_; }
- const talk_base::SSLFingerprint& dtls_fingerprint() const {
+ const rtc::SSLFingerprint& dtls_fingerprint() const {
return dtls_fingerprint_;
}
@@ -122,14 +122,14 @@
virtual void SetRemoteIceMode(IceMode mode) { remote_ice_mode_ = mode; }
virtual bool SetRemoteFingerprint(const std::string& alg, const uint8* digest,
size_t digest_len) {
- dtls_fingerprint_ = talk_base::SSLFingerprint(alg, digest, digest_len);
+ dtls_fingerprint_ = rtc::SSLFingerprint(alg, digest, digest_len);
return true;
}
- virtual bool SetSslRole(talk_base::SSLRole role) {
+ virtual bool SetSslRole(rtc::SSLRole role) {
ssl_role_ = role;
return true;
}
- virtual bool GetSslRole(talk_base::SSLRole* role) const {
+ virtual bool GetSslRole(rtc::SSLRole* role) const {
*role = ssl_role_;
return true;
}
@@ -184,7 +184,7 @@
}
virtual int SendPacket(const char* data, size_t len,
- const talk_base::PacketOptions& options, int flags) {
+ const rtc::PacketOptions& options, int flags) {
if (state_ != STATE_CONNECTED) {
return -1;
}
@@ -195,13 +195,13 @@
PacketMessageData* packet = new PacketMessageData(data, len);
if (async_) {
- talk_base::Thread::Current()->Post(this, 0, packet);
+ rtc::Thread::Current()->Post(this, 0, packet);
} else {
- talk_base::Thread::Current()->Send(this, 0, packet);
+ rtc::Thread::Current()->Send(this, 0, packet);
}
return static_cast<int>(len);
}
- virtual int SetOption(talk_base::Socket::Option opt, int value) {
+ virtual int SetOption(rtc::Socket::Option opt, int value) {
return true;
}
virtual int GetError() {
@@ -213,22 +213,22 @@
virtual void OnCandidate(const Candidate& candidate) {
}
- virtual void OnMessage(talk_base::Message* msg) {
+ virtual void OnMessage(rtc::Message* msg) {
PacketMessageData* data = static_cast<PacketMessageData*>(
msg->pdata);
dest_->SignalReadPacket(dest_, data->packet.data(),
data->packet.length(),
- talk_base::CreatePacketTime(0), 0);
+ rtc::CreatePacketTime(0), 0);
delete data;
}
- bool SetLocalIdentity(talk_base::SSLIdentity* identity) {
+ bool SetLocalIdentity(rtc::SSLIdentity* identity) {
identity_ = identity;
return true;
}
- void SetRemoteCertificate(talk_base::FakeSSLCertificate* cert) {
+ void SetRemoteCertificate(rtc::FakeSSLCertificate* cert) {
remote_cert_ = cert;
}
@@ -249,7 +249,7 @@
return false;
}
- virtual bool GetLocalIdentity(talk_base::SSLIdentity** identity) const {
+ virtual bool GetLocalIdentity(rtc::SSLIdentity** identity) const {
if (!identity_)
return false;
@@ -257,7 +257,7 @@
return true;
}
- virtual bool GetRemoteCertificate(talk_base::SSLCertificate** cert) const {
+ virtual bool GetRemoteCertificate(rtc::SSLCertificate** cert) const {
if (!remote_cert_)
return false;
@@ -307,8 +307,8 @@
FakeTransportChannel* dest_;
State state_;
bool async_;
- talk_base::SSLIdentity* identity_;
- talk_base::FakeSSLCertificate* remote_cert_;
+ rtc::SSLIdentity* identity_;
+ rtc::FakeSSLCertificate* remote_cert_;
bool do_dtls_;
std::vector<std::string> srtp_ciphers_;
std::string chosen_srtp_cipher_;
@@ -320,8 +320,8 @@
std::string remote_ice_ufrag_;
std::string remote_ice_pwd_;
IceMode remote_ice_mode_;
- talk_base::SSLFingerprint dtls_fingerprint_;
- talk_base::SSLRole ssl_role_;
+ rtc::SSLFingerprint dtls_fingerprint_;
+ rtc::SSLRole ssl_role_;
size_t connection_count_;
};
@@ -331,8 +331,8 @@
class FakeTransport : public Transport {
public:
typedef std::map<int, FakeTransportChannel*> ChannelMap;
- FakeTransport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ FakeTransport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
PortAllocator* alllocator = NULL)
: Transport(signaling_thread, worker_thread,
@@ -364,7 +364,7 @@
}
}
- void set_identity(talk_base::SSLIdentity* identity) {
+ void set_identity(rtc::SSLIdentity* identity) {
identity_ = identity;
}
@@ -387,10 +387,10 @@
channels_.erase(channel->component());
delete channel;
}
- virtual void SetIdentity_w(talk_base::SSLIdentity* identity) {
+ virtual void SetIdentity_w(rtc::SSLIdentity* identity) {
identity_ = identity;
}
- virtual bool GetIdentity_w(talk_base::SSLIdentity** identity) {
+ virtual bool GetIdentity_w(rtc::SSLIdentity** identity) {
if (!identity_)
return false;
@@ -420,7 +420,7 @@
ChannelMap channels_;
FakeTransport* dest_;
bool async_;
- talk_base::SSLIdentity* identity_;
+ rtc::SSLIdentity* identity_;
};
// Fake session class, which can be passed into a BaseChannel object for
@@ -428,19 +428,19 @@
class FakeSession : public BaseSession {
public:
explicit FakeSession()
- : BaseSession(talk_base::Thread::Current(),
- talk_base::Thread::Current(),
+ : BaseSession(rtc::Thread::Current(),
+ rtc::Thread::Current(),
NULL, "", "", true),
fail_create_channel_(false) {
}
explicit FakeSession(bool initiator)
- : BaseSession(talk_base::Thread::Current(),
- talk_base::Thread::Current(),
+ : BaseSession(rtc::Thread::Current(),
+ rtc::Thread::Current(),
NULL, "", "", initiator),
fail_create_channel_(false) {
}
- FakeSession(talk_base::Thread* worker_thread, bool initiator)
- : BaseSession(talk_base::Thread::Current(),
+ FakeSession(rtc::Thread* worker_thread, bool initiator)
+ : BaseSession(rtc::Thread::Current(),
worker_thread,
NULL, "", "", initiator),
fail_create_channel_(false) {
@@ -477,7 +477,7 @@
}
// TODO: Hoist this into Session when we re-work the Session code.
- void set_ssl_identity(talk_base::SSLIdentity* identity) {
+ void set_ssl_identity(rtc::SSLIdentity* identity) {
for (TransportMap::const_iterator it = transport_proxies().begin();
it != transport_proxies().end(); ++it) {
// We know that we have a FakeTransport*
diff --git a/p2p/base/p2ptransport.cc b/p2p/base/p2ptransport.cc
index 7f53cff..06941ac 100644
--- a/p2p/base/p2ptransport.cc
+++ b/p2p/base/p2ptransport.cc
@@ -30,18 +30,18 @@
#include <string>
#include <vector>
-#include "talk/base/base64.h"
-#include "talk/base/common.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/p2ptransportchannel.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/sessionmanager.h"
#include "talk/p2p/base/sessionmessages.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
namespace {
@@ -57,8 +57,8 @@
return new buzz::XmlElement(buzz::QName(name, LN_TRANSPORT), true);
}
-P2PTransport::P2PTransport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+P2PTransport::P2PTransport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
PortAllocator* allocator)
: Transport(signaling_thread, worker_thread,
@@ -112,7 +112,7 @@
buzz::XmlElement** out_elem,
WriteError* error) {
TransportProtocol proto = TransportProtocolFromDescription(&desc);
- talk_base::scoped_ptr<buzz::XmlElement> trans_elem(
+ rtc::scoped_ptr<buzz::XmlElement> trans_elem(
NewTransportElement(desc.transport_type));
// Fail if we get HYBRID or ICE right now.
@@ -124,7 +124,7 @@
for (std::vector<Candidate>::const_iterator iter = desc.candidates.begin();
iter != desc.candidates.end(); ++iter) {
- talk_base::scoped_ptr<buzz::XmlElement> cand_elem(
+ rtc::scoped_ptr<buzz::XmlElement> cand_elem(
new buzz::XmlElement(QN_GINGLE_P2P_CANDIDATE));
if (!WriteCandidate(proto, *iter, translator, cand_elem.get(), error)) {
return false;
@@ -149,7 +149,7 @@
const CandidateTranslator* translator,
buzz::XmlElement** out_elem,
WriteError* error) {
- talk_base::scoped_ptr<buzz::XmlElement> elem(
+ rtc::scoped_ptr<buzz::XmlElement> elem(
new buzz::XmlElement(QN_GINGLE_CANDIDATE));
bool ret = WriteCandidate(ICEPROTO_GOOGLE, candidate, translator, elem.get(),
error);
@@ -165,7 +165,7 @@
if (proto == ICEPROTO_GOOGLE || proto == ICEPROTO_HYBRID) {
if (username.size() > kMaxGiceUsernameSize)
return BadParse("candidate username is too long", error);
- if (!talk_base::Base64::IsBase64Encoded(username))
+ if (!rtc::Base64::IsBase64Encoded(username))
return BadParse("candidate username has non-base64 encoded characters",
error);
} else if (proto == ICEPROTO_RFC5245) {
@@ -192,7 +192,7 @@
return BadParse("candidate missing required attribute", error);
}
- talk_base::SocketAddress address;
+ rtc::SocketAddress address;
if (!ParseAddress(elem, QN_ADDRESS, QN_PORT, &address, error))
return false;
diff --git a/p2p/base/p2ptransport.h b/p2p/base/p2ptransport.h
index f2b10f8..500bb9b 100644
--- a/p2p/base/p2ptransport.h
+++ b/p2p/base/p2ptransport.h
@@ -36,8 +36,8 @@
class P2PTransport : public Transport {
public:
- P2PTransport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ P2PTransport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
PortAllocator* allocator);
virtual ~P2PTransport();
diff --git a/p2p/base/p2ptransportchannel.cc b/p2p/base/p2ptransportchannel.cc
index 887fc45..b1dc223 100644
--- a/p2p/base/p2ptransportchannel.cc
+++ b/p2p/base/p2ptransportchannel.cc
@@ -28,13 +28,13 @@
#include "talk/p2p/base/p2ptransportchannel.h"
#include <set>
-#include "talk/base/common.h"
-#include "talk/base/crc32.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/base/common.h"
#include "talk/p2p/base/relayport.h" // For RELAY_PORT_TYPE.
#include "talk/p2p/base/stunport.h" // For STUN_PORT_TYPE.
+#include "webrtc/base/common.h"
+#include "webrtc/base/crc32.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
namespace {
@@ -159,7 +159,7 @@
TransportChannelImpl(content_name, component),
transport_(transport),
allocator_(allocator),
- worker_thread_(talk_base::Thread::Current()),
+ worker_thread_(rtc::Thread::Current()),
incoming_only_(false),
waiting_for_signaling_(false),
error_(0),
@@ -175,7 +175,7 @@
}
P2PTransportChannel::~P2PTransportChannel() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
for (uint32 i = 0; i < allocator_sessions_.size(); ++i)
delete allocator_sessions_[i];
@@ -216,7 +216,7 @@
}
void P2PTransportChannel::SetIceRole(IceRole ice_role) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (ice_role_ != ice_role) {
ice_role_ = ice_role;
for (std::vector<PortInterface *>::iterator it = ports_.begin();
@@ -227,7 +227,7 @@
}
void P2PTransportChannel::SetIceTiebreaker(uint64 tiebreaker) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (!ports_.empty()) {
LOG(LS_ERROR)
<< "Attempt to change tiebreaker after Port has been allocated.";
@@ -243,7 +243,7 @@
}
void P2PTransportChannel::SetIceProtocolType(IceProtocolType type) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
protocol_type_ = type;
for (std::vector<PortInterface *>::iterator it = ports_.begin();
@@ -254,12 +254,13 @@
void P2PTransportChannel::SetIceCredentials(const std::string& ice_ufrag,
const std::string& ice_pwd) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
bool ice_restart = false;
if (!ice_ufrag_.empty() && !ice_pwd_.empty()) {
// Restart candidate allocation if there is any change in either
// ice ufrag or password.
- ice_restart = (ice_ufrag_ != ice_ufrag) || (ice_pwd_!= ice_pwd);
+ ice_restart =
+ IceCredentialsChanged(ice_ufrag_, ice_pwd_, ice_ufrag, ice_pwd);
}
ice_ufrag_ = ice_ufrag;
@@ -273,7 +274,7 @@
void P2PTransportChannel::SetRemoteIceCredentials(const std::string& ice_ufrag,
const std::string& ice_pwd) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
bool ice_restart = false;
if (!remote_ice_ufrag_.empty() && !remote_ice_pwd_.empty()) {
ice_restart = (remote_ice_ufrag_ != ice_ufrag) ||
@@ -297,7 +298,7 @@
// Go into the state of processing candidates, and running in general
void P2PTransportChannel::Connect() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (ice_ufrag_.empty() || ice_pwd_.empty()) {
ASSERT(false);
LOG(LS_ERROR) << "P2PTransportChannel::Connect: The ice_ufrag_ and the "
@@ -314,7 +315,7 @@
// Reset the socket, clear up any previous allocations and start over
void P2PTransportChannel::Reset() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Get rid of all the old allocators. This should clean up everything.
for (uint32 i = 0; i < allocator_sessions_.size(); ++i)
@@ -348,7 +349,7 @@
// A new port is available, attempt to make connections for it
void P2PTransportChannel::OnPortReady(PortAllocatorSession *session,
PortInterface* port) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Set in-effect options on the new port
for (OptionMap::const_iterator it = options_.begin();
@@ -391,7 +392,7 @@
// A new candidate is available, let listeners know
void P2PTransportChannel::OnCandidatesReady(
PortAllocatorSession *session, const std::vector<Candidate>& candidates) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
for (size_t i = 0; i < candidates.size(); ++i) {
SignalCandidateReady(this, candidates[i]);
}
@@ -399,17 +400,17 @@
void P2PTransportChannel::OnCandidatesAllocationDone(
PortAllocatorSession* session) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
SignalCandidatesAllocationDone(this);
}
// Handle stun packets
void P2PTransportChannel::OnUnknownAddress(
PortInterface* port,
- const talk_base::SocketAddress& address, ProtocolType proto,
+ const rtc::SocketAddress& address, ProtocolType proto,
IceMessage* stun_msg, const std::string &remote_username,
bool port_muxed) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Port has received a valid stun packet from an address that no Connection
// is currently available for. See if we already have a candidate with the
@@ -485,15 +486,15 @@
}
}
- std::string id = talk_base::CreateRandomString(8);
+ std::string id = rtc::CreateRandomString(8);
new_remote_candidate = Candidate(
id, component(), ProtoToString(proto), address,
0, remote_username, remote_password, type,
port->Network()->name(), 0U,
- talk_base::ToString<uint32>(talk_base::ComputeCrc32(id)));
+ rtc::ToString<uint32>(rtc::ComputeCrc32(id)));
new_remote_candidate.set_priority(
new_remote_candidate.GetPriority(ICE_TYPE_PREFERENCE_SRFLX,
- port->Network()->preference()));
+ port->Network()->preference(), 0));
}
if (port->IceProtocol() == ICEPROTO_RFC5245) {
@@ -590,7 +591,7 @@
// When the signalling channel is ready, we can really kick off the allocator
void P2PTransportChannel::OnSignalingReady() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (waiting_for_signaling_) {
waiting_for_signaling_ = false;
AddAllocatorSession(allocator_->CreateSession(
@@ -599,7 +600,7 @@
}
void P2PTransportChannel::OnUseCandidate(Connection* conn) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
ASSERT(ice_role_ == ICEROLE_CONTROLLED);
ASSERT(protocol_type_ == ICEPROTO_RFC5245);
if (conn->write_state() == Connection::STATE_WRITABLE) {
@@ -616,7 +617,7 @@
}
void P2PTransportChannel::OnCandidate(const Candidate& candidate) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Create connections to this remote candidate.
CreateConnections(candidate, NULL, false);
@@ -631,7 +632,7 @@
bool P2PTransportChannel::CreateConnections(const Candidate& remote_candidate,
PortInterface* origin_port,
bool readable) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
Candidate new_remote_candidate(remote_candidate);
new_remote_candidate.set_generation(
@@ -793,7 +794,7 @@
// Set options on ourselves is simply setting options on all of our available
// port objects.
-int P2PTransportChannel::SetOption(talk_base::Socket::Option opt, int value) {
+int P2PTransportChannel::SetOption(rtc::Socket::Option opt, int value) {
OptionMap::iterator it = options_.find(opt);
if (it == options_.end()) {
options_.insert(std::make_pair(opt, value));
@@ -817,9 +818,9 @@
// Send data to the other side, using our best connection.
int P2PTransportChannel::SendPacket(const char *data, size_t len,
- const talk_base::PacketOptions& options,
+ const rtc::PacketOptions& options,
int flags) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (flags != 0) {
error_ = EINVAL;
return -1;
@@ -838,7 +839,7 @@
}
bool P2PTransportChannel::GetStats(ConnectionInfos *infos) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Gather connection infos.
infos->clear();
@@ -869,12 +870,12 @@
return true;
}
-talk_base::DiffServCodePoint P2PTransportChannel::DefaultDscpValue() const {
- OptionMap::const_iterator it = options_.find(talk_base::Socket::OPT_DSCP);
+rtc::DiffServCodePoint P2PTransportChannel::DefaultDscpValue() const {
+ OptionMap::const_iterator it = options_.find(rtc::Socket::OPT_DSCP);
if (it == options_.end()) {
- return talk_base::DSCP_NO_CHANGE;
+ return rtc::DSCP_NO_CHANGE;
}
- return static_cast<talk_base::DiffServCodePoint> (it->second);
+ return static_cast<rtc::DiffServCodePoint> (it->second);
}
// Begin allocate (or immediately re-allocate, if MSG_ALLOCATE pending)
@@ -887,7 +888,7 @@
// Monitor connection states.
void P2PTransportChannel::UpdateConnectionStates() {
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
// We need to copy the list of connections since some may delete themselves
// when we call UpdateState.
@@ -906,7 +907,7 @@
// Sort the available connections to find the best one. We also monitor
// the number of available connections and the current state.
void P2PTransportChannel::SortConnections() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Make sure the connection states are up-to-date since this affects how they
// will be sorted.
@@ -925,7 +926,7 @@
sort_dirty_ = false;
// Get a list of the networks that we are using.
- std::set<talk_base::Network*> networks;
+ std::set<rtc::Network*> networks;
for (uint32 i = 0; i < connections_.size(); ++i)
networks.insert(connections_[i]->port()->Network());
@@ -961,7 +962,7 @@
// we would prune out the current best connection). We leave connections on
// other networks because they may not be using the same resources and they
// may represent very distinct paths over which we can switch.
- std::set<talk_base::Network*>::iterator network;
+ std::set<rtc::Network*>::iterator network;
for (network = networks.begin(); network != networks.end(); ++network) {
Connection* primier = GetBestConnectionOnNetwork(*network);
if (!primier || (primier->write_state() != Connection::STATE_WRITABLE))
@@ -1043,7 +1044,7 @@
// We checked the status of our connections and we had at least one that
// was writable, go into the writable state.
void P2PTransportChannel::HandleWritable() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (!writable()) {
for (uint32 i = 0; i < allocator_sessions_.size(); ++i) {
if (allocator_sessions_[i]->IsGettingPorts()) {
@@ -1058,7 +1059,7 @@
// Notify upper layer about channel not writable state, if it was before.
void P2PTransportChannel::HandleNotWritable() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (was_writable_) {
was_writable_ = false;
set_writable(false);
@@ -1073,7 +1074,7 @@
// If we have a best connection, return it, otherwise return top one in the
// list (later we will mark it best).
Connection* P2PTransportChannel::GetBestConnectionOnNetwork(
- talk_base::Network* network) {
+ rtc::Network* network) {
// If the best connection is on this network, then it wins.
if (best_connection_ && (best_connection_->port()->Network() == network))
return best_connection_;
@@ -1088,7 +1089,7 @@
}
// Handle any queued up requests
-void P2PTransportChannel::OnMessage(talk_base::Message *pmsg) {
+void P2PTransportChannel::OnMessage(rtc::Message *pmsg) {
switch (pmsg->message_id) {
case MSG_SORT:
OnSort();
@@ -1150,7 +1151,7 @@
// pingable connection unless we have a writable connection that is past the
// maximum acceptable ping delay.
Connection* P2PTransportChannel::FindNextPingableConnection() {
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
if (best_connection_ &&
(best_connection_->write_state() == Connection::STATE_WRITABLE) &&
(best_connection_->last_ping_sent()
@@ -1196,13 +1197,13 @@
}
}
conn->set_use_candidate_attr(use_candidate);
- conn->Ping(talk_base::Time());
+ conn->Ping(rtc::Time());
}
// When a connection's state changes, we need to figure out who to use as
// the best connection again. It could have become usable, or become unusable.
void P2PTransportChannel::OnConnectionStateChange(Connection* connection) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Update the best connection if the state change is from pending best
// connection and role is controlled.
@@ -1221,7 +1222,7 @@
// When a connection is removed, edit it out, and then update our best
// connection.
void P2PTransportChannel::OnConnectionDestroyed(Connection* connection) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Note: the previous best_connection_ may be destroyed by now, so don't
// use it.
@@ -1255,7 +1256,7 @@
// When a port is destroyed remove it from our list of ports to use for
// connection attempts.
void P2PTransportChannel::OnPortDestroyed(PortInterface* port) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Remove this port from the list (if we didn't drop it already).
std::vector<PortInterface*>::iterator iter =
@@ -1270,8 +1271,8 @@
// We data is available, let listeners know
void P2PTransportChannel::OnReadPacket(
Connection *connection, const char *data, size_t len,
- const talk_base::PacketTime& packet_time) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ const rtc::PacketTime& packet_time) {
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Do not deliver, if packet doesn't belong to the correct transport channel.
if (!FindConnection(connection))
diff --git a/p2p/base/p2ptransportchannel.h b/p2p/base/p2ptransportchannel.h
index 09dabd5..229e512 100644
--- a/p2p/base/p2ptransportchannel.h
+++ b/p2p/base/p2ptransportchannel.h
@@ -38,16 +38,16 @@
#define TALK_P2P_BASE_P2PTRANSPORTCHANNEL_H_
#include <map>
-#include <vector>
#include <string>
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/sigslot.h"
+#include <vector>
#include "talk/p2p/base/candidate.h"
-#include "talk/p2p/base/portinterface.h"
+#include "talk/p2p/base/p2ptransport.h"
#include "talk/p2p/base/portallocator.h"
+#include "talk/p2p/base/portinterface.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/transportchannelimpl.h"
-#include "talk/p2p/base/p2ptransport.h"
+#include "webrtc/base/asyncpacketsocket.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
@@ -66,7 +66,7 @@
// P2PTransportChannel manages the candidates and connection process to keep
// two P2P clients connected to each other.
class P2PTransportChannel : public TransportChannelImpl,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
P2PTransportChannel(const std::string& content_name,
int component,
@@ -94,8 +94,8 @@
// From TransportChannel:
virtual int SendPacket(const char *data, size_t len,
- const talk_base::PacketOptions& options, int flags);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
+ const rtc::PacketOptions& options, int flags);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
virtual int GetError() { return error_; }
virtual bool GetStats(std::vector<ConnectionInfo>* stats);
@@ -112,11 +112,11 @@
virtual bool IsDtlsActive() const { return false; }
// Default implementation.
- virtual bool GetSslRole(talk_base::SSLRole* role) const {
+ virtual bool GetSslRole(rtc::SSLRole* role) const {
return false;
}
- virtual bool SetSslRole(talk_base::SSLRole role) {
+ virtual bool SetSslRole(rtc::SSLRole role) {
return false;
}
@@ -131,11 +131,11 @@
}
// Returns false because the channel is not encrypted by default.
- virtual bool GetLocalIdentity(talk_base::SSLIdentity** identity) const {
+ virtual bool GetLocalIdentity(rtc::SSLIdentity** identity) const {
return false;
}
- virtual bool GetRemoteCertificate(talk_base::SSLCertificate** cert) const {
+ virtual bool GetRemoteCertificate(rtc::SSLCertificate** cert) const {
return false;
}
@@ -150,7 +150,7 @@
return false;
}
- virtual bool SetLocalIdentity(talk_base::SSLIdentity* identity) {
+ virtual bool SetLocalIdentity(rtc::SSLIdentity* identity) {
return false;
}
@@ -163,10 +163,10 @@
}
// Helper method used only in unittest.
- talk_base::DiffServCodePoint DefaultDscpValue() const;
+ rtc::DiffServCodePoint DefaultDscpValue() const;
private:
- talk_base::Thread* thread() { return worker_thread_; }
+ rtc::Thread* thread() { return worker_thread_; }
PortAllocatorSession* allocator_session() {
return allocator_sessions_.back();
}
@@ -181,7 +181,7 @@
void HandleNotWritable();
void HandleAllTimedOut();
- Connection* GetBestConnectionOnNetwork(talk_base::Network* network);
+ Connection* GetBestConnectionOnNetwork(rtc::Network* network);
bool CreateConnections(const Candidate &remote_candidate,
PortInterface* origin_port, bool readable);
bool CreateConnection(PortInterface* port, const Candidate& remote_candidate,
@@ -203,7 +203,7 @@
const std::vector<Candidate>& candidates);
void OnCandidatesAllocationDone(PortAllocatorSession* session);
void OnUnknownAddress(PortInterface* port,
- const talk_base::SocketAddress& addr,
+ const rtc::SocketAddress& addr,
ProtocolType proto,
IceMessage* stun_msg,
const std::string& remote_username,
@@ -213,19 +213,19 @@
void OnConnectionStateChange(Connection* connection);
void OnReadPacket(Connection *connection, const char *data, size_t len,
- const talk_base::PacketTime& packet_time);
+ const rtc::PacketTime& packet_time);
void OnReadyToSend(Connection* connection);
void OnConnectionDestroyed(Connection *connection);
void OnUseCandidate(Connection* conn);
- virtual void OnMessage(talk_base::Message *pmsg);
+ virtual void OnMessage(rtc::Message *pmsg);
void OnSort();
void OnPing();
P2PTransport* transport_;
PortAllocator *allocator_;
- talk_base::Thread *worker_thread_;
+ rtc::Thread *worker_thread_;
bool incoming_only_;
bool waiting_for_signaling_;
int error_;
@@ -239,7 +239,7 @@
std::vector<RemoteCandidate> remote_candidates_;
bool sort_dirty_; // indicates whether another sort is needed right now
bool was_writable_;
- typedef std::map<talk_base::Socket::Option, int> OptionMap;
+ typedef std::map<rtc::Socket::Option, int> OptionMap;
OptionMap options_;
std::string ice_ufrag_;
std::string ice_pwd_;
diff --git a/p2p/base/p2ptransportchannel_unittest.cc b/p2p/base/p2ptransportchannel_unittest.cc
index 498fde9..0b7f882 100644
--- a/p2p/base/p2ptransportchannel_unittest.cc
+++ b/p2p/base/p2ptransportchannel_unittest.cc
@@ -25,32 +25,33 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/dscp.h"
-#include "talk/base/fakenetwork.h"
-#include "talk/base/firewallsocketserver.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/natserver.h"
-#include "talk/base/natsocketfactory.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/proxyserver.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/thread.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/p2p/base/p2ptransportchannel.h"
#include "talk/p2p/base/testrelayserver.h"
#include "talk/p2p/base/teststunserver.h"
#include "talk/p2p/base/testturnserver.h"
#include "talk/p2p/client/basicportallocator.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/fakenetwork.h"
+#include "webrtc/base/firewallsocketserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/natserver.h"
+#include "webrtc/base/natsocketfactory.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/proxyserver.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/virtualsocketserver.h"
using cricket::kDefaultPortAllocatorFlags;
using cricket::kMinimumStepDelay;
using cricket::kDefaultStepDelay;
using cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG;
using cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET;
-using talk_base::SocketAddress;
+using cricket::ServerAddresses;
+using rtc::SocketAddress;
static const int kDefaultTimeout = 1000;
static const int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
@@ -128,15 +129,15 @@
// Note that this class is a base class for use by other tests, who will provide
// specialized test behavior.
class P2PTransportChannelTestBase : public testing::Test,
- public talk_base::MessageHandler,
+ public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
P2PTransportChannelTestBase()
- : main_(talk_base::Thread::Current()),
- pss_(new talk_base::PhysicalSocketServer),
- vss_(new talk_base::VirtualSocketServer(pss_.get())),
- nss_(new talk_base::NATSocketServer(vss_.get())),
- ss_(new talk_base::FirewallSocketServer(nss_.get())),
+ : main_(rtc::Thread::Current()),
+ pss_(new rtc::PhysicalSocketServer),
+ vss_(new rtc::VirtualSocketServer(pss_.get())),
+ nss_(new rtc::NATSocketServer(vss_.get())),
+ ss_(new rtc::FirewallSocketServer(nss_.get())),
ss_scope_(ss_.get()),
stun_server_(main_, kStunAddr),
turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
@@ -152,12 +153,14 @@
ep1_.role_ = cricket::ICEROLE_CONTROLLING;
ep2_.role_ = cricket::ICEROLE_CONTROLLED;
+ ServerAddresses stun_servers;
+ stun_servers.insert(kStunAddr);
ep1_.allocator_.reset(new cricket::BasicPortAllocator(
- &ep1_.network_manager_, kStunAddr, kRelayUdpIntAddr,
- kRelayTcpIntAddr, kRelaySslTcpIntAddr));
+ &ep1_.network_manager_,
+ stun_servers, kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr));
ep2_.allocator_.reset(new cricket::BasicPortAllocator(
- &ep2_.network_manager_, kStunAddr, kRelayUdpIntAddr,
- kRelayTcpIntAddr, kRelaySslTcpIntAddr));
+ &ep2_.network_manager_,
+ stun_servers, kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr));
}
protected:
@@ -210,7 +213,7 @@
std::string name_; // TODO - Currently not used.
std::list<std::string> ch_packets_;
- talk_base::scoped_ptr<cricket::P2PTransportChannel> ch_;
+ rtc::scoped_ptr<cricket::P2PTransportChannel> ch_;
};
struct Endpoint {
@@ -246,8 +249,8 @@
allocator_->set_allow_tcp_listen(allow_tcp_listen);
}
- talk_base::FakeNetworkManager network_manager_;
- talk_base::scoped_ptr<cricket::BasicPortAllocator> allocator_;
+ rtc::FakeNetworkManager network_manager_;
+ rtc::scoped_ptr<cricket::BasicPortAllocator> allocator_;
ChannelData cd1_;
ChannelData cd2_;
int signaling_delay_;
@@ -257,7 +260,7 @@
cricket::IceProtocolType protocol_type_;
};
- struct CandidateData : public talk_base::MessageData {
+ struct CandidateData : public rtc::MessageData {
CandidateData(cricket::TransportChannel* ch, const cricket::Candidate& c)
: channel(ch), candidate(c) {
}
@@ -364,15 +367,15 @@
static const Result kPrflxTcpToLocalTcp;
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
- talk_base::NATSocketServer* nat() { return nss_.get(); }
- talk_base::FirewallSocketServer* fw() { return ss_.get(); }
+ rtc::NATSocketServer* nat() { return nss_.get(); }
+ rtc::FirewallSocketServer* fw() { return ss_.get(); }
Endpoint* GetEndpoint(int endpoint) {
if (endpoint == 0) {
@@ -392,10 +395,10 @@
void RemoveAddress(int endpoint, const SocketAddress& addr) {
GetEndpoint(endpoint)->network_manager_.RemoveInterface(addr);
}
- void SetProxy(int endpoint, talk_base::ProxyType type) {
- talk_base::ProxyInfo info;
+ void SetProxy(int endpoint, rtc::ProxyType type) {
+ rtc::ProxyInfo info;
info.type = type;
- info.address = (type == talk_base::PROXY_HTTPS) ?
+ info.address = (type == rtc::PROXY_HTTPS) ?
kHttpsProxyAddrs[endpoint] : kSocksProxyAddrs[endpoint];
GetAllocator(endpoint)->set_proxy("unittest/1.0", info);
}
@@ -425,7 +428,7 @@
}
void Test(const Result& expected) {
- int32 connect_start = talk_base::Time(), connect_time;
+ int32 connect_start = rtc::Time(), connect_time;
// Create the channels and wait for them to connect.
CreateChannels(1);
@@ -437,7 +440,7 @@
ep2_ch1()->writable(),
expected.connect_wait,
1000);
- connect_time = talk_base::TimeSince(connect_start);
+ connect_time = rtc::TimeSince(connect_start);
if (connect_time < expected.connect_wait) {
LOG(LS_INFO) << "Connect time: " << connect_time << " ms";
} else {
@@ -449,7 +452,7 @@
// This may take up to 2 seconds.
if (ep1_ch1()->best_connection() &&
ep2_ch1()->best_connection()) {
- int32 converge_start = talk_base::Time(), converge_time;
+ int32 converge_start = rtc::Time(), converge_time;
int converge_wait = 2000;
EXPECT_TRUE_WAIT_MARGIN(
LocalCandidate(ep1_ch1())->type() == expected.local_type &&
@@ -501,7 +504,7 @@
}
}
- converge_time = talk_base::TimeSince(converge_start);
+ converge_time = rtc::TimeSince(converge_start);
if (converge_time < converge_wait) {
LOG(LS_INFO) << "Converge time: " << converge_time << " ms";
} else {
@@ -654,8 +657,8 @@
main_->PostDelayed(GetEndpoint(ch)->signaling_delay_, this, 0,
new CandidateData(ch, c));
}
- void OnMessage(talk_base::Message* msg) {
- talk_base::scoped_ptr<CandidateData> data(
+ void OnMessage(rtc::Message* msg) {
+ rtc::scoped_ptr<CandidateData> data(
static_cast<CandidateData*>(msg->pdata));
cricket::P2PTransportChannel* rch = GetRemoteChannel(data->channel);
cricket::Candidate c = data->candidate;
@@ -670,7 +673,7 @@
rch->OnCandidate(c);
}
void OnReadPacket(cricket::TransportChannel* channel, const char* data,
- size_t len, const talk_base::PacketTime& packet_time,
+ size_t len, const rtc::PacketTime& packet_time,
int flags) {
std::list<std::string>& packets = GetPacketList(channel);
packets.push_front(std::string(data, len));
@@ -684,7 +687,7 @@
}
int SendData(cricket::TransportChannel* channel,
const char* data, size_t len) {
- talk_base::PacketOptions options;
+ rtc::PacketOptions options;
return channel->SendPacket(data, len, options, 0);
}
bool CheckDataOnChannel(cricket::TransportChannel* channel,
@@ -736,17 +739,17 @@
}
private:
- talk_base::Thread* main_;
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> vss_;
- talk_base::scoped_ptr<talk_base::NATSocketServer> nss_;
- talk_base::scoped_ptr<talk_base::FirewallSocketServer> ss_;
- talk_base::SocketServerScope ss_scope_;
+ rtc::Thread* main_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> vss_;
+ rtc::scoped_ptr<rtc::NATSocketServer> nss_;
+ rtc::scoped_ptr<rtc::FirewallSocketServer> ss_;
+ rtc::SocketServerScope ss_scope_;
cricket::TestStunServer stun_server_;
cricket::TestTurnServer turn_server_;
cricket::TestRelayServer relay_server_;
- talk_base::SocksProxyServer socks_server1_;
- talk_base::SocksProxyServer socks_server2_;
+ rtc::SocksProxyServer socks_server1_;
+ rtc::SocksProxyServer socks_server2_;
Endpoint ep1_;
Endpoint ep2_;
bool clear_remote_candidates_ufrag_pwd_;
@@ -806,14 +809,18 @@
// Ideally we want to use TURN server for both GICE and ICE, but in case
// of GICE, TURN server usage is not producing results reliabally.
// TODO(mallinath): Remove Relay and use TURN server for all tests.
+ ServerAddresses stun_servers;
+ stun_servers.insert(kStunAddr);
GetEndpoint(0)->allocator_.reset(
new cricket::BasicPortAllocator(&(GetEndpoint(0)->network_manager_),
- kStunAddr, talk_base::SocketAddress(), talk_base::SocketAddress(),
- talk_base::SocketAddress()));
+ stun_servers,
+ rtc::SocketAddress(), rtc::SocketAddress(),
+ rtc::SocketAddress()));
GetEndpoint(1)->allocator_.reset(
new cricket::BasicPortAllocator(&(GetEndpoint(1)->network_manager_),
- kStunAddr, talk_base::SocketAddress(), talk_base::SocketAddress(),
- talk_base::SocketAddress()));
+ stun_servers,
+ rtc::SocketAddress(), rtc::SocketAddress(),
+ rtc::SocketAddress()));
cricket::RelayServerConfig relay_server(cricket::RELAY_GTURN);
if (type == cricket::ICEPROTO_RFC5245) {
@@ -853,7 +860,7 @@
AddAddress(endpoint, kPrivateAddrs[endpoint]);
// Add a single NAT of the desired type
nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
- static_cast<talk_base::NATType>(config - NAT_FULL_CONE))->
+ static_cast<rtc::NATType>(config - NAT_FULL_CONE))->
AddClient(kPrivateAddrs[endpoint]);
break;
case NAT_DOUBLE_CONE:
@@ -862,9 +869,9 @@
// Add a two cascaded NATs of the desired types
nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
(config == NAT_DOUBLE_CONE) ?
- talk_base::NAT_OPEN_CONE : talk_base::NAT_SYMMETRIC)->
+ rtc::NAT_OPEN_CONE : rtc::NAT_SYMMETRIC)->
AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint],
- talk_base::NAT_OPEN_CONE)->
+ rtc::NAT_OPEN_CONE)->
AddClient(kCascadedPrivateAddrs[endpoint]);
break;
case BLOCK_UDP:
@@ -874,34 +881,34 @@
case PROXY_SOCKS:
AddAddress(endpoint, kPublicAddrs[endpoint]);
// Block all UDP
- fw()->AddRule(false, talk_base::FP_UDP, talk_base::FD_ANY,
+ fw()->AddRule(false, rtc::FP_UDP, rtc::FD_ANY,
kPublicAddrs[endpoint]);
if (config == BLOCK_UDP_AND_INCOMING_TCP) {
// Block TCP inbound to the endpoint
- fw()->AddRule(false, talk_base::FP_TCP, SocketAddress(),
+ fw()->AddRule(false, rtc::FP_TCP, SocketAddress(),
kPublicAddrs[endpoint]);
} else if (config == BLOCK_ALL_BUT_OUTGOING_HTTP) {
// Block all TCP to/from the endpoint except 80/443 out
- fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
- SocketAddress(talk_base::IPAddress(INADDR_ANY), 80));
- fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
- SocketAddress(talk_base::IPAddress(INADDR_ANY), 443));
- fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
+ fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
+ SocketAddress(rtc::IPAddress(INADDR_ANY), 80));
+ fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
+ SocketAddress(rtc::IPAddress(INADDR_ANY), 443));
+ fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY,
kPublicAddrs[endpoint]);
} else if (config == PROXY_HTTPS) {
// Block all TCP to/from the endpoint except to the proxy server
- fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
+ fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
kHttpsProxyAddrs[endpoint]);
- fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
+ fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY,
kPublicAddrs[endpoint]);
- SetProxy(endpoint, talk_base::PROXY_HTTPS);
+ SetProxy(endpoint, rtc::PROXY_HTTPS);
} else if (config == PROXY_SOCKS) {
// Block all TCP to/from the endpoint except to the proxy server
- fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
+ fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
kSocksProxyAddrs[endpoint]);
- fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
+ fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY,
kPublicAddrs[endpoint]);
- SetProxy(endpoint, talk_base::PROXY_SOCKS5);
+ SetProxy(endpoint, rtc::PROXY_SOCKS5);
}
break;
default:
@@ -1303,7 +1310,7 @@
ep1_ch1()->set_incoming_only(true);
// Pump for 1 second and verify that the channels are not connected.
- talk_base::Thread::Current()->ProcessMessages(1000);
+ rtc::Thread::Current()->ProcessMessages(1000);
EXPECT_FALSE(ep1_ch1()->readable());
EXPECT_FALSE(ep1_ch1()->writable());
@@ -1507,25 +1514,25 @@
AddAddress(1, kPublicAddrs[1]);
CreateChannels(1);
- EXPECT_EQ(talk_base::DSCP_NO_CHANGE,
+ EXPECT_EQ(rtc::DSCP_NO_CHANGE,
GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
- EXPECT_EQ(talk_base::DSCP_NO_CHANGE,
+ EXPECT_EQ(rtc::DSCP_NO_CHANGE,
GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
GetEndpoint(0)->cd1_.ch_->SetOption(
- talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS6);
+ rtc::Socket::OPT_DSCP, rtc::DSCP_CS6);
GetEndpoint(1)->cd1_.ch_->SetOption(
- talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS6);
- EXPECT_EQ(talk_base::DSCP_CS6,
+ rtc::Socket::OPT_DSCP, rtc::DSCP_CS6);
+ EXPECT_EQ(rtc::DSCP_CS6,
GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
- EXPECT_EQ(talk_base::DSCP_CS6,
+ EXPECT_EQ(rtc::DSCP_CS6,
GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
GetEndpoint(0)->cd1_.ch_->SetOption(
- talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF41);
+ rtc::Socket::OPT_DSCP, rtc::DSCP_AF41);
GetEndpoint(1)->cd1_.ch_->SetOption(
- talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF41);
- EXPECT_EQ(talk_base::DSCP_AF41,
+ rtc::Socket::OPT_DSCP, rtc::DSCP_AF41);
+ EXPECT_EQ(rtc::DSCP_AF41,
GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
- EXPECT_EQ(talk_base::DSCP_AF41,
+ EXPECT_EQ(rtc::DSCP_AF41,
GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
}
@@ -1601,13 +1608,13 @@
protected:
void ConfigureEndpoints(Config nat_type, Config config1, Config config2) {
ASSERT(nat_type >= NAT_FULL_CONE && nat_type <= NAT_SYMMETRIC);
- talk_base::NATSocketServer::Translator* outer_nat =
+ rtc::NATSocketServer::Translator* outer_nat =
nat()->AddTranslator(kPublicAddrs[0], kNatAddrs[0],
- static_cast<talk_base::NATType>(nat_type - NAT_FULL_CONE));
+ static_cast<rtc::NATType>(nat_type - NAT_FULL_CONE));
ConfigureEndpoint(outer_nat, 0, config1);
ConfigureEndpoint(outer_nat, 1, config2);
}
- void ConfigureEndpoint(talk_base::NATSocketServer::Translator* nat,
+ void ConfigureEndpoint(rtc::NATSocketServer::Translator* nat,
int endpoint, Config config) {
ASSERT(config <= NAT_SYMMETRIC);
if (config == OPEN) {
@@ -1616,7 +1623,7 @@
} else {
AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]);
nat->AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint],
- static_cast<talk_base::NATType>(config - NAT_FULL_CONE))->AddClient(
+ static_cast<rtc::NATType>(config - NAT_FULL_CONE))->AddClient(
kCascadedPrivateAddrs[endpoint]);
}
}
@@ -1666,7 +1673,7 @@
// Blackhole any traffic to or from the public addrs.
LOG(LS_INFO) << "Failing over...";
- fw()->AddRule(false, talk_base::FP_ANY, talk_base::FD_ANY,
+ fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY,
kPublicAddrs[1]);
// We should detect loss of connectivity within 5 seconds or so.
diff --git a/p2p/base/packetsocketfactory.h b/p2p/base/packetsocketfactory.h
index e985b37..46767c2 100644
--- a/p2p/base/packetsocketfactory.h
+++ b/p2p/base/packetsocketfactory.h
@@ -25,12 +25,12 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef TALK_BASE_PACKETSOCKETFACTORY_H_
-#define TALK_BASE_PACKETSOCKETFACTORY_H_
+#ifndef TALK_P2P_BASE_PACKETSOCKETFACTORY_H_
+#define TALK_P2P_BASE_PACKETSOCKETFACTORY_H_
-#include "talk/base/proxyinfo.h"
+#include "webrtc/base/proxyinfo.h"
-namespace talk_base {
+namespace rtc {
class AsyncPacketSocket;
class AsyncResolverInterface;
@@ -64,6 +64,6 @@
DISALLOW_EVIL_CONSTRUCTORS(PacketSocketFactory);
};
-} // namespace talk_base
+} // namespace rtc
-#endif // TALK_BASE_PACKETSOCKETFACTORY_H_
+#endif // TALK_P2P_BASE_PACKETSOCKETFACTORY_H_
diff --git a/p2p/base/parsing.cc b/p2p/base/parsing.cc
index ebe0596..1465096 100644
--- a/p2p/base/parsing.cc
+++ b/p2p/base/parsing.cc
@@ -27,9 +27,9 @@
#include "talk/p2p/base/parsing.h"
-#include <algorithm>
#include <stdlib.h>
-#include "talk/base/stringutils.h"
+#include <algorithm>
+#include "webrtc/base/stringutils.h"
namespace {
static const char kTrue[] = "true";
diff --git a/p2p/base/parsing.h b/p2p/base/parsing.h
index c820056..2aab2f8 100644
--- a/p2p/base/parsing.h
+++ b/p2p/base/parsing.h
@@ -30,9 +30,9 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/stringencode.h"
-#include "talk/xmllite/xmlelement.h" // Needed to delete ParseError.extra.
+#include "webrtc/libjingle/xmllite/xmlelement.h" // Needed to delete ParseError.extra.
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
@@ -97,7 +97,7 @@
return false;
}
std::string unparsed = elem->Attr(name);
- return talk_base::FromString(unparsed, val_out);
+ return rtc::FromString(unparsed, val_out);
}
template <class T>
@@ -116,7 +116,7 @@
bool AddXmlAttr(buzz::XmlElement* elem,
const buzz::QName& name, const T& val) {
std::string buf;
- if (!talk_base::ToString(val, &buf)) {
+ if (!rtc::ToString(val, &buf)) {
return false;
}
elem->AddAttr(name, buf);
@@ -126,7 +126,7 @@
template <class T>
bool SetXmlBody(buzz::XmlElement* elem, const T& val) {
std::string buf;
- if (!talk_base::ToString(val, &buf)) {
+ if (!rtc::ToString(val, &buf)) {
return false;
}
elem->SetBodyText(buf);
diff --git a/p2p/base/port.cc b/p2p/base/port.cc
index ad692ce..0cf46eb 100644
--- a/p2p/base/port.cc
+++ b/p2p/base/port.cc
@@ -30,15 +30,15 @@
#include <algorithm>
#include <vector>
-#include "talk/base/base64.h"
-#include "talk/base/crc32.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
#include "talk/p2p/base/common.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/crc32.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
namespace {
@@ -81,7 +81,7 @@
}
// Change the last character to the one next to it in the base64 table.
char new_last_char;
- if (!talk_base::Base64::GetNextBase64Char(rtp_ufrag[rtp_ufrag.size() - 1],
+ if (!rtc::Base64::GetNextBase64Char(rtp_ufrag[rtp_ufrag.size() - 1],
&new_last_char)) {
// Should not be here.
ASSERT(false);
@@ -103,7 +103,7 @@
// Computes our estimate of the RTT given the current estimate.
inline uint32 ConservativeRTTEstimate(uint32 rtt) {
- return talk_base::_max(MINIMUM_RTT, talk_base::_min(MAXIMUM_RTT, 2 * rtt));
+ return rtc::_max(MINIMUM_RTT, rtc::_min(MAXIMUM_RTT, 2 * rtt));
}
// Weighting of the old rtt value to new data.
@@ -147,6 +147,12 @@
return false;
}
+// RFC 6544, TCP candidate encoding rules.
+const int DISCARD_PORT = 9;
+const char TCPTYPE_ACTIVE_STR[] = "active";
+const char TCPTYPE_PASSIVE_STR[] = "passive";
+const char TCPTYPE_SIMOPEN_STR[] = "so";
+
// Foundation: An arbitrary string that is the same for two candidates
// that have the same type, base IP address, protocol (UDP, TCP,
// etc.), and STUN or TURN server. If any of these are different,
@@ -156,14 +162,14 @@
static std::string ComputeFoundation(
const std::string& type,
const std::string& protocol,
- const talk_base::SocketAddress& base_address) {
+ const rtc::SocketAddress& base_address) {
std::ostringstream ost;
ost << type << base_address.ipaddr().ToString() << protocol;
- return talk_base::ToString<uint32>(talk_base::ComputeCrc32(ost.str()));
+ return rtc::ToString<uint32>(rtc::ComputeCrc32(ost.str()));
}
-Port::Port(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+Port::Port(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
const std::string& username_fragment, const std::string& password)
: thread_(thread),
factory_(factory),
@@ -185,9 +191,9 @@
Construct();
}
-Port::Port(talk_base::Thread* thread, const std::string& type,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+Port::Port(rtc::Thread* thread, const std::string& type,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port, const std::string& username_fragment,
const std::string& password)
: thread_(thread),
@@ -216,8 +222,8 @@
// If the username_fragment and password are empty, we should just create one.
if (ice_username_fragment_.empty()) {
ASSERT(password_.empty());
- ice_username_fragment_ = talk_base::CreateRandomString(ICE_UFRAG_LENGTH);
- password_ = talk_base::CreateRandomString(ICE_PWD_LENGTH);
+ ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
+ password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
}
LOG_J(LS_INFO, this) << "Port created";
}
@@ -238,7 +244,7 @@
delete list[i];
}
-Connection* Port::GetConnection(const talk_base::SocketAddress& remote_addr) {
+Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
AddressMap::const_iterator iter = connections_.find(remote_addr);
if (iter != connections_.end())
return iter->second;
@@ -246,20 +252,28 @@
return NULL;
}
-void Port::AddAddress(const talk_base::SocketAddress& address,
- const talk_base::SocketAddress& base_address,
- const talk_base::SocketAddress& related_address,
+void Port::AddAddress(const rtc::SocketAddress& address,
+ const rtc::SocketAddress& base_address,
+ const rtc::SocketAddress& related_address,
const std::string& protocol,
+ const std::string& tcptype,
const std::string& type,
uint32 type_preference,
+ uint32 relay_preference,
bool final) {
+ if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
+ ASSERT(!tcptype.empty());
+ }
+
Candidate c;
- c.set_id(talk_base::CreateRandomString(8));
+ c.set_id(rtc::CreateRandomString(8));
c.set_component(component_);
c.set_type(type);
c.set_protocol(protocol);
+ c.set_tcptype(tcptype);
c.set_address(address);
- c.set_priority(c.GetPriority(type_preference, network_->preference()));
+ c.set_priority(c.GetPriority(type_preference, network_->preference(),
+ relay_preference));
c.set_username(username_fragment());
c.set_password(password_);
c.set_network_name(network_->name());
@@ -281,7 +295,7 @@
}
void Port::OnReadPacket(
- const char* data, size_t size, const talk_base::SocketAddress& addr,
+ const char* data, size_t size, const rtc::SocketAddress& addr,
ProtocolType proto) {
// If the user has enabled port packets, just hand this over.
if (enable_port_packets_) {
@@ -291,7 +305,7 @@
// If this is an authenticated STUN request, then signal unknown address and
// send back a proper binding response.
- talk_base::scoped_ptr<IceMessage> msg;
+ rtc::scoped_ptr<IceMessage> msg;
std::string remote_username;
if (!GetStunMessage(data, size, addr, msg.accept(), &remote_username)) {
LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
@@ -345,7 +359,7 @@
}
bool Port::GetStunMessage(const char* data, size_t size,
- const talk_base::SocketAddress& addr,
+ const rtc::SocketAddress& addr,
IceMessage** out_msg, std::string* out_username) {
// NOTE: This could clearly be optimized to avoid allocating any memory.
// However, at the data rates we'll be looking at on the client side,
@@ -363,8 +377,8 @@
// Parse the request message. If the packet is not a complete and correct
// STUN message, then ignore it.
- talk_base::scoped_ptr<IceMessage> stun_msg(new IceMessage());
- talk_base::ByteBuffer buf(data, size);
+ rtc::scoped_ptr<IceMessage> stun_msg(new IceMessage());
+ rtc::ByteBuffer buf(data, size);
if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
return false;
}
@@ -452,7 +466,7 @@
return true;
}
-bool Port::IsCompatibleAddress(const talk_base::SocketAddress& addr) {
+bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
int family = ip().family();
// We use single-stack sockets, so families must match.
if (addr.family() != family) {
@@ -511,7 +525,7 @@
}
bool Port::MaybeIceRoleConflict(
- const talk_base::SocketAddress& addr, IceMessage* stun_msg,
+ const rtc::SocketAddress& addr, IceMessage* stun_msg,
const std::string& remote_ufrag) {
// Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
bool ret = true;
@@ -583,7 +597,7 @@
}
void Port::SendBindingResponse(StunMessage* request,
- const talk_base::SocketAddress& addr) {
+ const rtc::SocketAddress& addr) {
ASSERT(request->type() == STUN_BINDING_REQUEST);
// Retrieve the username from the request.
@@ -629,9 +643,9 @@
}
// Send the response message.
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
response.Write(&buf);
- talk_base::PacketOptions options(DefaultDscpValue());
+ rtc::PacketOptions options(DefaultDscpValue());
if (SendTo(buf.Data(), buf.Length(), addr, options, false) < 0) {
LOG_J(LS_ERROR, this) << "Failed to send STUN ping response to "
<< addr.ToSensitiveString();
@@ -646,7 +660,7 @@
}
void Port::SendBindingErrorResponse(StunMessage* request,
- const talk_base::SocketAddress& addr,
+ const rtc::SocketAddress& addr,
int error_code, const std::string& reason) {
ASSERT(request->type() == STUN_BINDING_REQUEST);
@@ -684,15 +698,15 @@
}
// Send the response message.
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
response.Write(&buf);
- talk_base::PacketOptions options(DefaultDscpValue());
+ rtc::PacketOptions options(DefaultDscpValue());
SendTo(buf.Data(), buf.Length(), addr, options, false);
LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
<< " to " << addr.ToSensitiveString();
}
-void Port::OnMessage(talk_base::Message *pmsg) {
+void Port::OnMessage(rtc::Message *pmsg) {
ASSERT(pmsg->message_id == MSG_CHECKTIMEOUT);
CheckTimeout();
}
@@ -886,9 +900,9 @@
g = remote_candidate_.priority();
d = local_candidate().priority();
}
- priority = talk_base::_min(g, d);
+ priority = rtc::_min(g, d);
priority = priority << 32;
- priority += 2 * talk_base::_max(g, d) + (g > d ? 1 : 0);
+ priority += 2 * rtc::_max(g, d) + (g > d ? 1 : 0);
}
return priority;
}
@@ -935,7 +949,7 @@
void Connection::OnSendStunPacket(const void* data, size_t size,
StunRequest* req) {
- talk_base::PacketOptions options(port_->DefaultDscpValue());
+ rtc::PacketOptions options(port_->DefaultDscpValue());
if (port_->SendTo(data, size, remote_candidate_.address(),
options, false) < 0) {
LOG_J(LS_WARNING, this) << "Failed to send STUN ping " << req->id();
@@ -943,10 +957,10 @@
}
void Connection::OnReadPacket(
- const char* data, size_t size, const talk_base::PacketTime& packet_time) {
- talk_base::scoped_ptr<IceMessage> msg;
+ const char* data, size_t size, const rtc::PacketTime& packet_time) {
+ rtc::scoped_ptr<IceMessage> msg;
std::string remote_ufrag;
- const talk_base::SocketAddress& addr(remote_candidate_.address());
+ const rtc::SocketAddress& addr(remote_candidate_.address());
if (!port_->GetStunMessage(data, size, addr, msg.accept(), &remote_ufrag)) {
// The packet did not parse as a valid STUN message
@@ -955,7 +969,7 @@
// readable means data from this address is acceptable
// Send it on!
- last_data_received_ = talk_base::Time();
+ last_data_received_ = rtc::Time();
recv_rate_tracker_.Update(size);
SignalReadPacket(this, data, size, packet_time);
@@ -1078,7 +1092,7 @@
std::string pings;
for (size_t i = 0; i < pings_since_last_response_.size(); ++i) {
char buf[32];
- talk_base::sprintfn(buf, sizeof(buf), "%u",
+ rtc::sprintfn(buf, sizeof(buf), "%u",
pings_since_last_response_[i]);
pings.append(buf).append(" ");
}
@@ -1163,7 +1177,7 @@
}
void Connection::ReceivedPing() {
- last_ping_received_ = talk_base::Time();
+ last_ping_received_ = rtc::Time();
set_read_state(STATE_READABLE);
}
@@ -1198,7 +1212,7 @@
<< ":" << local.type() << ":" << local.protocol()
<< ":" << local.address().ToSensitiveString()
<< "->" << remote.id() << ":" << remote.component()
- << ":" << remote.preference()
+ << ":" << remote.priority()
<< ":" << remote.type() << ":"
<< remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
<< CONNECT_STATE_ABBREV[connected()]
@@ -1238,21 +1252,21 @@
std::string pings;
for (size_t i = 0; i < pings_since_last_response_.size(); ++i) {
char buf[32];
- talk_base::sprintfn(buf, sizeof(buf), "%u",
+ rtc::sprintfn(buf, sizeof(buf), "%u",
pings_since_last_response_[i]);
pings.append(buf).append(" ");
}
- talk_base::LoggingSeverity level =
+ rtc::LoggingSeverity level =
(pings_since_last_response_.size() > CONNECTION_WRITE_CONNECT_FAILURES) ?
- talk_base::LS_INFO : talk_base::LS_VERBOSE;
+ rtc::LS_INFO : rtc::LS_VERBOSE;
LOG_JV(level, this) << "Received STUN ping response " << request->id()
<< ", pings_since_last_response_=" << pings
<< ", rtt=" << rtt;
pings_since_last_response_.clear();
- last_ping_response_received_ = talk_base::Time();
+ last_ping_response_received_ = rtc::Time();
rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
// Peer reflexive candidate is only for RFC 5245 ICE.
@@ -1294,8 +1308,8 @@
void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
// Log at LS_INFO if we miss a ping on a writable connection.
- talk_base::LoggingSeverity sev = (write_state_ == STATE_WRITABLE) ?
- talk_base::LS_INFO : talk_base::LS_VERBOSE;
+ rtc::LoggingSeverity sev = (write_state_ == STATE_WRITABLE) ?
+ rtc::LS_INFO : rtc::LS_VERBOSE;
LOG_JV(sev, this) << "Timing-out STUN ping " << request->id()
<< " after " << request->Elapsed() << " ms";
}
@@ -1317,7 +1331,7 @@
port_->SignalRoleConflict(port_);
}
-void Connection::OnMessage(talk_base::Message *pmsg) {
+void Connection::OnMessage(rtc::Message *pmsg) {
ASSERT(pmsg->message_id == MSG_DELETE);
LOG_J(LS_INFO, this) << "Connection deleted";
@@ -1380,7 +1394,7 @@
return;
}
const uint32 priority = priority_attr->value();
- std::string id = talk_base::CreateRandomString(8);
+ std::string id = rtc::CreateRandomString(8);
Candidate new_local_candidate;
new_local_candidate.set_id(id);
@@ -1411,7 +1425,7 @@
}
int ProxyConnection::Send(const void* data, size_t size,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
error_ = EWOULDBLOCK;
return SOCKET_ERROR;
diff --git a/p2p/base/port.h b/p2p/base/port.h
index 6e5c383..4893586 100644
--- a/p2p/base/port.h
+++ b/p2p/base/port.h
@@ -28,23 +28,24 @@
#ifndef TALK_P2P_BASE_PORT_H_
#define TALK_P2P_BASE_PORT_H_
+#include <map>
+#include <set>
#include <string>
#include <vector>
-#include <map>
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/network.h"
-#include "talk/base/proxyinfo.h"
-#include "talk/base/ratetracker.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/packetsocketfactory.h"
#include "talk/p2p/base/portinterface.h"
#include "talk/p2p/base/stun.h"
#include "talk/p2p/base/stunrequest.h"
#include "talk/p2p/base/transport.h"
+#include "webrtc/base/asyncpacketsocket.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/proxyinfo.h"
+#include "webrtc/base/ratetracker.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -60,6 +61,12 @@
extern const char TCP_PROTOCOL_NAME[];
extern const char SSLTCP_PROTOCOL_NAME[];
+// RFC 6544, TCP candidate encoding rules.
+extern const int DISCARD_PORT;
+extern const char TCPTYPE_ACTIVE_STR[];
+extern const char TCPTYPE_PASSIVE_STR[];
+extern const char TCPTYPE_SIMOPEN_STR[];
+
// The length of time we wait before timing out readability on a connection.
const uint32 CONNECTION_READ_TIMEOUT = 30 * 1000; // 30 seconds
@@ -99,34 +106,36 @@
bool StringToProto(const char* value, ProtocolType* proto);
struct ProtocolAddress {
- talk_base::SocketAddress address;
+ rtc::SocketAddress address;
ProtocolType proto;
bool secure;
- ProtocolAddress(const talk_base::SocketAddress& a, ProtocolType p)
+ ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
: address(a), proto(p), secure(false) { }
- ProtocolAddress(const talk_base::SocketAddress& a, ProtocolType p, bool sec)
+ ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p, bool sec)
: address(a), proto(p), secure(sec) { }
};
+typedef std::set<rtc::SocketAddress> ServerAddresses;
+
// Represents a local communication mechanism that can be used to create
// connections to similar mechanisms of the other client. Subclasses of this
// one add support for specific mechanisms like local UDP ports.
-class Port : public PortInterface, public talk_base::MessageHandler,
+class Port : public PortInterface, public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
- Port(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ Port(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
const std::string& username_fragment, const std::string& password);
- Port(talk_base::Thread* thread, const std::string& type,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ Port(rtc::Thread* thread, const std::string& type,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port, const std::string& username_fragment,
const std::string& password);
virtual ~Port();
virtual const std::string& Type() const { return type_; }
- virtual talk_base::Network* Network() const { return network_; }
+ virtual rtc::Network* Network() const { return network_; }
// This method will set the flag which enables standard ICE/STUN procedures
// in STUN connectivity checks. Currently this method does
@@ -146,13 +155,14 @@
uint64 IceTiebreaker() const { return tiebreaker_; }
virtual bool SharedSocket() const { return shared_socket_; }
+ void ResetSharedSocket() { shared_socket_ = false; }
// The thread on which this port performs its I/O.
- talk_base::Thread* thread() { return thread_; }
+ rtc::Thread* thread() { return thread_; }
// The factory used to create the sockets of this port.
- talk_base::PacketSocketFactory* socket_factory() const { return factory_; }
- void set_socket_factory(talk_base::PacketSocketFactory* factory) {
+ rtc::PacketSocketFactory* socket_factory() const { return factory_; }
+ void set_socket_factory(rtc::PacketSocketFactory* factory) {
factory_ = factory;
}
@@ -214,12 +224,12 @@
// Returns a map containing all of the connections of this port, keyed by the
// remote address.
- typedef std::map<talk_base::SocketAddress, Connection*> AddressMap;
+ typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
const AddressMap& connections() { return connections_; }
// Returns the connection to the given address or NULL if none exists.
virtual Connection* GetConnection(
- const talk_base::SocketAddress& remote_addr);
+ const rtc::SocketAddress& remote_addr);
// Called each time a connection is created.
sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
@@ -229,9 +239,9 @@
// port implemented this method.
// TODO(mallinath) - Make it pure virtual.
virtual bool HandleIncomingPacket(
- talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* data, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
ASSERT(false);
return false;
}
@@ -240,29 +250,29 @@
// these methods should be called as a response to SignalUnknownAddress.
// NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
virtual void SendBindingResponse(StunMessage* request,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
virtual void SendBindingErrorResponse(
- StunMessage* request, const talk_base::SocketAddress& addr,
+ StunMessage* request, const rtc::SocketAddress& addr,
int error_code, const std::string& reason);
void set_proxy(const std::string& user_agent,
- const talk_base::ProxyInfo& proxy) {
+ const rtc::ProxyInfo& proxy) {
user_agent_ = user_agent;
proxy_ = proxy;
}
const std::string& user_agent() { return user_agent_; }
- const talk_base::ProxyInfo& proxy() { return proxy_; }
+ const rtc::ProxyInfo& proxy() { return proxy_; }
virtual void EnablePortPackets();
// Called if the port has no connections and is no longer useful.
void Destroy();
- virtual void OnMessage(talk_base::Message *pmsg);
+ virtual void OnMessage(rtc::Message *pmsg);
// Debugging description of this port
virtual std::string ToString() const;
- talk_base::IPAddress& ip() { return ip_; }
+ rtc::IPAddress& ip() { return ip_; }
int min_port() { return min_port_; }
int max_port() { return max_port_; }
@@ -278,7 +288,7 @@
void CreateStunUsername(const std::string& remote_username,
std::string* stun_username_attr_str) const;
- bool MaybeIceRoleConflict(const talk_base::SocketAddress& addr,
+ bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
IceMessage* stun_msg,
const std::string& remote_ufrag);
@@ -305,12 +315,13 @@
};
void set_type(const std::string& type) { type_ = type; }
- // Fills in the local address of the port.
- void AddAddress(const talk_base::SocketAddress& address,
- const talk_base::SocketAddress& base_address,
- const talk_base::SocketAddress& related_address,
- const std::string& protocol, const std::string& type,
- uint32 type_preference, bool final);
+
+ void AddAddress(const rtc::SocketAddress& address,
+ const rtc::SocketAddress& base_address,
+ const rtc::SocketAddress& related_address,
+ const std::string& protocol, const std::string& tcptype,
+ const std::string& type, uint32 type_preference,
+ uint32 relay_preference, bool final);
// Adds the given connection to the list. (Deleting removes them.)
void AddConnection(Connection* conn);
@@ -319,7 +330,7 @@
// currently a connection. If this is an authenticated STUN binding request,
// then we will signal the client.
void OnReadPacket(const char* data, size_t size,
- const talk_base::SocketAddress& addr,
+ const rtc::SocketAddress& addr,
ProtocolType proto);
// If the given data comprises a complete and correct STUN message then the
@@ -328,16 +339,16 @@
// message. Otherwise, the function may send a STUN response internally.
// remote_username contains the remote fragment of the STUN username.
bool GetStunMessage(const char* data, size_t size,
- const talk_base::SocketAddress& addr,
+ const rtc::SocketAddress& addr,
IceMessage** out_msg, std::string* out_username);
// Checks if the address in addr is compatible with the port's ip.
- bool IsCompatibleAddress(const talk_base::SocketAddress& addr);
+ bool IsCompatibleAddress(const rtc::SocketAddress& addr);
// Returns default DSCP value.
- talk_base::DiffServCodePoint DefaultDscpValue() const {
+ rtc::DiffServCodePoint DefaultDscpValue() const {
// No change from what MediaChannel set.
- return talk_base::DSCP_NO_CHANGE;
+ return rtc::DSCP_NO_CHANGE;
}
private:
@@ -348,12 +359,12 @@
// Checks if this port is useless, and hence, should be destroyed.
void CheckTimeout();
- talk_base::Thread* thread_;
- talk_base::PacketSocketFactory* factory_;
+ rtc::Thread* thread_;
+ rtc::PacketSocketFactory* factory_;
std::string type_;
bool send_retransmit_count_attribute_;
- talk_base::Network* network_;
- talk_base::IPAddress ip_;
+ rtc::Network* network_;
+ rtc::IPAddress ip_;
int min_port_;
int max_port_;
std::string content_name_;
@@ -379,14 +390,14 @@
bool shared_socket_;
// Information to use when going through a proxy.
std::string user_agent_;
- talk_base::ProxyInfo proxy_;
+ rtc::ProxyInfo proxy_;
friend class Connection;
};
// Represents a communication link between a port on the local client and a
// port on the remote client.
-class Connection : public talk_base::MessageHandler,
+class Connection : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
// States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
@@ -452,19 +463,19 @@
// the interface of AsyncPacketSocket, which may use UDP or TCP under the
// covers.
virtual int Send(const void* data, size_t size,
- const talk_base::PacketOptions& options) = 0;
+ const rtc::PacketOptions& options) = 0;
// Error if Send() returns < 0
virtual int GetError() = 0;
sigslot::signal4<Connection*, const char*, size_t,
- const talk_base::PacketTime&> SignalReadPacket;
+ const rtc::PacketTime&> SignalReadPacket;
sigslot::signal1<Connection*> SignalReadyToSend;
// Called when a packet is received on this connection.
void OnReadPacket(const char* data, size_t size,
- const talk_base::PacketTime& packet_time);
+ const rtc::PacketTime& packet_time);
// Called when the socket is currently able to send.
void OnReadyToSend();
@@ -540,7 +551,7 @@
// Checks if this connection is useless, and hence, should be destroyed.
void CheckTimeout();
- void OnMessage(talk_base::Message *pmsg);
+ void OnMessage(rtc::Message *pmsg);
Port* port_;
size_t local_candidate_index_;
@@ -564,8 +575,8 @@
uint32 last_ping_response_received_;
std::vector<uint32> pings_since_last_response_;
- talk_base::RateTracker recv_rate_tracker_;
- talk_base::RateTracker send_rate_tracker_;
+ rtc::RateTracker recv_rate_tracker_;
+ rtc::RateTracker send_rate_tracker_;
private:
void MaybeAddPrflxCandidate(ConnectionRequest* request,
@@ -584,7 +595,7 @@
ProxyConnection(Port* port, size_t index, const Candidate& candidate);
virtual int Send(const void* data, size_t size,
- const talk_base::PacketOptions& options);
+ const rtc::PacketOptions& options);
virtual int GetError() { return error_; }
private:
diff --git a/p2p/base/port_unittest.cc b/p2p/base/port_unittest.cc
index fc6d48c..04becfc 100644
--- a/p2p/base/port_unittest.cc
+++ b/p2p/base/port_unittest.cc
@@ -25,19 +25,6 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/crc32.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/natserver.h"
-#include "talk/base/natsocketfactory.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/thread.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/portproxy.h"
#include "talk/p2p/base/relayport.h"
@@ -48,25 +35,38 @@
#include "talk/p2p/base/testturnserver.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/turnport.h"
+#include "webrtc/base/crc32.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/natserver.h"
+#include "webrtc/base/natsocketfactory.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/virtualsocketserver.h"
-using talk_base::AsyncPacketSocket;
-using talk_base::ByteBuffer;
-using talk_base::NATType;
-using talk_base::NAT_OPEN_CONE;
-using talk_base::NAT_ADDR_RESTRICTED;
-using talk_base::NAT_PORT_RESTRICTED;
-using talk_base::NAT_SYMMETRIC;
-using talk_base::PacketSocketFactory;
-using talk_base::scoped_ptr;
-using talk_base::Socket;
-using talk_base::SocketAddress;
+using rtc::AsyncPacketSocket;
+using rtc::ByteBuffer;
+using rtc::NATType;
+using rtc::NAT_OPEN_CONE;
+using rtc::NAT_ADDR_RESTRICTED;
+using rtc::NAT_PORT_RESTRICTED;
+using rtc::NAT_SYMMETRIC;
+using rtc::PacketSocketFactory;
+using rtc::scoped_ptr;
+using rtc::Socket;
+using rtc::SocketAddress;
using namespace cricket;
static const int kTimeout = 1000;
static const SocketAddress kLocalAddr1("192.168.1.2", 0);
static const SocketAddress kLocalAddr2("192.168.1.3", 0);
-static const SocketAddress kNatAddr1("77.77.77.77", talk_base::NAT_SERVER_PORT);
-static const SocketAddress kNatAddr2("88.88.88.88", talk_base::NAT_SERVER_PORT);
+static const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_PORT);
+static const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_PORT);
static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
@@ -117,9 +117,9 @@
// Stub port class for testing STUN generation and processing.
class TestPort : public Port {
public:
- TestPort(talk_base::Thread* thread, const std::string& type,
- talk_base::PacketSocketFactory* factory, talk_base::Network* network,
- const talk_base::IPAddress& ip, int min_port, int max_port,
+ TestPort(rtc::Thread* thread, const std::string& type,
+ rtc::PacketSocketFactory* factory, rtc::Network* network,
+ const rtc::IPAddress& ip, int min_port, int max_port,
const std::string& username_fragment, const std::string& password)
: Port(thread, type, factory, network, ip,
min_port, max_port, username_fragment, password) {
@@ -145,23 +145,23 @@
}
virtual void PrepareAddress() {
- talk_base::SocketAddress addr(ip(), min_port());
- AddAddress(addr, addr, talk_base::SocketAddress(), "udp", Type(),
- ICE_TYPE_PREFERENCE_HOST, true);
+ rtc::SocketAddress addr(ip(), min_port());
+ AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", Type(),
+ ICE_TYPE_PREFERENCE_HOST, 0, true);
}
// Exposed for testing candidate building.
- void AddCandidateAddress(const talk_base::SocketAddress& addr) {
- AddAddress(addr, addr, talk_base::SocketAddress(), "udp", Type(),
- type_preference_, false);
+ void AddCandidateAddress(const rtc::SocketAddress& addr) {
+ AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", Type(),
+ type_preference_, 0, false);
}
- void AddCandidateAddress(const talk_base::SocketAddress& addr,
- const talk_base::SocketAddress& base_address,
+ void AddCandidateAddress(const rtc::SocketAddress& addr,
+ const rtc::SocketAddress& base_address,
const std::string& type,
int type_preference,
bool final) {
- AddAddress(addr, base_address, talk_base::SocketAddress(), "udp", type,
- type_preference, final);
+ AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", type,
+ type_preference, 0, final);
}
virtual Connection* CreateConnection(const Candidate& remote_candidate,
@@ -174,8 +174,8 @@
return conn;
}
virtual int SendTo(
- const void* data, size_t size, const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options, bool payload) {
+ const void* data, size_t size, const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options, bool payload) {
if (!payload) {
IceMessage* msg = new IceMessage;
ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
@@ -191,10 +191,10 @@
}
return static_cast<int>(size);
}
- virtual int SetOption(talk_base::Socket::Option opt, int value) {
+ virtual int SetOption(rtc::Socket::Option opt, int value) {
return 0;
}
- virtual int GetOption(talk_base::Socket::Option opt, int* value) {
+ virtual int GetOption(rtc::Socket::Option opt, int* value) {
return -1;
}
virtual int GetError() {
@@ -209,8 +209,8 @@
}
private:
- talk_base::scoped_ptr<ByteBuffer> last_stun_buf_;
- talk_base::scoped_ptr<IceMessage> last_stun_msg_;
+ rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
+ rtc::scoped_ptr<IceMessage> last_stun_msg_;
int type_preference_;
};
@@ -319,13 +319,13 @@
private:
IceMode ice_mode_;
- talk_base::scoped_ptr<Port> src_;
+ rtc::scoped_ptr<Port> src_;
Port* dst_;
int complete_count_;
Connection* conn_;
SocketAddress remote_address_;
- talk_base::scoped_ptr<StunMessage> remote_request_;
+ rtc::scoped_ptr<StunMessage> remote_request_;
std::string remote_frag_;
bool nominated_;
};
@@ -333,12 +333,12 @@
class PortTest : public testing::Test, public sigslot::has_slots<> {
public:
PortTest()
- : main_(talk_base::Thread::Current()),
- pss_(new talk_base::PhysicalSocketServer),
- ss_(new talk_base::VirtualSocketServer(pss_.get())),
+ : main_(rtc::Thread::Current()),
+ pss_(new rtc::PhysicalSocketServer),
+ ss_(new rtc::VirtualSocketServer(pss_.get())),
ss_scope_(ss_.get()),
- network_("unittest", "unittest", talk_base::IPAddress(INADDR_ANY), 32),
- socket_factory_(talk_base::Thread::Current()),
+ network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
+ socket_factory_(rtc::Thread::Current()),
nat_factory1_(ss_.get(), kNatAddr1),
nat_factory2_(ss_.get(), kNatAddr2),
nat_socket_factory1_(&nat_factory1_),
@@ -348,21 +348,21 @@
relay_server_(main_, kRelayUdpIntAddr, kRelayUdpExtAddr,
kRelayTcpIntAddr, kRelayTcpExtAddr,
kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
- username_(talk_base::CreateRandomString(ICE_UFRAG_LENGTH)),
- password_(talk_base::CreateRandomString(ICE_PWD_LENGTH)),
+ username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
+ password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
ice_protocol_(cricket::ICEPROTO_GOOGLE),
role_conflict_(false),
destroyed_(false) {
- network_.AddIP(talk_base::IPAddress(INADDR_ANY));
+ network_.AddIP(rtc::IPAddress(INADDR_ANY));
}
protected:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
@@ -452,10 +452,12 @@
return port;
}
StunPort* CreateStunPort(const SocketAddress& addr,
- talk_base::PacketSocketFactory* factory) {
+ rtc::PacketSocketFactory* factory) {
+ ServerAddresses stun_servers;
+ stun_servers.insert(kStunAddr);
StunPort* port = StunPort::Create(main_, factory, &network_,
addr.ipaddr(), 0, 0,
- username_, password_, kStunAddr);
+ username_, password_, stun_servers);
port->SetIceProtocolType(ice_protocol_);
return port;
}
@@ -476,12 +478,12 @@
TurnPort* CreateTurnPort(const SocketAddress& addr,
PacketSocketFactory* socket_factory,
ProtocolType int_proto, ProtocolType ext_proto,
- const talk_base::SocketAddress& server_addr) {
+ const rtc::SocketAddress& server_addr) {
TurnPort* port = TurnPort::Create(main_, socket_factory, &network_,
addr.ipaddr(), 0, 0,
username_, password_, ProtocolAddress(
server_addr, PROTO_UDP),
- kRelayCredentials);
+ kRelayCredentials, 0);
port->SetIceProtocolType(ice_protocol_);
return port;
}
@@ -502,9 +504,9 @@
port->SetIceProtocolType(ice_protocol_);
return port;
}
- talk_base::NATServer* CreateNatServer(const SocketAddress& addr,
- talk_base::NATType type) {
- return new talk_base::NATServer(type, ss_.get(), addr, ss_.get(), addr);
+ rtc::NATServer* CreateNatServer(const SocketAddress& addr,
+ rtc::NATType type) {
+ return new rtc::NATServer(type, ss_.get(), addr, ss_.get(), addr);
}
static const char* StunName(NATType type) {
switch (type) {
@@ -563,7 +565,7 @@
new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
return msg;
}
- TestPort* CreateTestPort(const talk_base::SocketAddress& addr,
+ TestPort* CreateTestPort(const rtc::SocketAddress& addr,
const std::string& username,
const std::string& password) {
TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
@@ -571,7 +573,7 @@
port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
return port;
}
- TestPort* CreateTestPort(const talk_base::SocketAddress& addr,
+ TestPort* CreateTestPort(const rtc::SocketAddress& addr,
const std::string& username,
const std::string& password,
cricket::IceProtocolType type,
@@ -598,23 +600,23 @@
}
bool destroyed() const { return destroyed_; }
- talk_base::BasicPacketSocketFactory* nat_socket_factory1() {
+ rtc::BasicPacketSocketFactory* nat_socket_factory1() {
return &nat_socket_factory1_;
}
private:
- talk_base::Thread* main_;
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> ss_;
- talk_base::SocketServerScope ss_scope_;
- talk_base::Network network_;
- talk_base::BasicPacketSocketFactory socket_factory_;
- talk_base::scoped_ptr<talk_base::NATServer> nat_server1_;
- talk_base::scoped_ptr<talk_base::NATServer> nat_server2_;
- talk_base::NATSocketFactory nat_factory1_;
- talk_base::NATSocketFactory nat_factory2_;
- talk_base::BasicPacketSocketFactory nat_socket_factory1_;
- talk_base::BasicPacketSocketFactory nat_socket_factory2_;
+ rtc::Thread* main_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
+ rtc::SocketServerScope ss_scope_;
+ rtc::Network network_;
+ rtc::BasicPacketSocketFactory socket_factory_;
+ rtc::scoped_ptr<rtc::NATServer> nat_server1_;
+ rtc::scoped_ptr<rtc::NATServer> nat_server2_;
+ rtc::NATSocketFactory nat_factory1_;
+ rtc::NATSocketFactory nat_factory2_;
+ rtc::BasicPacketSocketFactory nat_socket_factory1_;
+ rtc::BasicPacketSocketFactory nat_socket_factory2_;
TestStunServer stun_server_;
TestTurnServer turn_server_;
TestRelayServer relay_server_;
@@ -779,7 +781,7 @@
ch2->Stop();
}
-class FakePacketSocketFactory : public talk_base::PacketSocketFactory {
+class FakePacketSocketFactory : public rtc::PacketSocketFactory {
public:
FakePacketSocketFactory()
: next_udp_socket_(NULL),
@@ -809,7 +811,7 @@
// per-factory and not when socket is created.
virtual AsyncPacketSocket* CreateClientTcpSocket(
const SocketAddress& local_address, const SocketAddress& remote_address,
- const talk_base::ProxyInfo& proxy_info,
+ const rtc::ProxyInfo& proxy_info,
const std::string& user_agent, int opts) {
EXPECT_TRUE(next_client_tcp_socket_ != NULL);
AsyncPacketSocket* result = next_client_tcp_socket_;
@@ -826,7 +828,7 @@
void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
next_client_tcp_socket_ = next_client_tcp_socket;
}
- talk_base::AsyncResolverInterface* CreateAsyncResolver() {
+ rtc::AsyncResolverInterface* CreateAsyncResolver() {
return NULL;
}
@@ -851,11 +853,11 @@
// Send a packet.
virtual int Send(const void *pv, size_t cb,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
return static_cast<int>(cb);
}
virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
return static_cast<int>(cb);
}
virtual int Close() {
@@ -1095,7 +1097,7 @@
// should remain equal to the request generated by the port and role of port
// must be in controlling.
TEST_F(PortTest, TestLoopbackCallAsIce) {
- talk_base::scoped_ptr<TestPort> lport(
+ rtc::scoped_ptr<TestPort> lport(
CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
lport->SetIceProtocolType(ICEPROTO_RFC5245);
lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
@@ -1111,7 +1113,7 @@
EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
conn->OnReadPacket(lport->last_stun_buf()->Data(),
lport->last_stun_buf()->Length(),
- talk_base::PacketTime());
+ rtc::PacketTime());
ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
msg = lport->last_stun_msg();
EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
@@ -1128,7 +1130,7 @@
ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
msg = lport->last_stun_msg();
EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
- talk_base::scoped_ptr<IceMessage> modified_req(
+ rtc::scoped_ptr<IceMessage> modified_req(
CreateStunMessage(STUN_BINDING_REQUEST));
const StunByteStringAttribute* username_attr = msg->GetByteString(
STUN_ATTR_USERNAME);
@@ -1142,9 +1144,9 @@
modified_req->AddFingerprint();
lport->Reset();
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
WriteStunMessage(modified_req.get(), buf.get());
- conn1->OnReadPacket(buf->Data(), buf->Length(), talk_base::PacketTime());
+ conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
msg = lport->last_stun_msg();
EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
@@ -1156,12 +1158,12 @@
// value of tiebreaker, when it receives ping request from |rport| it will
// send role conflict signal.
TEST_F(PortTest, TestIceRoleConflict) {
- talk_base::scoped_ptr<TestPort> lport(
+ rtc::scoped_ptr<TestPort> lport(
CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
lport->SetIceProtocolType(ICEPROTO_RFC5245);
lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
lport->SetIceTiebreaker(kTiebreaker1);
- talk_base::scoped_ptr<TestPort> rport(
+ rtc::scoped_ptr<TestPort> rport(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
rport->SetIceProtocolType(ICEPROTO_RFC5245);
rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
@@ -1183,7 +1185,7 @@
// Send rport binding request to lport.
lconn->OnReadPacket(rport->last_stun_buf()->Data(),
rport->last_stun_buf()->Length(),
- talk_base::PacketTime());
+ rtc::PacketTime());
ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
@@ -1193,7 +1195,7 @@
TEST_F(PortTest, TestTcpNoDelay) {
TCPPort* port1 = CreateTcpPort(kLocalAddr1);
int option_value = -1;
- int success = port1->GetOption(talk_base::Socket::OPT_NODELAY,
+ int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
&option_value);
ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
ASSERT_EQ(1, option_value);
@@ -1296,43 +1298,43 @@
// get through DefaultDscpValue.
TEST_F(PortTest, TestDefaultDscpValue) {
int dscp;
- talk_base::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
- EXPECT_EQ(0, udpport->SetOption(talk_base::Socket::OPT_DSCP,
- talk_base::DSCP_CS6));
- EXPECT_EQ(0, udpport->GetOption(talk_base::Socket::OPT_DSCP, &dscp));
- talk_base::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
- EXPECT_EQ(0, tcpport->SetOption(talk_base::Socket::OPT_DSCP,
- talk_base::DSCP_AF31));
- EXPECT_EQ(0, tcpport->GetOption(talk_base::Socket::OPT_DSCP, &dscp));
- EXPECT_EQ(talk_base::DSCP_AF31, dscp);
- talk_base::scoped_ptr<StunPort> stunport(
+ rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
+ EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
+ rtc::DSCP_CS6));
+ EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
+ rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
+ EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
+ rtc::DSCP_AF31));
+ EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
+ EXPECT_EQ(rtc::DSCP_AF31, dscp);
+ rtc::scoped_ptr<StunPort> stunport(
CreateStunPort(kLocalAddr1, nat_socket_factory1()));
- EXPECT_EQ(0, stunport->SetOption(talk_base::Socket::OPT_DSCP,
- talk_base::DSCP_AF41));
- EXPECT_EQ(0, stunport->GetOption(talk_base::Socket::OPT_DSCP, &dscp));
- EXPECT_EQ(talk_base::DSCP_AF41, dscp);
- talk_base::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
+ EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
+ rtc::DSCP_AF41));
+ EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
+ EXPECT_EQ(rtc::DSCP_AF41, dscp);
+ rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
// Socket is created in PrepareAddress.
turnport1->PrepareAddress();
- EXPECT_EQ(0, turnport1->SetOption(talk_base::Socket::OPT_DSCP,
- talk_base::DSCP_CS7));
- EXPECT_EQ(0, turnport1->GetOption(talk_base::Socket::OPT_DSCP, &dscp));
- EXPECT_EQ(talk_base::DSCP_CS7, dscp);
+ EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
+ rtc::DSCP_CS7));
+ EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
+ EXPECT_EQ(rtc::DSCP_CS7, dscp);
// This will verify correct value returned without the socket.
- talk_base::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
+ rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
- EXPECT_EQ(0, turnport2->SetOption(talk_base::Socket::OPT_DSCP,
- talk_base::DSCP_CS6));
- EXPECT_EQ(0, turnport2->GetOption(talk_base::Socket::OPT_DSCP, &dscp));
- EXPECT_EQ(talk_base::DSCP_CS6, dscp);
+ EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
+ rtc::DSCP_CS6));
+ EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
+ EXPECT_EQ(rtc::DSCP_CS6, dscp);
}
// Test sending STUN messages in GICE format.
TEST_F(PortTest, TestSendStunMessageAsGice) {
- talk_base::scoped_ptr<TestPort> lport(
+ rtc::scoped_ptr<TestPort> lport(
CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
- talk_base::scoped_ptr<TestPort> rport(
+ rtc::scoped_ptr<TestPort> rport(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
lport->SetIceProtocolType(ICEPROTO_GOOGLE);
rport->SetIceProtocolType(ICEPROTO_GOOGLE);
@@ -1360,7 +1362,7 @@
EXPECT_TRUE(msg->GetByteString(STUN_ATTR_FINGERPRINT) == NULL);
// Save a copy of the BINDING-REQUEST for use below.
- talk_base::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
+ rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
// Respond with a BINDING-RESPONSE.
rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
@@ -1407,9 +1409,9 @@
// Test sending STUN messages in ICE format.
TEST_F(PortTest, TestSendStunMessageAsIce) {
- talk_base::scoped_ptr<TestPort> lport(
+ rtc::scoped_ptr<TestPort> lport(
CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
- talk_base::scoped_ptr<TestPort> rport(
+ rtc::scoped_ptr<TestPort> rport(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
lport->SetIceProtocolType(ICEPROTO_RFC5245);
lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
@@ -1458,7 +1460,7 @@
ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
// Save a copy of the BINDING-REQUEST for use below.
- talk_base::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
+ rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
// Respond with a BINDING-RESPONSE.
rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
@@ -1549,9 +1551,9 @@
}
TEST_F(PortTest, TestUseCandidateAttribute) {
- talk_base::scoped_ptr<TestPort> lport(
+ rtc::scoped_ptr<TestPort> lport(
CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
- talk_base::scoped_ptr<TestPort> rport(
+ rtc::scoped_ptr<TestPort> rport(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
lport->SetIceProtocolType(ICEPROTO_RFC5245);
lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
@@ -1580,13 +1582,13 @@
// Test handling STUN messages in GICE format.
TEST_F(PortTest, TestHandleStunMessageAsGice) {
// Our port will act as the "remote" port.
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_GOOGLE);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST from local to remote with valid GICE username and no M-I.
@@ -1647,13 +1649,13 @@
// Test handling STUN messages in ICE format.
TEST_F(PortTest, TestHandleStunMessageAsIce) {
// Our port will act as the "remote" port.
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_RFC5245);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST from local to remote with valid ICE username,
@@ -1700,13 +1702,13 @@
// ICEPROTO_RFC5245 mode after successfully handling the message.
TEST_F(PortTest, TestHandleStunMessageAsIceInHybridMode) {
// Our port will act as the "remote" port.
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_HYBRID);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST from local to remote with valid ICE username,
@@ -1727,13 +1729,13 @@
// ICEPROTO_GOOGLE mode after successfully handling the message.
TEST_F(PortTest, TestHandleStunMessageAsGiceInHybridMode) {
// Our port will act as the "remote" port.
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_HYBRID);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST from local to remote with valid GICE username and no M-I.
@@ -1751,13 +1753,13 @@
// in that mode.
TEST_F(PortTest, TestHandleStunMessageAsGiceInIceMode) {
// Our port will act as the "remote" port.
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_RFC5245);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST from local to remote with valid GICE username and no M-I.
@@ -1773,13 +1775,13 @@
// Tests handling of GICE binding requests with missing or incorrect usernames.
TEST_F(PortTest, TestHandleStunMessageAsGiceBadUsername) {
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_GOOGLE);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST with no username.
@@ -1832,13 +1834,13 @@
// Tests handling of ICE binding requests with missing or incorrect usernames.
TEST_F(PortTest, TestHandleStunMessageAsIceBadUsername) {
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_RFC5245);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST with no username.
@@ -1902,13 +1904,13 @@
// Test handling STUN messages (as ICE) with missing or malformed M-I.
TEST_F(PortTest, TestHandleStunMessageAsIceBadMessageIntegrity) {
// Our port will act as the "remote" port.
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_RFC5245);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST from local to remote with valid ICE username and
@@ -1944,13 +1946,13 @@
// Test handling STUN messages (as ICE) with missing or malformed FINGERPRINT.
TEST_F(PortTest, TestHandleStunMessageAsIceBadFingerprint) {
// Our port will act as the "remote" port.
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
port->SetIceProtocolType(ICEPROTO_RFC5245);
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
// BINDING-REQUEST from local to remote with valid ICE username and
@@ -2011,16 +2013,16 @@
// Test handling of STUN binding indication messages (as ICE). STUN binding
// indications are allowed only to the connection which is in read mode.
TEST_F(PortTest, TestHandleStunBindingIndication) {
- talk_base::scoped_ptr<TestPort> lport(
+ rtc::scoped_ptr<TestPort> lport(
CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
lport->SetIceProtocolType(ICEPROTO_RFC5245);
lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
lport->SetIceTiebreaker(kTiebreaker1);
// Verifying encoding and decoding STUN indication message.
- talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
- talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
- talk_base::SocketAddress addr(kLocalAddr1);
+ rtc::scoped_ptr<IceMessage> in_msg, out_msg;
+ rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
+ rtc::SocketAddress addr(kLocalAddr1);
std::string username;
in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
@@ -2034,7 +2036,7 @@
// Verify connection can handle STUN indication and updates
// last_ping_received.
- talk_base::scoped_ptr<TestPort> rport(
+ rtc::scoped_ptr<TestPort> rport(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
rport->SetIceProtocolType(ICEPROTO_RFC5245);
rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
@@ -2057,21 +2059,21 @@
// Send rport binding request to lport.
lconn->OnReadPacket(rport->last_stun_buf()->Data(),
rport->last_stun_buf()->Length(),
- talk_base::PacketTime());
+ rtc::PacketTime());
ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
uint32 last_ping_received1 = lconn->last_ping_received();
// Adding a delay of 100ms.
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
// Pinging lconn using stun indication message.
- lconn->OnReadPacket(buf->Data(), buf->Length(), talk_base::PacketTime());
+ lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
uint32 last_ping_received2 = lconn->last_ping_received();
EXPECT_GT(last_ping_received2, last_ping_received1);
}
TEST_F(PortTest, TestComputeCandidatePriority) {
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr1, "name", "pass"));
port->set_type_preference(90);
port->set_component(177);
@@ -2107,13 +2109,13 @@
}
TEST_F(PortTest, TestPortProxyProperties) {
- talk_base::scoped_ptr<TestPort> port(
+ rtc::scoped_ptr<TestPort> port(
CreateTestPort(kLocalAddr1, "name", "pass"));
port->SetIceRole(cricket::ICEROLE_CONTROLLING);
port->SetIceTiebreaker(kTiebreaker1);
// Create a proxy port.
- talk_base::scoped_ptr<PortProxy> proxy(new PortProxy());
+ rtc::scoped_ptr<PortProxy> proxy(new PortProxy());
proxy->set_impl(port.get());
EXPECT_EQ(port->Type(), proxy->Type());
EXPECT_EQ(port->Network(), proxy->Network());
@@ -2124,7 +2126,7 @@
// In the case of shared socket, one port may be shared by local and stun.
// Test that candidates with different types will have different foundation.
TEST_F(PortTest, TestFoundation) {
- talk_base::scoped_ptr<TestPort> testport(
+ rtc::scoped_ptr<TestPort> testport(
CreateTestPort(kLocalAddr1, "name", "pass"));
testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
LOCAL_PORT_TYPE,
@@ -2138,21 +2140,21 @@
// This test verifies the foundation of different types of ICE candidates.
TEST_F(PortTest, TestCandidateFoundation) {
- talk_base::scoped_ptr<talk_base::NATServer> nat_server(
+ rtc::scoped_ptr<rtc::NATServer> nat_server(
CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
- talk_base::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
+ rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
udpport1->PrepareAddress();
- talk_base::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
+ rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
udpport2->PrepareAddress();
EXPECT_EQ(udpport1->Candidates()[0].foundation(),
udpport2->Candidates()[0].foundation());
- talk_base::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
+ rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
tcpport1->PrepareAddress();
- talk_base::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
+ rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
tcpport2->PrepareAddress();
EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
tcpport2->Candidates()[0].foundation());
- talk_base::scoped_ptr<Port> stunport(
+ rtc::scoped_ptr<Port> stunport(
CreateStunPort(kLocalAddr1, nat_socket_factory1()));
stunport->PrepareAddress();
ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
@@ -2165,7 +2167,7 @@
EXPECT_NE(udpport2->Candidates()[0].foundation(),
stunport->Candidates()[0].foundation());
// Verify GTURN candidate foundation.
- talk_base::scoped_ptr<RelayPort> relayport(
+ rtc::scoped_ptr<RelayPort> relayport(
CreateGturnPort(kLocalAddr1));
relayport->AddServerAddress(
cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
@@ -2176,7 +2178,7 @@
EXPECT_NE(udpport2->Candidates()[0].foundation(),
relayport->Candidates()[0].foundation());
// Verifying TURN candidate foundation.
- talk_base::scoped_ptr<Port> turnport1(CreateTurnPort(
+ rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
turnport1->PrepareAddress();
ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
@@ -2186,7 +2188,7 @@
turnport1->Candidates()[0].foundation());
EXPECT_NE(stunport->Candidates()[0].foundation(),
turnport1->Candidates()[0].foundation());
- talk_base::scoped_ptr<Port> turnport2(CreateTurnPort(
+ rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
turnport2->PrepareAddress();
ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
@@ -2197,8 +2199,8 @@
SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
TestTurnServer turn_server2(
- talk_base::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
- talk_base::scoped_ptr<Port> turnport3(CreateTurnPort(
+ rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
+ rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
kTurnUdpIntAddr2));
turnport3->PrepareAddress();
@@ -2210,16 +2212,16 @@
// This test verifies the related addresses of different types of
// ICE candiates.
TEST_F(PortTest, TestCandidateRelatedAddress) {
- talk_base::scoped_ptr<talk_base::NATServer> nat_server(
+ rtc::scoped_ptr<rtc::NATServer> nat_server(
CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
- talk_base::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
+ rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
udpport->PrepareAddress();
// For UDPPort, related address will be empty.
EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
// Testing related address for stun candidates.
// For stun candidate related address must be equal to the base
// socket address.
- talk_base::scoped_ptr<StunPort> stunport(
+ rtc::scoped_ptr<StunPort> stunport(
CreateStunPort(kLocalAddr1, nat_socket_factory1()));
stunport->PrepareAddress();
ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
@@ -2232,18 +2234,18 @@
// Verifying the related address for the GTURN candidates.
// NOTE: In case of GTURN related address will be equal to the mapped
// address, but address(mapped) will not be XOR.
- talk_base::scoped_ptr<RelayPort> relayport(
+ rtc::scoped_ptr<RelayPort> relayport(
CreateGturnPort(kLocalAddr1));
relayport->AddServerAddress(
cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
relayport->PrepareAddress();
ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
// For Gturn related address is set to "0.0.0.0:0"
- EXPECT_EQ(talk_base::SocketAddress(),
+ EXPECT_EQ(rtc::SocketAddress(),
relayport->Candidates()[0].related_address());
// Verifying the related address for TURN candidate.
// For TURN related address must be equal to the mapped address.
- talk_base::scoped_ptr<Port> turnport(CreateTurnPort(
+ rtc::scoped_ptr<Port> turnport(CreateTurnPort(
kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
turnport->PrepareAddress();
ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
@@ -2264,10 +2266,10 @@
// Test the Connection priority is calculated correctly.
TEST_F(PortTest, TestConnectionPriority) {
- talk_base::scoped_ptr<TestPort> lport(
+ rtc::scoped_ptr<TestPort> lport(
CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
- talk_base::scoped_ptr<TestPort> rport(
+ rtc::scoped_ptr<TestPort> rport(
CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
lport->set_component(123);
@@ -2326,7 +2328,7 @@
// Data should be unsendable until the connection is accepted.
char data[] = "abcd";
int data_size = ARRAY_SIZE(data);
- talk_base::PacketOptions options;
+ rtc::PacketOptions options;
EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
// Accept the connection to return the binding response, transition to
@@ -2403,7 +2405,7 @@
kLocalAddr1, "lfrag", "lpass", cricket::ICEPROTO_RFC5245,
cricket::ICEROLE_CONTROLLING, kTiebreaker1);
- talk_base::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
+ rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
kLocalAddr2, "rfrag", "rpass", cricket::ICEPROTO_RFC5245,
cricket::ICEROLE_CONTROLLED, kTiebreaker2));
// Setup TestChannel. This behaves like FULL mode client.
@@ -2437,14 +2439,14 @@
// But we need a connection to send a response message.
ice_lite_port->CreateConnection(
ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
- talk_base::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
+ rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
ice_lite_port->SendBindingResponse(
request.get(), ice_full_port->Candidates()[0].address());
// Feeding the respone message from litemode to the full mode connection.
ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
ice_lite_port->last_stun_buf()->Length(),
- talk_base::PacketTime());
+ rtc::PacketTime());
// Verifying full mode connection becomes writable from the response.
EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
kTimeout);
@@ -2482,7 +2484,7 @@
ConnectAndDisconnectChannels(&ch1, &ch2);
// After the connection is destroyed, the port should not be destroyed.
- talk_base::Thread::Current()->ProcessMessages(kTimeout);
+ rtc::Thread::Current()->ProcessMessages(kTimeout);
EXPECT_FALSE(destroyed());
}
diff --git a/p2p/base/portallocator.h b/p2p/base/portallocator.h
index e2cb3fd..5bc389e 100644
--- a/p2p/base/portallocator.h
+++ b/p2p/base/portallocator.h
@@ -31,10 +31,10 @@
#include <string>
#include <vector>
-#include "talk/base/helpers.h"
-#include "talk/base/proxyinfo.h"
-#include "talk/base/sigslot.h"
#include "talk/p2p/base/portinterface.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/proxyinfo.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
@@ -44,16 +44,18 @@
// Clients can override this class to control port allocation, including
// what kinds of ports are allocated.
-const uint32 PORTALLOCATOR_DISABLE_UDP = 0x01;
-const uint32 PORTALLOCATOR_DISABLE_STUN = 0x02;
-const uint32 PORTALLOCATOR_DISABLE_RELAY = 0x04;
-const uint32 PORTALLOCATOR_DISABLE_TCP = 0x08;
-const uint32 PORTALLOCATOR_ENABLE_SHAKER = 0x10;
-const uint32 PORTALLOCATOR_ENABLE_BUNDLE = 0x20;
-const uint32 PORTALLOCATOR_ENABLE_IPV6 = 0x40;
-const uint32 PORTALLOCATOR_ENABLE_SHARED_UFRAG = 0x80;
-const uint32 PORTALLOCATOR_ENABLE_SHARED_SOCKET = 0x100;
-const uint32 PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE = 0x200;
+enum {
+ PORTALLOCATOR_DISABLE_UDP = 0x01,
+ PORTALLOCATOR_DISABLE_STUN = 0x02,
+ PORTALLOCATOR_DISABLE_RELAY = 0x04,
+ PORTALLOCATOR_DISABLE_TCP = 0x08,
+ PORTALLOCATOR_ENABLE_SHAKER = 0x10,
+ PORTALLOCATOR_ENABLE_BUNDLE = 0x20,
+ PORTALLOCATOR_ENABLE_IPV6 = 0x40,
+ PORTALLOCATOR_ENABLE_SHARED_UFRAG = 0x80,
+ PORTALLOCATOR_ENABLE_SHARED_SOCKET = 0x100,
+ PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE = 0x200,
+};
const uint32 kDefaultPortAllocatorFlags = 0;
@@ -62,6 +64,15 @@
// internal. Less than 20ms is not acceptable. We choose 50ms as our default.
const uint32 kMinimumStepDelay = 50;
+// CF = CANDIDATE FILTER
+enum {
+ CF_NONE = 0x0,
+ CF_HOST = 0x1,
+ CF_REFLEXIVE = 0x2,
+ CF_RELAY = 0x4,
+ CF_ALL = 0x7,
+};
+
class PortAllocatorSessionMuxer;
class PortAllocatorSession : public sigslot::has_slots<> {
@@ -117,7 +128,8 @@
min_port_(0),
max_port_(0),
step_delay_(kDefaultStepDelay),
- allow_tcp_listen_(true) {
+ allow_tcp_listen_(true),
+ candidate_filter_(CF_ALL) {
// This will allow us to have old behavior on non webrtc clients.
}
virtual ~PortAllocator();
@@ -136,8 +148,8 @@
void set_flags(uint32 flags) { flags_ = flags; }
const std::string& user_agent() const { return agent_; }
- const talk_base::ProxyInfo& proxy() const { return proxy_; }
- void set_proxy(const std::string& agent, const talk_base::ProxyInfo& proxy) {
+ const rtc::ProxyInfo& proxy() const { return proxy_; }
+ void set_proxy(const std::string& agent, const rtc::ProxyInfo& proxy) {
agent_ = agent;
proxy_ = proxy;
}
@@ -157,7 +169,6 @@
uint32 step_delay() const { return step_delay_; }
void set_step_delay(uint32 delay) {
- ASSERT(delay >= kMinimumStepDelay);
step_delay_ = delay;
}
@@ -166,6 +177,13 @@
allow_tcp_listen_ = allow_tcp_listen;
}
+ uint32 candidate_filter() { return candidate_filter_; }
+ bool set_candidate_filter(uint32 filter) {
+ // TODO(mallinath) - Do transition check?
+ candidate_filter_ = filter;
+ return true;
+ }
+
protected:
virtual PortAllocatorSession* CreateSessionInternal(
const std::string& content_name,
@@ -177,12 +195,13 @@
uint32 flags_;
std::string agent_;
- talk_base::ProxyInfo proxy_;
+ rtc::ProxyInfo proxy_;
int min_port_;
int max_port_;
uint32 step_delay_;
SessionMuxerMap muxers_;
bool allow_tcp_listen_;
+ uint32 candidate_filter_;
};
} // namespace cricket
diff --git a/p2p/base/portallocatorsessionproxy.cc b/p2p/base/portallocatorsessionproxy.cc
index d804bdc..a6c8065 100644
--- a/p2p/base/portallocatorsessionproxy.cc
+++ b/p2p/base/portallocatorsessionproxy.cc
@@ -27,9 +27,9 @@
#include "talk/p2p/base/portallocatorsessionproxy.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/portallocator.h"
#include "talk/p2p/base/portproxy.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -38,11 +38,11 @@
MSG_SEND_ALLOCATED_PORTS,
};
-typedef talk_base::TypedMessageData<PortAllocatorSessionProxy*> ProxyObjData;
+typedef rtc::TypedMessageData<PortAllocatorSessionProxy*> ProxyObjData;
PortAllocatorSessionMuxer::PortAllocatorSessionMuxer(
PortAllocatorSession* session)
- : worker_thread_(talk_base::Thread::Current()),
+ : worker_thread_(rtc::Thread::Current()),
session_(session),
candidate_done_signal_received_(false) {
session_->SignalPortReady.connect(
@@ -114,7 +114,7 @@
}
}
-void PortAllocatorSessionMuxer::OnMessage(talk_base::Message *pmsg) {
+void PortAllocatorSessionMuxer::OnMessage(rtc::Message *pmsg) {
ProxyObjData* proxy = static_cast<ProxyObjData*>(pmsg->pdata);
switch (pmsg->message_id) {
case MSG_SEND_ALLOCATION_DONE:
diff --git a/p2p/base/portallocatorsessionproxy.h b/p2p/base/portallocatorsessionproxy.h
index 990ea8a..659c730 100644
--- a/p2p/base/portallocatorsessionproxy.h
+++ b/p2p/base/portallocatorsessionproxy.h
@@ -42,7 +42,7 @@
// deleted upon receiving SignalDestroyed signal. This class is used when
// PORTALLOCATOR_ENABLE_BUNDLE flag is set.
-class PortAllocatorSessionMuxer : public talk_base::MessageHandler,
+class PortAllocatorSessionMuxer : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
explicit PortAllocatorSessionMuxer(PortAllocatorSession* session);
@@ -59,16 +59,16 @@
sigslot::signal1<PortAllocatorSessionMuxer*> SignalDestroyed;
private:
- virtual void OnMessage(talk_base::Message *pmsg);
+ virtual void OnMessage(rtc::Message *pmsg);
void OnSessionProxyDestroyed(PortAllocatorSession* proxy);
void SendAllocationDone_w(PortAllocatorSessionProxy* proxy);
void SendAllocatedPorts_w(PortAllocatorSessionProxy* proxy);
// Port will be deleted when SignalDestroyed received, otherwise delete
// happens when PortAllocatorSession dtor is called.
- talk_base::Thread* worker_thread_;
+ rtc::Thread* worker_thread_;
std::vector<PortInterface*> ports_;
- talk_base::scoped_ptr<PortAllocatorSession> session_;
+ rtc::scoped_ptr<PortAllocatorSession> session_;
std::vector<PortAllocatorSessionProxy*> session_proxies_;
bool candidate_done_signal_received_;
};
diff --git a/p2p/base/portallocatorsessionproxy_unittest.cc b/p2p/base/portallocatorsessionproxy_unittest.cc
index 689fb96..3a69b46 100644
--- a/p2p/base/portallocatorsessionproxy_unittest.cc
+++ b/p2p/base/portallocatorsessionproxy_unittest.cc
@@ -27,13 +27,13 @@
#include <vector>
-#include "talk/base/fakenetwork.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/portallocatorsessionproxy.h"
#include "talk/p2p/client/basicportallocator.h"
#include "talk/p2p/client/fakeportallocator.h"
+#include "webrtc/base/fakenetwork.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/thread.h"
using cricket::Candidate;
using cricket::PortAllocatorSession;
@@ -102,10 +102,10 @@
class PortAllocatorSessionProxyTest : public testing::Test {
public:
PortAllocatorSessionProxyTest()
- : socket_factory_(talk_base::Thread::Current()),
- allocator_(talk_base::Thread::Current(), NULL),
+ : socket_factory_(rtc::Thread::Current()),
+ allocator_(rtc::Thread::Current(), NULL),
session_(new cricket::FakePortAllocatorSession(
- talk_base::Thread::Current(), &socket_factory_,
+ rtc::Thread::Current(), &socket_factory_,
"test content", 1,
kIceUfrag0, kIcePwd0)),
session_muxer_(new PortAllocatorSessionMuxer(session_)) {
@@ -125,7 +125,7 @@
}
protected:
- talk_base::BasicPacketSocketFactory socket_factory_;
+ rtc::BasicPacketSocketFactory socket_factory_;
cricket::FakePortAllocator allocator_;
cricket::FakePortAllocatorSession* session_;
// Muxer object will be delete itself after all registered session proxies
diff --git a/p2p/base/portinterface.h b/p2p/base/portinterface.h
index 5ebf653..8cab5b4 100644
--- a/p2p/base/portinterface.h
+++ b/p2p/base/portinterface.h
@@ -30,10 +30,10 @@
#include <string>
-#include "talk/base/socketaddress.h"
#include "talk/p2p/base/transport.h"
+#include "webrtc/base/socketaddress.h"
-namespace talk_base {
+namespace rtc {
class Network;
struct PacketOptions;
}
@@ -58,7 +58,7 @@
virtual ~PortInterface() {}
virtual const std::string& Type() const = 0;
- virtual talk_base::Network* Network() const = 0;
+ virtual rtc::Network* Network() const = 0;
virtual void SetIceProtocolType(IceProtocolType protocol) = 0;
virtual IceProtocolType IceProtocol() const = 0;
@@ -81,7 +81,7 @@
// Returns the connection to the given address or NULL if none exists.
virtual Connection* GetConnection(
- const talk_base::SocketAddress& remote_addr) = 0;
+ const rtc::SocketAddress& remote_addr) = 0;
// Creates a new connection to the given address.
enum CandidateOrigin { ORIGIN_THIS_PORT, ORIGIN_OTHER_PORT, ORIGIN_MESSAGE };
@@ -89,8 +89,8 @@
const Candidate& remote_candidate, CandidateOrigin origin) = 0;
// Functions on the underlying socket(s).
- virtual int SetOption(talk_base::Socket::Option opt, int value) = 0;
- virtual int GetOption(talk_base::Socket::Option opt, int* value) = 0;
+ virtual int SetOption(rtc::Socket::Option opt, int value) = 0;
+ virtual int GetOption(rtc::Socket::Option opt, int* value) = 0;
virtual int GetError() = 0;
virtual const std::vector<Candidate>& Candidates() const = 0;
@@ -98,13 +98,13 @@
// Sends the given packet to the given address, provided that the address is
// that of a connection or an address that has sent to us already.
virtual int SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options, bool payload) = 0;
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options, bool payload) = 0;
// Indicates that we received a successful STUN binding request from an
// address that doesn't correspond to any current connection. To turn this
// into a real connection, call CreateConnection.
- sigslot::signal6<PortInterface*, const talk_base::SocketAddress&,
+ sigslot::signal6<PortInterface*, const rtc::SocketAddress&,
ProtocolType, IceMessage*, const std::string&,
bool> SignalUnknownAddress;
@@ -112,9 +112,9 @@
// these methods should be called as a response to SignalUnknownAddress.
// NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
virtual void SendBindingResponse(StunMessage* request,
- const talk_base::SocketAddress& addr) = 0;
+ const rtc::SocketAddress& addr) = 0;
virtual void SendBindingErrorResponse(
- StunMessage* request, const talk_base::SocketAddress& addr,
+ StunMessage* request, const rtc::SocketAddress& addr,
int error_code, const std::string& reason) = 0;
// Signaled when this port decides to delete itself because it no longer has
@@ -130,7 +130,7 @@
// through this port.
virtual void EnablePortPackets() = 0;
sigslot::signal4<PortInterface*, const char*, size_t,
- const talk_base::SocketAddress&> SignalReadPacket;
+ const rtc::SocketAddress&> SignalReadPacket;
virtual std::string ToString() const = 0;
diff --git a/p2p/base/portproxy.cc b/p2p/base/portproxy.cc
index 43bb747..841cd85 100644
--- a/p2p/base/portproxy.cc
+++ b/p2p/base/portproxy.cc
@@ -42,7 +42,7 @@
return impl_->Type();
}
-talk_base::Network* PortProxy::Network() const {
+rtc::Network* PortProxy::Network() const {
ASSERT(impl_ != NULL);
return impl_->Network();
}
@@ -96,20 +96,20 @@
int PortProxy::SendTo(const void* data,
size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload) {
ASSERT(impl_ != NULL);
return impl_->SendTo(data, size, addr, options, payload);
}
-int PortProxy::SetOption(talk_base::Socket::Option opt,
+int PortProxy::SetOption(rtc::Socket::Option opt,
int value) {
ASSERT(impl_ != NULL);
return impl_->SetOption(opt, value);
}
-int PortProxy::GetOption(talk_base::Socket::Option opt,
+int PortProxy::GetOption(rtc::Socket::Option opt,
int* value) {
ASSERT(impl_ != NULL);
return impl_->GetOption(opt, value);
@@ -126,19 +126,19 @@
}
void PortProxy::SendBindingResponse(
- StunMessage* request, const talk_base::SocketAddress& addr) {
+ StunMessage* request, const rtc::SocketAddress& addr) {
ASSERT(impl_ != NULL);
impl_->SendBindingResponse(request, addr);
}
Connection* PortProxy::GetConnection(
- const talk_base::SocketAddress& remote_addr) {
+ const rtc::SocketAddress& remote_addr) {
ASSERT(impl_ != NULL);
return impl_->GetConnection(remote_addr);
}
void PortProxy::SendBindingErrorResponse(
- StunMessage* request, const talk_base::SocketAddress& addr,
+ StunMessage* request, const rtc::SocketAddress& addr,
int error_code, const std::string& reason) {
ASSERT(impl_ != NULL);
impl_->SendBindingErrorResponse(request, addr, error_code, reason);
@@ -156,7 +156,7 @@
void PortProxy::OnUnknownAddress(
PortInterface *port,
- const talk_base::SocketAddress &addr,
+ const rtc::SocketAddress &addr,
ProtocolType proto,
IceMessage *stun_msg,
const std::string &remote_username,
diff --git a/p2p/base/portproxy.h b/p2p/base/portproxy.h
index d138dc3..8c28223 100644
--- a/p2p/base/portproxy.h
+++ b/p2p/base/portproxy.h
@@ -28,10 +28,10 @@
#ifndef TALK_P2P_BASE_PORTPROXY_H_
#define TALK_P2P_BASE_PORTPROXY_H_
-#include "talk/base/sigslot.h"
#include "talk/p2p/base/portinterface.h"
+#include "webrtc/base/sigslot.h"
-namespace talk_base {
+namespace rtc {
class Network;
}
@@ -46,7 +46,7 @@
void set_impl(PortInterface* port);
virtual const std::string& Type() const;
- virtual talk_base::Network* Network() const;
+ virtual rtc::Network* Network() const;
virtual void SetIceProtocolType(IceProtocolType protocol);
virtual IceProtocolType IceProtocol() const;
@@ -65,22 +65,22 @@
virtual Connection* CreateConnection(const Candidate& remote_candidate,
CandidateOrigin origin);
virtual Connection* GetConnection(
- const talk_base::SocketAddress& remote_addr);
+ const rtc::SocketAddress& remote_addr);
virtual int SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
- virtual int GetOption(talk_base::Socket::Option opt, int* value);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
+ virtual int GetOption(rtc::Socket::Option opt, int* value);
virtual int GetError();
virtual const std::vector<Candidate>& Candidates() const;
virtual void SendBindingResponse(StunMessage* request,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
virtual void SendBindingErrorResponse(
- StunMessage* request, const talk_base::SocketAddress& addr,
+ StunMessage* request, const rtc::SocketAddress& addr,
int error_code, const std::string& reason);
virtual void EnablePortPackets();
@@ -88,7 +88,7 @@
private:
void OnUnknownAddress(PortInterface *port,
- const talk_base::SocketAddress &addr,
+ const rtc::SocketAddress &addr,
ProtocolType proto,
IceMessage *stun_msg,
const std::string &remote_username,
diff --git a/p2p/base/pseudotcp.cc b/p2p/base/pseudotcp.cc
index 3925637..9a944f0 100644
--- a/p2p/base/pseudotcp.cc
+++ b/p2p/base/pseudotcp.cc
@@ -32,15 +32,15 @@
#include <set>
-#include "talk/base/basictypes.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socket.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/timeutils.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socket.h"
+#include "webrtc/base/stringutils.h"
+#include "webrtc/base/timeutils.h"
// The following logging is for detailed (packet-level) analysis only.
#define _DBG_NONE 0
@@ -151,23 +151,23 @@
//////////////////////////////////////////////////////////////////////
inline void long_to_bytes(uint32 val, void* buf) {
- *static_cast<uint32*>(buf) = talk_base::HostToNetwork32(val);
+ *static_cast<uint32*>(buf) = rtc::HostToNetwork32(val);
}
inline void short_to_bytes(uint16 val, void* buf) {
- *static_cast<uint16*>(buf) = talk_base::HostToNetwork16(val);
+ *static_cast<uint16*>(buf) = rtc::HostToNetwork16(val);
}
inline uint32 bytes_to_long(const void* buf) {
- return talk_base::NetworkToHost32(*static_cast<const uint32*>(buf));
+ return rtc::NetworkToHost32(*static_cast<const uint32*>(buf));
}
inline uint16 bytes_to_short(const void* buf) {
- return talk_base::NetworkToHost16(*static_cast<const uint16*>(buf));
+ return rtc::NetworkToHost16(*static_cast<const uint16*>(buf));
}
uint32 bound(uint32 lower, uint32 middle, uint32 upper) {
- return talk_base::_min(talk_base::_max(lower, middle), upper);
+ return rtc::_min(rtc::_max(lower, middle), upper);
}
//////////////////////////////////////////////////////////////////////
@@ -199,7 +199,7 @@
char buffer[256];
size_t len = 0;
for (int i = 0; i < S_NUM_STATS; ++i) {
- len += talk_base::sprintfn(buffer, ARRAY_SIZE(buffer), "%s%s:%d",
+ len += rtc::sprintfn(buffer, ARRAY_SIZE(buffer), "%s%s:%d",
(i == 0) ? "" : ",", STAT_NAMES[i], g_stats[i]);
g_stats[i] = 0;
}
@@ -214,9 +214,9 @@
uint32 PseudoTcp::Now() {
#if 0 // Use this to synchronize timers with logging timestamps (easier debug)
- return talk_base::TimeSince(StartTime());
+ return rtc::TimeSince(StartTime());
#else
- return talk_base::Time();
+ return rtc::Time();
#endif
}
@@ -301,7 +301,7 @@
return;
// Check if it's time to retransmit a segment
- if (m_rto_base && (talk_base::TimeDiff(m_rto_base + m_rx_rto, now) <= 0)) {
+ if (m_rto_base && (rtc::TimeDiff(m_rto_base + m_rx_rto, now) <= 0)) {
if (m_slist.empty()) {
ASSERT(false);
} else {
@@ -320,21 +320,21 @@
}
uint32 nInFlight = m_snd_nxt - m_snd_una;
- m_ssthresh = talk_base::_max(nInFlight / 2, 2 * m_mss);
+ m_ssthresh = rtc::_max(nInFlight / 2, 2 * m_mss);
//LOG(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
m_cwnd = m_mss;
// Back off retransmit timer. Note: the limit is lower when connecting.
uint32 rto_limit = (m_state < TCP_ESTABLISHED) ? DEF_RTO : MAX_RTO;
- m_rx_rto = talk_base::_min(rto_limit, m_rx_rto * 2);
+ m_rx_rto = rtc::_min(rto_limit, m_rx_rto * 2);
m_rto_base = now;
}
}
// Check if it's time to probe closed windows
if ((m_snd_wnd == 0)
- && (talk_base::TimeDiff(m_lastsend + m_rx_rto, now) <= 0)) {
- if (talk_base::TimeDiff(now, m_lastrecv) >= 15000) {
+ && (rtc::TimeDiff(m_lastsend + m_rx_rto, now) <= 0)) {
+ if (rtc::TimeDiff(now, m_lastrecv) >= 15000) {
closedown(ECONNABORTED);
return;
}
@@ -344,11 +344,11 @@
m_lastsend = now;
// back off retransmit timer
- m_rx_rto = talk_base::_min(MAX_RTO, m_rx_rto * 2);
+ m_rx_rto = rtc::_min(MAX_RTO, m_rx_rto * 2);
}
// Check if it's time to send delayed acks
- if (m_t_ack && (talk_base::TimeDiff(m_t_ack + m_ack_delay, now) <= 0)) {
+ if (m_t_ack && (rtc::TimeDiff(m_t_ack + m_ack_delay, now) <= 0)) {
packet(m_snd_nxt, 0, 0, 0);
}
@@ -436,21 +436,21 @@
}
size_t read = 0;
- talk_base::StreamResult result = m_rbuf.Read(buffer, len, &read, NULL);
+ rtc::StreamResult result = m_rbuf.Read(buffer, len, &read, NULL);
// If there's no data in |m_rbuf|.
- if (result == talk_base::SR_BLOCK) {
+ if (result == rtc::SR_BLOCK) {
m_bReadEnable = true;
m_error = EWOULDBLOCK;
return SOCKET_ERROR;
}
- ASSERT(result == talk_base::SR_SUCCESS);
+ ASSERT(result == rtc::SR_SUCCESS);
size_t available_space = 0;
m_rbuf.GetWriteRemaining(&available_space);
if (uint32(available_space) - m_rcv_wnd >=
- talk_base::_min<uint32>(m_rbuf_len / 2, m_mss)) {
+ rtc::_min<uint32>(m_rbuf_len / 2, m_mss)) {
// TODO(jbeda): !?! Not sure about this was closed business
bool bWasClosed = (m_rcv_wnd == 0);
m_rcv_wnd = static_cast<uint32>(available_space);
@@ -528,7 +528,7 @@
uint32 now = Now();
- talk_base::scoped_ptr<uint8[]> buffer(new uint8[MAX_PACKET]);
+ rtc::scoped_ptr<uint8[]> buffer(new uint8[MAX_PACKET]);
long_to_bytes(m_conv, buffer.get());
long_to_bytes(seq, buffer.get() + 4);
long_to_bytes(m_rcv_nxt, buffer.get() + 8);
@@ -544,10 +544,10 @@
if (len) {
size_t bytes_read = 0;
- talk_base::StreamResult result = m_sbuf.ReadOffset(
+ rtc::StreamResult result = m_sbuf.ReadOffset(
buffer.get() + HEADER_SIZE, len, offset, &bytes_read);
- UNUSED(result);
- ASSERT(result == talk_base::SR_SUCCESS);
+ RTC_UNUSED(result);
+ ASSERT(result == rtc::SR_SUCCESS);
ASSERT(static_cast<uint32>(bytes_read) == len);
}
@@ -631,20 +631,20 @@
nTimeout = DEFAULT_TIMEOUT;
if (m_t_ack) {
- nTimeout = talk_base::_min<int32>(nTimeout,
- talk_base::TimeDiff(m_t_ack + m_ack_delay, now));
+ nTimeout = rtc::_min<int32>(nTimeout,
+ rtc::TimeDiff(m_t_ack + m_ack_delay, now));
}
if (m_rto_base) {
- nTimeout = talk_base::_min<int32>(nTimeout,
- talk_base::TimeDiff(m_rto_base + m_rx_rto, now));
+ nTimeout = rtc::_min<int32>(nTimeout,
+ rtc::TimeDiff(m_rto_base + m_rx_rto, now));
}
if (m_snd_wnd == 0) {
- nTimeout = talk_base::_min<int32>(nTimeout, talk_base::TimeDiff(m_lastsend + m_rx_rto, now));
+ nTimeout = rtc::_min<int32>(nTimeout, rtc::TimeDiff(m_lastsend + m_rx_rto, now));
}
#if PSEUDO_KEEPALIVE
if (m_state == TCP_ESTABLISHED) {
- nTimeout = talk_base::_min<int32>(nTimeout,
- talk_base::TimeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3/2 : IDLE_PING), now));
+ nTimeout = rtc::_min<int32>(nTimeout,
+ rtc::TimeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3/2 : IDLE_PING), now));
}
#endif // PSEUDO_KEEPALIVE
return true;
@@ -717,7 +717,7 @@
if ((seg.ack > m_snd_una) && (seg.ack <= m_snd_nxt)) {
// Calculate round-trip time
if (seg.tsecr) {
- int32 rtt = talk_base::TimeDiff(now, seg.tsecr);
+ int32 rtt = rtc::TimeDiff(now, seg.tsecr);
if (rtt >= 0) {
if (m_rx_srtt == 0) {
m_rx_srtt = rtt;
@@ -730,7 +730,7 @@
m_rx_srtt = (7 * m_rx_srtt + rtt) / 8;
}
m_rx_rto = bound(MIN_RTO, m_rx_srtt +
- talk_base::_max<uint32>(1, 4 * m_rx_rttvar), MAX_RTO);
+ rtc::_max<uint32>(1, 4 * m_rx_rttvar), MAX_RTO);
#if _DEBUGMSG >= _DBG_VERBOSE
LOG(LS_INFO) << "rtt: " << rtt
<< " srtt: " << m_rx_srtt
@@ -767,7 +767,7 @@
if (m_dup_acks >= 3) {
if (m_snd_una >= m_recover) { // NewReno
uint32 nInFlight = m_snd_nxt - m_snd_una;
- m_cwnd = talk_base::_min(m_ssthresh, nInFlight + m_mss); // (Fast Retransmit)
+ m_cwnd = rtc::_min(m_ssthresh, nInFlight + m_mss); // (Fast Retransmit)
#if _DEBUGMSG >= _DBG_NORMAL
LOG(LS_INFO) << "exit recovery";
#endif // _DEBUGMSG
@@ -780,7 +780,7 @@
closedown(ECONNABORTED);
return false;
}
- m_cwnd += m_mss - talk_base::_min(nAcked, m_cwnd);
+ m_cwnd += m_mss - rtc::_min(nAcked, m_cwnd);
}
} else {
m_dup_acks = 0;
@@ -788,7 +788,7 @@
if (m_cwnd < m_ssthresh) {
m_cwnd += m_mss;
} else {
- m_cwnd += talk_base::_max<uint32>(1, m_mss * m_mss / m_cwnd);
+ m_cwnd += rtc::_max<uint32>(1, m_mss * m_mss / m_cwnd);
}
}
} else if (seg.ack == m_snd_una) {
@@ -811,7 +811,7 @@
}
m_recover = m_snd_nxt;
uint32 nInFlight = m_snd_nxt - m_snd_una;
- m_ssthresh = talk_base::_max(nInFlight / 2, 2 * m_mss);
+ m_ssthresh = rtc::_max(nInFlight / 2, 2 * m_mss);
//LOG(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
m_cwnd = m_ssthresh + 3 * m_mss;
} else if (m_dup_acks > 3) {
@@ -908,10 +908,10 @@
} else {
uint32 nOffset = seg.seq - m_rcv_nxt;
- talk_base::StreamResult result = m_rbuf.WriteOffset(seg.data, seg.len,
+ rtc::StreamResult result = m_rbuf.WriteOffset(seg.data, seg.len,
nOffset, NULL);
- ASSERT(result == talk_base::SR_SUCCESS);
- UNUSED(result);
+ ASSERT(result == rtc::SR_SUCCESS);
+ RTC_UNUSED(result);
if (seg.seq == m_rcv_nxt) {
m_rbuf.ConsumeWriteBuffer(seg.len);
@@ -969,7 +969,7 @@
return false;
}
- uint32 nTransmit = talk_base::_min(seg->len, m_mss);
+ uint32 nTransmit = rtc::_min(seg->len, m_mss);
while (true) {
uint32 seq = seg->seq;
@@ -1035,13 +1035,13 @@
void PseudoTcp::attemptSend(SendFlags sflags) {
uint32 now = Now();
- if (talk_base::TimeDiff(now, m_lastsend) > static_cast<long>(m_rx_rto)) {
+ if (rtc::TimeDiff(now, m_lastsend) > static_cast<long>(m_rx_rto)) {
m_cwnd = m_mss;
}
#if _DEBUGMSG
bool bFirst = true;
- UNUSED(bFirst);
+ RTC_UNUSED(bFirst);
#endif // _DEBUGMSG
while (true) {
@@ -1049,14 +1049,14 @@
if ((m_dup_acks == 1) || (m_dup_acks == 2)) { // Limited Transmit
cwnd += m_dup_acks * m_mss;
}
- uint32 nWindow = talk_base::_min(m_snd_wnd, cwnd);
+ uint32 nWindow = rtc::_min(m_snd_wnd, cwnd);
uint32 nInFlight = m_snd_nxt - m_snd_una;
uint32 nUseable = (nInFlight < nWindow) ? (nWindow - nInFlight) : 0;
size_t snd_buffered = 0;
m_sbuf.GetBuffered(&snd_buffered);
uint32 nAvailable =
- talk_base::_min(static_cast<uint32>(snd_buffered) - nInFlight, m_mss);
+ rtc::_min(static_cast<uint32>(snd_buffered) - nInFlight, m_mss);
if (nAvailable > nUseable) {
if (nUseable * 4 < nWindow) {
@@ -1153,8 +1153,8 @@
LOG(LS_INFO) << "Adjusting mss to " << m_mss << " bytes";
#endif // _DEBUGMSG
// Enforce minimums on ssthresh and cwnd
- m_ssthresh = talk_base::_max(m_ssthresh, 2 * m_mss);
- m_cwnd = talk_base::_max(m_cwnd, m_mss);
+ m_ssthresh = rtc::_max(m_ssthresh, 2 * m_mss);
+ m_cwnd = rtc::_max(m_cwnd, m_mss);
}
bool
@@ -1171,7 +1171,7 @@
void
PseudoTcp::queueConnectMessage() {
- talk_base::ByteBuffer buf(talk_base::ByteBuffer::ORDER_NETWORK);
+ rtc::ByteBuffer buf(rtc::ByteBuffer::ORDER_NETWORK);
buf.WriteUInt8(CTL_CONNECT);
if (m_support_wnd_scale) {
@@ -1189,7 +1189,7 @@
// See http://www.freesoft.org/CIE/Course/Section4/8.htm for
// parsing the options list.
- talk_base::ByteBuffer buf(data, len);
+ rtc::ByteBuffer buf(data, len);
while (buf.Length()) {
uint8 kind = TCP_OPT_EOL;
buf.ReadUInt8(&kind);
@@ -1204,7 +1204,7 @@
// Length of this option.
ASSERT(len != 0);
- UNUSED(len);
+ RTC_UNUSED(len);
uint8 opt_len = 0;
buf.ReadUInt8(&opt_len);
@@ -1278,7 +1278,7 @@
// before connection is established or when peers are exchanging connect
// messages.
ASSERT(result);
- UNUSED(result);
+ RTC_UNUSED(result);
m_rbuf_len = new_size;
m_rwnd_scale = scale_factor;
m_ssthresh = new_size;
diff --git a/p2p/base/pseudotcp.h b/p2p/base/pseudotcp.h
index edd861b..46e9d3b 100644
--- a/p2p/base/pseudotcp.h
+++ b/p2p/base/pseudotcp.h
@@ -30,8 +30,8 @@
#include <list>
-#include "talk/base/basictypes.h"
-#include "talk/base/stream.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/stream.h"
namespace cricket {
@@ -219,13 +219,13 @@
RList m_rlist;
uint32 m_rbuf_len, m_rcv_nxt, m_rcv_wnd, m_lastrecv;
uint8 m_rwnd_scale; // Window scale factor.
- talk_base::FifoBuffer m_rbuf;
+ rtc::FifoBuffer m_rbuf;
// Outgoing data
SList m_slist;
uint32 m_sbuf_len, m_snd_nxt, m_snd_wnd, m_lastsend, m_snd_una;
uint8 m_swnd_scale; // Window scale factor.
- talk_base::FifoBuffer m_sbuf;
+ rtc::FifoBuffer m_sbuf;
// Maximum segment size, estimated protocol level, largest segment sent
uint32 m_mss, m_msslevel, m_largest, m_mtu_advise;
diff --git a/p2p/base/pseudotcp_unittest.cc b/p2p/base/pseudotcp_unittest.cc
index e18159e..d9435cf 100644
--- a/p2p/base/pseudotcp_unittest.cc
+++ b/p2p/base/pseudotcp_unittest.cc
@@ -27,13 +27,13 @@
#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/stream.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
#include "talk/p2p/base/pseudotcp.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timeutils.h"
using cricket::PseudoTcp;
@@ -57,7 +57,7 @@
};
class PseudoTcpTestBase : public testing::Test,
- public talk_base::MessageHandler,
+ public rtc::MessageHandler,
public cricket::IPseudoTcpNotify {
public:
PseudoTcpTestBase()
@@ -70,11 +70,11 @@
delay_(0),
loss_(0) {
// Set use of the test RNG to get predictable loss patterns.
- talk_base::SetRandomTestMode(true);
+ rtc::SetRandomTestMode(true);
}
~PseudoTcpTestBase() {
// Put it back for the next test.
- talk_base::SetRandomTestMode(false);
+ rtc::SetRandomTestMode(false);
}
void SetLocalMtu(int mtu) {
local_.NotifyMTU(mtu);
@@ -157,16 +157,16 @@
const char* buffer, size_t len) {
// Randomly drop the desired percentage of packets.
// Also drop packets that are larger than the configured MTU.
- if (talk_base::CreateRandomId() % 100 < static_cast<uint32>(loss_)) {
+ if (rtc::CreateRandomId() % 100 < static_cast<uint32>(loss_)) {
LOG(LS_VERBOSE) << "Randomly dropping packet, size=" << len;
} else if (len > static_cast<size_t>(
- talk_base::_min(local_mtu_, remote_mtu_))) {
+ rtc::_min(local_mtu_, remote_mtu_))) {
LOG(LS_VERBOSE) << "Dropping packet that exceeds path MTU, size=" << len;
} else {
int id = (tcp == &local_) ? MSG_RPACKET : MSG_LPACKET;
std::string packet(buffer, len);
- talk_base::Thread::Current()->PostDelayed(delay_, this, id,
- talk_base::WrapMessageData(packet));
+ rtc::Thread::Current()->PostDelayed(delay_, this, id,
+ rtc::WrapMessageData(packet));
}
return WR_SUCCESS;
}
@@ -176,23 +176,23 @@
void UpdateClock(PseudoTcp* tcp, uint32 message) {
long interval = 0; // NOLINT
tcp->GetNextClock(PseudoTcp::Now(), interval);
- interval = talk_base::_max<int>(interval, 0L); // sometimes interval is < 0
- talk_base::Thread::Current()->Clear(this, message);
- talk_base::Thread::Current()->PostDelayed(interval, this, message);
+ interval = rtc::_max<int>(interval, 0L); // sometimes interval is < 0
+ rtc::Thread::Current()->Clear(this, message);
+ rtc::Thread::Current()->PostDelayed(interval, this, message);
}
- virtual void OnMessage(talk_base::Message* message) {
+ virtual void OnMessage(rtc::Message* message) {
switch (message->message_id) {
case MSG_LPACKET: {
const std::string& s(
- talk_base::UseMessageData<std::string>(message->pdata));
+ rtc::UseMessageData<std::string>(message->pdata));
local_.NotifyPacket(s.c_str(), s.size());
UpdateLocalClock();
break;
}
case MSG_RPACKET: {
const std::string& s(
- talk_base::UseMessageData<std::string>(message->pdata));
+ rtc::UseMessageData<std::string>(message->pdata));
remote_.NotifyPacket(s.c_str(), s.size());
UpdateRemoteClock();
break;
@@ -213,8 +213,8 @@
PseudoTcpForTest local_;
PseudoTcpForTest remote_;
- talk_base::MemoryStream send_stream_;
- talk_base::MemoryStream recv_stream_;
+ rtc::MemoryStream send_stream_;
+ rtc::MemoryStream recv_stream_;
bool have_connected_;
bool have_disconnected_;
int local_mtu_;
@@ -238,13 +238,13 @@
// Prepare the receive stream.
recv_stream_.ReserveSize(size);
// Connect and wait until connected.
- start = talk_base::Time();
+ start = rtc::Time();
EXPECT_EQ(0, Connect());
EXPECT_TRUE_WAIT(have_connected_, kConnectTimeoutMs);
// Sending will start from OnTcpWriteable and complete when all data has
// been received.
EXPECT_TRUE_WAIT(have_disconnected_, kTransferTimeoutMs);
- elapsed = talk_base::TimeSince(start);
+ elapsed = rtc::TimeSince(start);
recv_stream_.GetSize(&received);
// Ensure we closed down OK and we got the right data.
// TODO: Ensure the errors are cleared properly.
@@ -308,7 +308,7 @@
do {
send_stream_.GetPosition(&position);
if (send_stream_.Read(block, sizeof(block), &tosend, NULL) !=
- talk_base::SR_EOS) {
+ rtc::SR_EOS) {
sent = local_.Send(block, tosend);
UpdateLocalClock();
if (sent != -1) {
@@ -326,8 +326,8 @@
}
private:
- talk_base::MemoryStream send_stream_;
- talk_base::MemoryStream recv_stream_;
+ rtc::MemoryStream send_stream_;
+ rtc::MemoryStream recv_stream_;
};
@@ -357,13 +357,13 @@
// Prepare the receive stream.
recv_stream_.ReserveSize(size);
// Connect and wait until connected.
- start = talk_base::Time();
+ start = rtc::Time();
EXPECT_EQ(0, Connect());
EXPECT_TRUE_WAIT(have_connected_, kConnectTimeoutMs);
// Sending will start from OnTcpWriteable and stop when the required
// number of iterations have completed.
EXPECT_TRUE_WAIT(have_disconnected_, kTransferTimeoutMs);
- elapsed = talk_base::TimeSince(start);
+ elapsed = rtc::TimeSince(start);
LOG(LS_INFO) << "Performed " << iterations << " pings in "
<< elapsed << " ms";
}
@@ -428,7 +428,7 @@
send_stream_.GetPosition(&position);
tosend = bytes_per_send_ ? bytes_per_send_ : sizeof(block);
if (send_stream_.Read(block, tosend, &tosend, NULL) !=
- talk_base::SR_EOS) {
+ rtc::SR_EOS) {
sent = sender_->Send(block, tosend);
UpdateLocalClock();
if (sent != -1) {
@@ -474,7 +474,7 @@
EXPECT_EQ(0, Connect());
EXPECT_TRUE_WAIT(have_connected_, kConnectTimeoutMs);
- talk_base::Thread::Current()->Post(this, MSG_WRITE);
+ rtc::Thread::Current()->Post(this, MSG_WRITE);
EXPECT_TRUE_WAIT(have_disconnected_, kTransferTimeoutMs);
ASSERT_EQ(2u, send_position_.size());
@@ -492,7 +492,7 @@
EXPECT_EQ(2 * estimated_recv_window, recv_position_[1]);
}
- virtual void OnMessage(talk_base::Message* message) {
+ virtual void OnMessage(rtc::Message* message) {
int message_id = message->message_id;
PseudoTcpTestBase::OnMessage(message);
@@ -555,7 +555,7 @@
do {
send_stream_.GetPosition(&position);
if (send_stream_.Read(block, sizeof(block), &tosend, NULL) !=
- talk_base::SR_EOS) {
+ rtc::SR_EOS) {
sent = local_.Send(block, tosend);
UpdateLocalClock();
if (sent != -1) {
@@ -572,7 +572,7 @@
// At this point, we've filled up the available space in the send queue.
int message_queue_size =
- static_cast<int>(talk_base::Thread::Current()->size());
+ static_cast<int>(rtc::Thread::Current()->size());
// The message queue will always have at least 2 messages, an RCLOCK and
// an LCLOCK, since they are added back on the delay queue at the same time
// they are pulled off and therefore are never really removed.
@@ -580,7 +580,7 @@
// If there are non-clock messages remaining, attempt to continue sending
// after giving those messages time to process, which should free up the
// send buffer.
- talk_base::Thread::Current()->PostDelayed(10, this, MSG_WRITE);
+ rtc::Thread::Current()->PostDelayed(10, this, MSG_WRITE);
} else {
if (!remote_.isReceiveBufferFull()) {
LOG(LS_ERROR) << "This shouldn't happen - the send buffer is full, "
@@ -596,8 +596,8 @@
}
private:
- talk_base::MemoryStream send_stream_;
- talk_base::MemoryStream recv_stream_;
+ rtc::MemoryStream send_stream_;
+ rtc::MemoryStream recv_stream_;
std::vector<size_t> send_position_;
std::vector<size_t> recv_position_;
diff --git a/p2p/base/rawtransport.cc b/p2p/base/rawtransport.cc
index fe4f3a2..2af1864 100644
--- a/p2p/base/rawtransport.cc
+++ b/p2p/base/rawtransport.cc
@@ -27,21 +27,21 @@
#include <string>
#include <vector>
-#include "talk/p2p/base/rawtransport.h"
-#include "talk/base/common.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/parsing.h"
-#include "talk/p2p/base/sessionmanager.h"
+#include "talk/p2p/base/rawtransport.h"
#include "talk/p2p/base/rawtransportchannel.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "talk/p2p/base/sessionmanager.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/common.h"
#if defined(FEATURE_ENABLE_PSTN)
namespace cricket {
-RawTransport::RawTransport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+RawTransport::RawTransport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
PortAllocator* allocator)
: Transport(signaling_thread, worker_thread,
@@ -67,7 +67,7 @@
if (type() != cand_elem->Attr(buzz::QN_NAME)) {
return BadParse("channel named does not exist", error);
}
- talk_base::SocketAddress addr;
+ rtc::SocketAddress addr;
if (!ParseRawAddress(cand_elem, &addr, error))
return false;
@@ -91,7 +91,7 @@
++cand) {
ASSERT(cand->component() == 1);
ASSERT(cand->protocol() == "udp");
- talk_base::SocketAddress addr = cand->address();
+ rtc::SocketAddress addr = cand->address();
buzz::XmlElement* elem = new buzz::XmlElement(QN_GINGLE_RAW_CHANNEL);
elem->SetAttr(buzz::QN_NAME, type());
@@ -103,7 +103,7 @@
}
bool RawTransport::ParseRawAddress(const buzz::XmlElement* elem,
- talk_base::SocketAddress* addr,
+ rtc::SocketAddress* addr,
ParseError* error) {
// Make sure the required attributes exist
if (!elem->HasAttr(QN_ADDRESS) ||
diff --git a/p2p/base/rawtransport.h b/p2p/base/rawtransport.h
index 6bb04fe..3a20ef5 100644
--- a/p2p/base/rawtransport.h
+++ b/p2p/base/rawtransport.h
@@ -39,8 +39,8 @@
// that it thinks will work.
class RawTransport : public Transport, public TransportParser {
public:
- RawTransport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ RawTransport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
PortAllocator* allocator);
virtual ~RawTransport();
@@ -66,7 +66,7 @@
// given channel. This will return false and signal an error if the address
// or channel name is bad.
bool ParseRawAddress(const buzz::XmlElement* elem,
- talk_base::SocketAddress* addr,
+ rtc::SocketAddress* addr,
ParseError* error);
friend class RawTransportChannel; // For ParseAddress.
diff --git a/p2p/base/rawtransportchannel.cc b/p2p/base/rawtransportchannel.cc
index 37478ca..ae268e3 100644
--- a/p2p/base/rawtransportchannel.cc
+++ b/p2p/base/rawtransportchannel.cc
@@ -29,7 +29,6 @@
#include <string>
#include <vector>
-#include "talk/base/common.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/portallocator.h"
#include "talk/p2p/base/portinterface.h"
@@ -37,15 +36,16 @@
#include "talk/p2p/base/relayport.h"
#include "talk/p2p/base/sessionmanager.h"
#include "talk/p2p/base/stunport.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/common.h"
#if defined(FEATURE_ENABLE_PSTN)
namespace {
-const uint32 MSG_DESTROY_UNUSED_PORTS = 1;
+const uint32 MSG_DESTROY_RTC_UNUSED_PORTS = 1;
} // namespace
@@ -54,7 +54,7 @@
RawTransportChannel::RawTransportChannel(const std::string& content_name,
int component,
RawTransport* transport,
- talk_base::Thread *worker_thread,
+ rtc::Thread *worker_thread,
PortAllocator *allocator)
: TransportChannelImpl(content_name, component),
raw_transport_(transport),
@@ -75,7 +75,7 @@
}
int RawTransportChannel::SendPacket(const char *data, size_t size,
- const talk_base::PacketOptions& options,
+ const rtc::PacketOptions& options,
int flags) {
if (port_ == NULL)
return -1;
@@ -86,7 +86,7 @@
return port_->SendTo(data, size, remote_address_, options, true);
}
-int RawTransportChannel::SetOption(talk_base::Socket::Option opt, int value) {
+int RawTransportChannel::SetOption(rtc::Socket::Option opt, int value) {
// TODO: allow these to be set before we have a port
if (port_ == NULL)
return -1;
@@ -130,7 +130,7 @@
stun_port_ = NULL;
relay_port_ = NULL;
port_ = NULL;
- remote_address_ = talk_base::SocketAddress();
+ remote_address_ = rtc::SocketAddress();
}
void RawTransportChannel::OnCandidate(const Candidate& candidate) {
@@ -144,7 +144,7 @@
}
void RawTransportChannel::OnRemoteAddress(
- const talk_base::SocketAddress& remote_address) {
+ const rtc::SocketAddress& remote_address) {
remote_address_ = remote_address;
set_readable(true);
@@ -225,7 +225,7 @@
// We don't need any ports other than the one we picked.
allocator_session_->StopGettingPorts();
worker_thread_->Post(
- this, MSG_DESTROY_UNUSED_PORTS, NULL);
+ this, MSG_DESTROY_RTC_UNUSED_PORTS, NULL);
// Send a message to the other client containing our address.
@@ -255,13 +255,13 @@
void RawTransportChannel::OnReadPacket(
PortInterface* port, const char* data, size_t size,
- const talk_base::SocketAddress& addr) {
+ const rtc::SocketAddress& addr) {
ASSERT(port_ == port);
- SignalReadPacket(this, data, size, talk_base::CreatePacketTime(0), 0);
+ SignalReadPacket(this, data, size, rtc::CreatePacketTime(0), 0);
}
-void RawTransportChannel::OnMessage(talk_base::Message* msg) {
- ASSERT(msg->message_id == MSG_DESTROY_UNUSED_PORTS);
+void RawTransportChannel::OnMessage(rtc::Message* msg) {
+ ASSERT(msg->message_id == MSG_DESTROY_RTC_UNUSED_PORTS);
ASSERT(port_ != NULL);
if (port_ != stun_port_) {
stun_port_->Destroy();
diff --git a/p2p/base/rawtransportchannel.h b/p2p/base/rawtransportchannel.h
index 52085c0..8fbf073 100644
--- a/p2p/base/rawtransportchannel.h
+++ b/p2p/base/rawtransportchannel.h
@@ -30,14 +30,14 @@
#include <string>
#include <vector>
-#include "talk/base/messagequeue.h"
-#include "talk/p2p/base/transportchannelimpl.h"
-#include "talk/p2p/base/rawtransport.h"
#include "talk/p2p/base/candidate.h"
+#include "talk/p2p/base/rawtransport.h"
+#include "talk/p2p/base/transportchannelimpl.h"
+#include "webrtc/base/messagequeue.h"
#if defined(FEATURE_ENABLE_PSTN)
-namespace talk_base {
+namespace rtc {
class Thread;
}
@@ -54,19 +54,19 @@
// address of the other side. We pick a single address to send them based on
// a simple investigation of NAT type.
class RawTransportChannel : public TransportChannelImpl,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
RawTransportChannel(const std::string& content_name,
int component,
RawTransport* transport,
- talk_base::Thread *worker_thread,
+ rtc::Thread *worker_thread,
PortAllocator *allocator);
virtual ~RawTransportChannel();
// Implementation of normal channel packet sending.
virtual int SendPacket(const char *data, size_t len,
- const talk_base::PacketOptions& options, int flags);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
+ const rtc::PacketOptions& options, int flags);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
virtual int GetError();
// Implements TransportChannelImpl.
@@ -91,7 +91,7 @@
// have this since we now know where to send.
virtual void OnCandidate(const Candidate& candidate);
- void OnRemoteAddress(const talk_base::SocketAddress& remote_address);
+ void OnRemoteAddress(const rtc::SocketAddress& remote_address);
// Below ICE specific virtual methods not implemented.
virtual IceRole GetIceRole() const { return ICEROLE_UNKNOWN; }
@@ -114,11 +114,11 @@
virtual bool IsDtlsActive() const { return false; }
// Default implementation.
- virtual bool GetSslRole(talk_base::SSLRole* role) const {
+ virtual bool GetSslRole(rtc::SSLRole* role) const {
return false;
}
- virtual bool SetSslRole(talk_base::SSLRole role) {
+ virtual bool SetSslRole(rtc::SSLRole role) {
return false;
}
@@ -133,11 +133,11 @@
}
// Returns false because the channel is not DTLS.
- virtual bool GetLocalIdentity(talk_base::SSLIdentity** identity) const {
+ virtual bool GetLocalIdentity(rtc::SSLIdentity** identity) const {
return false;
}
- virtual bool GetRemoteCertificate(talk_base::SSLCertificate** cert) const {
+ virtual bool GetRemoteCertificate(rtc::SSLCertificate** cert) const {
return false;
}
@@ -152,7 +152,7 @@
return false;
}
- virtual bool SetLocalIdentity(talk_base::SSLIdentity* identity) {
+ virtual bool SetLocalIdentity(rtc::SSLIdentity* identity) {
return false;
}
@@ -166,14 +166,14 @@
private:
RawTransport* raw_transport_;
- talk_base::Thread *worker_thread_;
+ rtc::Thread *worker_thread_;
PortAllocator* allocator_;
PortAllocatorSession* allocator_session_;
StunPort* stun_port_;
RelayPort* relay_port_;
PortInterface* port_;
bool use_relay_;
- talk_base::SocketAddress remote_address_;
+ rtc::SocketAddress remote_address_;
// Called when the allocator creates another port.
void OnPortReady(PortAllocatorSession* session, PortInterface* port);
@@ -192,10 +192,10 @@
// Called when we receive a packet from the other client.
void OnReadPacket(PortInterface* port, const char* data, size_t size,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
// Handles a message to destroy unused ports.
- virtual void OnMessage(talk_base::Message *msg);
+ virtual void OnMessage(rtc::Message *msg);
DISALLOW_EVIL_CONSTRUCTORS(RawTransportChannel);
};
diff --git a/p2p/base/relayport.cc b/p2p/base/relayport.cc
index 23571ea..55052a5 100644
--- a/p2p/base/relayport.cc
+++ b/p2p/base/relayport.cc
@@ -25,10 +25,10 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
#include "talk/p2p/base/relayport.h"
+#include "webrtc/base/asyncpacketsocket.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -44,16 +44,16 @@
class RelayConnection : public sigslot::has_slots<> {
public:
RelayConnection(const ProtocolAddress* protocol_address,
- talk_base::AsyncPacketSocket* socket,
- talk_base::Thread* thread);
+ rtc::AsyncPacketSocket* socket,
+ rtc::Thread* thread);
~RelayConnection();
- talk_base::AsyncPacketSocket* socket() const { return socket_; }
+ rtc::AsyncPacketSocket* socket() const { return socket_; }
const ProtocolAddress* protocol_address() {
return protocol_address_;
}
- talk_base::SocketAddress GetAddress() const {
+ rtc::SocketAddress GetAddress() const {
return protocol_address_->address;
}
@@ -61,13 +61,13 @@
return protocol_address_->proto;
}
- int SetSocketOption(talk_base::Socket::Option opt, int value);
+ int SetSocketOption(rtc::Socket::Option opt, int value);
// Validates a response to a STUN allocate request.
bool CheckResponse(StunMessage* msg);
// Sends data to the relay server.
- int Send(const void* pv, size_t cb, const talk_base::PacketOptions& options);
+ int Send(const void* pv, size_t cb, const rtc::PacketOptions& options);
// Sends a STUN allocate request message to the relay server.
void SendAllocateRequest(RelayEntry* entry, int delay);
@@ -80,7 +80,7 @@
void OnSendPacket(const void* data, size_t size, StunRequest* req);
private:
- talk_base::AsyncPacketSocket* socket_;
+ rtc::AsyncPacketSocket* socket_;
const ProtocolAddress* protocol_address_;
StunRequestManager *request_manager_;
};
@@ -89,16 +89,16 @@
// available protocol. We aim to use each connection for only a
// specific destination address so that we can avoid wrapping every
// packet in a STUN send / data indication.
-class RelayEntry : public talk_base::MessageHandler,
+class RelayEntry : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
- RelayEntry(RelayPort* port, const talk_base::SocketAddress& ext_addr);
+ RelayEntry(RelayPort* port, const rtc::SocketAddress& ext_addr);
~RelayEntry();
RelayPort* port() { return port_; }
- const talk_base::SocketAddress& address() const { return ext_addr_; }
- void set_address(const talk_base::SocketAddress& addr) { ext_addr_ = addr; }
+ const rtc::SocketAddress& address() const { return ext_addr_; }
+ void set_address(const rtc::SocketAddress& addr) { ext_addr_ = addr; }
bool connected() const { return connected_; }
bool locked() const { return locked_; }
@@ -117,14 +117,14 @@
// Called when this entry becomes connected. The address given is the one
// exposed to the outside world on the relay server.
- void OnConnect(const talk_base::SocketAddress& mapped_addr,
+ void OnConnect(const rtc::SocketAddress& mapped_addr,
RelayConnection* socket);
// Sends a packet to the given destination address using the socket of this
// entry. This will wrap the packet in STUN if necessary.
int SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options);
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options);
// Schedules a keep-alive allocate request.
void ScheduleKeepAlive();
@@ -132,41 +132,41 @@
void SetServerIndex(size_t sindex) { server_index_ = sindex; }
// Sets this option on the socket of each connection.
- int SetSocketOption(talk_base::Socket::Option opt, int value);
+ int SetSocketOption(rtc::Socket::Option opt, int value);
size_t ServerIndex() const { return server_index_; }
// Try a different server address
- void HandleConnectFailure(talk_base::AsyncPacketSocket* socket);
+ void HandleConnectFailure(rtc::AsyncPacketSocket* socket);
// Implementation of the MessageHandler Interface.
- virtual void OnMessage(talk_base::Message *pmsg);
+ virtual void OnMessage(rtc::Message *pmsg);
private:
RelayPort* port_;
- talk_base::SocketAddress ext_addr_;
+ rtc::SocketAddress ext_addr_;
size_t server_index_;
bool connected_;
bool locked_;
RelayConnection* current_connection_;
// Called when a TCP connection is established or fails
- void OnSocketConnect(talk_base::AsyncPacketSocket* socket);
- void OnSocketClose(talk_base::AsyncPacketSocket* socket, int error);
+ void OnSocketConnect(rtc::AsyncPacketSocket* socket);
+ void OnSocketClose(rtc::AsyncPacketSocket* socket, int error);
// Called when a packet is received on this socket.
void OnReadPacket(
- talk_base::AsyncPacketSocket* socket,
+ rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
// Called when the socket is currently able to send.
- void OnReadyToSend(talk_base::AsyncPacketSocket* socket);
+ void OnReadyToSend(rtc::AsyncPacketSocket* socket);
// Sends the given data on the socket to the server with no wrapping. This
// returns the number of bytes written or -1 if an error occurred.
int SendPacket(const void* data, size_t size,
- const talk_base::PacketOptions& options);
+ const rtc::PacketOptions& options);
};
// Handles an allocate request for a particular RelayEntry.
@@ -190,8 +190,8 @@
};
RelayPort::RelayPort(
- talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port, const std::string& username,
const std::string& password)
: Port(thread, RELAY_PORT_TYPE, factory, network, ip, min_port, max_port,
@@ -199,7 +199,7 @@
ready_(false),
error_(0) {
entries_.push_back(
- new RelayEntry(this, talk_base::SocketAddress()));
+ new RelayEntry(this, rtc::SocketAddress()));
// TODO: set local preference value for TCP based candidates.
}
@@ -213,8 +213,8 @@
// Since HTTP proxies usually only allow 443,
// let's up the priority on PROTO_SSLTCP
if (addr.proto == PROTO_SSLTCP &&
- (proxy().type == talk_base::PROXY_HTTPS ||
- proxy().type == talk_base::PROXY_UNKNOWN)) {
+ (proxy().type == rtc::PROXY_HTTPS ||
+ proxy().type == rtc::PROXY_UNKNOWN)) {
server_addr_.push_front(addr);
} else {
server_addr_.push_back(addr);
@@ -243,8 +243,9 @@
// In case of Gturn, related address is set to null socket address.
// This is due to as mapped address stun attribute is used for allocated
// address.
- AddAddress(iter->address, iter->address, talk_base::SocketAddress(),
- proto_name, RELAY_PORT_TYPE, ICE_TYPE_PREFERENCE_RELAY, false);
+ AddAddress(iter->address, iter->address, rtc::SocketAddress(),
+ proto_name, "", RELAY_PORT_TYPE,
+ ICE_TYPE_PREFERENCE_RELAY, 0, false);
}
ready_ = true;
SignalPortComplete(this);
@@ -307,8 +308,8 @@
}
int RelayPort::SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload) {
// Try to find an entry for this specific address. Note that the first entry
// created was not given an address initially, so it can be set to the first
@@ -361,7 +362,7 @@
return static_cast<int>(size);
}
-int RelayPort::SetOption(talk_base::Socket::Option opt, int value) {
+int RelayPort::SetOption(rtc::Socket::Option opt, int value) {
int result = 0;
for (size_t i = 0; i < entries_.size(); ++i) {
if (entries_[i]->SetSocketOption(opt, value) < 0) {
@@ -373,7 +374,7 @@
return result;
}
-int RelayPort::GetOption(talk_base::Socket::Option opt, int* value) {
+int RelayPort::GetOption(rtc::Socket::Option opt, int* value) {
std::vector<OptionValue>::iterator it;
for (it = options_.begin(); it < options_.end(); ++it) {
if (it->first == opt) {
@@ -390,9 +391,9 @@
void RelayPort::OnReadPacket(
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
+ const rtc::SocketAddress& remote_addr,
ProtocolType proto,
- const talk_base::PacketTime& packet_time) {
+ const rtc::PacketTime& packet_time) {
if (Connection* conn = GetConnection(remote_addr)) {
conn->OnReadPacket(data, size, packet_time);
} else {
@@ -401,8 +402,8 @@
}
RelayConnection::RelayConnection(const ProtocolAddress* protocol_address,
- talk_base::AsyncPacketSocket* socket,
- talk_base::Thread* thread)
+ rtc::AsyncPacketSocket* socket,
+ rtc::Thread* thread)
: socket_(socket),
protocol_address_(protocol_address) {
request_manager_ = new StunRequestManager(thread);
@@ -415,7 +416,7 @@
delete socket_;
}
-int RelayConnection::SetSocketOption(talk_base::Socket::Option opt,
+int RelayConnection::SetSocketOption(rtc::Socket::Option opt,
int value) {
if (socket_) {
return socket_->SetOption(opt, value);
@@ -430,7 +431,7 @@
void RelayConnection::OnSendPacket(const void* data, size_t size,
StunRequest* req) {
// TODO(mallinath) Find a way to get DSCP value from Port.
- talk_base::PacketOptions options; // Default dscp set to NO_CHANGE.
+ rtc::PacketOptions options; // Default dscp set to NO_CHANGE.
int sent = socket_->SendTo(data, size, GetAddress(), options);
if (sent <= 0) {
LOG(LS_VERBOSE) << "OnSendPacket: failed sending to " << GetAddress() <<
@@ -440,7 +441,7 @@
}
int RelayConnection::Send(const void* pv, size_t cb,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
return socket_->SendTo(pv, cb, GetAddress(), options);
}
@@ -449,7 +450,7 @@
}
RelayEntry::RelayEntry(RelayPort* port,
- const talk_base::SocketAddress& ext_addr)
+ const rtc::SocketAddress& ext_addr)
: port_(port), ext_addr_(ext_addr),
server_index_(0), connected_(false), locked_(false),
current_connection_(NULL) {
@@ -483,18 +484,18 @@
LOG(LS_INFO) << "Connecting to relay via " << ProtoToString(ra->proto) <<
" @ " << ra->address.ToSensitiveString();
- talk_base::AsyncPacketSocket* socket = NULL;
+ rtc::AsyncPacketSocket* socket = NULL;
if (ra->proto == PROTO_UDP) {
// UDP sockets are simple.
socket = port_->socket_factory()->CreateUdpSocket(
- talk_base::SocketAddress(port_->ip(), 0),
+ rtc::SocketAddress(port_->ip(), 0),
port_->min_port(), port_->max_port());
} else if (ra->proto == PROTO_TCP || ra->proto == PROTO_SSLTCP) {
int opts = (ra->proto == PROTO_SSLTCP) ?
- talk_base::PacketSocketFactory::OPT_SSLTCP : 0;
+ rtc::PacketSocketFactory::OPT_SSLTCP : 0;
socket = port_->socket_factory()->CreateClientTcpSocket(
- talk_base::SocketAddress(port_->ip(), 0), ra->address,
+ rtc::SocketAddress(port_->ip(), 0), ra->address,
port_->proxy(), port_->user_agent(), opts);
} else {
LOG(LS_WARNING) << "Unknown protocol (" << ra->proto << ")";
@@ -543,7 +544,7 @@
return conn1->GetProtocol() <= conn2->GetProtocol() ? conn1 : conn2;
}
-void RelayEntry::OnConnect(const talk_base::SocketAddress& mapped_addr,
+void RelayEntry::OnConnect(const rtc::SocketAddress& mapped_addr,
RelayConnection* connection) {
// We are connected, notify our parent.
ProtocolType proto = PROTO_UDP;
@@ -556,8 +557,8 @@
}
int RelayEntry::SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options) {
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options) {
// If this connection is locked to the address given, then we can send the
// packet with no wrapper.
if (locked_ && (ext_addr_ == addr))
@@ -606,7 +607,7 @@
// TODO: compute the HMAC.
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
request.Write(&buf);
return SendPacket(buf.Data(), buf.Length(), options);
@@ -618,7 +619,7 @@
}
}
-int RelayEntry::SetSocketOption(talk_base::Socket::Option opt, int value) {
+int RelayEntry::SetSocketOption(rtc::Socket::Option opt, int value) {
// Set the option on all available sockets.
int socket_error = 0;
if (current_connection_) {
@@ -628,7 +629,7 @@
}
void RelayEntry::HandleConnectFailure(
- talk_base::AsyncPacketSocket* socket) {
+ rtc::AsyncPacketSocket* socket) {
// Make sure it's the current connection that has failed, it might
// be an old socked that has not yet been disposed.
if (!socket ||
@@ -642,7 +643,7 @@
}
}
-void RelayEntry::OnMessage(talk_base::Message *pmsg) {
+void RelayEntry::OnMessage(rtc::Message *pmsg) {
ASSERT(pmsg->message_id == kMessageConnectTimeout);
if (current_connection_) {
const ProtocolAddress* ra = current_connection_->protocol_address();
@@ -663,7 +664,7 @@
}
}
-void RelayEntry::OnSocketConnect(talk_base::AsyncPacketSocket* socket) {
+void RelayEntry::OnSocketConnect(rtc::AsyncPacketSocket* socket) {
LOG(INFO) << "relay tcp connected to " <<
socket->GetRemoteAddress().ToSensitiveString();
if (current_connection_ != NULL) {
@@ -671,17 +672,17 @@
}
}
-void RelayEntry::OnSocketClose(talk_base::AsyncPacketSocket* socket,
+void RelayEntry::OnSocketClose(rtc::AsyncPacketSocket* socket,
int error) {
PLOG(LERROR, error) << "Relay connection failed: socket closed";
HandleConnectFailure(socket);
}
void RelayEntry::OnReadPacket(
- talk_base::AsyncPacketSocket* socket,
+ rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
// ASSERT(remote_addr == port_->server_addr());
// TODO: are we worried about this?
@@ -702,7 +703,7 @@
return;
}
- talk_base::ByteBuffer buf(data, size);
+ rtc::ByteBuffer buf(data, size);
RelayMessage msg;
if (!msg.Read(&buf)) {
LOG(INFO) << "Incoming packet was not STUN";
@@ -738,7 +739,7 @@
return;
}
- talk_base::SocketAddress remote_addr2(addr_attr->ipaddr(), addr_attr->port());
+ rtc::SocketAddress remote_addr2(addr_attr->ipaddr(), addr_attr->port());
const StunByteStringAttribute* data_attr = msg.GetByteString(STUN_ATTR_DATA);
if (!data_attr) {
@@ -751,14 +752,14 @@
PROTO_UDP, packet_time);
}
-void RelayEntry::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
+void RelayEntry::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
if (connected()) {
port_->OnReadyToSend();
}
}
int RelayEntry::SendPacket(const void* data, size_t size,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
int sent = 0;
if (current_connection_) {
// We are connected, no need to send packets anywere else than to
@@ -773,7 +774,7 @@
: StunRequest(new RelayMessage()),
entry_(entry),
connection_(connection) {
- start_time_ = talk_base::Time();
+ start_time_ = rtc::Time();
}
void AllocateRequest::Prepare(StunMessage* request) {
@@ -788,7 +789,7 @@
}
int AllocateRequest::GetNextDelay() {
- int delay = 100 * talk_base::_max(1 << count_, 2);
+ int delay = 100 * rtc::_max(1 << count_, 2);
count_ += 1;
if (count_ == 5)
timeout_ = true;
@@ -803,7 +804,7 @@
} else if (addr_attr->family() != 1) {
LOG(INFO) << "Mapped address has bad family";
} else {
- talk_base::SocketAddress addr(addr_attr->ipaddr(), addr_attr->port());
+ rtc::SocketAddress addr(addr_attr->ipaddr(), addr_attr->port());
entry_->OnConnect(addr, connection_);
}
@@ -822,7 +823,7 @@
<< " reason='" << attr->reason() << "'";
}
- if (talk_base::TimeSince(start_time_) <= kRetryTimeout)
+ if (rtc::TimeSince(start_time_) <= kRetryTimeout)
entry_->ScheduleKeepAlive();
}
diff --git a/p2p/base/relayport.h b/p2p/base/relayport.h
index 140c80f..f22d045 100644
--- a/p2p/base/relayport.h
+++ b/p2p/base/relayport.h
@@ -49,12 +49,12 @@
// successful all other connection attemts are aborted.
class RelayPort : public Port {
public:
- typedef std::pair<talk_base::Socket::Option, int> OptionValue;
+ typedef std::pair<rtc::Socket::Option, int> OptionValue;
// RelayPort doesn't yet do anything fancy in the ctor.
static RelayPort* Create(
- talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port, const std::string& username,
const std::string& password) {
return new RelayPort(thread, factory, network, ip, min_port, max_port,
@@ -71,8 +71,8 @@
virtual void PrepareAddress();
virtual Connection* CreateConnection(const Candidate& address,
CandidateOrigin origin);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
- virtual int GetOption(talk_base::Socket::Option opt, int* value);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
+ virtual int GetOption(rtc::Socket::Option opt, int* value);
virtual int GetError();
const ProtocolAddress * ServerAddress(size_t index) const;
@@ -83,8 +83,8 @@
sigslot::signal1<const ProtocolAddress*> SignalSoftTimeout;
protected:
- RelayPort(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network*, const talk_base::IPAddress& ip,
+ RelayPort(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network*, const rtc::IPAddress& ip,
int min_port, int max_port, const std::string& username,
const std::string& password);
bool Init();
@@ -92,15 +92,15 @@
void SetReady();
virtual int SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload);
// Dispatches the given packet to the port or connection as appropriate.
void OnReadPacket(const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
+ const rtc::SocketAddress& remote_addr,
ProtocolType proto,
- const talk_base::PacketTime& packet_time);
+ const rtc::PacketTime& packet_time);
private:
friend class RelayEntry;
diff --git a/p2p/base/relayport_unittest.cc b/p2p/base/relayport_unittest.cc
index 987fd1e..25777d1 100644
--- a/p2p/base/relayport_unittest.cc
+++ b/p2p/base/relayport_unittest.cc
@@ -25,21 +25,21 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/logging.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/thread.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/relayport.h"
#include "talk/p2p/base/relayserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketadapters.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/virtualsocketserver.h"
-using talk_base::SocketAddress;
+using rtc::SocketAddress;
static const SocketAddress kLocalAddress = SocketAddress("192.168.1.2", 0);
static const SocketAddress kRelayUdpAddr = SocketAddress("99.99.99.1", 5000);
@@ -61,15 +61,15 @@
public sigslot::has_slots<> {
public:
RelayPortTest()
- : main_(talk_base::Thread::Current()),
- physical_socket_server_(new talk_base::PhysicalSocketServer),
- virtual_socket_server_(new talk_base::VirtualSocketServer(
+ : main_(rtc::Thread::Current()),
+ physical_socket_server_(new rtc::PhysicalSocketServer),
+ virtual_socket_server_(new rtc::VirtualSocketServer(
physical_socket_server_.get())),
ss_scope_(virtual_socket_server_.get()),
- network_("unittest", "unittest", talk_base::IPAddress(INADDR_ANY), 32),
- socket_factory_(talk_base::Thread::Current()),
- username_(talk_base::CreateRandomString(16)),
- password_(talk_base::CreateRandomString(16)),
+ network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
+ socket_factory_(rtc::Thread::Current()),
+ username_(rtc::CreateRandomString(16)),
+ password_(rtc::CreateRandomString(16)),
relay_port_(cricket::RelayPort::Create(main_, &socket_factory_,
&network_,
kLocalAddress.ipaddr(),
@@ -77,10 +77,10 @@
relay_server_(new cricket::RelayServer(main_)) {
}
- void OnReadPacket(talk_base::AsyncPacketSocket* socket,
+ void OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
received_packet_count_[socket]++;
}
@@ -94,17 +94,17 @@
protected:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
virtual void SetUp() {
// The relay server needs an external socket to work properly.
- talk_base::AsyncUDPSocket* ext_socket =
+ rtc::AsyncUDPSocket* ext_socket =
CreateAsyncUdpSocket(kRelayExtAddr);
relay_server_->AddExternalSocket(ext_socket);
@@ -126,9 +126,9 @@
// abort any other connection attempts.
void TestConnectUdp() {
// Add a UDP socket to the relay server.
- talk_base::AsyncUDPSocket* internal_udp_socket =
+ rtc::AsyncUDPSocket* internal_udp_socket =
CreateAsyncUdpSocket(kRelayUdpAddr);
- talk_base::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
+ rtc::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
relay_server_->AddInternalSocket(internal_udp_socket);
relay_server_->AddInternalServerSocket(server_socket, cricket::PROTO_TCP);
@@ -165,7 +165,7 @@
cricket::ProtocolAddress(kRelayUdpAddr, cricket::PROTO_UDP);
// Create a server socket for the RelayServer.
- talk_base::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
+ rtc::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
relay_server_->AddInternalServerSocket(server_socket, cricket::PROTO_TCP);
// Add server addresses to the relay port and let it start.
@@ -198,14 +198,14 @@
cricket::ProtocolAddress(kRelayTcpAddr, cricket::PROTO_TCP);
// Create a ssl server socket for the RelayServer.
- talk_base::AsyncSocket* ssl_server_socket =
+ rtc::AsyncSocket* ssl_server_socket =
CreateServerSocket(kRelaySslAddr);
relay_server_->AddInternalServerSocket(ssl_server_socket,
cricket::PROTO_SSLTCP);
// Create a tcp server socket that listens on the fake address so
// the relay port can attempt to connect to it.
- talk_base::scoped_ptr<talk_base::AsyncSocket> tcp_server_socket(
+ rtc::scoped_ptr<rtc::AsyncSocket> tcp_server_socket(
CreateServerSocket(kRelayTcpAddr));
// Add server addresses to the relay port and let it start.
@@ -229,18 +229,18 @@
}
private:
- talk_base::AsyncUDPSocket* CreateAsyncUdpSocket(const SocketAddress addr) {
- talk_base::AsyncSocket* socket =
+ rtc::AsyncUDPSocket* CreateAsyncUdpSocket(const SocketAddress addr) {
+ rtc::AsyncSocket* socket =
virtual_socket_server_->CreateAsyncSocket(SOCK_DGRAM);
- talk_base::AsyncUDPSocket* packet_socket =
- talk_base::AsyncUDPSocket::Create(socket, addr);
+ rtc::AsyncUDPSocket* packet_socket =
+ rtc::AsyncUDPSocket::Create(socket, addr);
EXPECT_TRUE(packet_socket != NULL);
packet_socket->SignalReadPacket.connect(this, &RelayPortTest::OnReadPacket);
return packet_socket;
}
- talk_base::AsyncSocket* CreateServerSocket(const SocketAddress addr) {
- talk_base::AsyncSocket* socket =
+ rtc::AsyncSocket* CreateServerSocket(const SocketAddress addr) {
+ rtc::AsyncSocket* socket =
virtual_socket_server_->CreateAsyncSocket(SOCK_STREAM);
EXPECT_GE(socket->Bind(addr), 0);
EXPECT_GE(socket->Listen(5), 0);
@@ -267,19 +267,19 @@
return false;
}
- typedef std::map<talk_base::AsyncPacketSocket*, int> PacketMap;
+ typedef std::map<rtc::AsyncPacketSocket*, int> PacketMap;
- talk_base::Thread* main_;
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer>
+ rtc::Thread* main_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer>
physical_socket_server_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> virtual_socket_server_;
- talk_base::SocketServerScope ss_scope_;
- talk_base::Network network_;
- talk_base::BasicPacketSocketFactory socket_factory_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> virtual_socket_server_;
+ rtc::SocketServerScope ss_scope_;
+ rtc::Network network_;
+ rtc::BasicPacketSocketFactory socket_factory_;
std::string username_;
std::string password_;
- talk_base::scoped_ptr<cricket::RelayPort> relay_port_;
- talk_base::scoped_ptr<cricket::RelayServer> relay_server_;
+ rtc::scoped_ptr<cricket::RelayPort> relay_port_;
+ rtc::scoped_ptr<cricket::RelayServer> relay_server_;
std::vector<cricket::ProtocolAddress> failed_connections_;
std::vector<cricket::ProtocolAddress> soft_timedout_connections_;
PacketMap received_packet_count_;
diff --git a/p2p/base/relayserver.cc b/p2p/base/relayserver.cc
index 3dd8506..b5d1ac6 100644
--- a/p2p/base/relayserver.cc
+++ b/p2p/base/relayserver.cc
@@ -33,10 +33,10 @@
#include <algorithm>
-#include "talk/base/asynctcpsocket.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/socketadapters.h"
+#include "webrtc/base/asynctcpsocket.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/socketadapters.h"
namespace cricket {
@@ -47,9 +47,9 @@
const uint32 USERNAME_LENGTH = 16;
// Calls SendTo on the given socket and logs any bad results.
-void Send(talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
- const talk_base::SocketAddress& addr) {
- talk_base::PacketOptions options;
+void Send(rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
+ const rtc::SocketAddress& addr) {
+ rtc::PacketOptions options;
int result = socket->SendTo(bytes, size, addr, options);
if (result < static_cast<int>(size)) {
LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
@@ -61,16 +61,16 @@
// Sends the given STUN message on the given socket.
void SendStun(const StunMessage& msg,
- talk_base::AsyncPacketSocket* socket,
- const talk_base::SocketAddress& addr) {
- talk_base::ByteBuffer buf;
+ rtc::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& addr) {
+ rtc::ByteBuffer buf;
msg.Write(&buf);
Send(socket, buf.Data(), buf.Length(), addr);
}
// Constructs a STUN error response and sends it on the given socket.
-void SendStunError(const StunMessage& msg, talk_base::AsyncPacketSocket* socket,
- const talk_base::SocketAddress& remote_addr, int error_code,
+void SendStunError(const StunMessage& msg, rtc::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& remote_addr, int error_code,
const char* error_desc, const std::string& magic_cookie) {
RelayMessage err_msg;
err_msg.SetType(GetStunErrorResponseType(msg.type()));
@@ -95,7 +95,7 @@
SendStun(err_msg, socket, remote_addr);
}
-RelayServer::RelayServer(talk_base::Thread* thread)
+RelayServer::RelayServer(rtc::Thread* thread)
: thread_(thread), log_bindings_(true) {
}
@@ -110,20 +110,20 @@
for (size_t i = 0; i < removed_sockets_.size(); ++i)
delete removed_sockets_[i];
while (!server_sockets_.empty()) {
- talk_base::AsyncSocket* socket = server_sockets_.begin()->first;
+ rtc::AsyncSocket* socket = server_sockets_.begin()->first;
server_sockets_.erase(server_sockets_.begin()->first);
delete socket;
}
}
-void RelayServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket) {
+void RelayServer::AddInternalSocket(rtc::AsyncPacketSocket* socket) {
ASSERT(internal_sockets_.end() ==
std::find(internal_sockets_.begin(), internal_sockets_.end(), socket));
internal_sockets_.push_back(socket);
socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
}
-void RelayServer::RemoveInternalSocket(talk_base::AsyncPacketSocket* socket) {
+void RelayServer::RemoveInternalSocket(rtc::AsyncPacketSocket* socket) {
SocketList::iterator iter =
std::find(internal_sockets_.begin(), internal_sockets_.end(), socket);
ASSERT(iter != internal_sockets_.end());
@@ -132,14 +132,14 @@
socket->SignalReadPacket.disconnect(this);
}
-void RelayServer::AddExternalSocket(talk_base::AsyncPacketSocket* socket) {
+void RelayServer::AddExternalSocket(rtc::AsyncPacketSocket* socket) {
ASSERT(external_sockets_.end() ==
std::find(external_sockets_.begin(), external_sockets_.end(), socket));
external_sockets_.push_back(socket);
socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
}
-void RelayServer::RemoveExternalSocket(talk_base::AsyncPacketSocket* socket) {
+void RelayServer::RemoveExternalSocket(rtc::AsyncPacketSocket* socket) {
SocketList::iterator iter =
std::find(external_sockets_.begin(), external_sockets_.end(), socket);
ASSERT(iter != external_sockets_.end());
@@ -148,7 +148,7 @@
socket->SignalReadPacket.disconnect(this);
}
-void RelayServer::AddInternalServerSocket(talk_base::AsyncSocket* socket,
+void RelayServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
cricket::ProtocolType proto) {
ASSERT(server_sockets_.end() ==
server_sockets_.find(socket));
@@ -157,7 +157,7 @@
}
void RelayServer::RemoveInternalServerSocket(
- talk_base::AsyncSocket* socket) {
+ rtc::AsyncSocket* socket) {
ServerSocketMap::iterator iter = server_sockets_.find(socket);
ASSERT(iter != server_sockets_.end());
server_sockets_.erase(iter);
@@ -168,7 +168,7 @@
return static_cast<int>(connections_.size());
}
-talk_base::SocketAddressPair RelayServer::GetConnection(int connection) const {
+rtc::SocketAddressPair RelayServer::GetConnection(int connection) const {
int i = 0;
for (ConnectionMap::const_iterator it = connections_.begin();
it != connections_.end(); ++it) {
@@ -177,10 +177,10 @@
}
++i;
}
- return talk_base::SocketAddressPair();
+ return rtc::SocketAddressPair();
}
-bool RelayServer::HasConnection(const talk_base::SocketAddress& address) const {
+bool RelayServer::HasConnection(const rtc::SocketAddress& address) const {
for (ConnectionMap::const_iterator it = connections_.begin();
it != connections_.end(); ++it) {
if (it->second->addr_pair().destination() == address) {
@@ -190,18 +190,18 @@
return false;
}
-void RelayServer::OnReadEvent(talk_base::AsyncSocket* socket) {
+void RelayServer::OnReadEvent(rtc::AsyncSocket* socket) {
ASSERT(server_sockets_.find(socket) != server_sockets_.end());
AcceptConnection(socket);
}
void RelayServer::OnInternalPacket(
- talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
// Get the address of the connection we just received on.
- talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
+ rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
ASSERT(!ap.destination().IsNil());
// If this did not come from an existing connection, it should be a STUN
@@ -241,12 +241,12 @@
}
void RelayServer::OnExternalPacket(
- talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
// Get the address of the connection we just received on.
- talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
+ rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
ASSERT(!ap.destination().IsNil());
// If this connection already exists, then forward the traffic.
@@ -266,7 +266,7 @@
// The first packet should always be a STUN / TURN packet. If it isn't, then
// we should just ignore this packet.
RelayMessage msg;
- talk_base::ByteBuffer buf(bytes, size);
+ rtc::ByteBuffer buf(bytes, size);
if (!msg.Read(&buf)) {
LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
return;
@@ -280,7 +280,7 @@
return;
}
- uint32 length = talk_base::_min(static_cast<uint32>(username_attr->length()),
+ uint32 length = rtc::_min(static_cast<uint32>(username_attr->length()),
USERNAME_LENGTH);
std::string username(username_attr->bytes(), length);
// TODO: Check the HMAC.
@@ -310,12 +310,12 @@
}
bool RelayServer::HandleStun(
- const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr,
- talk_base::AsyncPacketSocket* socket, std::string* username,
+ const char* bytes, size_t size, const rtc::SocketAddress& remote_addr,
+ rtc::AsyncPacketSocket* socket, std::string* username,
StunMessage* msg) {
// Parse this into a stun message. Eat the message if this fails.
- talk_base::ByteBuffer buf(bytes, size);
+ rtc::ByteBuffer buf(bytes, size);
if (!msg->Read(&buf)) {
return false;
}
@@ -338,8 +338,8 @@
}
void RelayServer::HandleStunAllocate(
- const char* bytes, size_t size, const talk_base::SocketAddressPair& ap,
- talk_base::AsyncPacketSocket* socket) {
+ const char* bytes, size_t size, const rtc::SocketAddressPair& ap,
+ rtc::AsyncPacketSocket* socket) {
// Make sure this is a valid STUN request.
RelayMessage request;
@@ -376,7 +376,7 @@
const StunUInt32Attribute* lifetime_attr =
request.GetUInt32(STUN_ATTR_LIFETIME);
if (lifetime_attr)
- lifetime = talk_base::_min(lifetime, lifetime_attr->value() * 1000);
+ lifetime = rtc::_min(lifetime, lifetime_attr->value() * 1000);
binding = new RelayServerBinding(this, username, "0", lifetime);
binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
@@ -442,7 +442,7 @@
response.AddAttribute(magic_cookie_attr);
size_t index = rand() % external_sockets_.size();
- talk_base::SocketAddress ext_addr =
+ rtc::SocketAddress ext_addr =
external_sockets_[index]->GetLocalAddress();
StunAddressAttribute* addr_attr =
@@ -481,14 +481,14 @@
return;
}
- talk_base::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
+ rtc::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
RelayServerConnection* ext_conn =
int_conn->binding()->GetExternalConnection(ext_addr);
if (!ext_conn) {
// Create a new connection to establish the relationship with this binding.
ASSERT(external_sockets_.size() == 1);
- talk_base::AsyncPacketSocket* socket = external_sockets_[0];
- talk_base::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
+ rtc::AsyncPacketSocket* socket = external_sockets_[0];
+ rtc::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket);
ext_conn->binding()->AddExternalConnection(ext_conn);
AddConnection(ext_conn);
@@ -545,14 +545,14 @@
}
}
-void RelayServer::OnMessage(talk_base::Message *pmsg) {
+void RelayServer::OnMessage(rtc::Message *pmsg) {
#if ENABLE_DEBUG
static const uint32 kMessageAcceptConnection = 1;
ASSERT(pmsg->message_id == kMessageAcceptConnection);
#endif
- talk_base::MessageData* data = pmsg->pdata;
- talk_base::AsyncSocket* socket =
- static_cast <talk_base::TypedMessageData<talk_base::AsyncSocket*>*>
+ rtc::MessageData* data = pmsg->pdata;
+ rtc::AsyncSocket* socket =
+ static_cast <rtc::TypedMessageData<rtc::AsyncSocket*>*>
(data)->data();
AcceptConnection(socket);
delete data;
@@ -564,10 +564,10 @@
thread_->Dispose(binding);
}
-void RelayServer::AcceptConnection(talk_base::AsyncSocket* server_socket) {
+void RelayServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
// Check if someone is trying to connect to us.
- talk_base::SocketAddress accept_addr;
- talk_base::AsyncSocket* accepted_socket =
+ rtc::SocketAddress accept_addr;
+ rtc::AsyncSocket* accepted_socket =
server_socket->Accept(&accept_addr);
if (accepted_socket != NULL) {
// We had someone trying to connect, now check which protocol to
@@ -575,10 +575,10 @@
ASSERT(server_sockets_[server_socket] == cricket::PROTO_TCP ||
server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
- accepted_socket = new talk_base::AsyncSSLServerSocket(accepted_socket);
+ accepted_socket = new rtc::AsyncSSLServerSocket(accepted_socket);
}
- talk_base::AsyncTCPSocket* tcp_socket =
- new talk_base::AsyncTCPSocket(accepted_socket, false);
+ rtc::AsyncTCPSocket* tcp_socket =
+ new rtc::AsyncTCPSocket(accepted_socket, false);
// Finally add the socket so it can start communicating with the client.
AddInternalSocket(tcp_socket);
@@ -586,8 +586,8 @@
}
RelayServerConnection::RelayServerConnection(
- RelayServerBinding* binding, const talk_base::SocketAddressPair& addrs,
- talk_base::AsyncPacketSocket* socket)
+ RelayServerBinding* binding, const rtc::SocketAddressPair& addrs,
+ rtc::AsyncPacketSocket* socket)
: binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
// The creation of a new connection constitutes a use of the binding.
binding_->NoteUsed();
@@ -606,7 +606,7 @@
}
void RelayServerConnection::Send(
- const char* data, size_t size, const talk_base::SocketAddress& from_addr) {
+ const char* data, size_t size, const rtc::SocketAddress& from_addr) {
// If the from address is known to the client, we don't need to send it.
if (locked() && (from_addr == default_dest_)) {
Send(data, size);
@@ -707,7 +707,7 @@
}
void RelayServerBinding::NoteUsed() {
- last_used_ = talk_base::Time();
+ last_used_ = rtc::Time();
}
bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
@@ -719,7 +719,7 @@
}
RelayServerConnection* RelayServerBinding::GetInternalConnection(
- const talk_base::SocketAddress& ext_addr) {
+ const rtc::SocketAddress& ext_addr) {
// Look for an internal connection that is locked to this address.
for (size_t i = 0; i < internal_connections_.size(); ++i) {
@@ -734,7 +734,7 @@
}
RelayServerConnection* RelayServerBinding::GetExternalConnection(
- const talk_base::SocketAddress& ext_addr) {
+ const rtc::SocketAddress& ext_addr) {
for (size_t i = 0; i < external_connections_.size(); ++i) {
if (ext_addr == external_connections_[i]->addr_pair().source())
return external_connections_[i];
@@ -742,13 +742,13 @@
return 0;
}
-void RelayServerBinding::OnMessage(talk_base::Message *pmsg) {
+void RelayServerBinding::OnMessage(rtc::Message *pmsg) {
if (pmsg->message_id == MSG_LIFETIME_TIMER) {
ASSERT(!pmsg->pdata);
// If the lifetime timeout has been exceeded, then send a signal.
// Otherwise, just keep waiting.
- if (talk_base::Time() >= last_used_ + lifetime_) {
+ if (rtc::Time() >= last_used_ + lifetime_) {
LOG(LS_INFO) << "Expiring binding " << username_;
SignalTimeout(this);
} else {
diff --git a/p2p/base/relayserver.h b/p2p/base/relayserver.h
index 922a256..248d0e7 100644
--- a/p2p/base/relayserver.h
+++ b/p2p/base/relayserver.h
@@ -28,16 +28,16 @@
#ifndef TALK_P2P_BASE_RELAYSERVER_H_
#define TALK_P2P_BASE_RELAYSERVER_H_
+#include <map>
#include <string>
#include <vector>
-#include <map>
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/socketaddresspair.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
#include "talk/p2p/base/port.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/asyncudpsocket.h"
+#include "webrtc/base/socketaddresspair.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timeutils.h"
namespace cricket {
@@ -46,14 +46,14 @@
// Relays traffic between connections to the server that are "bound" together.
// All connections created with the same username/password are bound together.
-class RelayServer : public talk_base::MessageHandler,
+class RelayServer : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
// Creates a server, which will use this thread to post messages to itself.
- explicit RelayServer(talk_base::Thread* thread);
+ explicit RelayServer(rtc::Thread* thread);
~RelayServer();
- talk_base::Thread* thread() { return thread_; }
+ rtc::Thread* thread() { return thread_; }
// Indicates whether we will print updates of the number of bindings.
bool log_bindings() const { return log_bindings_; }
@@ -61,38 +61,38 @@
// Updates the set of sockets that the server uses to talk to "internal"
// clients. These are clients that do the "port allocations".
- void AddInternalSocket(talk_base::AsyncPacketSocket* socket);
- void RemoveInternalSocket(talk_base::AsyncPacketSocket* socket);
+ void AddInternalSocket(rtc::AsyncPacketSocket* socket);
+ void RemoveInternalSocket(rtc::AsyncPacketSocket* socket);
// Updates the set of sockets that the server uses to talk to "external"
// clients. These are the clients that do not do allocations. They do not
// know that these addresses represent a relay server.
- void AddExternalSocket(talk_base::AsyncPacketSocket* socket);
- void RemoveExternalSocket(talk_base::AsyncPacketSocket* socket);
+ void AddExternalSocket(rtc::AsyncPacketSocket* socket);
+ void RemoveExternalSocket(rtc::AsyncPacketSocket* socket);
// Starts listening for connections on this sockets. When someone
// tries to connect, the connection will be accepted and a new
// internal socket will be added.
- void AddInternalServerSocket(talk_base::AsyncSocket* socket,
+ void AddInternalServerSocket(rtc::AsyncSocket* socket,
cricket::ProtocolType proto);
// Removes this server socket from the list.
- void RemoveInternalServerSocket(talk_base::AsyncSocket* socket);
+ void RemoveInternalServerSocket(rtc::AsyncSocket* socket);
// Methods for testing and debuging.
int GetConnectionCount() const;
- talk_base::SocketAddressPair GetConnection(int connection) const;
- bool HasConnection(const talk_base::SocketAddress& address) const;
+ rtc::SocketAddressPair GetConnection(int connection) const;
+ bool HasConnection(const rtc::SocketAddress& address) const;
private:
- typedef std::vector<talk_base::AsyncPacketSocket*> SocketList;
- typedef std::map<talk_base::AsyncSocket*,
+ typedef std::vector<rtc::AsyncPacketSocket*> SocketList;
+ typedef std::map<rtc::AsyncSocket*,
cricket::ProtocolType> ServerSocketMap;
typedef std::map<std::string, RelayServerBinding*> BindingMap;
- typedef std::map<talk_base::SocketAddressPair,
+ typedef std::map<rtc::SocketAddressPair,
RelayServerConnection*> ConnectionMap;
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
bool log_bindings_;
SocketList internal_sockets_;
SocketList external_sockets_;
@@ -102,25 +102,25 @@
ConnectionMap connections_;
// Called when a packet is received by the server on one of its sockets.
- void OnInternalPacket(talk_base::AsyncPacketSocket* socket,
+ void OnInternalPacket(rtc::AsyncPacketSocket* socket,
const char* bytes, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
- void OnExternalPacket(talk_base::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
+ void OnExternalPacket(rtc::AsyncPacketSocket* socket,
const char* bytes, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
- void OnReadEvent(talk_base::AsyncSocket* socket);
+ void OnReadEvent(rtc::AsyncSocket* socket);
// Processes the relevant STUN request types from the client.
bool HandleStun(const char* bytes, size_t size,
- const talk_base::SocketAddress& remote_addr,
- talk_base::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& remote_addr,
+ rtc::AsyncPacketSocket* socket,
std::string* username, StunMessage* msg);
void HandleStunAllocate(const char* bytes, size_t size,
- const talk_base::SocketAddressPair& ap,
- talk_base::AsyncPacketSocket* socket);
+ const rtc::SocketAddressPair& ap,
+ rtc::AsyncPacketSocket* socket);
void HandleStun(RelayServerConnection* int_conn, const char* bytes,
size_t size);
void HandleStunAllocate(RelayServerConnection* int_conn,
@@ -133,13 +133,13 @@
void RemoveBinding(RelayServerBinding* binding);
// Handle messages in our worker thread.
- void OnMessage(talk_base::Message *pmsg);
+ void OnMessage(rtc::Message *pmsg);
// Called when the timer for checking lifetime times out.
void OnTimeout(RelayServerBinding* binding);
// Accept connections on this server socket.
- void AcceptConnection(talk_base::AsyncSocket* server_socket);
+ void AcceptConnection(rtc::AsyncSocket* server_socket);
friend class RelayServerConnection;
friend class RelayServerBinding;
@@ -150,22 +150,22 @@
class RelayServerConnection {
public:
RelayServerConnection(RelayServerBinding* binding,
- const talk_base::SocketAddressPair& addrs,
- talk_base::AsyncPacketSocket* socket);
+ const rtc::SocketAddressPair& addrs,
+ rtc::AsyncPacketSocket* socket);
~RelayServerConnection();
RelayServerBinding* binding() { return binding_; }
- talk_base::AsyncPacketSocket* socket() { return socket_; }
+ rtc::AsyncPacketSocket* socket() { return socket_; }
// Returns a pair where the source is the remote address and the destination
// is the local address.
- const talk_base::SocketAddressPair& addr_pair() { return addr_pair_; }
+ const rtc::SocketAddressPair& addr_pair() { return addr_pair_; }
// Sends a packet to the connected client. If an address is provided, then
// we make sure the internal client receives it, wrapping if necessary.
void Send(const char* data, size_t size);
void Send(const char* data, size_t size,
- const talk_base::SocketAddress& ext_addr);
+ const rtc::SocketAddress& ext_addr);
// Sends a STUN message to the connected client with no wrapping.
void SendStun(const StunMessage& msg);
@@ -179,24 +179,24 @@
// Records the address that raw packets should be forwarded to (for internal
// packets only; for external, we already know where they go).
- const talk_base::SocketAddress& default_destination() const {
+ const rtc::SocketAddress& default_destination() const {
return default_dest_;
}
- void set_default_destination(const talk_base::SocketAddress& addr) {
+ void set_default_destination(const rtc::SocketAddress& addr) {
default_dest_ = addr;
}
private:
RelayServerBinding* binding_;
- talk_base::SocketAddressPair addr_pair_;
- talk_base::AsyncPacketSocket* socket_;
+ rtc::SocketAddressPair addr_pair_;
+ rtc::AsyncPacketSocket* socket_;
bool locked_;
- talk_base::SocketAddress default_dest_;
+ rtc::SocketAddress default_dest_;
};
// Records a set of internal and external connections that we relay between,
// or in other words, that are "bound" together.
-class RelayServerBinding : public talk_base::MessageHandler {
+class RelayServerBinding : public rtc::MessageHandler {
public:
RelayServerBinding(
RelayServer* server, const std::string& username,
@@ -225,12 +225,12 @@
// Determines the connection to use to send packets to or from the given
// external address.
RelayServerConnection* GetInternalConnection(
- const talk_base::SocketAddress& ext_addr);
+ const rtc::SocketAddress& ext_addr);
RelayServerConnection* GetExternalConnection(
- const talk_base::SocketAddress& ext_addr);
+ const rtc::SocketAddress& ext_addr);
// MessageHandler:
- void OnMessage(talk_base::Message *pmsg);
+ void OnMessage(rtc::Message *pmsg);
private:
RelayServer* server_;
diff --git a/p2p/base/relayserver_unittest.cc b/p2p/base/relayserver_unittest.cc
index 239f644..1091807 100644
--- a/p2p/base/relayserver_unittest.cc
+++ b/p2p/base/relayserver_unittest.cc
@@ -27,17 +27,17 @@
#include <string>
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/testclient.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/relayserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/testclient.h"
+#include "webrtc/base/thread.h"
-using talk_base::SocketAddress;
+using rtc::SocketAddress;
using namespace cricket;
static const uint32 LIFETIME = 4; // seconds
@@ -54,35 +54,35 @@
class RelayServerTest : public testing::Test {
public:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
RelayServerTest()
- : main_(talk_base::Thread::Current()), ss_(main_->socketserver()),
- username_(talk_base::CreateRandomString(12)),
- password_(talk_base::CreateRandomString(12)) {
+ : main_(rtc::Thread::Current()), ss_(main_->socketserver()),
+ username_(rtc::CreateRandomString(12)),
+ password_(rtc::CreateRandomString(12)) {
}
protected:
virtual void SetUp() {
server_.reset(new RelayServer(main_));
server_->AddInternalSocket(
- talk_base::AsyncUDPSocket::Create(ss_, server_int_addr));
+ rtc::AsyncUDPSocket::Create(ss_, server_int_addr));
server_->AddExternalSocket(
- talk_base::AsyncUDPSocket::Create(ss_, server_ext_addr));
+ rtc::AsyncUDPSocket::Create(ss_, server_ext_addr));
- client1_.reset(new talk_base::TestClient(
- talk_base::AsyncUDPSocket::Create(ss_, client1_addr)));
- client2_.reset(new talk_base::TestClient(
- talk_base::AsyncUDPSocket::Create(ss_, client2_addr)));
+ client1_.reset(new rtc::TestClient(
+ rtc::AsyncUDPSocket::Create(ss_, client1_addr)));
+ client2_.reset(new rtc::TestClient(
+ rtc::AsyncUDPSocket::Create(ss_, client2_addr)));
}
void Allocate() {
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_ALLOCATE_REQUEST));
AddUsernameAttr(req.get(), username_);
AddLifetimeAttr(req.get(), LIFETIME);
@@ -90,7 +90,7 @@
delete Receive1();
}
void Bind() {
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_BINDING_REQUEST));
AddUsernameAttr(req.get(), username_);
Send2(req.get());
@@ -98,12 +98,12 @@
}
void Send1(const StunMessage* msg) {
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
msg->Write(&buf);
SendRaw1(buf.Data(), static_cast<int>(buf.Length()));
}
void Send2(const StunMessage* msg) {
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
msg->Write(&buf);
SendRaw2(buf.Data(), static_cast<int>(buf.Length()));
}
@@ -113,7 +113,7 @@
void SendRaw2(const char* data, int len) {
return Send(client2_.get(), data, len, server_ext_addr);
}
- void Send(talk_base::TestClient* client, const char* data,
+ void Send(rtc::TestClient* client, const char* data,
int len, const SocketAddress& addr) {
client->SendTo(data, len, addr);
}
@@ -130,20 +130,20 @@
std::string ReceiveRaw2() {
return ReceiveRaw(client2_.get());
}
- StunMessage* Receive(talk_base::TestClient* client) {
+ StunMessage* Receive(rtc::TestClient* client) {
StunMessage* msg = NULL;
- talk_base::TestClient::Packet* packet = client->NextPacket();
+ rtc::TestClient::Packet* packet = client->NextPacket();
if (packet) {
- talk_base::ByteBuffer buf(packet->buf, packet->size);
+ rtc::ByteBuffer buf(packet->buf, packet->size);
msg = new RelayMessage();
msg->Read(&buf);
delete packet;
}
return msg;
}
- std::string ReceiveRaw(talk_base::TestClient* client) {
+ std::string ReceiveRaw(rtc::TestClient* client) {
std::string raw;
- talk_base::TestClient::Packet* packet = client->NextPacket();
+ rtc::TestClient::Packet* packet = client->NextPacket();
if (packet) {
raw = std::string(packet->buf, packet->size);
delete packet;
@@ -155,7 +155,7 @@
StunMessage* msg = new RelayMessage();
msg->SetType(type);
msg->SetTransactionID(
- talk_base::CreateRandomString(kStunTransactionIdLength));
+ rtc::CreateRandomString(kStunTransactionIdLength));
return msg;
}
static void AddMagicCookieAttr(StunMessage* msg) {
@@ -184,18 +184,18 @@
msg->AddAttribute(attr);
}
- talk_base::Thread* main_;
- talk_base::SocketServer* ss_;
- talk_base::scoped_ptr<RelayServer> server_;
- talk_base::scoped_ptr<talk_base::TestClient> client1_;
- talk_base::scoped_ptr<talk_base::TestClient> client2_;
+ rtc::Thread* main_;
+ rtc::SocketServer* ss_;
+ rtc::scoped_ptr<RelayServer> server_;
+ rtc::scoped_ptr<rtc::TestClient> client1_;
+ rtc::scoped_ptr<rtc::TestClient> client2_;
std::string username_;
std::string password_;
};
// Send a complete nonsense message and verify that it is eaten.
TEST_F(RelayServerTest, TestBadRequest) {
- talk_base::scoped_ptr<StunMessage> res;
+ rtc::scoped_ptr<StunMessage> res;
SendRaw1(bad, static_cast<int>(strlen(bad)));
res.reset(Receive1());
@@ -205,7 +205,7 @@
// Send an allocate request without a username and verify it is rejected.
TEST_F(RelayServerTest, TestAllocateNoUsername) {
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_ALLOCATE_REQUEST)), res;
Send1(req.get());
@@ -224,7 +224,7 @@
// Send a binding request and verify that it is rejected.
TEST_F(RelayServerTest, TestBindingRequest) {
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_BINDING_REQUEST)), res;
AddUsernameAttr(req.get(), username_);
@@ -244,7 +244,7 @@
// Send an allocate request and verify that it is accepted.
TEST_F(RelayServerTest, TestAllocate) {
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_ALLOCATE_REQUEST)), res;
AddUsernameAttr(req.get(), username_);
AddLifetimeAttr(req.get(), LIFETIME);
@@ -274,7 +274,7 @@
TEST_F(RelayServerTest, TestReallocate) {
Allocate();
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_ALLOCATE_REQUEST)), res;
AddMagicCookieAttr(req.get());
AddUsernameAttr(req.get(), username_);
@@ -304,7 +304,7 @@
TEST_F(RelayServerTest, TestRemoteBind) {
Allocate();
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_BINDING_REQUEST)), res;
AddUsernameAttr(req.get(), username_);
@@ -318,8 +318,8 @@
res->GetByteString(STUN_ATTR_DATA);
ASSERT_TRUE(recv_data != NULL);
- talk_base::ByteBuffer buf(recv_data->bytes(), recv_data->length());
- talk_base::scoped_ptr<StunMessage> res2(new StunMessage());
+ rtc::ByteBuffer buf(recv_data->bytes(), recv_data->length());
+ rtc::scoped_ptr<StunMessage> res2(new StunMessage());
EXPECT_TRUE(res2->Read(&buf));
EXPECT_EQ(STUN_BINDING_REQUEST, res2->type());
EXPECT_EQ(req->transaction_id(), res2->transaction_id());
@@ -350,7 +350,7 @@
Allocate();
Bind();
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_SEND_REQUEST)), res;
AddMagicCookieAttr(req.get());
@@ -373,7 +373,7 @@
Allocate();
Bind();
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_SEND_REQUEST)), res;
AddMagicCookieAttr(req.get());
AddUsernameAttr(req.get(), "foobarbizbaz");
@@ -398,7 +398,7 @@
Allocate();
Bind();
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_SEND_REQUEST)), res;
AddMagicCookieAttr(req.get());
AddUsernameAttr(req.get(), username_);
@@ -422,7 +422,7 @@
Allocate();
Bind();
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_SEND_REQUEST)), res;
AddMagicCookieAttr(req.get());
AddUsernameAttr(req.get(), username_);
@@ -447,7 +447,7 @@
Allocate();
Bind();
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_BINDING_REQUEST)), res;
AddMagicCookieAttr(req.get());
AddUsernameAttr(req.get(), username_);
@@ -473,7 +473,7 @@
Bind();
for (int i = 0; i < 10; i++) {
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_SEND_REQUEST)), res;
AddMagicCookieAttr(req.get());
AddUsernameAttr(req.get(), username_);
@@ -513,9 +513,9 @@
Bind();
// Wait twice the lifetime to make sure the server has expired the binding.
- talk_base::Thread::Current()->ProcessMessages((LIFETIME * 2) * 1000);
+ rtc::Thread::Current()->ProcessMessages((LIFETIME * 2) * 1000);
- talk_base::scoped_ptr<StunMessage> req(
+ rtc::scoped_ptr<StunMessage> req(
CreateStunMessage(STUN_SEND_REQUEST)), res;
AddMagicCookieAttr(req.get());
AddUsernameAttr(req.get(), username_);
diff --git a/p2p/base/session.cc b/p2p/base/session.cc
index a48f3cb..a9bf815 100644
--- a/p2p/base/session.cc
+++ b/p2p/base/session.cc
@@ -27,26 +27,26 @@
#include "talk/p2p/base/session.h"
-#include "talk/base/bind.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/helpers.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslstreamadapter.h"
-#include "talk/xmpp/constants.h"
-#include "talk/xmpp/jid.h"
#include "talk/p2p/base/dtlstransport.h"
#include "talk/p2p/base/p2ptransport.h"
#include "talk/p2p/base/sessionclient.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/transportchannelproxy.h"
#include "talk/p2p/base/transportinfo.h"
+#include "talk/xmpp/constants.h"
+#include "talk/xmpp/jid.h"
+#include "webrtc/base/bind.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sslstreamadapter.h"
#include "talk/p2p/base/constants.h"
namespace cricket {
-using talk_base::Bind;
+using rtc::Bind;
bool BadMessage(const buzz::QName type,
const std::string& text,
@@ -64,18 +64,18 @@
}
}
-std::string TransportProxy::type() const {
+const std::string& TransportProxy::type() const {
return transport_->get()->type();
}
TransportChannel* TransportProxy::GetChannel(int component) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
return GetChannelProxy(component);
}
TransportChannel* TransportProxy::CreateChannel(
const std::string& name, int component) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(GetChannel(component) == NULL);
ASSERT(!transport_->get()->HasChannel(component));
@@ -99,7 +99,7 @@
}
void TransportProxy::DestroyChannel(int component) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
TransportChannel* channel = GetChannel(component);
if (channel) {
// If the state of TransportProxy is not NEGOTIATED
@@ -204,7 +204,7 @@
TransportChannelImpl* TransportProxy::GetOrCreateChannelProxyImpl_w(
int component) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
TransportChannelImpl* impl = transport_->get()->GetChannel(component);
if (impl == NULL) {
impl = transport_->get()->CreateChannel(component);
@@ -220,7 +220,7 @@
void TransportProxy::SetupChannelProxy_w(
int component, TransportChannelProxy* transproxy) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
TransportChannelImpl* impl = GetOrCreateChannelProxyImpl(component);
ASSERT(impl != NULL);
transproxy->SetImplementation(impl);
@@ -234,7 +234,7 @@
void TransportProxy::ReplaceChannelProxyImpl_w(TransportChannelProxy* proxy,
TransportChannelImpl* impl) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(proxy != NULL);
proxy->SetImplementation(impl);
}
@@ -336,7 +336,7 @@
}
void TransportProxy::SetIdentity(
- talk_base::SSLIdentity* identity) {
+ rtc::SSLIdentity* identity) {
transport_->get()->SetIdentity(identity);
}
@@ -377,11 +377,11 @@
default:
break;
}
- return "STATE_" + talk_base::ToString(state);
+ return "STATE_" + rtc::ToString(state);
}
-BaseSession::BaseSession(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+BaseSession::BaseSession(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
PortAllocator* port_allocator,
const std::string& sid,
const std::string& content_type,
@@ -396,9 +396,7 @@
transport_type_(NS_GINGLE_P2P),
initiator_(initiator),
identity_(NULL),
- local_description_(NULL),
- remote_description_(NULL),
- ice_tiebreaker_(talk_base::CreateRandomId64()),
+ ice_tiebreaker_(rtc::CreateRandomId64()),
role_switch_(false) {
ASSERT(signaling_thread->IsCurrent());
}
@@ -415,12 +413,41 @@
iter != transports_.end(); ++iter) {
delete iter->second;
}
-
- delete remote_description_;
- delete local_description_;
}
-bool BaseSession::SetIdentity(talk_base::SSLIdentity* identity) {
+const SessionDescription* BaseSession::local_description() const {
+ // TODO(tommi): Assert on thread correctness.
+ return local_description_.get();
+}
+
+const SessionDescription* BaseSession::remote_description() const {
+ // TODO(tommi): Assert on thread correctness.
+ return remote_description_.get();
+}
+
+SessionDescription* BaseSession::remote_description() {
+ // TODO(tommi): Assert on thread correctness.
+ return remote_description_.get();
+}
+
+void BaseSession::set_local_description(const SessionDescription* sdesc) {
+ // TODO(tommi): Assert on thread correctness.
+ if (sdesc != local_description_.get())
+ local_description_.reset(sdesc);
+}
+
+void BaseSession::set_remote_description(SessionDescription* sdesc) {
+ // TODO(tommi): Assert on thread correctness.
+ if (sdesc != remote_description_)
+ remote_description_.reset(sdesc);
+}
+
+const SessionDescription* BaseSession::initiator_description() const {
+ // TODO(tommi): Assert on thread correctness.
+ return initiator_ ? local_description_.get() : remote_description_.get();
+}
+
+bool BaseSession::SetIdentity(rtc::SSLIdentity* identity) {
if (identity_)
return false;
identity_ = identity;
@@ -435,11 +462,11 @@
ContentAction action,
std::string* error_desc) {
if (source == CS_LOCAL) {
- return PushdownLocalTransportDescription(local_description_,
+ return PushdownLocalTransportDescription(local_description(),
action,
error_desc);
}
- return PushdownRemoteTransportDescription(remote_description_,
+ return PushdownRemoteTransportDescription(remote_description(),
action,
error_desc);
}
@@ -509,8 +536,8 @@
TransportProxy* transproxy = GetTransportProxy(content_name);
if (transproxy == NULL)
return NULL;
- else
- return transproxy->GetChannel(component);
+
+ return transproxy->GetChannel(component);
}
void BaseSession::DestroyChannel(const std::string& content_name,
@@ -819,6 +846,7 @@
<< " Transport:" << transport_type();
}
+// static
bool BaseSession::GetTransportDescription(const SessionDescription* description,
const std::string& content_name,
TransportDescription* tdesc) {
@@ -882,7 +910,7 @@
return true;
}
-void BaseSession::OnMessage(talk_base::Message *pmsg) {
+void BaseSession::OnMessage(rtc::Message *pmsg) {
switch (pmsg->message_id) {
case MSG_TIMEOUT:
// Session timeout has occured.
@@ -928,7 +956,7 @@
delete transport_parser_;
}
-bool Session::Initiate(const std::string &to,
+bool Session::Initiate(const std::string& to,
const SessionDescription* sdesc) {
ASSERT(signaling_thread()->IsCurrent());
SessionError error;
@@ -1260,10 +1288,10 @@
}
void Session::OnInitiateAcked() {
- // TODO: This is to work around server re-ordering
- // messages. We send the candidates once the session-initiate
- // is acked. Once we have fixed the server to guarantee message
- // order, we can remove this case.
+ // TODO: This is to work around server re-ordering
+ // messages. We send the candidates once the session-initiate
+ // is acked. Once we have fixed the server to guarantee message
+ // order, we can remove this case.
if (!initiate_acked_) {
initiate_acked_ = true;
SessionError error;
@@ -1534,7 +1562,7 @@
signaling_thread()->Post(this, MSG_ERROR);
}
-void Session::OnMessage(talk_base::Message* pmsg) {
+void Session::OnMessage(rtc::Message* pmsg) {
// preserve this because BaseSession::OnMessage may modify it
State orig_state = state();
@@ -1682,7 +1710,7 @@
bool Session::SendMessage(ActionType type, const XmlElements& action_elems,
const std::string& remote_name, SessionError* error) {
- talk_base::scoped_ptr<buzz::XmlElement> stanza(
+ rtc::scoped_ptr<buzz::XmlElement> stanza(
new buzz::XmlElement(buzz::QN_IQ));
SessionMessage msg(current_protocol_, type, id(), initiator_name());
@@ -1696,7 +1724,7 @@
template <typename Action>
bool Session::SendMessage(ActionType type, const Action& action,
SessionError* error) {
- talk_base::scoped_ptr<buzz::XmlElement> stanza(
+ rtc::scoped_ptr<buzz::XmlElement> stanza(
new buzz::XmlElement(buzz::QN_IQ));
if (!WriteActionMessage(type, action, stanza.get(), error))
return false;
@@ -1737,7 +1765,7 @@
}
void Session::SendAcknowledgementMessage(const buzz::XmlElement* stanza) {
- talk_base::scoped_ptr<buzz::XmlElement> ack(
+ rtc::scoped_ptr<buzz::XmlElement> ack(
new buzz::XmlElement(buzz::QN_IQ));
ack->SetAttr(buzz::QN_TO, remote_name());
ack->SetAttr(buzz::QN_ID, stanza->Attr(buzz::QN_ID));
diff --git a/p2p/base/session.h b/p2p/base/session.h
index 504187f..e06cf00 100644
--- a/p2p/base/session.h
+++ b/p2p/base/session.h
@@ -33,18 +33,18 @@
#include <string>
#include <vector>
-#include "talk/base/refcount.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/scoped_ref_ptr.h"
-#include "talk/base/socketaddress.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/port.h"
#include "talk/p2p/base/sessionclient.h"
#include "talk/p2p/base/sessionmanager.h"
#include "talk/p2p/base/sessionmessages.h"
#include "talk/p2p/base/transport.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/refcount.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/scoped_ref_ptr.h"
+#include "webrtc/base/socketaddress.h"
namespace cricket {
@@ -55,7 +55,7 @@
class TransportChannelProxy;
class TransportChannelImpl;
-typedef talk_base::RefCountedObject<talk_base::scoped_ptr<Transport> >
+typedef rtc::RefCountedObject<rtc::scoped_ptr<Transport> >
TransportWrapper;
// Used for errors that will send back a specific error message to the
@@ -91,7 +91,7 @@
public CandidateTranslator {
public:
TransportProxy(
- talk_base::Thread* worker_thread,
+ rtc::Thread* worker_thread,
const std::string& sid,
const std::string& content_name,
TransportWrapper* transport)
@@ -110,12 +110,12 @@
}
~TransportProxy();
- std::string content_name() const { return content_name_; }
+ const std::string& content_name() const { return content_name_; }
// TODO(juberti): It's not good form to expose the object you're wrapping,
// since callers can mutate it. Can we make this return a const Transport*?
Transport* impl() const { return transport_->get(); }
- std::string type() const;
+ const std::string& type() const;
bool negotiated() const { return negotiated_; }
const Candidates& sent_candidates() const { return sent_candidates_; }
const Candidates& unsent_candidates() const { return unsent_candidates_; }
@@ -145,7 +145,7 @@
// Simple functions that thunk down to the same functions on Transport.
void SetIceRole(IceRole role);
- void SetIdentity(talk_base::SSLIdentity* identity);
+ void SetIdentity(rtc::SSLIdentity* identity);
bool SetLocalTransportDescription(const TransportDescription& description,
ContentAction action,
std::string* error_desc);
@@ -195,10 +195,10 @@
void ReplaceChannelProxyImpl_w(TransportChannelProxy* proxy,
TransportChannelImpl* impl);
- talk_base::Thread* worker_thread_;
- std::string sid_;
- std::string content_name_;
- talk_base::scoped_refptr<TransportWrapper> transport_;
+ rtc::Thread* const worker_thread_;
+ const std::string sid_;
+ const std::string content_name_;
+ rtc::scoped_refptr<TransportWrapper> transport_;
bool connecting_;
bool negotiated_;
ChannelMap channels_;
@@ -228,7 +228,7 @@
// packets are represented by TransportChannels. The application-level protocol
// is represented by SessionDecription objects.
class BaseSession : public sigslot::has_slots<>,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
enum {
MSG_TIMEOUT = 0,
@@ -267,17 +267,18 @@
// Convert State to a readable string.
static std::string StateToString(State state);
- BaseSession(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ BaseSession(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
PortAllocator* port_allocator,
const std::string& sid,
const std::string& content_type,
bool initiator);
virtual ~BaseSession();
- talk_base::Thread* signaling_thread() { return signaling_thread_; }
- talk_base::Thread* worker_thread() { return worker_thread_; }
- PortAllocator* port_allocator() { return port_allocator_; }
+ // These are const to allow them to be called from const methods.
+ rtc::Thread* signaling_thread() const { return signaling_thread_; }
+ rtc::Thread* worker_thread() const { return worker_thread_; }
+ PortAllocator* port_allocator() const { return port_allocator_; }
// The ID of this session.
const std::string& id() const { return sid_; }
@@ -294,43 +295,21 @@
// Returns the application-level description given by our client.
// If we are the recipient, this will be NULL until we send an accept.
- const SessionDescription* local_description() const {
- return local_description_;
- }
+ const SessionDescription* local_description() const;
+
// Returns the application-level description given by the other client.
// If we are the initiator, this will be NULL until we receive an accept.
- const SessionDescription* remote_description() const {
- return remote_description_;
- }
- SessionDescription* remote_description() {
- return remote_description_;
- }
+ const SessionDescription* remote_description() const;
+
+ SessionDescription* remote_description();
// Takes ownership of SessionDescription*
- bool set_local_description(const SessionDescription* sdesc) {
- if (sdesc != local_description_) {
- delete local_description_;
- local_description_ = sdesc;
- }
- return true;
- }
+ void set_local_description(const SessionDescription* sdesc);
// Takes ownership of SessionDescription*
- bool set_remote_description(SessionDescription* sdesc) {
- if (sdesc != remote_description_) {
- delete remote_description_;
- remote_description_ = sdesc;
- }
- return true;
- }
+ void set_remote_description(SessionDescription* sdesc);
- const SessionDescription* initiator_description() const {
- if (initiator_) {
- return local_description_;
- } else {
- return remote_description_;
- }
- }
+ const SessionDescription* initiator_description() const;
// Returns the current state of the session. See the enum above for details.
// Each time the state changes, we will fire this signal.
@@ -392,11 +371,11 @@
// This avoids exposing the internal structures used to track them.
virtual bool GetStats(SessionStats* stats);
- talk_base::SSLIdentity* identity() { return identity_; }
+ rtc::SSLIdentity* identity() { return identity_; }
protected:
// Specifies the identity to use in this session.
- bool SetIdentity(talk_base::SSLIdentity* identity);
+ bool SetIdentity(rtc::SSLIdentity* identity);
bool PushdownTransportDescription(ContentSource source,
ContentAction action,
@@ -485,7 +464,7 @@
virtual void OnRoleConflict();
// Handles messages posted to us.
- virtual void OnMessage(talk_base::Message *pmsg);
+ virtual void OnMessage(rtc::Message *pmsg);
protected:
State state_;
@@ -515,9 +494,9 @@
// Returns true and the TransportInfo of the given |content_name|
// from |description|. Returns false if it's not available.
- bool GetTransportDescription(const SessionDescription* description,
- const std::string& content_name,
- TransportDescription* info);
+ static bool GetTransportDescription(const SessionDescription* description,
+ const std::string& content_name,
+ TransportDescription* info);
// Fires the new description signal according to the current state.
void SignalNewDescription();
@@ -525,16 +504,16 @@
// Gets the ContentAction and ContentSource according to the session state.
bool GetContentAction(ContentAction* action, ContentSource* source);
- talk_base::Thread* signaling_thread_;
- talk_base::Thread* worker_thread_;
- PortAllocator* port_allocator_;
- std::string sid_;
- std::string content_type_;
- std::string transport_type_;
+ rtc::Thread* const signaling_thread_;
+ rtc::Thread* const worker_thread_;
+ PortAllocator* const port_allocator_;
+ const std::string sid_;
+ const std::string content_type_;
+ const std::string transport_type_;
bool initiator_;
- talk_base::SSLIdentity* identity_;
- const SessionDescription* local_description_;
- SessionDescription* remote_description_;
+ rtc::SSLIdentity* identity_;
+ rtc::scoped_ptr<const SessionDescription> local_description_;
+ rtc::scoped_ptr<SessionDescription> remote_description_;
uint64 ice_tiebreaker_;
// This flag will be set to true after the first role switch. This flag
// will enable us to stop any role switch during the call.
@@ -649,7 +628,7 @@
const std::string& type,
const std::string& text,
const buzz::XmlElement* extra_info);
- virtual void OnMessage(talk_base::Message *pmsg);
+ virtual void OnMessage(rtc::Message *pmsg);
// Send various kinds of session messages.
bool SendInitiateMessage(const SessionDescription* sdesc,
diff --git a/p2p/base/session_unittest.cc b/p2p/base/session_unittest.cc
index 1c08bf1..4674d2c 100644
--- a/p2p/base/session_unittest.cc
+++ b/p2p/base/session_unittest.cc
@@ -27,23 +27,15 @@
#include <string.h>
-#include <sstream>
#include <deque>
#include <map>
+#include <sstream>
-#include "talk/base/base64.h"
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/natserver.h"
-#include "talk/base/natsocketfactory.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/constants.h"
+#include "talk/p2p/base/p2ptransport.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/portallocator.h"
-#include "talk/p2p/base/p2ptransport.h"
#include "talk/p2p/base/relayport.h"
#include "talk/p2p/base/relayserver.h"
#include "talk/p2p/base/session.h"
@@ -55,6 +47,14 @@
#include "talk/p2p/base/transportchannelproxy.h"
#include "talk/p2p/base/udpport.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/natserver.h"
+#include "webrtc/base/natsocketfactory.h"
+#include "webrtc/base/stringencode.h"
using cricket::SignalingProtocol;
using cricket::PROTOCOL_HYBRID;
@@ -82,17 +82,17 @@
}
std::string GetPortString(int port_index) {
- return talk_base::ToString(GetPort(port_index));
+ return rtc::ToString(GetPort(port_index));
}
// Only works for port_index < 10, which is fine for our purposes.
std::string GetUsername(int port_index) {
- return "username" + std::string(8, talk_base::ToString(port_index)[0]);
+ return "username" + std::string(8, rtc::ToString(port_index)[0]);
}
// Only works for port_index < 10, which is fine for our purposes.
std::string GetPassword(int port_index) {
- return "password" + std::string(8, talk_base::ToString(port_index)[0]);
+ return "password" + std::string(8, rtc::ToString(port_index)[0]);
}
std::string IqAck(const std::string& id,
@@ -164,7 +164,7 @@
if (name == "rtcp" || name == "video_rtcp" || name == "chanb") {
char next_ch = username[username.size() - 1];
ASSERT(username.size() > 0);
- talk_base::Base64::GetNextBase64Char(next_ch, &next_ch);
+ rtc::Base64::GetNextBase64Char(next_ch, &next_ch);
username[username.size() - 1] = next_ch;
}
return "<candidate"
@@ -599,10 +599,9 @@
ports_(kNumPorts),
address_("127.0.0.1", 0),
network_("network", "unittest",
- talk_base::IPAddress(INADDR_LOOPBACK), 8),
- socket_factory_(talk_base::Thread::Current()),
- running_(false),
- port_(28653) {
+ rtc::IPAddress(INADDR_LOOPBACK), 8),
+ socket_factory_(rtc::Thread::Current()),
+ running_(false) {
network_.AddIP(address_.ipaddr());
}
@@ -615,7 +614,7 @@
for (int i = 0; i < kNumPorts; i++) {
int index = port_offset_ + i;
ports_[i] = cricket::UDPPort::Create(
- talk_base::Thread::Current(), &socket_factory_,
+ rtc::Thread::Current(), &socket_factory_,
&network_, address_.ipaddr(), GetPort(index), GetPort(index),
GetUsername(index), GetPassword(index));
AddPort(ports_[i]);
@@ -651,11 +650,10 @@
private:
int port_offset_;
std::vector<cricket::Port*> ports_;
- talk_base::SocketAddress address_;
- talk_base::Network network_;
- talk_base::BasicPacketSocketFactory socket_factory_;
+ rtc::SocketAddress address_;
+ rtc::Network network_;
+ rtc::BasicPacketSocketFactory socket_factory_;
bool running_;
- int port_;
};
class TestPortAllocator : public cricket::PortAllocator {
@@ -801,7 +799,7 @@
}
void OnReadPacket(cricket::TransportChannel* p, const char* buf,
- size_t size, const talk_base::PacketTime& time, int flags) {
+ size_t size, const rtc::PacketTime& time, int flags) {
if (memcmp(buf, name.c_str(), name.size()) != 0)
return; // drop packet if packet doesn't belong to this channel. This
// can happen when transport channels are muxed together.
@@ -815,7 +813,7 @@
}
void Send(const char* data, size_t size) {
- talk_base::PacketOptions options;
+ rtc::PacketOptions options;
std::string data_with_id(name);
data_with_id += data;
int result = channel->SendPacket(data_with_id.c_str(), data_with_id.size(),
@@ -1108,15 +1106,15 @@
cricket::ContentAction last_content_action;
cricket::ContentSource last_content_source;
std::deque<buzz::XmlElement*> sent_stanzas;
- talk_base::scoped_ptr<buzz::XmlElement> last_expected_sent_stanza;
+ rtc::scoped_ptr<buzz::XmlElement> last_expected_sent_stanza;
cricket::SessionManager* session_manager;
TestSessionClient* client;
cricket::PortAllocator* port_allocator_;
cricket::Session* session;
cricket::BaseSession::State last_session_state;
- talk_base::scoped_ptr<ChannelHandler> chan_a;
- talk_base::scoped_ptr<ChannelHandler> chan_b;
+ rtc::scoped_ptr<ChannelHandler> chan_a;
+ rtc::scoped_ptr<ChannelHandler> chan_b;
bool blow_up_on_error;
int error_count;
};
@@ -1125,11 +1123,11 @@
protected:
virtual void SetUp() {
// Seed needed for each test to satisfy expectations.
- talk_base::SetRandomTestMode(true);
+ rtc::SetRandomTestMode(true);
}
virtual void TearDown() {
- talk_base::SetRandomTestMode(false);
+ rtc::SetRandomTestMode(false);
}
// Tests sending data between two clients, over two channels.
@@ -1185,17 +1183,17 @@
const std::string& transport_info_reply_b_xml,
const std::string& accept_xml,
bool bundle = false) {
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, initiator_protocol,
content_type,
content_name_a, channel_name_a,
content_name_b, channel_name_b));
- talk_base::scoped_ptr<TestClient> responder(
+ rtc::scoped_ptr<TestClient> responder(
new TestClient(allocator.get(), &next_message_id,
kResponder, responder_protocol,
content_type,
@@ -1624,18 +1622,18 @@
protocol, content_name, content_type);
std::string responder_full = kResponder + "/full";
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, protocol,
content_type,
content_name, channel_name_a,
content_name, channel_name_b));
- talk_base::scoped_ptr<TestClient> responder(
+ rtc::scoped_ptr<TestClient> responder(
new TestClient(allocator.get(), &next_message_id,
responder_full, protocol,
content_type,
@@ -1676,7 +1674,7 @@
// Send an unauthorized redirect to the initiator and expect it be ignored.
initiator->blow_up_on_error = false;
const buzz::XmlElement* initiate_stanza = initiator->stanza();
- talk_base::scoped_ptr<buzz::XmlElement> redirect_stanza(
+ rtc::scoped_ptr<buzz::XmlElement> redirect_stanza(
buzz::XmlElement::ForStr(
IqError("ER", kResponder, kInitiator,
RedirectXml(protocol, initiate_xml, "not@allowed.com"))));
@@ -1706,18 +1704,18 @@
protocol, content_name, content_type);
std::string responder_full = kResponder + "/full";
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, protocol,
content_type,
content_name, channel_name_a,
content_name, channel_name_b));
- talk_base::scoped_ptr<TestClient> responder(
+ rtc::scoped_ptr<TestClient> responder(
new TestClient(allocator.get(), &next_message_id,
responder_full, protocol,
content_type,
@@ -1758,7 +1756,7 @@
// Send a redirect to the initiator and expect all of the message
// to be resent.
const buzz::XmlElement* initiate_stanza = initiator->stanza();
- talk_base::scoped_ptr<buzz::XmlElement> redirect_stanza(
+ rtc::scoped_ptr<buzz::XmlElement> redirect_stanza(
buzz::XmlElement::ForStr(
IqError("ER2", kResponder, kInitiator,
RedirectXml(protocol, initiate_xml, responder_full))));
@@ -1851,18 +1849,18 @@
std::string channel_name_b = "rtcp";
cricket::SignalingProtocol protocol = PROTOCOL_JINGLE;
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, protocol,
content_type,
content_name, channel_name_a,
content_name, channel_name_b));
- talk_base::scoped_ptr<TestClient> responder(
+ rtc::scoped_ptr<TestClient> responder(
new TestClient(allocator.get(), &next_message_id,
kResponder, protocol,
content_type,
@@ -1988,18 +1986,18 @@
std::string content_name = "main";
std::string content_type = "http://oink.splat/session";
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, protocol,
content_type,
content_name, "a",
content_name, "b"));
- talk_base::scoped_ptr<TestClient> responder(
+ rtc::scoped_ptr<TestClient> responder(
new TestClient(allocator.get(), &next_message_id,
kResponder, protocol,
content_type,
@@ -2042,11 +2040,11 @@
std::string content_name = "main";
std::string content_type = "http://oink.splat/session";
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, protocol,
content_type,
@@ -2124,13 +2122,13 @@
}
void TestSendDescriptionInfo() {
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
std::string content_name = "content-name";
std::string content_type = "content-type";
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, PROTOCOL_JINGLE,
content_type,
@@ -2178,13 +2176,13 @@
}
void TestCallerSignalNewDescription() {
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
std::string content_name = "content-name";
std::string content_type = "content-type";
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, PROTOCOL_JINGLE,
content_type,
@@ -2218,13 +2216,13 @@
}
void TestCalleeSignalNewDescription() {
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
std::string content_name = "content-name";
std::string content_type = "content-type";
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, PROTOCOL_JINGLE,
content_type,
@@ -2258,13 +2256,13 @@
}
void TestGetTransportStats() {
- talk_base::scoped_ptr<cricket::PortAllocator> allocator(
+ rtc::scoped_ptr<cricket::PortAllocator> allocator(
new TestPortAllocator());
int next_message_id = 0;
std::string content_name = "content-name";
std::string content_type = "content-type";
- talk_base::scoped_ptr<TestClient> initiator(
+ rtc::scoped_ptr<TestClient> initiator(
new TestClient(allocator.get(), &next_message_id,
kInitiator, PROTOCOL_JINGLE,
content_type,
diff --git a/p2p/base/sessiondescription.cc b/p2p/base/sessiondescription.cc
index 7009aa8..7ad3d48 100644
--- a/p2p/base/sessiondescription.cc
+++ b/p2p/base/sessiondescription.cc
@@ -27,7 +27,7 @@
#include "talk/p2p/base/sessiondescription.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
namespace cricket {
diff --git a/p2p/base/sessiondescription.h b/p2p/base/sessiondescription.h
index d33b4c3..56dd412 100644
--- a/p2p/base/sessiondescription.h
+++ b/p2p/base/sessiondescription.h
@@ -31,8 +31,8 @@
#include <string>
#include <vector>
-#include "talk/base/constructormagic.h"
#include "talk/p2p/base/transportinfo.h"
+#include "webrtc/base/constructormagic.h"
namespace cricket {
diff --git a/p2p/base/sessionmanager.cc b/p2p/base/sessionmanager.cc
index 15b7452..d173517 100644
--- a/p2p/base/sessionmanager.cc
+++ b/p2p/base/sessionmanager.cc
@@ -27,25 +27,25 @@
#include "talk/p2p/base/sessionmanager.h"
-#include "talk/base/common.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/session.h"
#include "talk/p2p/base/sessionmessages.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/jid.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
SessionManager::SessionManager(PortAllocator *allocator,
- talk_base::Thread *worker) {
+ rtc::Thread *worker) {
allocator_ = allocator;
- signaling_thread_ = talk_base::Thread::Current();
+ signaling_thread_ = rtc::Thread::Current();
if (worker == NULL) {
- worker_thread_ = talk_base::Thread::Current();
+ worker_thread_ = rtc::Thread::Current();
} else {
worker_thread_ = worker;
}
@@ -87,7 +87,7 @@
const std::string& local_name,
const std::string& content_type) {
std::string sid =
- id.empty() ? talk_base::ToString(talk_base::CreateRandomId64()) : id;
+ id.empty() ? rtc::ToString(rtc::CreateRandomId64()) : id;
return CreateSession(local_name, local_name, sid, content_type, false);
}
@@ -231,7 +231,7 @@
Session* session = FindSession(msg.sid, msg.to);
if (session) {
- talk_base::scoped_ptr<buzz::XmlElement> synthetic_error;
+ rtc::scoped_ptr<buzz::XmlElement> synthetic_error;
if (!error_stanza) {
// A failed send is semantically equivalent to an error response, so we
// can just turn the former into the latter.
@@ -250,7 +250,7 @@
const std::string& type,
const std::string& text,
const buzz::XmlElement* extra_info) {
- talk_base::scoped_ptr<buzz::XmlElement> msg(
+ rtc::scoped_ptr<buzz::XmlElement> msg(
CreateErrorMessage(stanza, name, type, text, extra_info));
SignalOutgoingMessage(this, msg.get());
}
diff --git a/p2p/base/sessionmanager.h b/p2p/base/sessionmanager.h
index d88e050..92aeb3d 100644
--- a/p2p/base/sessionmanager.h
+++ b/p2p/base/sessionmanager.h
@@ -33,10 +33,10 @@
#include <utility>
#include <vector>
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/portallocator.h"
#include "talk/p2p/base/transportdescriptionfactory.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
namespace buzz {
class QName;
@@ -53,12 +53,12 @@
class SessionManager : public sigslot::has_slots<> {
public:
SessionManager(PortAllocator *allocator,
- talk_base::Thread *worker_thread = NULL);
+ rtc::Thread *worker_thread = NULL);
virtual ~SessionManager();
PortAllocator *port_allocator() const { return allocator_; }
- talk_base::Thread *worker_thread() const { return worker_thread_; }
- talk_base::Thread *signaling_thread() const { return signaling_thread_; }
+ rtc::Thread *worker_thread() const { return worker_thread_; }
+ rtc::Thread *signaling_thread() const { return signaling_thread_; }
int session_timeout() const { return timeout_; }
void set_session_timeout(int timeout) { timeout_ = timeout; }
@@ -72,7 +72,7 @@
void set_secure(SecurePolicy policy) {
transport_desc_factory_.set_secure(policy);
}
- void set_identity(talk_base::SSLIdentity* identity) {
+ void set_identity(rtc::SSLIdentity* identity) {
transport_desc_factory_.set_identity(identity);
}
const TransportDescriptionFactory* transport_desc_factory() const {
@@ -198,8 +198,8 @@
const buzz::XmlElement* extra_info);
PortAllocator *allocator_;
- talk_base::Thread *signaling_thread_;
- talk_base::Thread *worker_thread_;
+ rtc::Thread *signaling_thread_;
+ rtc::Thread *worker_thread_;
int timeout_;
TransportDescriptionFactory transport_desc_factory_;
SessionMap session_map_;
diff --git a/p2p/base/sessionmessages.cc b/p2p/base/sessionmessages.cc
index 7a03d76..b2fd9d6 100644
--- a/p2p/base/sessionmessages.cc
+++ b/p2p/base/sessionmessages.cc
@@ -30,17 +30,17 @@
#include <stdio.h>
#include <string>
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/p2ptransport.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/sessionclient.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/p2p/base/transport.h"
-#include "talk/xmllite/xmlconstants.h"
+#include "webrtc/libjingle/xmllite/xmlconstants.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
@@ -491,7 +491,7 @@
return false;
for (size_t i = 0; i < candidates.size(); ++i) {
- talk_base::scoped_ptr<buzz::XmlElement> element;
+ rtc::scoped_ptr<buzz::XmlElement> element;
if (!trans_parser->WriteGingleCandidate(candidates[i], translator,
element.accept(), error)) {
return false;
@@ -627,7 +627,7 @@
// namespace and only parse the codecs relevant to that namespace.
// We use this to control which codecs get parsed: first audio,
// then video.
- talk_base::scoped_ptr<buzz::XmlElement> audio_elem(
+ rtc::scoped_ptr<buzz::XmlElement> audio_elem(
new buzz::XmlElement(QN_GINGLE_AUDIO_CONTENT));
CopyXmlChildren(content_elem, audio_elem.get());
if (!ParseContentInfo(PROTOCOL_GINGLE, CN_AUDIO, NS_JINGLE_RTP,
diff --git a/p2p/base/sessionmessages.h b/p2p/base/sessionmessages.h
index 5cd565c..7e1f8ac 100644
--- a/p2p/base/sessionmessages.h
+++ b/p2p/base/sessionmessages.h
@@ -28,16 +28,16 @@
#ifndef TALK_P2P_BASE_SESSIONMESSAGES_H_
#define TALK_P2P_BASE_SESSIONMESSAGES_H_
+#include <map>
#include <string>
#include <vector>
-#include <map>
-#include "talk/base/basictypes.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/sessiondescription.h" // Needed to delete contents.
#include "talk/p2p/base/transportinfo.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
+#include "webrtc/base/basictypes.h"
namespace cricket {
diff --git a/p2p/base/stun.cc b/p2p/base/stun.cc
index 6331ba9..061fd9a 100644
--- a/p2p/base/stun.cc
+++ b/p2p/base/stun.cc
@@ -29,18 +29,19 @@
#include <string.h>
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/crc32.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringencode.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/crc32.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stringencode.h"
-using talk_base::ByteBuffer;
+using rtc::ByteBuffer;
namespace cricket {
+const char STUN_ERROR_REASON_TRY_ALTERNATE_SERVER[] = "Try Alternate Server";
const char STUN_ERROR_REASON_BAD_REQUEST[] = "Bad Request";
const char STUN_ERROR_REASON_UNAUTHORIZED[] = "Unauthorized";
const char STUN_ERROR_REASON_FORBIDDEN[] = "Forbidden";
@@ -151,7 +152,7 @@
}
// Getting the message length from the STUN header.
- uint16 msg_length = talk_base::GetBE16(&data[2]);
+ uint16 msg_length = rtc::GetBE16(&data[2]);
if (size != (msg_length + kStunHeaderSize)) {
return false;
}
@@ -162,8 +163,8 @@
while (current_pos < size) {
uint16 attr_type, attr_length;
// Getting attribute type and length.
- attr_type = talk_base::GetBE16(&data[current_pos]);
- attr_length = talk_base::GetBE16(&data[current_pos + sizeof(attr_type)]);
+ attr_type = rtc::GetBE16(&data[current_pos]);
+ attr_length = rtc::GetBE16(&data[current_pos + sizeof(attr_type)]);
// If M-I, sanity check it, and break out.
if (attr_type == STUN_ATTR_MESSAGE_INTEGRITY) {
@@ -188,7 +189,7 @@
// Getting length of the message to calculate Message Integrity.
size_t mi_pos = current_pos;
- talk_base::scoped_ptr<char[]> temp_data(new char[current_pos]);
+ rtc::scoped_ptr<char[]> temp_data(new char[current_pos]);
memcpy(temp_data.get(), data, current_pos);
if (size > mi_pos + kStunAttributeHeaderSize + kStunMessageIntegritySize) {
// Stun message has other attributes after message integrity.
@@ -203,12 +204,12 @@
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |0 0| STUN Message Type | Message Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- talk_base::SetBE16(temp_data.get() + 2,
+ rtc::SetBE16(temp_data.get() + 2,
static_cast<uint16>(new_adjusted_len));
}
char hmac[kStunMessageIntegritySize];
- size_t ret = talk_base::ComputeHmac(talk_base::DIGEST_SHA_1,
+ size_t ret = rtc::ComputeHmac(rtc::DIGEST_SHA_1,
password.c_str(), password.size(),
temp_data.get(), mi_pos,
hmac, sizeof(hmac));
@@ -236,14 +237,14 @@
VERIFY(AddAttribute(msg_integrity_attr));
// Calculate the HMAC for the message.
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
if (!Write(&buf))
return false;
int msg_len_for_hmac = static_cast<int>(
buf.Length() - kStunAttributeHeaderSize - msg_integrity_attr->length());
char hmac[kStunMessageIntegritySize];
- size_t ret = talk_base::ComputeHmac(talk_base::DIGEST_SHA_1,
+ size_t ret = rtc::ComputeHmac(rtc::DIGEST_SHA_1,
key, keylen,
buf.Data(), msg_len_for_hmac,
hmac, sizeof(hmac));
@@ -272,21 +273,21 @@
// Skip the rest if the magic cookie isn't present.
const char* magic_cookie =
data + kStunTransactionIdOffset - kStunMagicCookieLength;
- if (talk_base::GetBE32(magic_cookie) != kStunMagicCookie)
+ if (rtc::GetBE32(magic_cookie) != kStunMagicCookie)
return false;
// Check the fingerprint type and length.
const char* fingerprint_attr_data = data + size - fingerprint_attr_size;
- if (talk_base::GetBE16(fingerprint_attr_data) != STUN_ATTR_FINGERPRINT ||
- talk_base::GetBE16(fingerprint_attr_data + sizeof(uint16)) !=
+ if (rtc::GetBE16(fingerprint_attr_data) != STUN_ATTR_FINGERPRINT ||
+ rtc::GetBE16(fingerprint_attr_data + sizeof(uint16)) !=
StunUInt32Attribute::SIZE)
return false;
// Check the fingerprint value.
uint32 fingerprint =
- talk_base::GetBE32(fingerprint_attr_data + kStunAttributeHeaderSize);
+ rtc::GetBE32(fingerprint_attr_data + kStunAttributeHeaderSize);
return ((fingerprint ^ STUN_FINGERPRINT_XOR_VALUE) ==
- talk_base::ComputeCrc32(data, size - fingerprint_attr_size));
+ rtc::ComputeCrc32(data, size - fingerprint_attr_size));
}
bool StunMessage::AddFingerprint() {
@@ -297,13 +298,13 @@
VERIFY(AddAttribute(fingerprint_attr));
// Calculate the CRC-32 for the message and insert it.
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
if (!Write(&buf))
return false;
int msg_len_for_crc32 = static_cast<int>(
buf.Length() - kStunAttributeHeaderSize - fingerprint_attr->length());
- uint32 c = talk_base::ComputeCrc32(buf.Data(), msg_len_for_crc32);
+ uint32 c = rtc::ComputeCrc32(buf.Data(), msg_len_for_crc32);
// Insert the correct CRC-32, XORed with a constant, into the attribute.
fingerprint_attr->SetValue(c ^ STUN_FINGERPRINT_XOR_VALUE);
@@ -333,7 +334,7 @@
uint32 magic_cookie_int =
*reinterpret_cast<const uint32*>(magic_cookie.data());
- if (talk_base::NetworkToHost32(magic_cookie_int) != kStunMagicCookie) {
+ if (rtc::NetworkToHost32(magic_cookie_int) != kStunMagicCookie) {
// If magic cookie is invalid it means that the peer implements
// RFC3489 instead of RFC5389.
transaction_id.insert(0, magic_cookie);
@@ -401,7 +402,7 @@
case STUN_ATTR_NONCE: return STUN_VALUE_BYTE_STRING;
case STUN_ATTR_XOR_MAPPED_ADDRESS: return STUN_VALUE_XOR_ADDRESS;
case STUN_ATTR_SOFTWARE: return STUN_VALUE_BYTE_STRING;
- case STUN_ATTR_ALTERNATE_SERVER: return STUN_VALUE_BYTE_STRING;
+ case STUN_ATTR_ALTERNATE_SERVER: return STUN_VALUE_ADDRESS;
case STUN_ATTR_FINGERPRINT: return STUN_VALUE_UINT32;
case STUN_ATTR_RETRANSMIT_COUNT: return STUN_VALUE_UINT32;
default: return STUN_VALUE_UNKNOWN;
@@ -433,14 +434,14 @@
: type_(type), length_(length) {
}
-void StunAttribute::ConsumePadding(talk_base::ByteBuffer* buf) const {
+void StunAttribute::ConsumePadding(rtc::ByteBuffer* buf) const {
int remainder = length_ % 4;
if (remainder > 0) {
buf->Consume(4 - remainder);
}
}
-void StunAttribute::WritePadding(talk_base::ByteBuffer* buf) const {
+void StunAttribute::WritePadding(rtc::ByteBuffer* buf) const {
int remainder = length_ % 4;
if (remainder > 0) {
char zeroes[4] = {0};
@@ -501,7 +502,7 @@
}
StunAddressAttribute::StunAddressAttribute(uint16 type,
- const talk_base::SocketAddress& addr)
+ const rtc::SocketAddress& addr)
: StunAttribute(type, 0) {
SetAddress(addr);
}
@@ -530,8 +531,8 @@
if (!buf->ReadBytes(reinterpret_cast<char*>(&v4addr), sizeof(v4addr))) {
return false;
}
- talk_base::IPAddress ipaddr(v4addr);
- SetAddress(talk_base::SocketAddress(ipaddr, port));
+ rtc::IPAddress ipaddr(v4addr);
+ SetAddress(rtc::SocketAddress(ipaddr, port));
} else if (stun_family == STUN_ADDRESS_IPV6) {
in6_addr v6addr;
if (length() != SIZE_IP6) {
@@ -540,8 +541,8 @@
if (!buf->ReadBytes(reinterpret_cast<char*>(&v6addr), sizeof(v6addr))) {
return false;
}
- talk_base::IPAddress ipaddr(v6addr);
- SetAddress(talk_base::SocketAddress(ipaddr, port));
+ rtc::IPAddress ipaddr(v6addr);
+ SetAddress(rtc::SocketAddress(ipaddr, port));
} else {
return false;
}
@@ -573,7 +574,7 @@
}
StunXorAddressAttribute::StunXorAddressAttribute(uint16 type,
- const talk_base::SocketAddress& addr)
+ const rtc::SocketAddress& addr)
: StunAddressAttribute(type, addr), owner_(NULL) {
}
@@ -582,15 +583,15 @@
StunMessage* owner)
: StunAddressAttribute(type, length), owner_(owner) {}
-talk_base::IPAddress StunXorAddressAttribute::GetXoredIP() const {
+rtc::IPAddress StunXorAddressAttribute::GetXoredIP() const {
if (owner_) {
- talk_base::IPAddress ip = ipaddr();
+ rtc::IPAddress ip = ipaddr();
switch (ip.family()) {
case AF_INET: {
in_addr v4addr = ip.ipv4_address();
v4addr.s_addr =
- (v4addr.s_addr ^ talk_base::HostToNetwork32(kStunMagicCookie));
- return talk_base::IPAddress(v4addr);
+ (v4addr.s_addr ^ rtc::HostToNetwork32(kStunMagicCookie));
+ return rtc::IPAddress(v4addr);
}
case AF_INET6: {
in6_addr v6addr = ip.ipv6_address();
@@ -603,11 +604,11 @@
// Transaction ID is in network byte order, but magic cookie
// is stored in host byte order.
ip_as_ints[0] =
- (ip_as_ints[0] ^ talk_base::HostToNetwork32(kStunMagicCookie));
+ (ip_as_ints[0] ^ rtc::HostToNetwork32(kStunMagicCookie));
ip_as_ints[1] = (ip_as_ints[1] ^ transactionid_as_ints[0]);
ip_as_ints[2] = (ip_as_ints[2] ^ transactionid_as_ints[1]);
ip_as_ints[3] = (ip_as_ints[3] ^ transactionid_as_ints[2]);
- return talk_base::IPAddress(v6addr);
+ return rtc::IPAddress(v6addr);
}
break;
}
@@ -615,15 +616,15 @@
}
// Invalid ip family or transaction ID, or missing owner.
// Return an AF_UNSPEC address.
- return talk_base::IPAddress();
+ return rtc::IPAddress();
}
bool StunXorAddressAttribute::Read(ByteBuffer* buf) {
if (!StunAddressAttribute::Read(buf))
return false;
uint16 xoredport = port() ^ (kStunMagicCookie >> 16);
- talk_base::IPAddress xored_ip = GetXoredIP();
- SetAddress(talk_base::SocketAddress(xored_ip, xoredport));
+ rtc::IPAddress xored_ip = GetXoredIP();
+ SetAddress(rtc::SocketAddress(xored_ip, xoredport));
return true;
}
@@ -633,7 +634,7 @@
LOG(LS_ERROR) << "Error writing xor-address attribute: unknown family.";
return false;
}
- talk_base::IPAddress xored_ip = GetXoredIP();
+ rtc::IPAddress xored_ip = GetXoredIP();
if (xored_ip.family() == AF_UNSPEC) {
return false;
}
@@ -916,9 +917,9 @@
input += ':';
input += password;
- char digest[talk_base::MessageDigest::kMaxSize];
- size_t size = talk_base::ComputeDigest(
- talk_base::DIGEST_MD5, input.c_str(), input.size(),
+ char digest[rtc::MessageDigest::kMaxSize];
+ size_t size = rtc::ComputeDigest(
+ rtc::DIGEST_MD5, input.c_str(), input.size(),
digest, sizeof(digest));
if (size == 0) {
return false;
diff --git a/p2p/base/stun.h b/p2p/base/stun.h
index 6416e51..c4f522b 100644
--- a/p2p/base/stun.h
+++ b/p2p/base/stun.h
@@ -34,9 +34,9 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/socketaddress.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/socketaddress.h"
namespace cricket {
@@ -63,7 +63,7 @@
STUN_ATTR_NONCE = 0x0015, // ByteString
STUN_ATTR_XOR_MAPPED_ADDRESS = 0x0020, // XorAddress
STUN_ATTR_SOFTWARE = 0x8022, // ByteString
- STUN_ATTR_ALTERNATE_SERVER = 0x8023, // ByteString
+ STUN_ATTR_ALTERNATE_SERVER = 0x8023, // Address
STUN_ATTR_FINGERPRINT = 0x8028, // UInt32
STUN_ATTR_RETRANSMIT_COUNT = 0xFF00 // UInt32
};
@@ -104,6 +104,7 @@
};
// Strings for the error codes above.
+extern const char STUN_ERROR_REASON_TRY_ALTERNATE_SERVER[];
extern const char STUN_ERROR_REASON_BAD_REQUEST[];
extern const char STUN_ERROR_REASON_UNAUTHORIZED[];
extern const char STUN_ERROR_REASON_UNKNOWN_ATTRIBUTE[];
@@ -195,11 +196,11 @@
// Parses the STUN packet in the given buffer and records it here. The
// return value indicates whether this was successful.
- bool Read(talk_base::ByteBuffer* buf);
+ bool Read(rtc::ByteBuffer* buf);
// Writes this object into a STUN packet. The return value indicates whether
// this was successful.
- bool Write(talk_base::ByteBuffer* buf) const;
+ bool Write(rtc::ByteBuffer* buf) const;
// Creates an empty message. Overridable by derived classes.
virtual StunMessage* CreateNew() const { return new StunMessage(); }
@@ -236,11 +237,11 @@
// Reads the body (not the type or length) for this type of attribute from
// the given buffer. Return value is true if successful.
- virtual bool Read(talk_base::ByteBuffer* buf) = 0;
+ virtual bool Read(rtc::ByteBuffer* buf) = 0;
// Writes the body (not the type or length) to the given buffer. Return
// value is true if successful.
- virtual bool Write(talk_base::ByteBuffer* buf) const = 0;
+ virtual bool Write(rtc::ByteBuffer* buf) const = 0;
// Creates an attribute object with the given type and smallest length.
static StunAttribute* Create(StunAttributeValueType value_type, uint16 type,
@@ -258,8 +259,8 @@
protected:
StunAttribute(uint16 type, uint16 length);
void SetLength(uint16 length) { length_ = length; }
- void WritePadding(talk_base::ByteBuffer* buf) const;
- void ConsumePadding(talk_base::ByteBuffer* buf) const;
+ void WritePadding(rtc::ByteBuffer* buf) const;
+ void ConsumePadding(rtc::ByteBuffer* buf) const;
private:
uint16 type_;
@@ -272,7 +273,7 @@
static const uint16 SIZE_UNDEF = 0;
static const uint16 SIZE_IP4 = 8;
static const uint16 SIZE_IP6 = 20;
- StunAddressAttribute(uint16 type, const talk_base::SocketAddress& addr);
+ StunAddressAttribute(uint16 type, const rtc::SocketAddress& addr);
StunAddressAttribute(uint16 type, uint16 length);
virtual StunAttributeValueType value_type() const {
@@ -289,22 +290,22 @@
return STUN_ADDRESS_UNDEF;
}
- const talk_base::SocketAddress& GetAddress() const { return address_; }
- const talk_base::IPAddress& ipaddr() const { return address_.ipaddr(); }
+ const rtc::SocketAddress& GetAddress() const { return address_; }
+ const rtc::IPAddress& ipaddr() const { return address_.ipaddr(); }
uint16 port() const { return address_.port(); }
- void SetAddress(const talk_base::SocketAddress& addr) {
+ void SetAddress(const rtc::SocketAddress& addr) {
address_ = addr;
EnsureAddressLength();
}
- void SetIP(const talk_base::IPAddress& ip) {
+ void SetIP(const rtc::IPAddress& ip) {
address_.SetIP(ip);
EnsureAddressLength();
}
void SetPort(uint16 port) { address_.SetPort(port); }
- virtual bool Read(talk_base::ByteBuffer* buf);
- virtual bool Write(talk_base::ByteBuffer* buf) const;
+ virtual bool Read(rtc::ByteBuffer* buf);
+ virtual bool Write(rtc::ByteBuffer* buf) const;
private:
void EnsureAddressLength() {
@@ -323,7 +324,7 @@
}
}
}
- talk_base::SocketAddress address_;
+ rtc::SocketAddress address_;
};
// Implements STUN attributes that record an Internet address. When encoded
@@ -331,7 +332,7 @@
// transaction ID of the message.
class StunXorAddressAttribute : public StunAddressAttribute {
public:
- StunXorAddressAttribute(uint16 type, const talk_base::SocketAddress& addr);
+ StunXorAddressAttribute(uint16 type, const rtc::SocketAddress& addr);
StunXorAddressAttribute(uint16 type, uint16 length,
StunMessage* owner);
@@ -341,11 +342,11 @@
virtual void SetOwner(StunMessage* owner) {
owner_ = owner;
}
- virtual bool Read(talk_base::ByteBuffer* buf);
- virtual bool Write(talk_base::ByteBuffer* buf) const;
+ virtual bool Read(rtc::ByteBuffer* buf);
+ virtual bool Write(rtc::ByteBuffer* buf) const;
private:
- talk_base::IPAddress GetXoredIP() const;
+ rtc::IPAddress GetXoredIP() const;
StunMessage* owner_;
};
@@ -366,8 +367,8 @@
bool GetBit(size_t index) const;
void SetBit(size_t index, bool value);
- virtual bool Read(talk_base::ByteBuffer* buf);
- virtual bool Write(talk_base::ByteBuffer* buf) const;
+ virtual bool Read(rtc::ByteBuffer* buf);
+ virtual bool Write(rtc::ByteBuffer* buf) const;
private:
uint32 bits_;
@@ -386,8 +387,8 @@
uint64 value() const { return bits_; }
void SetValue(uint64 bits) { bits_ = bits; }
- virtual bool Read(talk_base::ByteBuffer* buf);
- virtual bool Write(talk_base::ByteBuffer* buf) const;
+ virtual bool Read(rtc::ByteBuffer* buf);
+ virtual bool Write(rtc::ByteBuffer* buf) const;
private:
uint64 bits_;
@@ -415,8 +416,8 @@
uint8 GetByte(size_t index) const;
void SetByte(size_t index, uint8 value);
- virtual bool Read(talk_base::ByteBuffer* buf);
- virtual bool Write(talk_base::ByteBuffer* buf) const;
+ virtual bool Read(rtc::ByteBuffer* buf);
+ virtual bool Write(rtc::ByteBuffer* buf) const;
private:
void SetBytes(char* bytes, size_t length);
@@ -448,8 +449,8 @@
void SetNumber(uint8 number) { number_ = number; }
void SetReason(const std::string& reason);
- bool Read(talk_base::ByteBuffer* buf);
- bool Write(talk_base::ByteBuffer* buf) const;
+ bool Read(rtc::ByteBuffer* buf);
+ bool Write(rtc::ByteBuffer* buf) const;
private:
uint8 class_;
@@ -472,8 +473,8 @@
void SetType(int index, uint16 value);
void AddType(uint16 value);
- bool Read(talk_base::ByteBuffer* buf);
- bool Write(talk_base::ByteBuffer* buf) const;
+ bool Read(rtc::ByteBuffer* buf);
+ bool Write(rtc::ByteBuffer* buf) const;
private:
std::vector<uint16>* attr_types_;
diff --git a/p2p/base/stun_unittest.cc b/p2p/base/stun_unittest.cc
index 71d8750..00dffed 100644
--- a/p2p/base/stun_unittest.cc
+++ b/p2p/base/stun_unittest.cc
@@ -27,13 +27,13 @@
#include <string>
-#include "talk/base/bytebuffer.h"
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketaddress.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketaddress.h"
namespace cricket {
@@ -56,7 +56,7 @@
void CheckStunAddressAttribute(const StunAddressAttribute* addr,
StunAddressFamily expected_family,
int expected_port,
- talk_base::IPAddress expected_address) {
+ rtc::IPAddress expected_address) {
ASSERT_EQ(expected_family, addr->family());
ASSERT_EQ(expected_port, addr->port());
@@ -78,7 +78,7 @@
const unsigned char* testcase,
size_t size) {
const char* input = reinterpret_cast<const char*>(testcase);
- talk_base::ByteBuffer buf(input, size);
+ rtc::ByteBuffer buf(input, size);
if (msg->Read(&buf)) {
// Returns the size the stun message should report itself as being
return (size - 20);
@@ -267,9 +267,9 @@
static const char kRfc5769SampleMsgServerSoftware[] = "test vector";
static const char kRfc5769SampleMsgUsername[] = "evtj:h6vY";
static const char kRfc5769SampleMsgPassword[] = "VOkJxbRl1RmTxUk/WvJxBt";
-static const talk_base::SocketAddress kRfc5769SampleMsgMappedAddress(
+static const rtc::SocketAddress kRfc5769SampleMsgMappedAddress(
"192.0.2.1", 32853);
-static const talk_base::SocketAddress kRfc5769SampleMsgIPv6MappedAddress(
+static const rtc::SocketAddress kRfc5769SampleMsgIPv6MappedAddress(
"2001:db8:1234:5678:11:2233:4455:6677", 32853);
static const unsigned char kRfc5769SampleMsgWithAuthTransactionId[] = {
@@ -533,7 +533,7 @@
CheckStunTransactionID(msg, kTestTransactionId1, kStunTransactionIdLength);
const StunAddressAttribute* addr = msg.GetAddress(STUN_ATTR_MAPPED_ADDRESS);
- talk_base::IPAddress test_address(kIPv4TestAddress1);
+ rtc::IPAddress test_address(kIPv4TestAddress1);
CheckStunAddressAttribute(addr, STUN_ADDRESS_IPV4,
kTestMessagePort4, test_address);
}
@@ -547,7 +547,7 @@
const StunAddressAttribute* addr =
msg.GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
- talk_base::IPAddress test_address(kIPv4TestAddress1);
+ rtc::IPAddress test_address(kIPv4TestAddress1);
CheckStunAddressAttribute(addr, STUN_ADDRESS_IPV4,
kTestMessagePort3, test_address);
}
@@ -558,7 +558,7 @@
CheckStunHeader(msg, STUN_BINDING_REQUEST, size);
CheckStunTransactionID(msg, kTestTransactionId1, kStunTransactionIdLength);
- talk_base::IPAddress test_address(kIPv6TestAddress1);
+ rtc::IPAddress test_address(kIPv6TestAddress1);
const StunAddressAttribute* addr = msg.GetAddress(STUN_ATTR_MAPPED_ADDRESS);
CheckStunAddressAttribute(addr, STUN_ADDRESS_IPV6,
@@ -571,7 +571,7 @@
CheckStunHeader(msg, STUN_BINDING_REQUEST, size);
CheckStunTransactionID(msg, kTestTransactionId1, kStunTransactionIdLength);
- talk_base::IPAddress test_address(kIPv6TestAddress1);
+ rtc::IPAddress test_address(kIPv6TestAddress1);
const StunAddressAttribute* addr = msg.GetAddress(STUN_ATTR_MAPPED_ADDRESS);
CheckStunAddressAttribute(addr, STUN_ADDRESS_IPV6,
@@ -582,7 +582,7 @@
StunMessage msg;
size_t size = ReadStunMessage(&msg, kStunMessageWithIPv6XorMappedAddress);
- talk_base::IPAddress test_address(kIPv6TestAddress1);
+ rtc::IPAddress test_address(kIPv6TestAddress1);
CheckStunHeader(msg, STUN_BINDING_RESPONSE, size);
CheckStunTransactionID(msg, kTestTransactionId2, kStunTransactionIdLength);
@@ -711,7 +711,7 @@
CheckStunTransactionID(msg, &rfc3489_packet[4], kStunTransactionIdLength + 4);
const StunAddressAttribute* addr = msg.GetAddress(STUN_ATTR_MAPPED_ADDRESS);
- talk_base::IPAddress test_address(kIPv4TestAddress1);
+ rtc::IPAddress test_address(kIPv4TestAddress1);
CheckStunAddressAttribute(addr, STUN_ADDRESS_IPV4,
kTestMessagePort4, test_address);
}
@@ -721,7 +721,7 @@
StunMessage msg2;
size_t size = ReadStunMessage(&msg, kStunMessageWithIPv6XorMappedAddress);
- talk_base::IPAddress test_address(kIPv6TestAddress1);
+ rtc::IPAddress test_address(kIPv6TestAddress1);
CheckStunHeader(msg, STUN_BINDING_RESPONSE, size);
CheckStunTransactionID(msg, kTestTransactionId2, kStunTransactionIdLength);
@@ -740,8 +740,8 @@
// The internal IP address shouldn't change.
ASSERT_EQ(addr2.ipaddr(), addr->ipaddr());
- talk_base::ByteBuffer correct_buf;
- talk_base::ByteBuffer wrong_buf;
+ rtc::ByteBuffer correct_buf;
+ rtc::ByteBuffer wrong_buf;
EXPECT_TRUE(addr->Write(&correct_buf));
EXPECT_TRUE(addr2.Write(&wrong_buf));
// But when written out, the buffers should look different.
@@ -768,7 +768,7 @@
StunMessage msg2;
size_t size = ReadStunMessage(&msg, kStunMessageWithIPv4XorMappedAddress);
- talk_base::IPAddress test_address(kIPv4TestAddress1);
+ rtc::IPAddress test_address(kIPv4TestAddress1);
CheckStunHeader(msg, STUN_BINDING_RESPONSE, size);
CheckStunTransactionID(msg, kTestTransactionId1, kStunTransactionIdLength);
@@ -787,8 +787,8 @@
// The internal IP address shouldn't change.
ASSERT_EQ(addr2.ipaddr(), addr->ipaddr());
- talk_base::ByteBuffer correct_buf;
- talk_base::ByteBuffer wrong_buf;
+ rtc::ByteBuffer correct_buf;
+ rtc::ByteBuffer wrong_buf;
EXPECT_TRUE(addr->Write(&correct_buf));
EXPECT_TRUE(addr2.Write(&wrong_buf));
// The same address data should be written.
@@ -807,11 +807,11 @@
}
TEST_F(StunTest, CreateIPv6AddressAttribute) {
- talk_base::IPAddress test_ip(kIPv6TestAddress2);
+ rtc::IPAddress test_ip(kIPv6TestAddress2);
StunAddressAttribute* addr =
StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
- talk_base::SocketAddress test_addr(test_ip, kTestMessagePort2);
+ rtc::SocketAddress test_addr(test_ip, kTestMessagePort2);
addr->SetAddress(test_addr);
CheckStunAddressAttribute(addr, STUN_ADDRESS_IPV6,
@@ -822,11 +822,11 @@
TEST_F(StunTest, CreateIPv4AddressAttribute) {
struct in_addr test_in_addr;
test_in_addr.s_addr = 0xBEB0B0BE;
- talk_base::IPAddress test_ip(test_in_addr);
+ rtc::IPAddress test_ip(test_in_addr);
StunAddressAttribute* addr =
StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
- talk_base::SocketAddress test_addr(test_ip, kTestMessagePort2);
+ rtc::SocketAddress test_addr(test_ip, kTestMessagePort2);
addr->SetAddress(test_addr);
CheckStunAddressAttribute(addr, STUN_ADDRESS_IPV4,
@@ -840,17 +840,17 @@
StunAttribute::CreateAddress(STUN_ATTR_DESTINATION_ADDRESS);
// Port first
addr->SetPort(kTestMessagePort1);
- addr->SetIP(talk_base::IPAddress(kIPv4TestAddress1));
+ addr->SetIP(rtc::IPAddress(kIPv4TestAddress1));
ASSERT_EQ(kTestMessagePort1, addr->port());
- ASSERT_EQ(talk_base::IPAddress(kIPv4TestAddress1), addr->ipaddr());
+ ASSERT_EQ(rtc::IPAddress(kIPv4TestAddress1), addr->ipaddr());
StunAddressAttribute* addr2 =
StunAttribute::CreateAddress(STUN_ATTR_DESTINATION_ADDRESS);
// IP first
- addr2->SetIP(talk_base::IPAddress(kIPv4TestAddress1));
+ addr2->SetIP(rtc::IPAddress(kIPv4TestAddress1));
addr2->SetPort(kTestMessagePort2);
ASSERT_EQ(kTestMessagePort2, addr2->port());
- ASSERT_EQ(talk_base::IPAddress(kIPv4TestAddress1), addr2->ipaddr());
+ ASSERT_EQ(rtc::IPAddress(kIPv4TestAddress1), addr2->ipaddr());
delete addr;
delete addr2;
@@ -860,7 +860,7 @@
StunMessage msg;
size_t size = sizeof(kStunMessageWithIPv6MappedAddress);
- talk_base::IPAddress test_ip(kIPv6TestAddress1);
+ rtc::IPAddress test_ip(kIPv6TestAddress1);
msg.SetType(STUN_BINDING_REQUEST);
msg.SetTransactionID(
@@ -870,13 +870,13 @@
StunAddressAttribute* addr =
StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
- talk_base::SocketAddress test_addr(test_ip, kTestMessagePort2);
+ rtc::SocketAddress test_addr(test_ip, kTestMessagePort2);
addr->SetAddress(test_addr);
EXPECT_TRUE(msg.AddAttribute(addr));
CheckStunHeader(msg, STUN_BINDING_REQUEST, (size - 20));
- talk_base::ByteBuffer out;
+ rtc::ByteBuffer out;
EXPECT_TRUE(msg.Write(&out));
ASSERT_EQ(out.Length(), sizeof(kStunMessageWithIPv6MappedAddress));
int len1 = static_cast<int>(out.Length());
@@ -889,7 +889,7 @@
StunMessage msg;
size_t size = sizeof(kStunMessageWithIPv4MappedAddress);
- talk_base::IPAddress test_ip(kIPv4TestAddress1);
+ rtc::IPAddress test_ip(kIPv4TestAddress1);
msg.SetType(STUN_BINDING_RESPONSE);
msg.SetTransactionID(
@@ -899,13 +899,13 @@
StunAddressAttribute* addr =
StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
- talk_base::SocketAddress test_addr(test_ip, kTestMessagePort4);
+ rtc::SocketAddress test_addr(test_ip, kTestMessagePort4);
addr->SetAddress(test_addr);
EXPECT_TRUE(msg.AddAttribute(addr));
CheckStunHeader(msg, STUN_BINDING_RESPONSE, (size - 20));
- talk_base::ByteBuffer out;
+ rtc::ByteBuffer out;
EXPECT_TRUE(msg.Write(&out));
ASSERT_EQ(out.Length(), sizeof(kStunMessageWithIPv4MappedAddress));
int len1 = static_cast<int>(out.Length());
@@ -918,7 +918,7 @@
StunMessage msg;
size_t size = sizeof(kStunMessageWithIPv6XorMappedAddress);
- talk_base::IPAddress test_ip(kIPv6TestAddress1);
+ rtc::IPAddress test_ip(kIPv6TestAddress1);
msg.SetType(STUN_BINDING_RESPONSE);
msg.SetTransactionID(
@@ -928,13 +928,13 @@
StunAddressAttribute* addr =
StunAttribute::CreateXorAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
- talk_base::SocketAddress test_addr(test_ip, kTestMessagePort1);
+ rtc::SocketAddress test_addr(test_ip, kTestMessagePort1);
addr->SetAddress(test_addr);
EXPECT_TRUE(msg.AddAttribute(addr));
CheckStunHeader(msg, STUN_BINDING_RESPONSE, (size - 20));
- talk_base::ByteBuffer out;
+ rtc::ByteBuffer out;
EXPECT_TRUE(msg.Write(&out));
ASSERT_EQ(out.Length(), sizeof(kStunMessageWithIPv6XorMappedAddress));
int len1 = static_cast<int>(out.Length());
@@ -948,7 +948,7 @@
StunMessage msg;
size_t size = sizeof(kStunMessageWithIPv4XorMappedAddress);
- talk_base::IPAddress test_ip(kIPv4TestAddress1);
+ rtc::IPAddress test_ip(kIPv4TestAddress1);
msg.SetType(STUN_BINDING_RESPONSE);
msg.SetTransactionID(
@@ -958,13 +958,13 @@
StunAddressAttribute* addr =
StunAttribute::CreateXorAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
- talk_base::SocketAddress test_addr(test_ip, kTestMessagePort3);
+ rtc::SocketAddress test_addr(test_ip, kTestMessagePort3);
addr->SetAddress(test_addr);
EXPECT_TRUE(msg.AddAttribute(addr));
CheckStunHeader(msg, STUN_BINDING_RESPONSE, (size - 20));
- talk_base::ByteBuffer out;
+ rtc::ByteBuffer out;
EXPECT_TRUE(msg.Write(&out));
ASSERT_EQ(out.Length(), sizeof(kStunMessageWithIPv4XorMappedAddress));
int len1 = static_cast<int>(out.Length());
@@ -1052,7 +1052,7 @@
EXPECT_TRUE(msg.AddAttribute(errorcode));
CheckStunHeader(msg, STUN_BINDING_ERROR_RESPONSE, (size - 20));
- talk_base::ByteBuffer out;
+ rtc::ByteBuffer out;
EXPECT_TRUE(msg.Write(&out));
ASSERT_EQ(size, out.Length());
// No padding.
@@ -1075,7 +1075,7 @@
EXPECT_TRUE(msg.AddAttribute(list));
CheckStunHeader(msg, STUN_BINDING_REQUEST, (size - 20));
- talk_base::ByteBuffer out;
+ rtc::ByteBuffer out;
EXPECT_TRUE(msg.Write(&out));
ASSERT_EQ(size, out.Length());
// Check everything up to the padding.
@@ -1087,7 +1087,7 @@
void CheckFailureToRead(const unsigned char* testcase, size_t length) {
StunMessage msg;
const char* input = reinterpret_cast<const char*>(testcase);
- talk_base::ByteBuffer buf(input, length);
+ rtc::ByteBuffer buf(input, length);
ASSERT_FALSE(msg.Read(&buf));
}
@@ -1179,7 +1179,7 @@
// the RFC5769 test messages used include attributes not found in basic STUN.
TEST_F(StunTest, AddMessageIntegrity) {
IceMessage msg;
- talk_base::ByteBuffer buf(
+ rtc::ByteBuffer buf(
reinterpret_cast<const char*>(kRfc5769SampleRequestWithoutMI),
sizeof(kRfc5769SampleRequestWithoutMI));
EXPECT_TRUE(msg.Read(&buf));
@@ -1190,14 +1190,14 @@
EXPECT_EQ(0, memcmp(
mi_attr->bytes(), kCalculatedHmac1, sizeof(kCalculatedHmac1)));
- talk_base::ByteBuffer buf1;
+ rtc::ByteBuffer buf1;
EXPECT_TRUE(msg.Write(&buf1));
EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
reinterpret_cast<const char*>(buf1.Data()), buf1.Length(),
kRfc5769SampleMsgPassword));
IceMessage msg2;
- talk_base::ByteBuffer buf2(
+ rtc::ByteBuffer buf2(
reinterpret_cast<const char*>(kRfc5769SampleResponseWithoutMI),
sizeof(kRfc5769SampleResponseWithoutMI));
EXPECT_TRUE(msg2.Read(&buf2));
@@ -1208,7 +1208,7 @@
EXPECT_EQ(
0, memcmp(mi_attr2->bytes(), kCalculatedHmac2, sizeof(kCalculatedHmac2)));
- talk_base::ByteBuffer buf3;
+ rtc::ByteBuffer buf3;
EXPECT_TRUE(msg2.Write(&buf3));
EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
reinterpret_cast<const char*>(buf3.Data()), buf3.Length(),
@@ -1254,13 +1254,13 @@
TEST_F(StunTest, AddFingerprint) {
IceMessage msg;
- talk_base::ByteBuffer buf(
+ rtc::ByteBuffer buf(
reinterpret_cast<const char*>(kRfc5769SampleRequestWithoutMI),
sizeof(kRfc5769SampleRequestWithoutMI));
EXPECT_TRUE(msg.Read(&buf));
EXPECT_TRUE(msg.AddFingerprint());
- talk_base::ByteBuffer buf1;
+ rtc::ByteBuffer buf1;
EXPECT_TRUE(msg.Write(&buf1));
EXPECT_TRUE(StunMessage::ValidateFingerprint(
reinterpret_cast<const char*>(buf1.Data()), buf1.Length()));
@@ -1303,7 +1303,7 @@
const char* input = reinterpret_cast<const char*>(kRelayMessage);
size_t size = sizeof(kRelayMessage);
- talk_base::ByteBuffer buf(input, size);
+ rtc::ByteBuffer buf(input, size);
EXPECT_TRUE(msg.Read(&buf));
EXPECT_EQ(STUN_BINDING_REQUEST, msg.type());
@@ -1315,7 +1315,7 @@
in_addr legacy_in_addr;
legacy_in_addr.s_addr = htonl(17U);
- talk_base::IPAddress legacy_ip(legacy_in_addr);
+ rtc::IPAddress legacy_ip(legacy_in_addr);
const StunAddressAttribute* addr = msg.GetAddress(STUN_ATTR_MAPPED_ADDRESS);
ASSERT_TRUE(addr != NULL);
@@ -1399,7 +1399,7 @@
bytes2->CopyBytes("abcdefg");
EXPECT_TRUE(msg2.AddAttribute(bytes2));
- talk_base::ByteBuffer out;
+ rtc::ByteBuffer out;
EXPECT_TRUE(msg.Write(&out));
EXPECT_EQ(size, out.Length());
size_t len1 = out.Length();
@@ -1407,7 +1407,7 @@
out.ReadString(&outstring, len1);
EXPECT_EQ(0, memcmp(outstring.c_str(), input, len1));
- talk_base::ByteBuffer out2;
+ rtc::ByteBuffer out2;
EXPECT_TRUE(msg2.Write(&out2));
EXPECT_EQ(size, out2.Length());
size_t len2 = out2.Length();
diff --git a/p2p/base/stunport.cc b/p2p/base/stunport.cc
index 6e18fc5..a178eb4 100644
--- a/p2p/base/stunport.cc
+++ b/p2p/base/stunport.cc
@@ -27,12 +27,12 @@
#include "talk/p2p/base/stunport.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/helpers.h"
-#include "talk/base/nethelpers.h"
#include "talk/p2p/base/common.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/nethelpers.h"
namespace cricket {
@@ -45,15 +45,15 @@
class StunBindingRequest : public StunRequest {
public:
StunBindingRequest(UDPPort* port, bool keep_alive,
- const talk_base::SocketAddress& addr)
+ const rtc::SocketAddress& addr)
: port_(port), keep_alive_(keep_alive), server_addr_(addr) {
- start_time_ = talk_base::Time();
+ start_time_ = rtc::Time();
}
virtual ~StunBindingRequest() {
}
- const talk_base::SocketAddress& server_addr() const { return server_addr_; }
+ const rtc::SocketAddress& server_addr() const { return server_addr_; }
virtual void Prepare(StunMessage* request) {
request->SetType(STUN_BINDING_REQUEST);
@@ -68,11 +68,11 @@
addr_attr->family() != STUN_ADDRESS_IPV6) {
LOG(LS_ERROR) << "Binding address has bad family";
} else {
- talk_base::SocketAddress addr(addr_attr->ipaddr(), addr_attr->port());
- port_->OnStunBindingRequestSucceeded(addr);
+ rtc::SocketAddress addr(addr_attr->ipaddr(), addr_attr->port());
+ port_->OnStunBindingRequestSucceeded(server_addr_, addr);
}
- // We will do a keep-alive regardless of whether this request suceeds.
+ // We will do a keep-alive regardless of whether this request succeeds.
// This should have almost no impact on network usage.
if (keep_alive_) {
port_->requests_.SendDelayed(
@@ -92,10 +92,10 @@
<< " reason='" << attr->reason() << "'";
}
- port_->OnStunBindingOrResolveRequestFailed();
+ port_->OnStunBindingOrResolveRequestFailed(server_addr_);
if (keep_alive_
- && (talk_base::TimeSince(start_time_) <= RETRY_TIMEOUT)) {
+ && (rtc::TimeSince(start_time_) <= RETRY_TIMEOUT)) {
port_->requests_.SendDelayed(
new StunBindingRequest(port_, true, server_addr_),
port_->stun_keepalive_delay());
@@ -107,10 +107,10 @@
<< port_->GetLocalAddress().ToSensitiveString()
<< " (" << port_->Network()->name() << ")";
- port_->OnStunBindingOrResolveRequestFailed();
+ port_->OnStunBindingOrResolveRequestFailed(server_addr_);
if (keep_alive_
- && (talk_base::TimeSince(start_time_) <= RETRY_TIMEOUT)) {
+ && (rtc::TimeSince(start_time_) <= RETRY_TIMEOUT)) {
port_->requests_.SendDelayed(
new StunBindingRequest(port_, true, server_addr_),
RETRY_DELAY);
@@ -120,36 +120,84 @@
private:
UDPPort* port_;
bool keep_alive_;
- talk_base::SocketAddress server_addr_;
+ const rtc::SocketAddress server_addr_;
uint32 start_time_;
};
-UDPPort::UDPPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- talk_base::AsyncPacketSocket* socket,
+UDPPort::AddressResolver::AddressResolver(
+ rtc::PacketSocketFactory* factory)
+ : socket_factory_(factory) {}
+
+UDPPort::AddressResolver::~AddressResolver() {
+ for (ResolverMap::iterator it = resolvers_.begin();
+ it != resolvers_.end(); ++it) {
+ it->second->Destroy(true);
+ }
+}
+
+void UDPPort::AddressResolver::Resolve(
+ const rtc::SocketAddress& address) {
+ if (resolvers_.find(address) != resolvers_.end())
+ return;
+
+ rtc::AsyncResolverInterface* resolver =
+ socket_factory_->CreateAsyncResolver();
+ resolvers_.insert(
+ std::pair<rtc::SocketAddress, rtc::AsyncResolverInterface*>(
+ address, resolver));
+
+ resolver->SignalDone.connect(this,
+ &UDPPort::AddressResolver::OnResolveResult);
+
+ resolver->Start(address);
+}
+
+bool UDPPort::AddressResolver::GetResolvedAddress(
+ const rtc::SocketAddress& input,
+ int family,
+ rtc::SocketAddress* output) const {
+ ResolverMap::const_iterator it = resolvers_.find(input);
+ if (it == resolvers_.end())
+ return false;
+
+ return it->second->GetResolvedAddress(family, output);
+}
+
+void UDPPort::AddressResolver::OnResolveResult(
+ rtc::AsyncResolverInterface* resolver) {
+ for (ResolverMap::iterator it = resolvers_.begin();
+ it != resolvers_.end(); ++it) {
+ if (it->second == resolver) {
+ SignalDone(it->first, resolver->GetError());
+ return;
+ }
+ }
+}
+
+UDPPort::UDPPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ rtc::AsyncPacketSocket* socket,
const std::string& username, const std::string& password)
: Port(thread, factory, network, socket->GetLocalAddress().ipaddr(),
username, password),
requests_(thread),
socket_(socket),
error_(0),
- resolver_(NULL),
ready_(false),
stun_keepalive_delay_(KEEPALIVE_DELAY) {
}
-UDPPort::UDPPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip, int min_port, int max_port,
+UDPPort::UDPPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip, int min_port, int max_port,
const std::string& username, const std::string& password)
: Port(thread, LOCAL_PORT_TYPE, factory, network, ip, min_port, max_port,
username, password),
requests_(thread),
socket_(NULL),
error_(0),
- resolver_(NULL),
ready_(false),
stun_keepalive_delay_(KEEPALIVE_DELAY) {
}
@@ -158,7 +206,7 @@
if (!SharedSocket()) {
ASSERT(socket_ == NULL);
socket_ = socket_factory()->CreateUdpSocket(
- talk_base::SocketAddress(ip(), 0), min_port(), max_port());
+ rtc::SocketAddress(ip(), 0), min_port(), max_port());
if (!socket_) {
LOG_J(LS_WARNING, this) << "UDP socket creation failed";
return false;
@@ -172,16 +220,13 @@
}
UDPPort::~UDPPort() {
- if (resolver_) {
- resolver_->Destroy(true);
- }
if (!SharedSocket())
delete socket_;
}
void UDPPort::PrepareAddress() {
ASSERT(requests_.empty());
- if (socket_->GetState() == talk_base::AsyncPacketSocket::STATE_BOUND) {
+ if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND) {
OnLocalAddressReady(socket_, socket_->GetLocalAddress());
}
}
@@ -189,11 +234,11 @@
void UDPPort::MaybePrepareStunCandidate() {
// Sending binding request to the STUN server if address is available to
// prepare STUN candidate.
- if (!server_addr_.IsNil()) {
- SendStunBindingRequest();
+ if (!server_addresses_.empty()) {
+ SendStunBindingRequests();
} else {
// Port is done allocating candidates.
- SetResult(true);
+ MaybeSetPortCompleteOrError();
}
}
@@ -217,8 +262,8 @@
}
int UDPPort::SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload) {
int sent = socket_->SendTo(data, size, addr, options);
if (sent < 0) {
@@ -229,11 +274,11 @@
return sent;
}
-int UDPPort::SetOption(talk_base::Socket::Option opt, int value) {
+int UDPPort::SetOption(rtc::Socket::Option opt, int value) {
return socket_->SetOption(opt, value);
}
-int UDPPort::GetOption(talk_base::Socket::Option opt, int* value) {
+int UDPPort::GetOption(rtc::Socket::Option opt, int* value) {
return socket_->GetOption(opt, value);
}
@@ -241,25 +286,26 @@
return error_;
}
-void UDPPort::OnLocalAddressReady(talk_base::AsyncPacketSocket* socket,
- const talk_base::SocketAddress& address) {
- AddAddress(address, address, talk_base::SocketAddress(),
- UDP_PROTOCOL_NAME, LOCAL_PORT_TYPE,
- ICE_TYPE_PREFERENCE_HOST, false);
+void UDPPort::OnLocalAddressReady(rtc::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& address) {
+ AddAddress(address, address, rtc::SocketAddress(),
+ UDP_PROTOCOL_NAME, "", LOCAL_PORT_TYPE,
+ ICE_TYPE_PREFERENCE_HOST, 0, false);
MaybePrepareStunCandidate();
}
void UDPPort::OnReadPacket(
- talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* data, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
ASSERT(socket == socket_);
+ ASSERT(!remote_addr.IsUnresolved());
// Look for a response from the STUN server.
// Even if the response doesn't match one of our outstanding requests, we
// will eat it because it might be a response to a retransmitted packet, and
// we already cleared the request when we got the first response.
- if (!server_addr_.IsUnresolved() && remote_addr == server_addr_) {
+ if (server_addresses_.find(remote_addr) != server_addresses_.end()) {
requests_.CheckResponse(data, size);
return;
}
@@ -271,80 +317,118 @@
}
}
-void UDPPort::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
+void UDPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
Port::OnReadyToSend();
}
-void UDPPort::SendStunBindingRequest() {
+void UDPPort::SendStunBindingRequests() {
// We will keep pinging the stun server to make sure our NAT pin-hole stays
// open during the call.
- // TODO: Support multiple stun servers, or make ResolveStunAddress find a
- // server with the correct family, or something similar.
ASSERT(requests_.empty());
- if (server_addr_.IsUnresolved()) {
- ResolveStunAddress();
- } else if (socket_->GetState() == talk_base::AsyncPacketSocket::STATE_BOUND) {
+
+ for (ServerAddresses::const_iterator it = server_addresses_.begin();
+ it != server_addresses_.end(); ++it) {
+ SendStunBindingRequest(*it);
+ }
+}
+
+void UDPPort::ResolveStunAddress(const rtc::SocketAddress& stun_addr) {
+ if (!resolver_) {
+ resolver_.reset(new AddressResolver(socket_factory()));
+ resolver_->SignalDone.connect(this, &UDPPort::OnResolveResult);
+ }
+
+ resolver_->Resolve(stun_addr);
+}
+
+void UDPPort::OnResolveResult(const rtc::SocketAddress& input,
+ int error) {
+ ASSERT(resolver_.get() != NULL);
+
+ rtc::SocketAddress resolved;
+ if (error != 0 ||
+ !resolver_->GetResolvedAddress(input, ip().family(), &resolved)) {
+ LOG_J(LS_WARNING, this) << "StunPort: stun host lookup received error "
+ << error;
+ OnStunBindingOrResolveRequestFailed(input);
+ return;
+ }
+
+ server_addresses_.erase(input);
+
+ if (server_addresses_.find(resolved) == server_addresses_.end()) {
+ server_addresses_.insert(resolved);
+ SendStunBindingRequest(resolved);
+ }
+}
+
+void UDPPort::SendStunBindingRequest(
+ const rtc::SocketAddress& stun_addr) {
+ if (stun_addr.IsUnresolved()) {
+ ResolveStunAddress(stun_addr);
+
+ } else if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND) {
// Check if |server_addr_| is compatible with the port's ip.
- if (IsCompatibleAddress(server_addr_)) {
- requests_.Send(new StunBindingRequest(this, true, server_addr_));
+ if (IsCompatibleAddress(stun_addr)) {
+ requests_.Send(new StunBindingRequest(this, true, stun_addr));
} else {
// Since we can't send stun messages to the server, we should mark this
// port ready.
- OnStunBindingOrResolveRequestFailed();
+ LOG(LS_WARNING) << "STUN server address is incompatible.";
+ OnStunBindingOrResolveRequestFailed(stun_addr);
}
}
}
-void UDPPort::ResolveStunAddress() {
- if (resolver_)
- return;
-
- resolver_ = socket_factory()->CreateAsyncResolver();
- resolver_->SignalDone.connect(this, &UDPPort::OnResolveResult);
- resolver_->Start(server_addr_);
-}
-
-void UDPPort::OnResolveResult(talk_base::AsyncResolverInterface* resolver) {
- ASSERT(resolver == resolver_);
- if (resolver_->GetError() != 0 ||
- !resolver_->GetResolvedAddress(ip().family(), &server_addr_)) {
- LOG_J(LS_WARNING, this) << "StunPort: stun host lookup received error "
- << resolver_->GetError();
- OnStunBindingOrResolveRequestFailed();
+void UDPPort::OnStunBindingRequestSucceeded(
+ const rtc::SocketAddress& stun_server_addr,
+ const rtc::SocketAddress& stun_reflected_addr) {
+ if (bind_request_succeeded_servers_.find(stun_server_addr) !=
+ bind_request_succeeded_servers_.end()) {
return;
}
+ bind_request_succeeded_servers_.insert(stun_server_addr);
- SendStunBindingRequest();
-}
-
-void UDPPort::OnStunBindingRequestSucceeded(
- const talk_base::SocketAddress& stun_addr) {
- if (ready_) // Discarding the binding response if port is already enabled.
- return;
-
- if (!SharedSocket() || stun_addr != socket_->GetLocalAddress()) {
- // If socket is shared and |stun_addr| is equal to local socket
+ if (!SharedSocket() || stun_reflected_addr != socket_->GetLocalAddress()) {
+ // If socket is shared and |stun_reflected_addr| is equal to local socket
// address then discarding the stun address.
// For STUN related address is local socket address.
- AddAddress(stun_addr, socket_->GetLocalAddress(),
- socket_->GetLocalAddress(), UDP_PROTOCOL_NAME,
- STUN_PORT_TYPE, ICE_TYPE_PREFERENCE_SRFLX, false);
+ AddAddress(stun_reflected_addr, socket_->GetLocalAddress(),
+ socket_->GetLocalAddress(), UDP_PROTOCOL_NAME, "",
+ STUN_PORT_TYPE, ICE_TYPE_PREFERENCE_SRFLX, 0, false);
}
- SetResult(true);
+ MaybeSetPortCompleteOrError();
}
-void UDPPort::OnStunBindingOrResolveRequestFailed() {
- if (ready_) // Discarding failure response if port is already enabled.
+void UDPPort::OnStunBindingOrResolveRequestFailed(
+ const rtc::SocketAddress& stun_server_addr) {
+ if (bind_request_failed_servers_.find(stun_server_addr) !=
+ bind_request_failed_servers_.end()) {
+ return;
+ }
+ bind_request_failed_servers_.insert(stun_server_addr);
+ MaybeSetPortCompleteOrError();
+}
+
+void UDPPort::MaybeSetPortCompleteOrError() {
+ if (ready_)
return;
- // If socket is shared, we should process local udp candidate.
- SetResult(SharedSocket());
-}
+ // Do not set port ready if we are still waiting for bind responses.
+ const size_t servers_done_bind_request = bind_request_failed_servers_.size() +
+ bind_request_succeeded_servers_.size();
+ if (server_addresses_.size() != servers_done_bind_request) {
+ return;
+ }
-void UDPPort::SetResult(bool success) {
// Setting ready status.
ready_ = true;
- if (success) {
+
+ // The port is "completed" if there is no stun server provided, or the bind
+ // request succeeded for any stun server, or the socket is shared.
+ if (server_addresses_.empty() ||
+ bind_request_succeeded_servers_.size() > 0 ||
+ SharedSocket()) {
SignalPortComplete(this);
} else {
SignalPortError(this);
@@ -354,7 +438,7 @@
// TODO: merge this with SendTo above.
void UDPPort::OnSendPacket(const void* data, size_t size, StunRequest* req) {
StunBindingRequest* sreq = static_cast<StunBindingRequest*>(req);
- talk_base::PacketOptions options(DefaultDscpValue());
+ rtc::PacketOptions options(DefaultDscpValue());
if (socket_->SendTo(data, size, sreq->server_addr(), options) < 0)
PLOG(LERROR, socket_->GetError()) << "sendto";
}
diff --git a/p2p/base/stunport.h b/p2p/base/stunport.h
index c45d6af..b3b6d5b 100644
--- a/p2p/base/stunport.h
+++ b/p2p/base/stunport.h
@@ -30,12 +30,12 @@
#include <string>
-#include "talk/base/asyncpacketsocket.h"
#include "talk/p2p/base/port.h"
#include "talk/p2p/base/stunrequest.h"
+#include "webrtc/base/asyncpacketsocket.h"
// TODO(mallinath) - Rename stunport.cc|h to udpport.cc|h.
-namespace talk_base {
+namespace rtc {
class AsyncResolver;
class SignalThread;
}
@@ -45,10 +45,10 @@
// Communicates using the address on the outside of a NAT.
class UDPPort : public Port {
public:
- static UDPPort* Create(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- talk_base::AsyncPacketSocket* socket,
+ static UDPPort* Create(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ rtc::AsyncPacketSocket* socket,
const std::string& username,
const std::string& password) {
UDPPort* port = new UDPPort(thread, factory, network, socket,
@@ -60,10 +60,10 @@
return port;
}
- static UDPPort* Create(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip,
+ static UDPPort* Create(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username,
const std::string& password) {
@@ -78,27 +78,30 @@
}
virtual ~UDPPort();
- talk_base::SocketAddress GetLocalAddress() const {
+ rtc::SocketAddress GetLocalAddress() const {
return socket_->GetLocalAddress();
}
- const talk_base::SocketAddress& server_addr() const { return server_addr_; }
- void set_server_addr(const talk_base::SocketAddress& addr) {
- server_addr_ = addr;
+ const ServerAddresses& server_addresses() const {
+ return server_addresses_;
+ }
+ void
+ set_server_addresses(const ServerAddresses& addresses) {
+ server_addresses_ = addresses;
}
virtual void PrepareAddress();
virtual Connection* CreateConnection(const Candidate& address,
CandidateOrigin origin);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
- virtual int GetOption(talk_base::Socket::Option opt, int* value);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
+ virtual int GetOption(rtc::Socket::Option opt, int* value);
virtual int GetError();
virtual bool HandleIncomingPacket(
- talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* data, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
// All packets given to UDP port will be consumed.
OnReadPacket(socket, data, size, remote_addr, packet_time);
return true;
@@ -112,57 +115,92 @@
}
protected:
- UDPPort(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ UDPPort(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username, const std::string& password);
- UDPPort(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, talk_base::AsyncPacketSocket* socket,
+ UDPPort(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, rtc::AsyncPacketSocket* socket,
const std::string& username, const std::string& password);
bool Init();
virtual int SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload);
- void OnLocalAddressReady(talk_base::AsyncPacketSocket* socket,
- const talk_base::SocketAddress& address);
- void OnReadPacket(talk_base::AsyncPacketSocket* socket,
+ void OnLocalAddressReady(rtc::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& address);
+ void OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
- void OnReadyToSend(talk_base::AsyncPacketSocket* socket);
+ void OnReadyToSend(rtc::AsyncPacketSocket* socket);
// This method will send STUN binding request if STUN server address is set.
void MaybePrepareStunCandidate();
- void SendStunBindingRequest();
+ void SendStunBindingRequests();
private:
+ // A helper class which can be called repeatedly to resolve multiple
+ // addresses, as opposed to rtc::AsyncResolverInterface, which can only
+ // resolve one address per instance.
+ class AddressResolver : public sigslot::has_slots<> {
+ public:
+ explicit AddressResolver(rtc::PacketSocketFactory* factory);
+ ~AddressResolver();
+
+ void Resolve(const rtc::SocketAddress& address);
+ bool GetResolvedAddress(const rtc::SocketAddress& input,
+ int family,
+ rtc::SocketAddress* output) const;
+
+ // The signal is sent when resolving the specified address is finished. The
+ // first argument is the input address, the second argument is the error
+ // or 0 if it succeeded.
+ sigslot::signal2<const rtc::SocketAddress&, int> SignalDone;
+
+ private:
+ typedef std::map<rtc::SocketAddress,
+ rtc::AsyncResolverInterface*> ResolverMap;
+
+ void OnResolveResult(rtc::AsyncResolverInterface* resolver);
+
+ rtc::PacketSocketFactory* socket_factory_;
+ ResolverMap resolvers_;
+ };
+
// DNS resolution of the STUN server.
- void ResolveStunAddress();
- void OnResolveResult(talk_base::AsyncResolverInterface* resolver);
+ void ResolveStunAddress(const rtc::SocketAddress& stun_addr);
+ void OnResolveResult(const rtc::SocketAddress& input, int error);
+
+ void SendStunBindingRequest(const rtc::SocketAddress& stun_addr);
// Below methods handles binding request responses.
- void OnStunBindingRequestSucceeded(const talk_base::SocketAddress& stun_addr);
- void OnStunBindingOrResolveRequestFailed();
+ void OnStunBindingRequestSucceeded(
+ const rtc::SocketAddress& stun_server_addr,
+ const rtc::SocketAddress& stun_reflected_addr);
+ void OnStunBindingOrResolveRequestFailed(
+ const rtc::SocketAddress& stun_server_addr);
// Sends STUN requests to the server.
void OnSendPacket(const void* data, size_t size, StunRequest* req);
// TODO(mallinaht) - Move this up to cricket::Port when SignalAddressReady is
// changed to SignalPortReady.
- void SetResult(bool success);
+ void MaybeSetPortCompleteOrError();
- talk_base::SocketAddress server_addr_;
+ ServerAddresses server_addresses_;
+ ServerAddresses bind_request_succeeded_servers_;
+ ServerAddresses bind_request_failed_servers_;
StunRequestManager requests_;
- talk_base::AsyncPacketSocket* socket_;
+ rtc::AsyncPacketSocket* socket_;
int error_;
- talk_base::AsyncResolverInterface* resolver_;
+ rtc::scoped_ptr<AddressResolver> resolver_;
bool ready_;
int stun_keepalive_delay_;
@@ -171,17 +209,18 @@
class StunPort : public UDPPort {
public:
- static StunPort* Create(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip,
- int min_port, int max_port,
- const std::string& username,
- const std::string& password,
- const talk_base::SocketAddress& server_addr) {
+ static StunPort* Create(
+ rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip,
+ int min_port, int max_port,
+ const std::string& username,
+ const std::string& password,
+ const ServerAddresses& servers) {
StunPort* port = new StunPort(thread, factory, network,
ip, min_port, max_port,
- username, password, server_addr);
+ username, password, servers);
if (!port->Init()) {
delete port;
port = NULL;
@@ -192,20 +231,20 @@
virtual ~StunPort() {}
virtual void PrepareAddress() {
- SendStunBindingRequest();
+ SendStunBindingRequests();
}
protected:
- StunPort(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ StunPort(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username, const std::string& password,
- const talk_base::SocketAddress& server_address)
+ const ServerAddresses& servers)
: UDPPort(thread, factory, network, ip, min_port, max_port, username,
password) {
// UDPPort will set these to local udp, updating these to STUN.
set_type(STUN_PORT_TYPE);
- set_server_addr(server_address);
+ set_server_addresses(servers);
}
};
diff --git a/p2p/base/stunport_unittest.cc b/p2p/base/stunport_unittest.cc
index 5850027..6506181 100644
--- a/p2p/base/stunport_unittest.cc
+++ b/p2p/base/stunport_unittest.cc
@@ -25,20 +25,23 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/stunport.h"
#include "talk/p2p/base/teststunserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/virtualsocketserver.h"
-using talk_base::SocketAddress;
+using cricket::ServerAddresses;
+using rtc::SocketAddress;
static const SocketAddress kLocalAddr("127.0.0.1", 0);
-static const SocketAddress kStunAddr("127.0.0.1", 5000);
+static const SocketAddress kStunAddr1("127.0.0.1", 5000);
+static const SocketAddress kStunAddr2("127.0.0.1", 4000);
static const SocketAddress kBadAddr("0.0.0.1", 5000);
static const SocketAddress kStunHostnameAddr("localhost", 5000);
static const SocketAddress kBadHostnameAddr("not-a-real-hostname", 5000);
@@ -53,13 +56,15 @@
public sigslot::has_slots<> {
public:
StunPortTest()
- : pss_(new talk_base::PhysicalSocketServer),
- ss_(new talk_base::VirtualSocketServer(pss_.get())),
+ : pss_(new rtc::PhysicalSocketServer),
+ ss_(new rtc::VirtualSocketServer(pss_.get())),
ss_scope_(ss_.get()),
- network_("unittest", "unittest", talk_base::IPAddress(INADDR_ANY), 32),
- socket_factory_(talk_base::Thread::Current()),
- stun_server_(new cricket::TestStunServer(
- talk_base::Thread::Current(), kStunAddr)),
+ network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
+ socket_factory_(rtc::Thread::Current()),
+ stun_server_1_(new cricket::TestStunServer(
+ rtc::Thread::Current(), kStunAddr1)),
+ stun_server_2_(new cricket::TestStunServer(
+ rtc::Thread::Current(), kStunAddr2)),
done_(false), error_(false), stun_keepalive_delay_(0) {
}
@@ -67,11 +72,17 @@
bool done() const { return done_; }
bool error() const { return error_; }
- void CreateStunPort(const talk_base::SocketAddress& server_addr) {
+ void CreateStunPort(const rtc::SocketAddress& server_addr) {
+ ServerAddresses stun_servers;
+ stun_servers.insert(server_addr);
+ CreateStunPort(stun_servers);
+ }
+
+ void CreateStunPort(const ServerAddresses& stun_servers) {
stun_port_.reset(cricket::StunPort::Create(
- talk_base::Thread::Current(), &socket_factory_, &network_,
- kLocalAddr.ipaddr(), 0, 0, talk_base::CreateRandomString(16),
- talk_base::CreateRandomString(22), server_addr));
+ rtc::Thread::Current(), &socket_factory_, &network_,
+ kLocalAddr.ipaddr(), 0, 0, rtc::CreateRandomString(16),
+ rtc::CreateRandomString(22), stun_servers));
stun_port_->set_stun_keepalive_delay(stun_keepalive_delay_);
stun_port_->SignalPortComplete.connect(this,
&StunPortTest::OnPortComplete);
@@ -79,17 +90,19 @@
&StunPortTest::OnPortError);
}
- void CreateSharedStunPort(const talk_base::SocketAddress& server_addr) {
+ void CreateSharedStunPort(const rtc::SocketAddress& server_addr) {
socket_.reset(socket_factory_.CreateUdpSocket(
- talk_base::SocketAddress(kLocalAddr.ipaddr(), 0), 0, 0));
+ rtc::SocketAddress(kLocalAddr.ipaddr(), 0), 0, 0));
ASSERT_TRUE(socket_ != NULL);
socket_->SignalReadPacket.connect(this, &StunPortTest::OnReadPacket);
stun_port_.reset(cricket::UDPPort::Create(
- talk_base::Thread::Current(), &socket_factory_,
+ rtc::Thread::Current(), &socket_factory_,
&network_, socket_.get(),
- talk_base::CreateRandomString(16), talk_base::CreateRandomString(22)));
+ rtc::CreateRandomString(16), rtc::CreateRandomString(22)));
ASSERT_TRUE(stun_port_ != NULL);
- stun_port_->set_server_addr(server_addr);
+ ServerAddresses stun_servers;
+ stun_servers.insert(server_addr);
+ stun_port_->set_server_addresses(stun_servers);
stun_port_->SignalPortComplete.connect(this,
&StunPortTest::OnPortComplete);
stun_port_->SignalPortError.connect(this,
@@ -100,26 +113,32 @@
stun_port_->PrepareAddress();
}
- void OnReadPacket(talk_base::AsyncPacketSocket* socket, const char* data,
- size_t size, const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ void OnReadPacket(rtc::AsyncPacketSocket* socket, const char* data,
+ size_t size, const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
stun_port_->HandleIncomingPacket(
- socket, data, size, remote_addr, talk_base::PacketTime());
+ socket, data, size, remote_addr, rtc::PacketTime());
}
void SendData(const char* data, size_t len) {
stun_port_->HandleIncomingPacket(
- socket_.get(), data, len, talk_base::SocketAddress("22.22.22.22", 0),
- talk_base::PacketTime());
+ socket_.get(), data, len, rtc::SocketAddress("22.22.22.22", 0),
+ rtc::PacketTime());
}
protected:
static void SetUpTestCase() {
+ rtc::InitializeSSL();
// Ensure the RNG is inited.
- talk_base::InitRandom(NULL, 0);
+ rtc::InitRandom(NULL, 0);
+
+ }
+ static void TearDownTestCase() {
+ rtc::CleanupSSL();
}
void OnPortComplete(cricket::Port* port) {
+ ASSERT_FALSE(done_);
done_ = true;
error_ = false;
}
@@ -132,14 +151,15 @@
}
private:
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> ss_;
- talk_base::SocketServerScope ss_scope_;
- talk_base::Network network_;
- talk_base::BasicPacketSocketFactory socket_factory_;
- talk_base::scoped_ptr<cricket::UDPPort> stun_port_;
- talk_base::scoped_ptr<cricket::TestStunServer> stun_server_;
- talk_base::scoped_ptr<talk_base::AsyncPacketSocket> socket_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
+ rtc::SocketServerScope ss_scope_;
+ rtc::Network network_;
+ rtc::BasicPacketSocketFactory socket_factory_;
+ rtc::scoped_ptr<cricket::UDPPort> stun_port_;
+ rtc::scoped_ptr<cricket::TestStunServer> stun_server_1_;
+ rtc::scoped_ptr<cricket::TestStunServer> stun_server_2_;
+ rtc::scoped_ptr<rtc::AsyncPacketSocket> socket_;
bool done_;
bool error_;
int stun_keepalive_delay_;
@@ -147,14 +167,14 @@
// Test that we can create a STUN port
TEST_F(StunPortTest, TestBasic) {
- CreateStunPort(kStunAddr);
+ CreateStunPort(kStunAddr1);
EXPECT_EQ("stun", port()->Type());
EXPECT_EQ(0U, port()->Candidates().size());
}
// Test that we can get an address from a STUN server.
TEST_F(StunPortTest, TestPrepareAddress) {
- CreateStunPort(kStunAddr);
+ CreateStunPort(kStunAddr1);
PrepareAddress();
EXPECT_TRUE_WAIT(done(), kTimeoutMs);
ASSERT_EQ(1U, port()->Candidates().size());
@@ -203,13 +223,13 @@
EXPECT_TRUE(kLocalAddr.EqualIPs(port()->Candidates()[0].address()));
// Waiting for 1 seond, which will allow us to process
// response for keepalive binding request. 500 ms is the keepalive delay.
- talk_base::Thread::Current()->ProcessMessages(1000);
+ rtc::Thread::Current()->ProcessMessages(1000);
ASSERT_EQ(1U, port()->Candidates().size());
}
// Test that a local candidate can be generated using a shared socket.
TEST_F(StunPortTest, TestSharedSocketPrepareAddress) {
- CreateSharedStunPort(kStunAddr);
+ CreateSharedStunPort(kStunAddr1);
PrepareAddress();
EXPECT_TRUE_WAIT(done(), kTimeoutMs);
ASSERT_EQ(1U, port()->Candidates().size());
@@ -232,3 +252,28 @@
SendData(data.c_str(), data.length());
// No crash is success.
}
+
+// Test that candidates can be allocated for multiple STUN servers.
+TEST_F(StunPortTest, TestMultipleGoodStunServers) {
+ ServerAddresses stun_servers;
+ stun_servers.insert(kStunAddr1);
+ stun_servers.insert(kStunAddr2);
+ CreateStunPort(stun_servers);
+ EXPECT_EQ("stun", port()->Type());
+ PrepareAddress();
+ EXPECT_TRUE_WAIT(done(), kTimeoutMs);
+ EXPECT_EQ(2U, port()->Candidates().size());
+}
+
+// Test that candidates can be allocated for multiple STUN servers, one of which
+// is not reachable.
+TEST_F(StunPortTest, TestMultipleStunServersWithBadServer) {
+ ServerAddresses stun_servers;
+ stun_servers.insert(kStunAddr1);
+ stun_servers.insert(kBadAddr);
+ CreateStunPort(stun_servers);
+ EXPECT_EQ("stun", port()->Type());
+ PrepareAddress();
+ EXPECT_TRUE_WAIT(done(), kTimeoutMs);
+ EXPECT_EQ(1U, port()->Candidates().size());
+}
diff --git a/p2p/base/stunrequest.cc b/p2p/base/stunrequest.cc
index b3b1118..148718f 100644
--- a/p2p/base/stunrequest.cc
+++ b/p2p/base/stunrequest.cc
@@ -27,9 +27,9 @@
#include "talk/p2p/base/stunrequest.h"
-#include "talk/base/common.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -39,7 +39,7 @@
const int DELAY_UNIT = 100; // 100 milliseconds
const int DELAY_MAX_FACTOR = 16;
-StunRequestManager::StunRequestManager(talk_base::Thread* thread)
+StunRequestManager::StunRequestManager(rtc::Thread* thread)
: thread_(thread) {
}
@@ -122,8 +122,8 @@
// Parse the STUN message and continue processing as usual.
- talk_base::ByteBuffer buf(data, size);
- talk_base::scoped_ptr<StunMessage> response(iter->second->msg_->CreateNew());
+ rtc::ByteBuffer buf(data, size);
+ rtc::scoped_ptr<StunMessage> response(iter->second->msg_->CreateNew());
if (!response->Read(&buf))
return false;
@@ -134,14 +134,14 @@
: count_(0), timeout_(false), manager_(0),
msg_(new StunMessage()), tstamp_(0) {
msg_->SetTransactionID(
- talk_base::CreateRandomString(kStunTransactionIdLength));
+ rtc::CreateRandomString(kStunTransactionIdLength));
}
StunRequest::StunRequest(StunMessage* request)
: count_(0), timeout_(false), manager_(0),
msg_(request), tstamp_(0) {
msg_->SetTransactionID(
- talk_base::CreateRandomString(kStunTransactionIdLength));
+ rtc::CreateRandomString(kStunTransactionIdLength));
}
StunRequest::~StunRequest() {
@@ -170,7 +170,7 @@
}
uint32 StunRequest::Elapsed() const {
- return talk_base::TimeSince(tstamp_);
+ return rtc::TimeSince(tstamp_);
}
@@ -179,7 +179,7 @@
manager_ = manager;
}
-void StunRequest::OnMessage(talk_base::Message* pmsg) {
+void StunRequest::OnMessage(rtc::Message* pmsg) {
ASSERT(manager_ != NULL);
ASSERT(pmsg->message_id == MSG_STUN_SEND);
@@ -189,9 +189,9 @@
return;
}
- tstamp_ = talk_base::Time();
+ tstamp_ = rtc::Time();
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
msg_->Write(&buf);
manager_->SignalSendPacket(buf.Data(), buf.Length(), this);
@@ -200,7 +200,7 @@
}
int StunRequest::GetNextDelay() {
- int delay = DELAY_UNIT * talk_base::_min(1 << count_, DELAY_MAX_FACTOR);
+ int delay = DELAY_UNIT * rtc::_min(1 << count_, DELAY_MAX_FACTOR);
count_ += 1;
if (count_ == MAX_SENDS)
timeout_ = true;
diff --git a/p2p/base/stunrequest.h b/p2p/base/stunrequest.h
index f2c85b3..374f7e7 100644
--- a/p2p/base/stunrequest.h
+++ b/p2p/base/stunrequest.h
@@ -28,11 +28,11 @@
#ifndef TALK_P2P_BASE_STUNREQUEST_H_
#define TALK_P2P_BASE_STUNREQUEST_H_
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
-#include "talk/p2p/base/stun.h"
#include <map>
#include <string>
+#include "talk/p2p/base/stun.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -42,7 +42,7 @@
// response or determine that the request has timed out.
class StunRequestManager {
public:
- StunRequestManager(talk_base::Thread* thread);
+ StunRequestManager(rtc::Thread* thread);
~StunRequestManager();
// Starts sending the given request (perhaps after a delay).
@@ -69,7 +69,7 @@
private:
typedef std::map<std::string, StunRequest*> RequestMap;
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
RequestMap requests_;
friend class StunRequest;
@@ -77,7 +77,7 @@
// Represents an individual request to be sent. The STUN message can either be
// constructed beforehand or built on demand.
-class StunRequest : public talk_base::MessageHandler {
+class StunRequest : public rtc::MessageHandler {
public:
StunRequest();
StunRequest(StunMessage* request);
@@ -119,7 +119,7 @@
void set_manager(StunRequestManager* manager);
// Handles messages for sending and timeout.
- void OnMessage(talk_base::Message* pmsg);
+ void OnMessage(rtc::Message* pmsg);
StunRequestManager* manager_;
StunMessage* msg_;
diff --git a/p2p/base/stunrequest_unittest.cc b/p2p/base/stunrequest_unittest.cc
index 508660c..3c42214 100644
--- a/p2p/base/stunrequest_unittest.cc
+++ b/p2p/base/stunrequest_unittest.cc
@@ -25,12 +25,12 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/timeutils.h"
#include "talk/p2p/base/stunrequest.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/timeutils.h"
using namespace cricket;
@@ -38,15 +38,15 @@
public sigslot::has_slots<> {
public:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
StunRequestTest()
- : manager_(talk_base::Thread::Current()),
+ : manager_(rtc::Thread::Current()),
request_count_(0), response_(NULL),
success_(false), failure_(false), timeout_(false) {
manager_.SignalSendPacket.connect(this, &StunRequestTest::OnSendPacket);
@@ -171,13 +171,13 @@
TEST_F(StunRequestTest, TestBackoff) {
StunMessage* req = CreateStunMessage(STUN_BINDING_REQUEST, NULL);
- uint32 start = talk_base::Time();
+ uint32 start = rtc::Time();
manager_.Send(new StunRequestThunker(req, this));
StunMessage* res = CreateStunMessage(STUN_BINDING_RESPONSE, req);
for (int i = 0; i < 9; ++i) {
while (request_count_ == i)
- talk_base::Thread::Current()->ProcessMessages(1);
- int32 elapsed = talk_base::TimeSince(start);
+ rtc::Thread::Current()->ProcessMessages(1);
+ int32 elapsed = rtc::TimeSince(start);
LOG(LS_INFO) << "STUN request #" << (i + 1)
<< " sent at " << elapsed << " ms";
EXPECT_GE(TotalDelay(i + 1), elapsed);
@@ -197,7 +197,7 @@
StunMessage* res = CreateStunMessage(STUN_BINDING_RESPONSE, req);
manager_.Send(new StunRequestThunker(req, this));
- talk_base::Thread::Current()->ProcessMessages(10000); // > STUN timeout
+ rtc::Thread::Current()->ProcessMessages(10000); // > STUN timeout
EXPECT_FALSE(manager_.CheckResponse(res));
EXPECT_TRUE(response_ == NULL);
diff --git a/p2p/base/stunserver.cc b/p2p/base/stunserver.cc
index ee6c643..d9633f0 100644
--- a/p2p/base/stunserver.cc
+++ b/p2p/base/stunserver.cc
@@ -27,12 +27,12 @@
#include "talk/p2p/base/stunserver.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/logging.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/logging.h"
namespace cricket {
-StunServer::StunServer(talk_base::AsyncUDPSocket* socket) : socket_(socket) {
+StunServer::StunServer(rtc::AsyncUDPSocket* socket) : socket_(socket) {
socket_->SignalReadPacket.connect(this, &StunServer::OnPacket);
}
@@ -41,11 +41,11 @@
}
void StunServer::OnPacket(
- talk_base::AsyncPacketSocket* socket, const char* buf, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* buf, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
// Parse the STUN message; eat any messages that fail to parse.
- talk_base::ByteBuffer bbuf(buf, size);
+ rtc::ByteBuffer bbuf(buf, size);
StunMessage msg;
if (!msg.Read(&bbuf)) {
return;
@@ -66,7 +66,7 @@
}
void StunServer::OnBindingRequest(
- StunMessage* msg, const talk_base::SocketAddress& remote_addr) {
+ StunMessage* msg, const rtc::SocketAddress& remote_addr) {
StunMessage response;
response.SetType(STUN_BINDING_RESPONSE);
response.SetTransactionID(msg->transaction_id());
@@ -85,7 +85,7 @@
}
void StunServer::SendErrorResponse(
- const StunMessage& msg, const talk_base::SocketAddress& addr,
+ const StunMessage& msg, const rtc::SocketAddress& addr,
int error_code, const char* error_desc) {
StunMessage err_msg;
err_msg.SetType(GetStunErrorResponseType(msg.type()));
@@ -100,10 +100,10 @@
}
void StunServer::SendResponse(
- const StunMessage& msg, const talk_base::SocketAddress& addr) {
- talk_base::ByteBuffer buf;
+ const StunMessage& msg, const rtc::SocketAddress& addr) {
+ rtc::ByteBuffer buf;
msg.Write(&buf);
- talk_base::PacketOptions options;
+ rtc::PacketOptions options;
if (socket_->SendTo(buf.Data(), buf.Length(), addr, options) < 0)
LOG_ERR(LS_ERROR) << "sendto";
}
diff --git a/p2p/base/stunserver.h b/p2p/base/stunserver.h
index c5d12e1..1e14408 100644
--- a/p2p/base/stunserver.h
+++ b/p2p/base/stunserver.h
@@ -28,9 +28,9 @@
#ifndef TALK_P2P_BASE_STUNSERVER_H_
#define TALK_P2P_BASE_STUNSERVER_H_
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/asyncudpsocket.h"
+#include "webrtc/base/scoped_ptr.h"
namespace cricket {
@@ -39,38 +39,38 @@
class StunServer : public sigslot::has_slots<> {
public:
// Creates a STUN server, which will listen on the given socket.
- explicit StunServer(talk_base::AsyncUDPSocket* socket);
+ explicit StunServer(rtc::AsyncUDPSocket* socket);
// Removes the STUN server from the socket and deletes the socket.
~StunServer();
protected:
// Slot for AsyncSocket.PacketRead:
void OnPacket(
- talk_base::AsyncPacketSocket* socket, const char* buf, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
+ rtc::AsyncPacketSocket* socket, const char* buf, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
// Handlers for the different types of STUN/TURN requests:
void OnBindingRequest(StunMessage* msg,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
void OnAllocateRequest(StunMessage* msg,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
void OnSharedSecretRequest(StunMessage* msg,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
void OnSendRequest(StunMessage* msg,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
// Sends an error response to the given message back to the user.
void SendErrorResponse(
- const StunMessage& msg, const talk_base::SocketAddress& addr,
+ const StunMessage& msg, const rtc::SocketAddress& addr,
int error_code, const char* error_desc);
// Sends the given message to the appropriate destination.
void SendResponse(const StunMessage& msg,
- const talk_base::SocketAddress& addr);
+ const rtc::SocketAddress& addr);
private:
- talk_base::scoped_ptr<talk_base::AsyncUDPSocket> socket_;
+ rtc::scoped_ptr<rtc::AsyncUDPSocket> socket_;
};
} // namespace cricket
diff --git a/p2p/base/stunserver_unittest.cc b/p2p/base/stunserver_unittest.cc
index a6f56a5..405d8ae 100644
--- a/p2p/base/stunserver_unittest.cc
+++ b/p2p/base/stunserver_unittest.cc
@@ -27,36 +27,36 @@
#include <string>
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/virtualsocketserver.h"
-#include "talk/base/testclient.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/stunserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/testclient.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/virtualsocketserver.h"
using namespace cricket;
-static const talk_base::SocketAddress server_addr("99.99.99.1", 3478);
-static const talk_base::SocketAddress client_addr("1.2.3.4", 1234);
+static const rtc::SocketAddress server_addr("99.99.99.1", 3478);
+static const rtc::SocketAddress client_addr("1.2.3.4", 1234);
class StunServerTest : public testing::Test {
public:
StunServerTest()
- : pss_(new talk_base::PhysicalSocketServer),
- ss_(new talk_base::VirtualSocketServer(pss_.get())),
+ : pss_(new rtc::PhysicalSocketServer),
+ ss_(new rtc::VirtualSocketServer(pss_.get())),
worker_(ss_.get()) {
}
virtual void SetUp() {
server_.reset(new StunServer(
- talk_base::AsyncUDPSocket::Create(ss_.get(), server_addr)));
- client_.reset(new talk_base::TestClient(
- talk_base::AsyncUDPSocket::Create(ss_.get(), client_addr)));
+ rtc::AsyncUDPSocket::Create(ss_.get(), server_addr)));
+ client_.reset(new rtc::TestClient(
+ rtc::AsyncUDPSocket::Create(ss_.get(), client_addr)));
worker_.Start();
}
void Send(const StunMessage& msg) {
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
msg.Write(&buf);
Send(buf.Data(), static_cast<int>(buf.Length()));
}
@@ -65,9 +65,9 @@
}
StunMessage* Receive() {
StunMessage* msg = NULL;
- talk_base::TestClient::Packet* packet = client_->NextPacket();
+ rtc::TestClient::Packet* packet = client_->NextPacket();
if (packet) {
- talk_base::ByteBuffer buf(packet->buf, packet->size);
+ rtc::ByteBuffer buf(packet->buf, packet->size);
msg = new StunMessage();
msg->Read(&buf);
delete packet;
@@ -75,11 +75,11 @@
return msg;
}
private:
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> ss_;
- talk_base::Thread worker_;
- talk_base::scoped_ptr<StunServer> server_;
- talk_base::scoped_ptr<talk_base::TestClient> client_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
+ rtc::Thread worker_;
+ rtc::scoped_ptr<StunServer> server_;
+ rtc::scoped_ptr<rtc::TestClient> client_;
};
// Disable for TSan v2, see
diff --git a/p2p/base/tcpport.cc b/p2p/base/tcpport.cc
index 069323a..cb5b726 100644
--- a/p2p/base/tcpport.cc
+++ b/p2p/base/tcpport.cc
@@ -27,15 +27,15 @@
#include "talk/p2p/base/tcpport.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
#include "talk/p2p/base/common.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
namespace cricket {
-TCPPort::TCPPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+TCPPort::TCPPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port, const std::string& username,
const std::string& password, bool allow_listen)
: Port(thread, LOCAL_PORT_TYPE, factory, network, ip, min_port, max_port,
@@ -53,7 +53,7 @@
// Treat failure to create or bind a TCP socket as fatal. This
// should never happen.
socket_ = socket_factory()->CreateServerTcpSocket(
- talk_base::SocketAddress(ip(), 0), min_port(), max_port(),
+ rtc::SocketAddress(ip(), 0), min_port(), max_port(),
false /* ssl */);
if (!socket_) {
LOG_J(LS_ERROR, this) << "TCP socket creation failed.";
@@ -81,6 +81,13 @@
return NULL;
}
+ if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
+ (address.tcptype().empty() && address.address().port() == 0)) {
+ // It's active only candidate, we should not try to create connections
+ // for these candidates.
+ return NULL;
+ }
+
// We can't accept TCP connections incoming on other ports
if (origin == ORIGIN_OTHER_PORT)
return NULL;
@@ -100,7 +107,7 @@
}
TCPConnection* conn = NULL;
- if (talk_base::AsyncPacketSocket* socket =
+ if (rtc::AsyncPacketSocket* socket =
GetIncoming(address.address(), true)) {
socket->SignalReadPacket.disconnect(this);
conn = new TCPConnection(this, address, socket);
@@ -115,31 +122,31 @@
if (socket_) {
// If socket isn't bound yet the address will be added in
// OnAddressReady(). Socket may be in the CLOSED state if Listen()
- // failed, we still want ot add the socket address.
+ // failed, we still want to add the socket address.
LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
<< socket_->GetState();
- if (socket_->GetState() == talk_base::AsyncPacketSocket::STATE_BOUND ||
- socket_->GetState() == talk_base::AsyncPacketSocket::STATE_CLOSED)
+ if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
+ socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
- talk_base::SocketAddress(),
- TCP_PROTOCOL_NAME, LOCAL_PORT_TYPE,
- ICE_TYPE_PREFERENCE_HOST_TCP, true);
+ rtc::SocketAddress(),
+ TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
+ ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
} else {
LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
// Note: We still add the address, since otherwise the remote side won't
// recognize our incoming TCP connections.
- AddAddress(talk_base::SocketAddress(ip(), 0),
- talk_base::SocketAddress(ip(), 0), talk_base::SocketAddress(),
- TCP_PROTOCOL_NAME, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
- true);
+ AddAddress(rtc::SocketAddress(ip(), 0),
+ rtc::SocketAddress(ip(), 0), rtc::SocketAddress(),
+ TCP_PROTOCOL_NAME, TCPTYPE_ACTIVE_STR, LOCAL_PORT_TYPE,
+ ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
}
}
int TCPPort::SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload) {
- talk_base::AsyncPacketSocket * socket = NULL;
+ rtc::AsyncPacketSocket * socket = NULL;
if (TCPConnection * conn = static_cast<TCPConnection*>(GetConnection(addr))) {
socket = conn->socket();
} else {
@@ -160,7 +167,7 @@
return sent;
}
-int TCPPort::GetOption(talk_base::Socket::Option opt, int* value) {
+int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
if (socket_) {
return socket_->GetOption(opt, value);
} else {
@@ -168,7 +175,7 @@
}
}
-int TCPPort::SetOption(talk_base::Socket::Option opt, int value) {
+int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
if (socket_) {
return socket_->SetOption(opt, value);
} else {
@@ -180,8 +187,8 @@
return error_;
}
-void TCPPort::OnNewConnection(talk_base::AsyncPacketSocket* socket,
- talk_base::AsyncPacketSocket* new_socket) {
+void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
+ rtc::AsyncPacketSocket* new_socket) {
ASSERT(socket == socket_);
Incoming incoming;
@@ -195,9 +202,9 @@
incoming_.push_back(incoming);
}
-talk_base::AsyncPacketSocket* TCPPort::GetIncoming(
- const talk_base::SocketAddress& addr, bool remove) {
- talk_base::AsyncPacketSocket* socket = NULL;
+rtc::AsyncPacketSocket* TCPPort::GetIncoming(
+ const rtc::SocketAddress& addr, bool remove) {
+ rtc::AsyncPacketSocket* socket = NULL;
for (std::list<Incoming>::iterator it = incoming_.begin();
it != incoming_.end(); ++it) {
if (it->addr == addr) {
@@ -210,34 +217,34 @@
return socket;
}
-void TCPPort::OnReadPacket(talk_base::AsyncPacketSocket* socket,
+void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
}
-void TCPPort::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
+void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
Port::OnReadyToSend();
}
-void TCPPort::OnAddressReady(talk_base::AsyncPacketSocket* socket,
- const talk_base::SocketAddress& address) {
- AddAddress(address, address, talk_base::SocketAddress(), "tcp",
- LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
- true);
+void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& address) {
+ AddAddress(address, address, rtc::SocketAddress(),
+ TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
+ ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
}
TCPConnection::TCPConnection(TCPPort* port, const Candidate& candidate,
- talk_base::AsyncPacketSocket* socket)
+ rtc::AsyncPacketSocket* socket)
: Connection(port, 0, candidate), socket_(socket), error_(0) {
bool outgoing = (socket_ == NULL);
if (outgoing) {
// TODO: Handle failures here (unlikely since TCP).
int opts = (candidate.protocol() == SSLTCP_PROTOCOL_NAME) ?
- talk_base::PacketSocketFactory::OPT_SSLTCP : 0;
+ rtc::PacketSocketFactory::OPT_SSLTCP : 0;
socket_ = port->socket_factory()->CreateClientTcpSocket(
- talk_base::SocketAddress(port->ip(), 0),
+ rtc::SocketAddress(port->ip(), 0),
candidate.address(), port->proxy(), port->user_agent(), opts);
if (socket_) {
LOG_J(LS_VERBOSE, this) << "Connecting from "
@@ -267,7 +274,7 @@
}
int TCPConnection::Send(const void* data, size_t size,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
if (!socket_) {
error_ = ENOTCONN;
return SOCKET_ERROR;
@@ -291,7 +298,7 @@
return error_;
}
-void TCPConnection::OnConnect(talk_base::AsyncPacketSocket* socket) {
+void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
ASSERT(socket == socket_);
// Do not use this connection if the socket bound to a different address than
// the one we asked for. This is seen in Chrome, where TCP sockets cannot be
@@ -308,7 +315,7 @@
}
}
-void TCPConnection::OnClose(talk_base::AsyncPacketSocket* socket, int error) {
+void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
ASSERT(socket == socket_);
LOG_J(LS_VERBOSE, this) << "Connection closed with error " << error;
set_connected(false);
@@ -316,14 +323,14 @@
}
void TCPConnection::OnReadPacket(
- talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* data, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
ASSERT(socket == socket_);
Connection::OnReadPacket(data, size, packet_time);
}
-void TCPConnection::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
+void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
ASSERT(socket == socket_);
Connection::OnReadyToSend();
}
diff --git a/p2p/base/tcpport.h b/p2p/base/tcpport.h
index c152ec0..97bd977 100644
--- a/p2p/base/tcpport.h
+++ b/p2p/base/tcpport.h
@@ -28,10 +28,10 @@
#ifndef TALK_P2P_BASE_TCPPORT_H_
#define TALK_P2P_BASE_TCPPORT_H_
-#include <string>
#include <list>
-#include "talk/base/asyncpacketsocket.h"
+#include <string>
#include "talk/p2p/base/port.h"
+#include "webrtc/base/asyncpacketsocket.h"
namespace cricket {
@@ -45,10 +45,10 @@
// call this TCPPort::OnReadPacket (3 arg) to dispatch to a connection.
class TCPPort : public Port {
public:
- static TCPPort* Create(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip,
+ static TCPPort* Create(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username,
const std::string& password,
@@ -69,51 +69,51 @@
virtual void PrepareAddress();
- virtual int GetOption(talk_base::Socket::Option opt, int* value);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
+ virtual int GetOption(rtc::Socket::Option opt, int* value);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
virtual int GetError();
protected:
- TCPPort(talk_base::Thread* thread, talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ TCPPort(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port, const std::string& username,
const std::string& password, bool allow_listen);
bool Init();
// Handles sending using the local TCP socket.
virtual int SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload);
// Accepts incoming TCP connection.
- void OnNewConnection(talk_base::AsyncPacketSocket* socket,
- talk_base::AsyncPacketSocket* new_socket);
+ void OnNewConnection(rtc::AsyncPacketSocket* socket,
+ rtc::AsyncPacketSocket* new_socket);
private:
struct Incoming {
- talk_base::SocketAddress addr;
- talk_base::AsyncPacketSocket* socket;
+ rtc::SocketAddress addr;
+ rtc::AsyncPacketSocket* socket;
};
- talk_base::AsyncPacketSocket* GetIncoming(
- const talk_base::SocketAddress& addr, bool remove = false);
+ rtc::AsyncPacketSocket* GetIncoming(
+ const rtc::SocketAddress& addr, bool remove = false);
// Receives packet signal from the local TCP Socket.
- void OnReadPacket(talk_base::AsyncPacketSocket* socket,
+ void OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
- void OnReadyToSend(talk_base::AsyncPacketSocket* socket);
+ void OnReadyToSend(rtc::AsyncPacketSocket* socket);
- void OnAddressReady(talk_base::AsyncPacketSocket* socket,
- const talk_base::SocketAddress& address);
+ void OnAddressReady(rtc::AsyncPacketSocket* socket,
+ const rtc::SocketAddress& address);
// TODO: Is this still needed?
bool incoming_only_;
bool allow_listen_;
- talk_base::AsyncPacketSocket* socket_;
+ rtc::AsyncPacketSocket* socket_;
int error_;
std::list<Incoming> incoming_;
@@ -124,25 +124,25 @@
public:
// Connection is outgoing unless socket is specified
TCPConnection(TCPPort* port, const Candidate& candidate,
- talk_base::AsyncPacketSocket* socket = 0);
+ rtc::AsyncPacketSocket* socket = 0);
virtual ~TCPConnection();
virtual int Send(const void* data, size_t size,
- const talk_base::PacketOptions& options);
+ const rtc::PacketOptions& options);
virtual int GetError();
- talk_base::AsyncPacketSocket* socket() { return socket_; }
+ rtc::AsyncPacketSocket* socket() { return socket_; }
private:
- void OnConnect(talk_base::AsyncPacketSocket* socket);
- void OnClose(talk_base::AsyncPacketSocket* socket, int error);
- void OnReadPacket(talk_base::AsyncPacketSocket* socket,
+ void OnConnect(rtc::AsyncPacketSocket* socket);
+ void OnClose(rtc::AsyncPacketSocket* socket, int error);
+ void OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
- void OnReadyToSend(talk_base::AsyncPacketSocket* socket);
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
+ void OnReadyToSend(rtc::AsyncPacketSocket* socket);
- talk_base::AsyncPacketSocket* socket_;
+ rtc::AsyncPacketSocket* socket_;
int error_;
friend class TCPPort;
diff --git a/p2p/base/testrelayserver.h b/p2p/base/testrelayserver.h
index 29e9fe4..eaeefc8 100644
--- a/p2p/base/testrelayserver.h
+++ b/p2p/base/testrelayserver.h
@@ -28,29 +28,29 @@
#ifndef TALK_P2P_BASE_TESTRELAYSERVER_H_
#define TALK_P2P_BASE_TESTRELAYSERVER_H_
-#include "talk/base/asynctcpsocket.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/relayserver.h"
+#include "webrtc/base/asynctcpsocket.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/socketadapters.h"
+#include "webrtc/base/thread.h"
namespace cricket {
// A test relay server. Useful for unit tests.
class TestRelayServer : public sigslot::has_slots<> {
public:
- TestRelayServer(talk_base::Thread* thread,
- const talk_base::SocketAddress& udp_int_addr,
- const talk_base::SocketAddress& udp_ext_addr,
- const talk_base::SocketAddress& tcp_int_addr,
- const talk_base::SocketAddress& tcp_ext_addr,
- const talk_base::SocketAddress& ssl_int_addr,
- const talk_base::SocketAddress& ssl_ext_addr)
+ TestRelayServer(rtc::Thread* thread,
+ const rtc::SocketAddress& udp_int_addr,
+ const rtc::SocketAddress& udp_ext_addr,
+ const rtc::SocketAddress& tcp_int_addr,
+ const rtc::SocketAddress& tcp_ext_addr,
+ const rtc::SocketAddress& ssl_int_addr,
+ const rtc::SocketAddress& ssl_ext_addr)
: server_(thread) {
- server_.AddInternalSocket(talk_base::AsyncUDPSocket::Create(
+ server_.AddInternalSocket(rtc::AsyncUDPSocket::Create(
thread->socketserver(), udp_int_addr));
- server_.AddExternalSocket(talk_base::AsyncUDPSocket::Create(
+ server_.AddExternalSocket(rtc::AsyncUDPSocket::Create(
thread->socketserver(), udp_ext_addr));
tcp_int_socket_.reset(CreateListenSocket(thread, tcp_int_addr));
@@ -61,33 +61,33 @@
int GetConnectionCount() const {
return server_.GetConnectionCount();
}
- talk_base::SocketAddressPair GetConnection(int connection) const {
+ rtc::SocketAddressPair GetConnection(int connection) const {
return server_.GetConnection(connection);
}
- bool HasConnection(const talk_base::SocketAddress& address) const {
+ bool HasConnection(const rtc::SocketAddress& address) const {
return server_.HasConnection(address);
}
private:
- talk_base::AsyncSocket* CreateListenSocket(talk_base::Thread* thread,
- const talk_base::SocketAddress& addr) {
- talk_base::AsyncSocket* socket =
+ rtc::AsyncSocket* CreateListenSocket(rtc::Thread* thread,
+ const rtc::SocketAddress& addr) {
+ rtc::AsyncSocket* socket =
thread->socketserver()->CreateAsyncSocket(addr.family(), SOCK_STREAM);
socket->Bind(addr);
socket->Listen(5);
socket->SignalReadEvent.connect(this, &TestRelayServer::OnAccept);
return socket;
}
- void OnAccept(talk_base::AsyncSocket* socket) {
+ void OnAccept(rtc::AsyncSocket* socket) {
bool external = (socket == tcp_ext_socket_.get() ||
socket == ssl_ext_socket_.get());
bool ssl = (socket == ssl_int_socket_.get() ||
socket == ssl_ext_socket_.get());
- talk_base::AsyncSocket* raw_socket = socket->Accept(NULL);
+ rtc::AsyncSocket* raw_socket = socket->Accept(NULL);
if (raw_socket) {
- talk_base::AsyncTCPSocket* packet_socket = new talk_base::AsyncTCPSocket(
+ rtc::AsyncTCPSocket* packet_socket = new rtc::AsyncTCPSocket(
(!ssl) ? raw_socket :
- new talk_base::AsyncSSLServerSocket(raw_socket), false);
+ new rtc::AsyncSSLServerSocket(raw_socket), false);
if (!external) {
packet_socket->SignalClose.connect(this,
&TestRelayServer::OnInternalClose);
@@ -99,18 +99,18 @@
}
}
}
- void OnInternalClose(talk_base::AsyncPacketSocket* socket, int error) {
+ void OnInternalClose(rtc::AsyncPacketSocket* socket, int error) {
server_.RemoveInternalSocket(socket);
}
- void OnExternalClose(talk_base::AsyncPacketSocket* socket, int error) {
+ void OnExternalClose(rtc::AsyncPacketSocket* socket, int error) {
server_.RemoveExternalSocket(socket);
}
private:
cricket::RelayServer server_;
- talk_base::scoped_ptr<talk_base::AsyncSocket> tcp_int_socket_;
- talk_base::scoped_ptr<talk_base::AsyncSocket> tcp_ext_socket_;
- talk_base::scoped_ptr<talk_base::AsyncSocket> ssl_int_socket_;
- talk_base::scoped_ptr<talk_base::AsyncSocket> ssl_ext_socket_;
+ rtc::scoped_ptr<rtc::AsyncSocket> tcp_int_socket_;
+ rtc::scoped_ptr<rtc::AsyncSocket> tcp_ext_socket_;
+ rtc::scoped_ptr<rtc::AsyncSocket> ssl_int_socket_;
+ rtc::scoped_ptr<rtc::AsyncSocket> ssl_ext_socket_;
};
} // namespace cricket
diff --git a/p2p/base/teststunserver.h b/p2p/base/teststunserver.h
index 67bac21..6f85009 100644
--- a/p2p/base/teststunserver.h
+++ b/p2p/base/teststunserver.h
@@ -28,25 +28,25 @@
#ifndef TALK_P2P_BASE_TESTSTUNSERVER_H_
#define TALK_P2P_BASE_TESTSTUNSERVER_H_
-#include "talk/base/socketaddress.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/stunserver.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/thread.h"
namespace cricket {
// A test STUN server. Useful for unit tests.
class TestStunServer {
public:
- TestStunServer(talk_base::Thread* thread,
- const talk_base::SocketAddress& addr)
+ TestStunServer(rtc::Thread* thread,
+ const rtc::SocketAddress& addr)
: socket_(thread->socketserver()->CreateAsyncSocket(addr.family(),
SOCK_DGRAM)),
- udp_socket_(talk_base::AsyncUDPSocket::Create(socket_, addr)),
+ udp_socket_(rtc::AsyncUDPSocket::Create(socket_, addr)),
server_(udp_socket_) {
}
private:
- talk_base::AsyncSocket* socket_;
- talk_base::AsyncUDPSocket* udp_socket_;
+ rtc::AsyncSocket* socket_;
+ rtc::AsyncUDPSocket* udp_socket_;
cricket::StunServer server_;
};
diff --git a/p2p/base/testturnserver.h b/p2p/base/testturnserver.h
index 7a3c83f..6c30afe 100644
--- a/p2p/base/testturnserver.h
+++ b/p2p/base/testturnserver.h
@@ -29,26 +29,48 @@
#define TALK_P2P_BASE_TESTTURNSERVER_H_
#include <string>
+#include <vector>
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/stun.h"
#include "talk/p2p/base/turnserver.h"
+#include "webrtc/base/asyncudpsocket.h"
+#include "webrtc/base/thread.h"
namespace cricket {
static const char kTestRealm[] = "example.org";
static const char kTestSoftware[] = "TestTurnServer";
+class TestTurnRedirector : public TurnRedirectInterface {
+ public:
+ explicit TestTurnRedirector(const std::vector<rtc::SocketAddress>& addresses)
+ : alternate_server_addresses_(addresses),
+ iter_(alternate_server_addresses_.begin()) {
+ }
+
+ virtual bool ShouldRedirect(const rtc::SocketAddress&,
+ rtc::SocketAddress* out) {
+ if (!out || iter_ == alternate_server_addresses_.end()) {
+ return false;
+ }
+ *out = *iter_++;
+ return true;
+ }
+
+ private:
+ const std::vector<rtc::SocketAddress>& alternate_server_addresses_;
+ std::vector<rtc::SocketAddress>::const_iterator iter_;
+};
+
class TestTurnServer : public TurnAuthInterface {
public:
- TestTurnServer(talk_base::Thread* thread,
- const talk_base::SocketAddress& udp_int_addr,
- const talk_base::SocketAddress& udp_ext_addr)
+ TestTurnServer(rtc::Thread* thread,
+ const rtc::SocketAddress& udp_int_addr,
+ const rtc::SocketAddress& udp_ext_addr)
: server_(thread) {
AddInternalSocket(udp_int_addr, cricket::PROTO_UDP);
- server_.SetExternalSocketFactory(new talk_base::BasicPacketSocketFactory(),
+ server_.SetExternalSocketFactory(new rtc::BasicPacketSocketFactory(),
udp_ext_addr);
server_.set_realm(kTestRealm);
server_.set_software(kTestSoftware);
@@ -61,16 +83,20 @@
TurnServer* server() { return &server_; }
- void AddInternalSocket(const talk_base::SocketAddress& int_addr,
+ void set_redirect_hook(TurnRedirectInterface* redirect_hook) {
+ server_.set_redirect_hook(redirect_hook);
+ }
+
+ void AddInternalSocket(const rtc::SocketAddress& int_addr,
ProtocolType proto) {
- talk_base::Thread* thread = talk_base::Thread::Current();
+ rtc::Thread* thread = rtc::Thread::Current();
if (proto == cricket::PROTO_UDP) {
- server_.AddInternalSocket(talk_base::AsyncUDPSocket::Create(
+ server_.AddInternalSocket(rtc::AsyncUDPSocket::Create(
thread->socketserver(), int_addr), proto);
} else if (proto == cricket::PROTO_TCP) {
// For TCP we need to create a server socket which can listen for incoming
// new connections.
- talk_base::AsyncSocket* socket =
+ rtc::AsyncSocket* socket =
thread->socketserver()->CreateAsyncSocket(SOCK_STREAM);
socket->Bind(int_addr);
socket->Listen(5);
diff --git a/p2p/base/transport.cc b/p2p/base/transport.cc
index 16087e3..d88f5e7 100644
--- a/p2p/base/transport.cc
+++ b/p2p/base/transport.cc
@@ -27,20 +27,21 @@
#include "talk/p2p/base/transport.h"
-#include "talk/base/bind.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/constants.h"
-#include "talk/p2p/base/sessionmanager.h"
#include "talk/p2p/base/parsing.h"
+#include "talk/p2p/base/port.h"
+#include "talk/p2p/base/sessionmanager.h"
#include "talk/p2p/base/transportchannelimpl.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/bind.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
namespace cricket {
-using talk_base::Bind;
+using rtc::Bind;
enum {
MSG_ONSIGNALINGREADY = 1,
@@ -57,7 +58,7 @@
MSG_FAILED,
};
-struct ChannelParams : public talk_base::MessageData {
+struct ChannelParams : public rtc::MessageData {
ChannelParams() : channel(NULL), candidate(NULL) {}
explicit ChannelParams(int component)
: component(component), channel(NULL), candidate(NULL) {}
@@ -118,8 +119,25 @@
return false;
}
-Transport::Transport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+bool IceCredentialsChanged(const std::string& old_ufrag,
+ const std::string& old_pwd,
+ const std::string& new_ufrag,
+ const std::string& new_pwd) {
+ // TODO(jiayl): The standard (RFC 5245 Section 9.1.1.1) says that ICE should
+ // restart when both the ufrag and password are changed, but we do restart
+ // when either ufrag or passwrod is changed to keep compatible with GICE. We
+ // should clean this up when GICE is no longer used.
+ return (old_ufrag != new_ufrag) || (old_pwd != new_pwd);
+}
+
+static bool IceCredentialsChanged(const TransportDescription& old_desc,
+ const TransportDescription& new_desc) {
+ return IceCredentialsChanged(old_desc.ice_ufrag, old_desc.ice_pwd,
+ new_desc.ice_ufrag, new_desc.ice_pwd);
+}
+
+Transport::Transport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
const std::string& type,
PortAllocator* allocator)
@@ -148,25 +166,25 @@
worker_thread_->Invoke<void>(Bind(&Transport::SetIceRole_w, this, role));
}
-void Transport::SetIdentity(talk_base::SSLIdentity* identity) {
+void Transport::SetIdentity(rtc::SSLIdentity* identity) {
worker_thread_->Invoke<void>(Bind(&Transport::SetIdentity_w, this, identity));
}
-bool Transport::GetIdentity(talk_base::SSLIdentity** identity) {
+bool Transport::GetIdentity(rtc::SSLIdentity** identity) {
// The identity is set on the worker thread, so for safety it must also be
// acquired on the worker thread.
return worker_thread_->Invoke<bool>(
Bind(&Transport::GetIdentity_w, this, identity));
}
-bool Transport::GetRemoteCertificate(talk_base::SSLCertificate** cert) {
+bool Transport::GetRemoteCertificate(rtc::SSLCertificate** cert) {
// Channels can be deleted on the worker thread, so for safety the remote
// certificate is acquired on the worker thread.
return worker_thread_->Invoke<bool>(
Bind(&Transport::GetRemoteCertificate_w, this, cert));
}
-bool Transport::GetRemoteCertificate_w(talk_base::SSLCertificate** cert) {
+bool Transport::GetRemoteCertificate_w(rtc::SSLCertificate** cert) {
ASSERT(worker_thread()->IsCurrent());
if (channels_.empty())
return false;
@@ -201,7 +219,7 @@
TransportChannelImpl* Transport::CreateChannel_w(int component) {
ASSERT(worker_thread()->IsCurrent());
TransportChannelImpl *impl;
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
// Create the entry if it does not exist.
bool impl_exists = false;
@@ -259,13 +277,13 @@
}
TransportChannelImpl* Transport::GetChannel(int component) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ChannelMap::iterator iter = channels_.find(component);
return (iter != channels_.end()) ? iter->second.get() : NULL;
}
bool Transport::HasChannels() {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
return !channels_.empty();
}
@@ -279,7 +297,7 @@
TransportChannelImpl* impl = NULL;
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ChannelMap::iterator iter = channels_.find(component);
if (iter == channels_.end())
return;
@@ -326,8 +344,8 @@
LOG(LS_INFO) << "Transport::ConnectChannels_w: No local description has "
<< "been set. Will generate one.";
TransportDescription desc(NS_GINGLE_P2P, std::vector<std::string>(),
- talk_base::CreateRandomString(ICE_UFRAG_LENGTH),
- talk_base::CreateRandomString(ICE_PWD_LENGTH),
+ rtc::CreateRandomString(ICE_UFRAG_LENGTH),
+ rtc::CreateRandomString(ICE_PWD_LENGTH),
ICEMODE_FULL, CONNECTIONROLE_NONE, NULL,
Candidates());
SetLocalTransportDescription_w(desc, CA_OFFER, NULL);
@@ -357,7 +375,7 @@
ASSERT(worker_thread()->IsCurrent());
std::vector<TransportChannelImpl*> impls;
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
for (ChannelMap::iterator iter = channels_.begin();
iter != channels_.end();
++iter) {
@@ -385,7 +403,7 @@
connect_requested_ = false;
// Clear out the old messages, they aren't relevant
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ready_candidates_.clear();
// Reset all of the channels
@@ -404,7 +422,7 @@
void Transport::CallChannels_w(TransportChannelFunc func) {
ASSERT(worker_thread()->IsCurrent());
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
for (ChannelMap::iterator iter = channels_.begin();
iter != channels_.end();
++iter) {
@@ -421,11 +439,12 @@
// Disallow all ports below 1024, except for 80 and 443 on public addresses.
int port = cand.address().port();
- if (port == 0) {
+ if (cand.protocol() == TCP_PROTOCOL_NAME &&
+ (cand.tcptype() == TCPTYPE_ACTIVE_STR || port == 0)) {
// Expected for active-only candidates per
// http://tools.ietf.org/html/rfc6544#section-4.5 so no error.
- *error = "";
- return false;
+ // Libjingle clients emit port 0, in "active" mode.
+ return true;
}
if (port < 1024) {
if ((port != 80) && (port != 443)) {
@@ -466,7 +485,7 @@
return true;
}
-bool Transport::GetSslRole(talk_base::SSLRole* ssl_role) const {
+bool Transport::GetSslRole(rtc::SSLRole* ssl_role) const {
return worker_thread_->Invoke<bool>(Bind(
&Transport::GetSslRole_w, this, ssl_role));
}
@@ -535,7 +554,7 @@
TransportState Transport::GetTransportState_s(bool read) {
ASSERT(signaling_thread()->IsCurrent());
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
bool any = false;
bool all = !channels_.empty();
for (ChannelMap::iterator iter = channels_.begin();
@@ -566,7 +585,7 @@
LOG(LS_INFO) << "Transport: " << content_name_ << ", allocating candidates";
// Resetting ICE state for the channel.
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ChannelMap::iterator iter = channels_.find(component);
if (iter != channels_.end())
iter->second.set_candidates_allocated(false);
@@ -577,7 +596,7 @@
void Transport::OnChannelCandidateReady(TransportChannelImpl* channel,
const Candidate& candidate) {
ASSERT(worker_thread()->IsCurrent());
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ready_candidates_.push_back(candidate);
// We hold any messages until the client lets us connect.
@@ -593,7 +612,7 @@
std::vector<Candidate> candidates;
{
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
candidates.swap(ready_candidates_);
}
@@ -621,7 +640,7 @@
void Transport::OnChannelCandidatesAllocationDone(
TransportChannelImpl* channel) {
ASSERT(worker_thread()->IsCurrent());
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ChannelMap::iterator iter = channels_.find(channel->component());
ASSERT(iter != channels_.end());
LOG(LS_INFO) << "Transport: " << content_name_ << ", component "
@@ -696,7 +715,7 @@
}
void Transport::SetIceRole_w(IceRole role) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
ice_role_ = role;
for (ChannelMap::iterator iter = channels_.begin();
iter != channels_.end(); ++iter) {
@@ -705,7 +724,7 @@
}
void Transport::SetRemoteIceMode_w(IceMode mode) {
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
remote_ice_mode_ = mode;
// Shouldn't channels be created after this method executed?
for (ChannelMap::iterator iter = channels_.begin();
@@ -719,14 +738,24 @@
ContentAction action,
std::string* error_desc) {
bool ret = true;
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
if (!VerifyIceParams(desc)) {
return BadTransportDescription("Invalid ice-ufrag or ice-pwd length",
error_desc);
}
+ if (local_description_ && IceCredentialsChanged(*local_description_, desc)) {
+ IceRole new_ice_role = (action == CA_OFFER) ? ICEROLE_CONTROLLING
+ : ICEROLE_CONTROLLED;
+
+ // It must be called before ApplyLocalTransportDescription_w, which may
+ // trigger an ICE restart and depends on the new ICE role.
+ SetIceRole_w(new_ice_role);
+ }
+
local_description_.reset(new TransportDescription(desc));
+
for (ChannelMap::iterator iter = channels_.begin();
iter != channels_.end(); ++iter) {
ret &= ApplyLocalTransportDescription_w(iter->second.get(), error_desc);
@@ -746,7 +775,7 @@
ContentAction action,
std::string* error_desc) {
bool ret = true;
- talk_base::CritScope cs(&crit_);
+ rtc::CritScope cs(&crit_);
if (!VerifyIceParams(desc)) {
return BadTransportDescription("Invalid ice-ufrag or ice-pwd length",
@@ -864,7 +893,7 @@
return true;
}
-void Transport::OnMessage(talk_base::Message* msg) {
+void Transport::OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_ONSIGNALINGREADY:
CallChannels_w(&TransportChannelImpl::OnSignalingReady);
@@ -917,7 +946,7 @@
bool TransportParser::ParseAddress(const buzz::XmlElement* elem,
const buzz::QName& address_name,
const buzz::QName& port_name,
- talk_base::SocketAddress* address,
+ rtc::SocketAddress* address,
ParseError* error) {
if (!elem->HasAttr(address_name))
return BadParse("address does not have " + address_name.LocalPart(), error);
diff --git a/p2p/base/transport.h b/p2p/base/transport.h
index 7f460d1..21661f6 100644
--- a/p2p/base/transport.h
+++ b/p2p/base/transport.h
@@ -46,19 +46,19 @@
#ifndef TALK_P2P_BASE_TRANSPORT_H_
#define TALK_P2P_BASE_TRANSPORT_H_
-#include <string>
#include <map>
+#include <string>
#include <vector>
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/sslstreamadapter.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/p2p/base/transportinfo.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/sslstreamadapter.h"
-namespace talk_base {
+namespace rtc {
class Thread;
}
@@ -123,7 +123,7 @@
bool ParseAddress(const buzz::XmlElement* elem,
const buzz::QName& address_name,
const buzz::QName& port_name,
- talk_base::SocketAddress* address,
+ rtc::SocketAddress* address,
ParseError* error);
virtual ~TransportParser() {}
@@ -189,20 +189,25 @@
bool BadTransportDescription(const std::string& desc, std::string* err_desc);
-class Transport : public talk_base::MessageHandler,
+bool IceCredentialsChanged(const std::string& old_ufrag,
+ const std::string& old_pwd,
+ const std::string& new_ufrag,
+ const std::string& new_pwd);
+
+class Transport : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
- Transport(talk_base::Thread* signaling_thread,
- talk_base::Thread* worker_thread,
+ Transport(rtc::Thread* signaling_thread,
+ rtc::Thread* worker_thread,
const std::string& content_name,
const std::string& type,
PortAllocator* allocator);
virtual ~Transport();
// Returns the signaling thread. The app talks to Transport on this thread.
- talk_base::Thread* signaling_thread() { return signaling_thread_; }
+ rtc::Thread* signaling_thread() { return signaling_thread_; }
// Returns the worker thread. The actual networking is done on this thread.
- talk_base::Thread* worker_thread() { return worker_thread_; }
+ rtc::Thread* worker_thread() { return worker_thread_; }
// Returns the content_name of this transport.
const std::string& content_name() const { return content_name_; }
@@ -249,13 +254,13 @@
uint64 IceTiebreaker() { return tiebreaker_; }
// Must be called before applying local session description.
- void SetIdentity(talk_base::SSLIdentity* identity);
+ void SetIdentity(rtc::SSLIdentity* identity);
// Get a copy of the local identity provided by SetIdentity.
- bool GetIdentity(talk_base::SSLIdentity** identity);
+ bool GetIdentity(rtc::SSLIdentity** identity);
// Get a copy of the remote certificate in use by the specified channel.
- bool GetRemoteCertificate(talk_base::SSLCertificate** cert);
+ bool GetRemoteCertificate(rtc::SSLCertificate** cert);
TransportProtocol protocol() const { return protocol_; }
@@ -336,7 +341,7 @@
// Forwards the signal from TransportChannel to BaseSession.
sigslot::signal0<> SignalRoleConflict;
- virtual bool GetSslRole(talk_base::SSLRole* ssl_role) const;
+ virtual bool GetSslRole(rtc::SSLRole* ssl_role) const;
protected:
// These are called by Create/DestroyChannel above in order to create or
@@ -359,9 +364,9 @@
return remote_description_.get();
}
- virtual void SetIdentity_w(talk_base::SSLIdentity* identity) {}
+ virtual void SetIdentity_w(rtc::SSLIdentity* identity) {}
- virtual bool GetIdentity_w(talk_base::SSLIdentity** identity) {
+ virtual bool GetIdentity_w(rtc::SSLIdentity** identity) {
return false;
}
@@ -390,7 +395,7 @@
virtual bool ApplyNegotiatedTransportDescription_w(
TransportChannelImpl* channel, std::string* error_desc);
- virtual bool GetSslRole_w(talk_base::SSLRole* ssl_role) const {
+ virtual bool GetSslRole_w(rtc::SSLRole* ssl_role) const {
return false;
}
@@ -447,7 +452,7 @@
void OnChannelConnectionRemoved(TransportChannelImpl* channel);
// Dispatches messages to the appropriate handler (below).
- void OnMessage(talk_base::Message* msg);
+ void OnMessage(rtc::Message* msg);
// These are versions of the above methods that are called only on a
// particular thread (s = signaling, w = worker). The above methods post or
@@ -484,13 +489,13 @@
ContentAction action,
std::string* error_desc);
bool GetStats_w(TransportStats* infos);
- bool GetRemoteCertificate_w(talk_base::SSLCertificate** cert);
+ bool GetRemoteCertificate_w(rtc::SSLCertificate** cert);
// Sends SignalCompleted if we are now in that state.
void MaybeCompleted_w();
- talk_base::Thread* signaling_thread_;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* signaling_thread_;
+ rtc::Thread* worker_thread_;
std::string content_name_;
std::string type_;
PortAllocator* allocator_;
@@ -503,15 +508,15 @@
uint64 tiebreaker_;
TransportProtocol protocol_;
IceMode remote_ice_mode_;
- talk_base::scoped_ptr<TransportDescription> local_description_;
- talk_base::scoped_ptr<TransportDescription> remote_description_;
+ rtc::scoped_ptr<TransportDescription> local_description_;
+ rtc::scoped_ptr<TransportDescription> remote_description_;
ChannelMap channels_;
// Buffers the ready_candidates so that SignalCanidatesReady can
// provide them in multiples.
std::vector<Candidate> ready_candidates_;
// Protects changes to channels and messages
- talk_base::CriticalSection crit_;
+ rtc::CriticalSection crit_;
DISALLOW_EVIL_CONSTRUCTORS(Transport);
};
diff --git a/p2p/base/transport_unittest.cc b/p2p/base/transport_unittest.cc
index b91b1a0..8f7dae2 100644
--- a/p2p/base/transport_unittest.cc
+++ b/p2p/base/transport_unittest.cc
@@ -25,17 +25,17 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/fakesslidentity.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/fakesession.h"
-#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/p2ptransport.h"
+#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/rawtransport.h"
#include "talk/p2p/base/sessionmessages.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/fakesslidentity.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/thread.h"
using cricket::Candidate;
using cricket::Candidates;
@@ -47,16 +47,19 @@
using cricket::TransportDescription;
using cricket::WriteError;
using cricket::ParseError;
-using talk_base::SocketAddress;
+using rtc::SocketAddress;
static const char kIceUfrag1[] = "TESTICEUFRAG0001";
static const char kIcePwd1[] = "TESTICEPWD00000000000001";
+static const char kIceUfrag2[] = "TESTICEUFRAG0002";
+static const char kIcePwd2[] = "TESTICEPWD00000000000002";
+
class TransportTest : public testing::Test,
public sigslot::has_slots<> {
public:
TransportTest()
- : thread_(talk_base::Thread::Current()),
+ : thread_(rtc::Thread::Current()),
transport_(new FakeTransport(
thread_, thread_, "test content name", NULL)),
channel_(NULL),
@@ -94,8 +97,8 @@
failed_ = true;
}
- talk_base::Thread* thread_;
- talk_base::scoped_ptr<FakeTransport> transport_;
+ rtc::Thread* thread_;
+ rtc::scoped_ptr<FakeTransport> transport_;
FakeTransportChannel* channel_;
bool connecting_signalled_;
bool completed_;
@@ -184,6 +187,96 @@
EXPECT_EQ(kIcePwd1, channel_->remote_ice_pwd());
}
+// Verifies that IceCredentialsChanged returns true when either ufrag or pwd
+// changed, and false in other cases.
+TEST_F(TransportTest, TestIceCredentialsChanged) {
+ EXPECT_TRUE(cricket::IceCredentialsChanged("u1", "p1", "u2", "p2"));
+ EXPECT_TRUE(cricket::IceCredentialsChanged("u1", "p1", "u2", "p1"));
+ EXPECT_TRUE(cricket::IceCredentialsChanged("u1", "p1", "u1", "p2"));
+ EXPECT_FALSE(cricket::IceCredentialsChanged("u1", "p1", "u1", "p1"));
+}
+
+// This test verifies that the callee's ICE role changes from controlled to
+// controlling when the callee triggers an ICE restart.
+TEST_F(TransportTest, TestIceControlledToControllingOnIceRestart) {
+ EXPECT_TRUE(SetupChannel());
+ transport_->SetIceRole(cricket::ICEROLE_CONTROLLED);
+
+ cricket::TransportDescription desc(
+ cricket::NS_JINGLE_ICE_UDP, kIceUfrag1, kIcePwd1);
+ ASSERT_TRUE(transport_->SetRemoteTransportDescription(desc,
+ cricket::CA_OFFER,
+ NULL));
+ ASSERT_TRUE(transport_->SetLocalTransportDescription(desc,
+ cricket::CA_ANSWER,
+ NULL));
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLED, transport_->ice_role());
+
+ cricket::TransportDescription new_local_desc(
+ cricket::NS_JINGLE_ICE_UDP, kIceUfrag2, kIcePwd2);
+ ASSERT_TRUE(transport_->SetLocalTransportDescription(new_local_desc,
+ cricket::CA_OFFER,
+ NULL));
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLING, transport_->ice_role());
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLING, channel_->GetIceRole());
+}
+
+// This test verifies that the caller's ICE role changes from controlling to
+// controlled when the callee triggers an ICE restart.
+TEST_F(TransportTest, TestIceControllingToControlledOnIceRestart) {
+ EXPECT_TRUE(SetupChannel());
+ transport_->SetIceRole(cricket::ICEROLE_CONTROLLING);
+
+ cricket::TransportDescription desc(
+ cricket::NS_JINGLE_ICE_UDP, kIceUfrag1, kIcePwd1);
+ ASSERT_TRUE(transport_->SetLocalTransportDescription(desc,
+ cricket::CA_OFFER,
+ NULL));
+ ASSERT_TRUE(transport_->SetRemoteTransportDescription(desc,
+ cricket::CA_ANSWER,
+ NULL));
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLING, transport_->ice_role());
+
+ cricket::TransportDescription new_local_desc(
+ cricket::NS_JINGLE_ICE_UDP, kIceUfrag2, kIcePwd2);
+ ASSERT_TRUE(transport_->SetLocalTransportDescription(new_local_desc,
+ cricket::CA_ANSWER,
+ NULL));
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLED, transport_->ice_role());
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLED, channel_->GetIceRole());
+}
+
+// This test verifies that the caller's ICE role is still controlling after the
+// callee triggers ICE restart if the callee's ICE mode is LITE.
+TEST_F(TransportTest, TestIceControllingOnIceRestartIfRemoteIsIceLite) {
+ EXPECT_TRUE(SetupChannel());
+ transport_->SetIceRole(cricket::ICEROLE_CONTROLLING);
+
+ cricket::TransportDescription desc(
+ cricket::NS_JINGLE_ICE_UDP, kIceUfrag1, kIcePwd1);
+ ASSERT_TRUE(transport_->SetLocalTransportDescription(desc,
+ cricket::CA_OFFER,
+ NULL));
+
+ cricket::TransportDescription remote_desc(
+ cricket::NS_JINGLE_ICE_UDP, std::vector<std::string>(),
+ kIceUfrag1, kIcePwd1, cricket::ICEMODE_LITE,
+ cricket::CONNECTIONROLE_NONE, NULL, cricket::Candidates());
+ ASSERT_TRUE(transport_->SetRemoteTransportDescription(remote_desc,
+ cricket::CA_ANSWER,
+ NULL));
+
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLING, transport_->ice_role());
+
+ cricket::TransportDescription new_local_desc(
+ cricket::NS_JINGLE_ICE_UDP, kIceUfrag2, kIcePwd2);
+ ASSERT_TRUE(transport_->SetLocalTransportDescription(new_local_desc,
+ cricket::CA_ANSWER,
+ NULL));
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLING, transport_->ice_role());
+ EXPECT_EQ(cricket::ICEROLE_CONTROLLING, channel_->GetIceRole());
+}
+
// This test verifies that the Completed and Failed states can be reached.
TEST_F(TransportTest, TestChannelCompletedAndFailed) {
transport_->SetIceRole(cricket::ICEROLE_CONTROLLING);
@@ -272,20 +365,20 @@
TEST_F(TransportTest, TestP2PTransportWriteAndParseCandidate) {
Candidate test_candidate(
"", 1, "udp",
- talk_base::SocketAddress("2001:db8:fefe::1", 9999),
+ rtc::SocketAddress("2001:db8:fefe::1", 9999),
738197504, "abcdef", "ghijkl", "foo", "testnet", 50, "");
Candidate test_candidate2(
"", 2, "tcp",
- talk_base::SocketAddress("192.168.7.1", 9999),
+ rtc::SocketAddress("192.168.7.1", 9999),
1107296256, "mnopqr", "stuvwx", "bar", "testnet2", 100, "");
- talk_base::SocketAddress host_address("www.google.com", 24601);
- host_address.SetResolvedIP(talk_base::IPAddress(0x0A000001));
+ rtc::SocketAddress host_address("www.google.com", 24601);
+ host_address.SetResolvedIP(rtc::IPAddress(0x0A000001));
Candidate test_candidate3(
"", 3, "spdy", host_address, 1476395008, "yzabcd",
"efghij", "baz", "testnet3", 150, "");
WriteError write_error;
ParseError parse_error;
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<buzz::XmlElement> elem;
cricket::Candidate parsed_candidate;
cricket::P2PTransportParser parser;
diff --git a/p2p/base/transportchannel.h b/p2p/base/transportchannel.h
index c548c1c..b0beb04 100644
--- a/p2p/base/transportchannel.h
+++ b/p2p/base/transportchannel.h
@@ -31,16 +31,16 @@
#include <string>
#include <vector>
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/basictypes.h"
-#include "talk/base/dscp.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socket.h"
-#include "talk/base/sslidentity.h"
-#include "talk/base/sslstreamadapter.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/transportdescription.h"
+#include "webrtc/base/asyncpacketsocket.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/socket.h"
+#include "webrtc/base/sslidentity.h"
+#include "webrtc/base/sslstreamadapter.h"
namespace cricket {
@@ -83,12 +83,12 @@
// Attempts to send the given packet. The return value is < 0 on failure.
// TODO: Remove the default argument once channel code is updated.
virtual int SendPacket(const char* data, size_t len,
- const talk_base::PacketOptions& options,
+ const rtc::PacketOptions& options,
int flags = 0) = 0;
// Sets a socket option on this channel. Note that not all options are
// supported by all transport types.
- virtual int SetOption(talk_base::Socket::Option opt, int value) = 0;
+ virtual int SetOption(rtc::Socket::Option opt, int value) = 0;
// Returns the most recent error that occurred on this channel.
virtual int GetError() = 0;
@@ -100,7 +100,7 @@
virtual bool IsDtlsActive() const = 0;
// Default implementation.
- virtual bool GetSslRole(talk_base::SSLRole* role) const = 0;
+ virtual bool GetSslRole(rtc::SSLRole* role) const = 0;
// Sets up the ciphers to use for DTLS-SRTP.
virtual bool SetSrtpCiphers(const std::vector<std::string>& ciphers) = 0;
@@ -109,10 +109,10 @@
virtual bool GetSrtpCipher(std::string* cipher) = 0;
// Gets a copy of the local SSL identity, owned by the caller.
- virtual bool GetLocalIdentity(talk_base::SSLIdentity** identity) const = 0;
+ virtual bool GetLocalIdentity(rtc::SSLIdentity** identity) const = 0;
// Gets a copy of the remote side's SSL certificate, owned by the caller.
- virtual bool GetRemoteCertificate(talk_base::SSLCertificate** cert) const = 0;
+ virtual bool GetRemoteCertificate(rtc::SSLCertificate** cert) const = 0;
// Allows key material to be extracted for external encryption.
virtual bool ExportKeyingMaterial(const std::string& label,
@@ -124,7 +124,7 @@
// Signalled each time a packet is received on this channel.
sigslot::signal5<TransportChannel*, const char*,
- size_t, const talk_base::PacketTime&, int> SignalReadPacket;
+ size_t, const rtc::PacketTime&, int> SignalReadPacket;
// This signal occurs when there is a change in the way that packets are
// being routed, i.e. to a different remote location. The candidate
diff --git a/p2p/base/transportchannelimpl.h b/p2p/base/transportchannelimpl.h
index 25c3121..fde980b 100644
--- a/p2p/base/transportchannelimpl.h
+++ b/p2p/base/transportchannelimpl.h
@@ -99,14 +99,14 @@
// retains ownership and must delete it after this TransportChannelImpl is
// destroyed.
// TODO(bemasc): Fix the ownership semantics of this method.
- virtual bool SetLocalIdentity(talk_base::SSLIdentity* identity) = 0;
+ virtual bool SetLocalIdentity(rtc::SSLIdentity* identity) = 0;
// Set DTLS Remote fingerprint. Must be after local identity set.
virtual bool SetRemoteFingerprint(const std::string& digest_alg,
const uint8* digest,
size_t digest_len) = 0;
- virtual bool SetSslRole(talk_base::SSLRole role) = 0;
+ virtual bool SetSslRole(rtc::SSLRole role) = 0;
// TransportChannel is forwarding this signal from PortAllocatorSession.
sigslot::signal1<TransportChannelImpl*> SignalCandidatesAllocationDone;
diff --git a/p2p/base/transportchannelproxy.cc b/p2p/base/transportchannelproxy.cc
index fdcc509..9fa0b6a 100644
--- a/p2p/base/transportchannelproxy.cc
+++ b/p2p/base/transportchannelproxy.cc
@@ -25,12 +25,12 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/p2p/base/transportchannelproxy.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/transportchannelimpl.h"
+#include "talk/p2p/base/transportchannelproxy.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -44,7 +44,7 @@
: TransportChannel(content_name, component),
name_(name),
impl_(NULL) {
- worker_thread_ = talk_base::Thread::Current();
+ worker_thread_ = rtc::Thread::Current();
}
TransportChannelProxy::~TransportChannelProxy() {
@@ -55,7 +55,7 @@
}
void TransportChannelProxy::SetImplementation(TransportChannelImpl* impl) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (impl == impl_) {
// Ignore if the |impl| has already been set.
@@ -101,9 +101,9 @@
}
int TransportChannelProxy::SendPacket(const char* data, size_t len,
- const talk_base::PacketOptions& options,
+ const rtc::PacketOptions& options,
int flags) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
// Fail if we don't have an impl yet.
if (!impl_) {
return -1;
@@ -111,8 +111,8 @@
return impl_->SendPacket(data, len, options, flags);
}
-int TransportChannelProxy::SetOption(talk_base::Socket::Option opt, int value) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+int TransportChannelProxy::SetOption(rtc::Socket::Option opt, int value) {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
pending_options_.push_back(OptionPair(opt, value));
return 0;
@@ -121,7 +121,7 @@
}
int TransportChannelProxy::GetError() {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return 0;
}
@@ -129,7 +129,7 @@
}
bool TransportChannelProxy::GetStats(ConnectionInfos* infos) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
@@ -137,23 +137,23 @@
}
bool TransportChannelProxy::IsDtlsActive() const {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
return impl_->IsDtlsActive();
}
-bool TransportChannelProxy::GetSslRole(talk_base::SSLRole* role) const {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+bool TransportChannelProxy::GetSslRole(rtc::SSLRole* role) const {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
return impl_->GetSslRole(role);
}
-bool TransportChannelProxy::SetSslRole(talk_base::SSLRole role) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+bool TransportChannelProxy::SetSslRole(rtc::SSLRole role) {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
@@ -162,7 +162,7 @@
bool TransportChannelProxy::SetSrtpCiphers(const std::vector<std::string>&
ciphers) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
pending_srtp_ciphers_ = ciphers; // Cache so we can send later, but always
// set so it stays consistent.
if (impl_) {
@@ -172,7 +172,7 @@
}
bool TransportChannelProxy::GetSrtpCipher(std::string* cipher) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
@@ -180,8 +180,8 @@
}
bool TransportChannelProxy::GetLocalIdentity(
- talk_base::SSLIdentity** identity) const {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ rtc::SSLIdentity** identity) const {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
@@ -189,8 +189,8 @@
}
bool TransportChannelProxy::GetRemoteCertificate(
- talk_base::SSLCertificate** cert) const {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ rtc::SSLCertificate** cert) const {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
@@ -203,7 +203,7 @@
bool use_context,
uint8* result,
size_t result_len) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return false;
}
@@ -212,7 +212,7 @@
}
IceRole TransportChannelProxy::GetIceRole() const {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!impl_) {
return ICEROLE_UNKNOWN;
}
@@ -220,14 +220,14 @@
}
void TransportChannelProxy::OnReadableState(TransportChannel* channel) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == impl_);
set_readable(impl_->readable());
// Note: SignalReadableState fired by set_readable.
}
void TransportChannelProxy::OnWritableState(TransportChannel* channel) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == impl_);
set_writable(impl_->writable());
// Note: SignalWritableState fired by set_readable.
@@ -235,27 +235,27 @@
void TransportChannelProxy::OnReadPacket(
TransportChannel* channel, const char* data, size_t size,
- const talk_base::PacketTime& packet_time, int flags) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ const rtc::PacketTime& packet_time, int flags) {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == impl_);
SignalReadPacket(this, data, size, packet_time, flags);
}
void TransportChannelProxy::OnReadyToSend(TransportChannel* channel) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == impl_);
SignalReadyToSend(this);
}
void TransportChannelProxy::OnRouteChange(TransportChannel* channel,
const Candidate& candidate) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
ASSERT(channel == impl_);
SignalRouteChange(this, candidate);
}
-void TransportChannelProxy::OnMessage(talk_base::Message* msg) {
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+void TransportChannelProxy::OnMessage(rtc::Message* msg) {
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (msg->message_id == MSG_UPDATESTATE) {
// If impl_ is already readable or writable, push up those signals.
set_readable(impl_ ? impl_->readable() : false);
diff --git a/p2p/base/transportchannelproxy.h b/p2p/base/transportchannelproxy.h
index cb38c7b..07b9090 100644
--- a/p2p/base/transportchannelproxy.h
+++ b/p2p/base/transportchannelproxy.h
@@ -32,10 +32,10 @@
#include <utility>
#include <vector>
-#include "talk/base/messagehandler.h"
#include "talk/p2p/base/transportchannel.h"
+#include "webrtc/base/messagehandler.h"
-namespace talk_base {
+namespace rtc {
class Thread;
}
@@ -48,7 +48,7 @@
// network negotiation is complete. Hence, we create a proxy up front, and
// when negotiation completes, connect the proxy to the implementaiton.
class TransportChannelProxy : public TransportChannel,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
TransportChannelProxy(const std::string& content_name,
const std::string& name,
@@ -64,19 +64,19 @@
// Implementation of the TransportChannel interface. These simply forward to
// the implementation.
virtual int SendPacket(const char* data, size_t len,
- const talk_base::PacketOptions& options,
+ const rtc::PacketOptions& options,
int flags);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
virtual int GetError();
virtual IceRole GetIceRole() const;
virtual bool GetStats(ConnectionInfos* infos);
virtual bool IsDtlsActive() const;
- virtual bool GetSslRole(talk_base::SSLRole* role) const;
- virtual bool SetSslRole(talk_base::SSLRole role);
+ virtual bool GetSslRole(rtc::SSLRole* role) const;
+ virtual bool SetSslRole(rtc::SSLRole role);
virtual bool SetSrtpCiphers(const std::vector<std::string>& ciphers);
virtual bool GetSrtpCipher(std::string* cipher);
- virtual bool GetLocalIdentity(talk_base::SSLIdentity** identity) const;
- virtual bool GetRemoteCertificate(talk_base::SSLCertificate** cert) const;
+ virtual bool GetLocalIdentity(rtc::SSLIdentity** identity) const;
+ virtual bool GetRemoteCertificate(rtc::SSLCertificate** cert) const;
virtual bool ExportKeyingMaterial(const std::string& label,
const uint8* context,
size_t context_len,
@@ -90,16 +90,16 @@
void OnReadableState(TransportChannel* channel);
void OnWritableState(TransportChannel* channel);
void OnReadPacket(TransportChannel* channel, const char* data, size_t size,
- const talk_base::PacketTime& packet_time, int flags);
+ const rtc::PacketTime& packet_time, int flags);
void OnReadyToSend(TransportChannel* channel);
void OnRouteChange(TransportChannel* channel, const Candidate& candidate);
- void OnMessage(talk_base::Message* message);
+ void OnMessage(rtc::Message* message);
- typedef std::pair<talk_base::Socket::Option, int> OptionPair;
+ typedef std::pair<rtc::Socket::Option, int> OptionPair;
typedef std::vector<OptionPair> OptionList;
std::string name_;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* worker_thread_;
TransportChannelImpl* impl_;
OptionList pending_options_;
std::vector<std::string> pending_srtp_ciphers_;
diff --git a/p2p/base/transportdescription.h b/p2p/base/transportdescription.h
index 59dfa0b..efd04ff 100644
--- a/p2p/base/transportdescription.h
+++ b/p2p/base/transportdescription.h
@@ -32,10 +32,10 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslfingerprint.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/constants.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sslfingerprint.h"
namespace cricket {
@@ -99,7 +99,9 @@
typedef std::vector<Candidate> Candidates;
struct TransportDescription {
- TransportDescription() : ice_mode(ICEMODE_FULL) {}
+ TransportDescription()
+ : ice_mode(ICEMODE_FULL),
+ connection_role(CONNECTIONROLE_NONE) {}
TransportDescription(const std::string& transport_type,
const std::vector<std::string>& transport_options,
@@ -107,7 +109,7 @@
const std::string& ice_pwd,
IceMode ice_mode,
ConnectionRole role,
- const talk_base::SSLFingerprint* identity_fingerprint,
+ const rtc::SSLFingerprint* identity_fingerprint,
const Candidates& candidates)
: transport_type(transport_type),
transport_options(transport_options),
@@ -162,12 +164,12 @@
}
bool secure() const { return identity_fingerprint != NULL; }
- static talk_base::SSLFingerprint* CopyFingerprint(
- const talk_base::SSLFingerprint* from) {
+ static rtc::SSLFingerprint* CopyFingerprint(
+ const rtc::SSLFingerprint* from) {
if (!from)
return NULL;
- return new talk_base::SSLFingerprint(*from);
+ return new rtc::SSLFingerprint(*from);
}
std::string transport_type; // xmlns of <transport>
@@ -177,7 +179,7 @@
IceMode ice_mode;
ConnectionRole connection_role;
- talk_base::scoped_ptr<talk_base::SSLFingerprint> identity_fingerprint;
+ rtc::scoped_ptr<rtc::SSLFingerprint> identity_fingerprint;
Candidates candidates;
};
diff --git a/p2p/base/transportdescriptionfactory.cc b/p2p/base/transportdescriptionfactory.cc
index c8fb0b3..4eb603c 100644
--- a/p2p/base/transportdescriptionfactory.cc
+++ b/p2p/base/transportdescriptionfactory.cc
@@ -27,12 +27,12 @@
#include "talk/p2p/base/transportdescriptionfactory.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sslfingerprint.h"
#include "talk/p2p/base/transportdescription.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sslfingerprint.h"
namespace cricket {
@@ -47,7 +47,7 @@
TransportDescription* TransportDescriptionFactory::CreateOffer(
const TransportOptions& options,
const TransportDescription* current_description) const {
- talk_base::scoped_ptr<TransportDescription> desc(new TransportDescription());
+ rtc::scoped_ptr<TransportDescription> desc(new TransportDescription());
// Set the transport type depending on the selected protocol.
if (protocol_ == ICEPROTO_RFC5245) {
@@ -61,8 +61,8 @@
// Generate the ICE credentials if we don't already have them.
if (!current_description || options.ice_restart) {
- desc->ice_ufrag = talk_base::CreateRandomString(ICE_UFRAG_LENGTH);
- desc->ice_pwd = talk_base::CreateRandomString(ICE_PWD_LENGTH);
+ desc->ice_ufrag = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
+ desc->ice_pwd = rtc::CreateRandomString(ICE_PWD_LENGTH);
} else {
desc->ice_ufrag = current_description->ice_ufrag;
desc->ice_pwd = current_description->ice_pwd;
@@ -86,7 +86,7 @@
const TransportDescription* current_description) const {
// A NULL offer is treated as a GICE transport description.
// TODO(juberti): Figure out why we get NULL offers, and fix this upstream.
- talk_base::scoped_ptr<TransportDescription> desc(new TransportDescription());
+ rtc::scoped_ptr<TransportDescription> desc(new TransportDescription());
// Figure out which ICE variant to negotiate; prefer RFC 5245 ICE, but fall
// back to G-ICE if needed. Note that we never create a hybrid answer, since
@@ -114,8 +114,8 @@
// Generate the ICE credentials if we don't already have them or ice is
// being restarted.
if (!current_description || options.ice_restart) {
- desc->ice_ufrag = talk_base::CreateRandomString(ICE_UFRAG_LENGTH);
- desc->ice_pwd = talk_base::CreateRandomString(ICE_PWD_LENGTH);
+ desc->ice_ufrag = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
+ desc->ice_pwd = rtc::CreateRandomString(ICE_PWD_LENGTH);
} else {
desc->ice_ufrag = current_description->ice_ufrag;
desc->ice_pwd = current_description->ice_pwd;
@@ -161,7 +161,7 @@
}
desc->identity_fingerprint.reset(
- talk_base::SSLFingerprint::Create(digest_alg, identity_));
+ rtc::SSLFingerprint::Create(digest_alg, identity_));
if (!desc->identity_fingerprint.get()) {
LOG(LS_ERROR) << "Failed to create identity fingerprint, alg="
<< digest_alg;
diff --git a/p2p/base/transportdescriptionfactory.h b/p2p/base/transportdescriptionfactory.h
index 53dd238..84f25ac 100644
--- a/p2p/base/transportdescriptionfactory.h
+++ b/p2p/base/transportdescriptionfactory.h
@@ -30,7 +30,7 @@
#include "talk/p2p/base/transportdescription.h"
-namespace talk_base {
+namespace rtc {
class SSLIdentity;
}
@@ -51,14 +51,14 @@
TransportDescriptionFactory();
SecurePolicy secure() const { return secure_; }
// The identity to use when setting up DTLS.
- talk_base::SSLIdentity* identity() const { return identity_; }
+ rtc::SSLIdentity* identity() const { return identity_; }
// Specifies the transport protocol to be use.
void set_protocol(TransportProtocol protocol) { protocol_ = protocol; }
// Specifies the transport security policy to use.
void set_secure(SecurePolicy s) { secure_ = s; }
// Specifies the identity to use (only used when secure is not SEC_DISABLED).
- void set_identity(talk_base::SSLIdentity* identity) { identity_ = identity; }
+ void set_identity(rtc::SSLIdentity* identity) { identity_ = identity; }
// Creates a transport description suitable for use in an offer.
TransportDescription* CreateOffer(const TransportOptions& options,
@@ -75,7 +75,7 @@
TransportProtocol protocol_;
SecurePolicy secure_;
- talk_base::SSLIdentity* identity_;
+ rtc::SSLIdentity* identity_;
};
} // namespace cricket
diff --git a/p2p/base/transportdescriptionfactory_unittest.cc b/p2p/base/transportdescriptionfactory_unittest.cc
index 8d9a73f..b7f7008 100644
--- a/p2p/base/transportdescriptionfactory_unittest.cc
+++ b/p2p/base/transportdescriptionfactory_unittest.cc
@@ -28,13 +28,13 @@
#include <string>
#include <vector>
-#include "talk/base/fakesslidentity.h"
-#include "talk/base/gunit.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/transportdescription.h"
#include "talk/p2p/base/transportdescriptionfactory.h"
+#include "webrtc/base/fakesslidentity.h"
+#include "webrtc/base/gunit.h"
-using talk_base::scoped_ptr;
+using rtc::scoped_ptr;
using cricket::TransportDescriptionFactory;
using cricket::TransportDescription;
using cricket::TransportOptions;
@@ -42,8 +42,8 @@
class TransportDescriptionFactoryTest : public testing::Test {
public:
TransportDescriptionFactoryTest()
- : id1_(new talk_base::FakeSSLIdentity("User1")),
- id2_(new talk_base::FakeSSLIdentity("User2")) {
+ : id1_(new rtc::FakeSSLIdentity("User1")),
+ id2_(new rtc::FakeSSLIdentity("User2")) {
}
void CheckDesc(const TransportDescription* desc, const std::string& type,
const std::string& opt, const std::string& ice_ufrag,
@@ -86,22 +86,22 @@
cricket::TransportOptions options;
// The initial offer / answer exchange.
- talk_base::scoped_ptr<TransportDescription> offer(f1_.CreateOffer(
+ rtc::scoped_ptr<TransportDescription> offer(f1_.CreateOffer(
options, NULL));
- talk_base::scoped_ptr<TransportDescription> answer(
+ rtc::scoped_ptr<TransportDescription> answer(
f2_.CreateAnswer(offer.get(),
options, NULL));
// Create an updated offer where we restart ice.
options.ice_restart = true;
- talk_base::scoped_ptr<TransportDescription> restart_offer(f1_.CreateOffer(
+ rtc::scoped_ptr<TransportDescription> restart_offer(f1_.CreateOffer(
options, offer.get()));
VerifyUfragAndPasswordChanged(dtls, offer.get(), restart_offer.get());
// Create a new answer. The transport ufrag and password is changed since
// |options.ice_restart == true|
- talk_base::scoped_ptr<TransportDescription> restart_answer(
+ rtc::scoped_ptr<TransportDescription> restart_answer(
f2_.CreateAnswer(restart_offer.get(), options, answer.get()));
ASSERT_TRUE(restart_answer.get() != NULL);
@@ -129,8 +129,8 @@
protected:
TransportDescriptionFactory f1_;
TransportDescriptionFactory f2_;
- scoped_ptr<talk_base::SSLIdentity> id1_;
- scoped_ptr<talk_base::SSLIdentity> id2_;
+ scoped_ptr<rtc::SSLIdentity> id1_;
+ scoped_ptr<rtc::SSLIdentity> id2_;
};
// Test that in the default case, we generate the expected G-ICE offer.
diff --git a/p2p/base/transportinfo.h b/p2p/base/transportinfo.h
index ad8b6a2..5ffb10a 100644
--- a/p2p/base/transportinfo.h
+++ b/p2p/base/transportinfo.h
@@ -31,10 +31,10 @@
#include <string>
#include <vector>
-#include "talk/base/helpers.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/transportdescription.h"
+#include "webrtc/base/helpers.h"
namespace cricket {
diff --git a/p2p/base/turnport.cc b/p2p/base/turnport.cc
index 195e970..2908d71 100644
--- a/p2p/base/turnport.cc
+++ b/p2p/base/turnport.cc
@@ -29,15 +29,15 @@
#include <functional>
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/base/common.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/asyncpacketsocket.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/nethelpers.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
@@ -51,6 +51,10 @@
static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
+// Retry at most twice (i.e. three different ALLOCATE requests) on
+// STUN_ERROR_ALLOCATION_MISMATCH error per rfc5766.
+static const size_t MAX_ALLOCATE_MISMATCH_RETRIES = 2;
+
inline bool IsTurnChannelData(uint16 msg_type) {
return ((msg_type & 0xC000) == 0x4000); // MSB are 0b01
}
@@ -78,6 +82,7 @@
private:
// Handles authentication challenge from the server.
void OnAuthChallenge(StunMessage* response, int code);
+ void OnTryAlternate(StunMessage* response, int code);
void OnUnknownAttribute(StunMessage* response);
TurnPort* port_;
@@ -99,7 +104,7 @@
public sigslot::has_slots<> {
public:
TurnCreatePermissionRequest(TurnPort* port, TurnEntry* entry,
- const talk_base::SocketAddress& ext_addr);
+ const rtc::SocketAddress& ext_addr);
virtual void Prepare(StunMessage* request);
virtual void OnResponse(StunMessage* response);
virtual void OnErrorResponse(StunMessage* response);
@@ -110,14 +115,14 @@
TurnPort* port_;
TurnEntry* entry_;
- talk_base::SocketAddress ext_addr_;
+ rtc::SocketAddress ext_addr_;
};
class TurnChannelBindRequest : public StunRequest,
public sigslot::has_slots<> {
public:
TurnChannelBindRequest(TurnPort* port, TurnEntry* entry, int channel_id,
- const talk_base::SocketAddress& ext_addr);
+ const rtc::SocketAddress& ext_addr);
virtual void Prepare(StunMessage* request);
virtual void OnResponse(StunMessage* response);
virtual void OnErrorResponse(StunMessage* response);
@@ -129,7 +134,7 @@
TurnPort* port_;
TurnEntry* entry_;
int channel_id_;
- talk_base::SocketAddress ext_addr_;
+ rtc::SocketAddress ext_addr_;
};
// Manages a "connection" to a remote destination. We will attempt to bring up
@@ -138,12 +143,12 @@
public:
enum BindState { STATE_UNBOUND, STATE_BINDING, STATE_BOUND };
TurnEntry(TurnPort* port, int channel_id,
- const talk_base::SocketAddress& ext_addr);
+ const rtc::SocketAddress& ext_addr);
TurnPort* port() { return port_; }
int channel_id() const { return channel_id_; }
- const talk_base::SocketAddress& address() const { return ext_addr_; }
+ const rtc::SocketAddress& address() const { return ext_addr_; }
BindState state() const { return state_; }
// Helper methods to send permission and channel bind requests.
@@ -152,7 +157,7 @@
// Sends a packet to the given destination address.
// This will wrap the packet in STUN if necessary.
int Send(const void* data, size_t size, bool payload,
- const talk_base::PacketOptions& options);
+ const rtc::PacketOptions& options);
void OnCreatePermissionSuccess();
void OnCreatePermissionError(StunMessage* response, int code);
@@ -164,18 +169,19 @@
private:
TurnPort* port_;
int channel_id_;
- talk_base::SocketAddress ext_addr_;
+ rtc::SocketAddress ext_addr_;
BindState state_;
};
-TurnPort::TurnPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- talk_base::AsyncPacketSocket* socket,
+TurnPort::TurnPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ rtc::AsyncPacketSocket* socket,
const std::string& username,
const std::string& password,
const ProtocolAddress& server_address,
- const RelayCredentials& credentials)
+ const RelayCredentials& credentials,
+ int server_priority)
: Port(thread, factory, network, socket->GetLocalAddress().ipaddr(),
username, password),
server_address_(server_address),
@@ -185,19 +191,22 @@
error_(0),
request_manager_(thread),
next_channel_number_(TURN_CHANNEL_NUMBER_START),
- connected_(false) {
+ connected_(false),
+ server_priority_(server_priority),
+ allocate_mismatch_retries_(0) {
request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
}
-TurnPort::TurnPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip,
+TurnPort::TurnPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username,
const std::string& password,
const ProtocolAddress& server_address,
- const RelayCredentials& credentials)
+ const RelayCredentials& credentials,
+ int server_priority)
: Port(thread, RELAY_PORT_TYPE, factory, network, ip, min_port, max_port,
username, password),
server_address_(server_address),
@@ -207,7 +216,9 @@
error_(0),
request_manager_(thread),
next_channel_number_(TURN_CHANNEL_NUMBER_START),
- connected_(false) {
+ connected_(false),
+ server_priority_(server_priority),
+ allocate_mismatch_retries_(0) {
request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
}
@@ -249,46 +260,15 @@
return;
}
+ // Insert the current address to prevent redirection pingpong.
+ attempted_server_addresses_.insert(server_address_.address);
+
LOG_J(LS_INFO, this) << "Trying to connect to TURN server via "
<< ProtoToString(server_address_.proto) << " @ "
<< server_address_.address.ToSensitiveString();
- if (server_address_.proto == PROTO_UDP && !SharedSocket()) {
- socket_ = socket_factory()->CreateUdpSocket(
- talk_base::SocketAddress(ip(), 0), min_port(), max_port());
- } else if (server_address_.proto == PROTO_TCP) {
- ASSERT(!SharedSocket());
- int opts = talk_base::PacketSocketFactory::OPT_STUN;
- // If secure bit is enabled in server address, use TLS over TCP.
- if (server_address_.secure) {
- opts |= talk_base::PacketSocketFactory::OPT_TLS;
- }
- socket_ = socket_factory()->CreateClientTcpSocket(
- talk_base::SocketAddress(ip(), 0), server_address_.address,
- proxy(), user_agent(), opts);
- }
-
- if (!socket_) {
+ if (!CreateTurnClientSocket()) {
OnAllocateError();
- return;
- }
-
- // Apply options if any.
- for (SocketOptionsMap::iterator iter = socket_options_.begin();
- iter != socket_options_.end(); ++iter) {
- socket_->SetOption(iter->first, iter->second);
- }
-
- if (!SharedSocket()) {
- // If socket is shared, AllocationSequence will receive the packet.
- socket_->SignalReadPacket.connect(this, &TurnPort::OnReadPacket);
- }
-
- socket_->SignalReadyToSend.connect(this, &TurnPort::OnReadyToSend);
-
- if (server_address_.proto == PROTO_TCP) {
- socket_->SignalConnect.connect(this, &TurnPort::OnSocketConnect);
- socket_->SignalClose.connect(this, &TurnPort::OnSocketClose);
- } else {
+ } else if (server_address_.proto == PROTO_UDP) {
// If its UDP, send AllocateRequest now.
// For TCP and TLS AllcateRequest will be sent by OnSocketConnect.
SendRequest(new TurnAllocateRequest(this), 0);
@@ -296,7 +276,50 @@
}
}
-void TurnPort::OnSocketConnect(talk_base::AsyncPacketSocket* socket) {
+bool TurnPort::CreateTurnClientSocket() {
+ ASSERT(!socket_ || SharedSocket());
+
+ if (server_address_.proto == PROTO_UDP && !SharedSocket()) {
+ socket_ = socket_factory()->CreateUdpSocket(
+ rtc::SocketAddress(ip(), 0), min_port(), max_port());
+ } else if (server_address_.proto == PROTO_TCP) {
+ ASSERT(!SharedSocket());
+ int opts = rtc::PacketSocketFactory::OPT_STUN;
+ // If secure bit is enabled in server address, use TLS over TCP.
+ if (server_address_.secure) {
+ opts |= rtc::PacketSocketFactory::OPT_TLS;
+ }
+ socket_ = socket_factory()->CreateClientTcpSocket(
+ rtc::SocketAddress(ip(), 0), server_address_.address,
+ proxy(), user_agent(), opts);
+ }
+
+ if (!socket_) {
+ error_ = SOCKET_ERROR;
+ return false;
+ }
+
+ // Apply options if any.
+ for (SocketOptionsMap::iterator iter = socket_options_.begin();
+ iter != socket_options_.end(); ++iter) {
+ socket_->SetOption(iter->first, iter->second);
+ }
+
+ if (!SharedSocket()) {
+ // If socket is shared, AllocationSequence will receive the packet.
+ socket_->SignalReadPacket.connect(this, &TurnPort::OnReadPacket);
+ }
+
+ socket_->SignalReadyToSend.connect(this, &TurnPort::OnReadyToSend);
+
+ if (server_address_.proto == PROTO_TCP) {
+ socket_->SignalConnect.connect(this, &TurnPort::OnSocketConnect);
+ socket_->SignalClose.connect(this, &TurnPort::OnSocketClose);
+ }
+ return true;
+}
+
+void TurnPort::OnSocketConnect(rtc::AsyncPacketSocket* socket) {
ASSERT(server_address_.proto == PROTO_TCP);
// Do not use this port if the socket bound to a different address than
// the one we asked for. This is seen in Chrome, where TCP sockets cannot be
@@ -309,18 +332,45 @@
return;
}
+ if (server_address_.address.IsUnresolved()) {
+ server_address_.address = socket_->GetRemoteAddress();
+ }
+
LOG(LS_INFO) << "TurnPort connected to " << socket->GetRemoteAddress()
<< " using tcp.";
SendRequest(new TurnAllocateRequest(this), 0);
}
-void TurnPort::OnSocketClose(talk_base::AsyncPacketSocket* socket, int error) {
+void TurnPort::OnSocketClose(rtc::AsyncPacketSocket* socket, int error) {
LOG_J(LS_WARNING, this) << "Connection with server failed, error=" << error;
if (!connected_) {
OnAllocateError();
}
}
+void TurnPort::OnAllocateMismatch() {
+ if (allocate_mismatch_retries_ >= MAX_ALLOCATE_MISMATCH_RETRIES) {
+ LOG_J(LS_WARNING, this) << "Giving up on the port after "
+ << allocate_mismatch_retries_
+ << " retries for STUN_ERROR_ALLOCATION_MISMATCH";
+ OnAllocateError();
+ return;
+ }
+
+ LOG_J(LS_INFO, this) << "Allocating a new socket after "
+ << "STUN_ERROR_ALLOCATION_MISMATCH, retry = "
+ << allocate_mismatch_retries_ + 1;
+ if (SharedSocket()) {
+ ResetSharedSocket();
+ } else {
+ delete socket_;
+ }
+ socket_ = NULL;
+
+ PrepareAddress();
+ ++allocate_mismatch_retries_;
+}
+
Connection* TurnPort::CreateConnection(const Candidate& address,
CandidateOrigin origin) {
// TURN-UDP can only connect to UDP candidates.
@@ -349,7 +399,7 @@
return NULL;
}
-int TurnPort::SetOption(talk_base::Socket::Option opt, int value) {
+int TurnPort::SetOption(rtc::Socket::Option opt, int value) {
if (!socket_) {
// If socket is not created yet, these options will be applied during socket
// creation.
@@ -359,7 +409,7 @@
return socket_->SetOption(opt, value);
}
-int TurnPort::GetOption(talk_base::Socket::Option opt, int* value) {
+int TurnPort::GetOption(rtc::Socket::Option opt, int* value) {
if (!socket_) {
SocketOptionsMap::const_iterator it = socket_options_.find(opt);
if (it == socket_options_.end()) {
@@ -377,8 +427,8 @@
}
int TurnPort::SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload) {
// Try to find an entry for this specific address; we should have one.
TurnEntry* entry = FindEntry(addr);
@@ -404,9 +454,9 @@
}
void TurnPort::OnReadPacket(
- talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* data, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
ASSERT(socket == socket_);
ASSERT(remote_addr == server_address_.address);
@@ -419,7 +469,7 @@
// Check the message type, to see if is a Channel Data message.
// The message will either be channel data, a TURN data indication, or
// a response to a previous request.
- uint16 msg_type = talk_base::GetBE16(data);
+ uint16 msg_type = rtc::GetBE16(data);
if (IsTurnChannelData(msg_type)) {
HandleChannelData(msg_type, data, size, packet_time);
} else if (msg_type == TURN_DATA_INDICATION) {
@@ -437,13 +487,45 @@
}
}
-void TurnPort::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
+void TurnPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
if (connected_) {
Port::OnReadyToSend();
}
}
-void TurnPort::ResolveTurnAddress(const talk_base::SocketAddress& address) {
+
+// Update current server address port with the alternate server address port.
+bool TurnPort::SetAlternateServer(const rtc::SocketAddress& address) {
+ // Check if we have seen this address before and reject if we did.
+ AttemptedServerSet::iterator iter = attempted_server_addresses_.find(address);
+ if (iter != attempted_server_addresses_.end()) {
+ LOG_J(LS_WARNING, this) << "Redirection to ["
+ << address.ToSensitiveString()
+ << "] ignored, allocation failed.";
+ return false;
+ }
+
+ // If protocol family of server address doesn't match with local, return.
+ if (!IsCompatibleAddress(address)) {
+ LOG(LS_WARNING) << "Server IP address family does not match with "
+ << "local host address family type";
+ return false;
+ }
+
+ LOG_J(LS_INFO, this) << "Redirecting from TURN server ["
+ << server_address_.address.ToSensitiveString()
+ << "] to TURN server ["
+ << address.ToSensitiveString()
+ << "]";
+ server_address_ = ProtocolAddress(address, server_address_.proto,
+ server_address_.secure);
+
+ // Insert the current address to prevent redirection pingpong.
+ attempted_server_addresses_.insert(server_address_.address);
+ return true;
+}
+
+void TurnPort::ResolveTurnAddress(const rtc::SocketAddress& address) {
if (resolver_)
return;
@@ -452,15 +534,27 @@
resolver_->Start(address);
}
-void TurnPort::OnResolveResult(talk_base::AsyncResolverInterface* resolver) {
+void TurnPort::OnResolveResult(rtc::AsyncResolverInterface* resolver) {
ASSERT(resolver == resolver_);
+ // If DNS resolve is failed when trying to connect to the server using TCP,
+ // one of the reason could be due to DNS queries blocked by firewall.
+ // In such cases we will try to connect to the server with hostname, assuming
+ // socket layer will resolve the hostname through a HTTP proxy (if any).
+ if (resolver_->GetError() != 0 && server_address_.proto == PROTO_TCP) {
+ if (!CreateTurnClientSocket()) {
+ OnAllocateError();
+ }
+ return;
+ }
+
// Copy the original server address in |resolved_address|. For TLS based
// sockets we need hostname along with resolved address.
- talk_base::SocketAddress resolved_address = server_address_.address;
+ rtc::SocketAddress resolved_address = server_address_.address;
if (resolver_->GetError() != 0 ||
!resolver_->GetResolvedAddress(ip().family(), &resolved_address)) {
LOG_J(LS_WARNING, this) << "TURN host lookup received error "
<< resolver_->GetError();
+ error_ = resolver_->GetError();
OnAllocateError();
return;
}
@@ -474,14 +568,14 @@
void TurnPort::OnSendStunPacket(const void* data, size_t size,
StunRequest* request) {
- talk_base::PacketOptions options(DefaultDscpValue());
+ rtc::PacketOptions options(DefaultDscpValue());
if (Send(data, size, options) < 0) {
LOG_J(LS_ERROR, this) << "Failed to send TURN message, err="
<< socket_->GetError();
}
}
-void TurnPort::OnStunAddress(const talk_base::SocketAddress& address) {
+void TurnPort::OnStunAddress(const rtc::SocketAddress& address) {
// STUN Port will discover STUN candidate, as it's supplied with first TURN
// server address.
// Why not using this address? - P2PTransportChannel will start creating
@@ -491,16 +585,18 @@
// handle to UDPPort to pass back the address.
}
-void TurnPort::OnAllocateSuccess(const talk_base::SocketAddress& address,
- const talk_base::SocketAddress& stun_address) {
+void TurnPort::OnAllocateSuccess(const rtc::SocketAddress& address,
+ const rtc::SocketAddress& stun_address) {
connected_ = true;
// For relayed candidate, Base is the candidate itself.
AddAddress(address, // Candidate address.
address, // Base address.
stun_address, // Related address.
UDP_PROTOCOL_NAME,
+ "", // TCP canddiate type, empty for turn candidates.
RELAY_PORT_TYPE,
GetRelayPreference(server_address_.proto, server_address_.secure),
+ server_priority_,
true);
}
@@ -511,10 +607,13 @@
thread()->Post(this, MSG_ERROR);
}
-void TurnPort::OnMessage(talk_base::Message* message) {
+void TurnPort::OnMessage(rtc::Message* message) {
if (message->message_id == MSG_ERROR) {
SignalPortError(this);
return;
+ } else if (message->message_id == MSG_ALLOCATE_MISMATCH) {
+ OnAllocateMismatch();
+ return;
}
Port::OnMessage(message);
@@ -525,9 +624,9 @@
}
void TurnPort::HandleDataIndication(const char* data, size_t size,
- const talk_base::PacketTime& packet_time) {
+ const rtc::PacketTime& packet_time) {
// Read in the message, and process according to RFC5766, Section 10.4.
- talk_base::ByteBuffer buf(data, size);
+ rtc::ByteBuffer buf(data, size);
TurnMessage msg;
if (!msg.Read(&buf)) {
LOG_J(LS_WARNING, this) << "Received invalid TURN data indication";
@@ -552,7 +651,7 @@
}
// Verify that the data came from somewhere we think we have a permission for.
- talk_base::SocketAddress ext_addr(addr_attr->GetAddress());
+ rtc::SocketAddress ext_addr(addr_attr->GetAddress());
if (!HasPermission(ext_addr.ipaddr())) {
LOG_J(LS_WARNING, this) << "Received TURN data indication with invalid "
<< "peer address, addr="
@@ -566,7 +665,7 @@
void TurnPort::HandleChannelData(int channel_id, const char* data,
size_t size,
- const talk_base::PacketTime& packet_time) {
+ const rtc::PacketTime& packet_time) {
// Read the message, and process according to RFC5766, Section 11.6.
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
@@ -582,7 +681,7 @@
// +-------------------------------+
// Extract header fields from the message.
- uint16 len = talk_base::GetBE16(data + 2);
+ uint16 len = rtc::GetBE16(data + 2);
if (len > size - TURN_CHANNEL_HEADER_SIZE) {
LOG_J(LS_WARNING, this) << "Received TURN channel data message with "
<< "incorrect length, len=" << len;
@@ -602,8 +701,8 @@
}
void TurnPort::DispatchPacket(const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- ProtocolType proto, const talk_base::PacketTime& packet_time) {
+ const rtc::SocketAddress& remote_addr,
+ ProtocolType proto, const rtc::PacketTime& packet_time) {
if (Connection* conn = GetConnection(remote_addr)) {
conn->OnReadPacket(data, size, packet_time);
} else {
@@ -640,7 +739,7 @@
}
int TurnPort::Send(const void* data, size_t len,
- const talk_base::PacketOptions& options) {
+ const rtc::PacketOptions& options) {
return socket_->SendTo(data, len, server_address_.address, options);
}
@@ -673,18 +772,18 @@
return true;
}
-static bool MatchesIP(TurnEntry* e, talk_base::IPAddress ipaddr) {
+static bool MatchesIP(TurnEntry* e, rtc::IPAddress ipaddr) {
return e->address().ipaddr() == ipaddr;
}
-bool TurnPort::HasPermission(const talk_base::IPAddress& ipaddr) const {
+bool TurnPort::HasPermission(const rtc::IPAddress& ipaddr) const {
return (std::find_if(entries_.begin(), entries_.end(),
std::bind2nd(std::ptr_fun(MatchesIP), ipaddr)) != entries_.end());
}
-static bool MatchesAddress(TurnEntry* e, talk_base::SocketAddress addr) {
+static bool MatchesAddress(TurnEntry* e, rtc::SocketAddress addr) {
return e->address() == addr;
}
-TurnEntry* TurnPort::FindEntry(const talk_base::SocketAddress& addr) const {
+TurnEntry* TurnPort::FindEntry(const rtc::SocketAddress& addr) const {
EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
std::bind2nd(std::ptr_fun(MatchesAddress), addr));
return (it != entries_.end()) ? *it : NULL;
@@ -699,14 +798,14 @@
return (it != entries_.end()) ? *it : NULL;
}
-TurnEntry* TurnPort::CreateEntry(const talk_base::SocketAddress& addr) {
+TurnEntry* TurnPort::CreateEntry(const rtc::SocketAddress& addr) {
ASSERT(FindEntry(addr) == NULL);
TurnEntry* entry = new TurnEntry(this, next_channel_number_++, addr);
entries_.push_back(entry);
return entry;
}
-void TurnPort::DestroyEntry(const talk_base::SocketAddress& addr) {
+void TurnPort::DestroyEntry(const rtc::SocketAddress& addr) {
TurnEntry* entry = FindEntry(addr);
ASSERT(entry != NULL);
entry->SignalDestroyed(entry);
@@ -776,6 +875,14 @@
case STUN_ERROR_UNAUTHORIZED: // Unauthrorized.
OnAuthChallenge(response, error_code->code());
break;
+ case STUN_ERROR_TRY_ALTERNATE:
+ OnTryAlternate(response, error_code->code());
+ break;
+ case STUN_ERROR_ALLOCATION_MISMATCH:
+ // We must handle this error async because trying to delete the socket in
+ // OnErrorResponse will cause a deadlock on the socket.
+ port_->thread()->Post(port_, TurnPort::MSG_ALLOCATE_MISMATCH);
+ break;
default:
LOG_J(LS_WARNING, port_) << "Allocate response error, code="
<< error_code->code();
@@ -820,6 +927,57 @@
port_->SendRequest(new TurnAllocateRequest(port_), 0);
}
+void TurnAllocateRequest::OnTryAlternate(StunMessage* response, int code) {
+ // TODO(guoweis): Currently, we only support UDP redirect
+ if (port_->server_address().proto != PROTO_UDP) {
+ LOG_J(LS_WARNING, port_) << "Receiving 300 Alternate Server on non-UDP "
+ << "allocating request from ["
+ << port_->server_address().address.ToSensitiveString()
+ << "], failed as currently not supported";
+ port_->OnAllocateError();
+ return;
+ }
+
+ // According to RFC 5389 section 11, there are use cases where
+ // authentication of response is not possible, we're not validating
+ // message integrity.
+
+ // Get the alternate server address attribute value.
+ const StunAddressAttribute* alternate_server_attr =
+ response->GetAddress(STUN_ATTR_ALTERNATE_SERVER);
+ if (!alternate_server_attr) {
+ LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_ALTERNATE_SERVER "
+ << "attribute in try alternate error response";
+ port_->OnAllocateError();
+ return;
+ }
+ if (!port_->SetAlternateServer(alternate_server_attr->GetAddress())) {
+ port_->OnAllocateError();
+ return;
+ }
+
+ // Check the attributes.
+ const StunByteStringAttribute* realm_attr =
+ response->GetByteString(STUN_ATTR_REALM);
+ if (realm_attr) {
+ LOG_J(LS_INFO, port_) << "Applying STUN_ATTR_REALM attribute in "
+ << "try alternate error response.";
+ port_->set_realm(realm_attr->GetString());
+ }
+
+ const StunByteStringAttribute* nonce_attr =
+ response->GetByteString(STUN_ATTR_NONCE);
+ if (nonce_attr) {
+ LOG_J(LS_INFO, port_) << "Applying STUN_ATTR_NONCE attribute in "
+ << "try alternate error response.";
+ port_->set_nonce(nonce_attr->GetString());
+ }
+
+ // Send another allocate request to alternate server,
+ // with the received realm and nonce values.
+ port_->SendRequest(new TurnAllocateRequest(port_), 0);
+}
+
TurnRefreshRequest::TurnRefreshRequest(TurnPort* port)
: StunRequest(new TurnMessage()),
port_(port) {
@@ -847,7 +1005,6 @@
}
void TurnRefreshRequest::OnErrorResponse(StunMessage* response) {
- // TODO(juberti): Handle 437 error response as a success.
const StunErrorCodeAttribute* error_code = response->GetErrorCode();
LOG_J(LS_WARNING, port_) << "Refresh response error, code="
<< error_code->code();
@@ -865,7 +1022,7 @@
TurnCreatePermissionRequest::TurnCreatePermissionRequest(
TurnPort* port, TurnEntry* entry,
- const talk_base::SocketAddress& ext_addr)
+ const rtc::SocketAddress& ext_addr)
: StunRequest(new TurnMessage()),
port_(port),
entry_(entry),
@@ -906,7 +1063,7 @@
TurnChannelBindRequest::TurnChannelBindRequest(
TurnPort* port, TurnEntry* entry,
- int channel_id, const talk_base::SocketAddress& ext_addr)
+ int channel_id, const rtc::SocketAddress& ext_addr)
: StunRequest(new TurnMessage()),
port_(port),
entry_(entry),
@@ -954,7 +1111,7 @@
}
TurnEntry::TurnEntry(TurnPort* port, int channel_id,
- const talk_base::SocketAddress& ext_addr)
+ const rtc::SocketAddress& ext_addr)
: port_(port),
channel_id_(channel_id),
ext_addr_(ext_addr),
@@ -974,14 +1131,14 @@
}
int TurnEntry::Send(const void* data, size_t size, bool payload,
- const talk_base::PacketOptions& options) {
- talk_base::ByteBuffer buf;
+ const rtc::PacketOptions& options) {
+ rtc::ByteBuffer buf;
if (state_ != STATE_BOUND) {
// If we haven't bound the channel yet, we have to use a Send Indication.
TurnMessage msg;
msg.SetType(TURN_SEND_INDICATION);
msg.SetTransactionID(
- talk_base::CreateRandomString(kStunTransactionIdLength));
+ rtc::CreateRandomString(kStunTransactionIdLength));
VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
VERIFY(msg.AddAttribute(new StunByteStringAttribute(
diff --git a/p2p/base/turnport.h b/p2p/base/turnport.h
index 2f5e8c4..ab7d4e7 100644
--- a/p2p/base/turnport.h
+++ b/p2p/base/turnport.h
@@ -29,14 +29,15 @@
#define TALK_P2P_BASE_TURNPORT_H_
#include <stdio.h>
-#include <string>
#include <list>
+#include <set>
+#include <string>
-#include "talk/base/asyncpacketsocket.h"
#include "talk/p2p/base/port.h"
#include "talk/p2p/client/basicportallocator.h"
+#include "webrtc/base/asyncpacketsocket.h"
-namespace talk_base {
+namespace rtc {
class AsyncResolver;
class SignalThread;
}
@@ -49,29 +50,33 @@
class TurnPort : public Port {
public:
- static TurnPort* Create(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- talk_base::AsyncPacketSocket* socket,
+ static TurnPort* Create(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ rtc::AsyncPacketSocket* socket,
const std::string& username, // ice username.
const std::string& password, // ice password.
const ProtocolAddress& server_address,
- const RelayCredentials& credentials) {
+ const RelayCredentials& credentials,
+ int server_priority) {
return new TurnPort(thread, factory, network, socket,
- username, password, server_address, credentials);
+ username, password, server_address,
+ credentials, server_priority);
}
- static TurnPort* Create(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip,
+ static TurnPort* Create(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username, // ice username.
const std::string& password, // ice password.
const ProtocolAddress& server_address,
- const RelayCredentials& credentials) {
+ const RelayCredentials& credentials,
+ int server_priority) {
return new TurnPort(thread, factory, network, ip, min_port, max_port,
- username, password, server_address, credentials);
+ username, password, server_address, credentials,
+ server_priority);
}
virtual ~TurnPort();
@@ -85,72 +90,88 @@
virtual Connection* CreateConnection(
const Candidate& c, PortInterface::CandidateOrigin origin);
virtual int SendTo(const void* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketOptions& options,
+ const rtc::SocketAddress& addr,
+ const rtc::PacketOptions& options,
bool payload);
- virtual int SetOption(talk_base::Socket::Option opt, int value);
- virtual int GetOption(talk_base::Socket::Option opt, int* value);
+ virtual int SetOption(rtc::Socket::Option opt, int value);
+ virtual int GetOption(rtc::Socket::Option opt, int* value);
virtual int GetError();
virtual bool HandleIncomingPacket(
- talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* data, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
OnReadPacket(socket, data, size, remote_addr, packet_time);
return true;
}
- virtual void OnReadPacket(talk_base::AsyncPacketSocket* socket,
+ virtual void OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
- virtual void OnReadyToSend(talk_base::AsyncPacketSocket* socket);
+ virtual void OnReadyToSend(rtc::AsyncPacketSocket* socket);
- void OnSocketConnect(talk_base::AsyncPacketSocket* socket);
- void OnSocketClose(talk_base::AsyncPacketSocket* socket, int error);
+ void OnSocketConnect(rtc::AsyncPacketSocket* socket);
+ void OnSocketClose(rtc::AsyncPacketSocket* socket, int error);
const std::string& hash() const { return hash_; }
const std::string& nonce() const { return nonce_; }
+ int error() const { return error_; }
+
+ void OnAllocateMismatch();
+
+ rtc::AsyncPacketSocket* socket() const {
+ return socket_;
+ }
+
// Signal with resolved server address.
// Parameters are port, server address and resolved server address.
// This signal will be sent only if server address is resolved successfully.
sigslot::signal3<TurnPort*,
- const talk_base::SocketAddress&,
- const talk_base::SocketAddress&> SignalResolvedServerAddress;
+ const rtc::SocketAddress&,
+ const rtc::SocketAddress&> SignalResolvedServerAddress;
// This signal is only for testing purpose.
- sigslot::signal3<TurnPort*, const talk_base::SocketAddress&, int>
+ sigslot::signal3<TurnPort*, const rtc::SocketAddress&, int>
SignalCreatePermissionResult;
protected:
- TurnPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- talk_base::AsyncPacketSocket* socket,
+ TurnPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ rtc::AsyncPacketSocket* socket,
const std::string& username,
const std::string& password,
const ProtocolAddress& server_address,
- const RelayCredentials& credentials);
+ const RelayCredentials& credentials,
+ int server_priority);
- TurnPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip,
+ TurnPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username,
const std::string& password,
const ProtocolAddress& server_address,
- const RelayCredentials& credentials);
+ const RelayCredentials& credentials,
+ int server_priority);
private:
- enum { MSG_ERROR = MSG_FIRST_AVAILABLE };
+ enum {
+ MSG_ERROR = MSG_FIRST_AVAILABLE,
+ MSG_ALLOCATE_MISMATCH
+ };
typedef std::list<TurnEntry*> EntryList;
- typedef std::map<talk_base::Socket::Option, int> SocketOptionsMap;
+ typedef std::map<rtc::Socket::Option, int> SocketOptionsMap;
+ typedef std::set<rtc::SocketAddress> AttemptedServerSet;
- virtual void OnMessage(talk_base::Message* pmsg);
+ virtual void OnMessage(rtc::Message* pmsg);
+
+ bool CreateTurnClientSocket();
void set_nonce(const std::string& nonce) { nonce_ = nonce; }
void set_realm(const std::string& realm) {
@@ -160,47 +181,49 @@
}
}
- void ResolveTurnAddress(const talk_base::SocketAddress& address);
- void OnResolveResult(talk_base::AsyncResolverInterface* resolver);
+ bool SetAlternateServer(const rtc::SocketAddress& address);
+ void ResolveTurnAddress(const rtc::SocketAddress& address);
+ void OnResolveResult(rtc::AsyncResolverInterface* resolver);
void AddRequestAuthInfo(StunMessage* msg);
void OnSendStunPacket(const void* data, size_t size, StunRequest* request);
// Stun address from allocate success response.
// Currently used only for testing.
- void OnStunAddress(const talk_base::SocketAddress& address);
- void OnAllocateSuccess(const talk_base::SocketAddress& address,
- const talk_base::SocketAddress& stun_address);
+ void OnStunAddress(const rtc::SocketAddress& address);
+ void OnAllocateSuccess(const rtc::SocketAddress& address,
+ const rtc::SocketAddress& stun_address);
void OnAllocateError();
void OnAllocateRequestTimeout();
void HandleDataIndication(const char* data, size_t size,
- const talk_base::PacketTime& packet_time);
+ const rtc::PacketTime& packet_time);
void HandleChannelData(int channel_id, const char* data, size_t size,
- const talk_base::PacketTime& packet_time);
+ const rtc::PacketTime& packet_time);
void DispatchPacket(const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- ProtocolType proto, const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& remote_addr,
+ ProtocolType proto, const rtc::PacketTime& packet_time);
bool ScheduleRefresh(int lifetime);
void SendRequest(StunRequest* request, int delay);
int Send(const void* data, size_t size,
- const talk_base::PacketOptions& options);
+ const rtc::PacketOptions& options);
void UpdateHash();
bool UpdateNonce(StunMessage* response);
- bool HasPermission(const talk_base::IPAddress& ipaddr) const;
- TurnEntry* FindEntry(const talk_base::SocketAddress& address) const;
+ bool HasPermission(const rtc::IPAddress& ipaddr) const;
+ TurnEntry* FindEntry(const rtc::SocketAddress& address) const;
TurnEntry* FindEntry(int channel_id) const;
- TurnEntry* CreateEntry(const talk_base::SocketAddress& address);
- void DestroyEntry(const talk_base::SocketAddress& address);
+ TurnEntry* CreateEntry(const rtc::SocketAddress& address);
+ void DestroyEntry(const rtc::SocketAddress& address);
void OnConnectionDestroyed(Connection* conn);
ProtocolAddress server_address_;
RelayCredentials credentials_;
+ AttemptedServerSet attempted_server_addresses_;
- talk_base::AsyncPacketSocket* socket_;
+ rtc::AsyncPacketSocket* socket_;
SocketOptionsMap socket_options_;
- talk_base::AsyncResolverInterface* resolver_;
+ rtc::AsyncResolverInterface* resolver_;
int error_;
StunRequestManager request_manager_;
@@ -212,6 +235,12 @@
EntryList entries_;
bool connected_;
+ // By default the value will be set to 0. This value will be used in
+ // calculating the candidate priority.
+ int server_priority_;
+
+ // The number of retries made due to allocate mismatch error.
+ size_t allocate_mismatch_retries_;
friend class TurnEntry;
friend class TurnAllocateRequest;
diff --git a/p2p/base/turnport_unittest.cc b/p2p/base/turnport_unittest.cc
index 12a19aa..d895cbd 100644
--- a/p2p/base/turnport_unittest.cc
+++ b/p2p/base/turnport_unittest.cc
@@ -28,26 +28,27 @@
#include <dirent.h>
#endif
-#include "talk/base/asynctcpsocket.h"
-#include "talk/base/buffer.h"
-#include "talk/base/dscp.h"
-#include "talk/base/firewallsocketserver.h"
-#include "talk/base/logging.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/thread.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/tcpport.h"
#include "talk/p2p/base/testturnserver.h"
#include "talk/p2p/base/turnport.h"
#include "talk/p2p/base/udpport.h"
+#include "webrtc/base/asynctcpsocket.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/firewallsocketserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/virtualsocketserver.h"
-using talk_base::SocketAddress;
+using rtc::SocketAddress;
using cricket::Connection;
using cricket::Port;
using cricket::PortInterface;
@@ -63,6 +64,8 @@
static const SocketAddress kTurnTcpIntAddr("99.99.99.4",
cricket::TURN_SERVER_PORT);
static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
+static const SocketAddress kTurnAlternateUdpIntAddr(
+ "99.99.99.6", cricket::TURN_SERVER_PORT);
static const SocketAddress kTurnUdpIPv6IntAddr(
"2400:4030:1:2c00:be30:abcd:efab:cdef", cricket::TURN_SERVER_PORT);
static const SocketAddress kTurnUdpIPv6ExtAddr(
@@ -102,15 +105,15 @@
class TurnPortTest : public testing::Test,
public sigslot::has_slots<>,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
TurnPortTest()
- : main_(talk_base::Thread::Current()),
- pss_(new talk_base::PhysicalSocketServer),
- ss_(new talk_base::VirtualSocketServer(pss_.get())),
+ : main_(rtc::Thread::Current()),
+ pss_(new rtc::PhysicalSocketServer),
+ ss_(new rtc::VirtualSocketServer(pss_.get())),
ss_scope_(ss_.get()),
- network_("unittest", "unittest", talk_base::IPAddress(INADDR_ANY), 32),
- socket_factory_(talk_base::Thread::Current()),
+ network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
+ socket_factory_(rtc::Thread::Current()),
turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
turn_ready_(false),
turn_error_(false),
@@ -118,10 +121,18 @@
turn_create_permission_success_(false),
udp_ready_(false),
test_finish_(false) {
- network_.AddIP(talk_base::IPAddress(INADDR_ANY));
+ network_.AddIP(rtc::IPAddress(INADDR_ANY));
}
- virtual void OnMessage(talk_base::Message* msg) {
+ static void SetUpTestCase() {
+ rtc::InitializeSSL();
+ }
+
+ static void TearDownTestCase() {
+ rtc::CleanupSSL();
+ }
+
+ virtual void OnMessage(rtc::Message* msg) {
ASSERT(msg->message_id == MSG_TESTFINISH);
if (msg->message_id == MSG_TESTFINISH)
test_finish_ = true;
@@ -147,25 +158,25 @@
}
}
void OnTurnReadPacket(Connection* conn, const char* data, size_t size,
- const talk_base::PacketTime& packet_time) {
- turn_packets_.push_back(talk_base::Buffer(data, size));
+ const rtc::PacketTime& packet_time) {
+ turn_packets_.push_back(rtc::Buffer(data, size));
}
void OnUdpPortComplete(Port* port) {
udp_ready_ = true;
}
void OnUdpReadPacket(Connection* conn, const char* data, size_t size,
- const talk_base::PacketTime& packet_time) {
- udp_packets_.push_back(talk_base::Buffer(data, size));
+ const rtc::PacketTime& packet_time) {
+ udp_packets_.push_back(rtc::Buffer(data, size));
}
- void OnSocketReadPacket(talk_base::AsyncPacketSocket* socket,
+ void OnSocketReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
turn_port_->HandleIncomingPacket(socket, data, size, remote_addr,
packet_time);
}
- talk_base::AsyncSocket* CreateServerSocket(const SocketAddress addr) {
- talk_base::AsyncSocket* socket = ss_->CreateAsyncSocket(SOCK_STREAM);
+ rtc::AsyncSocket* CreateServerSocket(const SocketAddress addr) {
+ rtc::AsyncSocket* socket = ss_->CreateAsyncSocket(SOCK_STREAM);
EXPECT_GE(socket->Bind(addr), 0);
EXPECT_GE(socket->Listen(5), 0);
return socket;
@@ -176,7 +187,7 @@
const cricket::ProtocolAddress& server_address) {
CreateTurnPort(kLocalAddr1, username, password, server_address);
}
- void CreateTurnPort(const talk_base::SocketAddress& local_address,
+ void CreateTurnPort(const rtc::SocketAddress& local_address,
const std::string& username,
const std::string& password,
const cricket::ProtocolAddress& server_address) {
@@ -184,7 +195,7 @@
turn_port_.reset(TurnPort::Create(main_, &socket_factory_, &network_,
local_address.ipaddr(), 0, 0,
kIceUfrag1, kIcePwd1,
- server_address, credentials));
+ server_address, credentials, 0));
// Set ICE protocol type to ICEPROTO_RFC5245, as port by default will be
// in Hybrid mode. Protocol type is necessary to send correct type STUN ping
// messages.
@@ -199,15 +210,18 @@
const cricket::ProtocolAddress& server_address) {
ASSERT(server_address.proto == cricket::PROTO_UDP);
- socket_.reset(socket_factory_.CreateUdpSocket(
- talk_base::SocketAddress(kLocalAddr1.ipaddr(), 0), 0, 0));
- ASSERT_TRUE(socket_ != NULL);
- socket_->SignalReadPacket.connect(this, &TurnPortTest::OnSocketReadPacket);
+ if (!socket_) {
+ socket_.reset(socket_factory_.CreateUdpSocket(
+ rtc::SocketAddress(kLocalAddr1.ipaddr(), 0), 0, 0));
+ ASSERT_TRUE(socket_ != NULL);
+ socket_->SignalReadPacket.connect(
+ this, &TurnPortTest::OnSocketReadPacket);
+ }
cricket::RelayCredentials credentials(username, password);
turn_port_.reset(cricket::TurnPort::Create(
main_, &socket_factory_, &network_, socket_.get(),
- kIceUfrag1, kIcePwd1, server_address, credentials));
+ kIceUfrag1, kIcePwd1, server_address, credentials, 0));
// Set ICE protocol type to ICEPROTO_RFC5245, as port by default will be
// in Hybrid mode. Protocol type is necessary to send correct type STUN ping
// messages.
@@ -301,9 +315,9 @@
// Send some data.
size_t num_packets = 256;
for (size_t i = 0; i < num_packets; ++i) {
- char buf[256];
+ unsigned char buf[256] = { 0 };
for (size_t j = 0; j < i + 1; ++j) {
- buf[j] = 0xFF - j;
+ buf[j] = 0xFF - static_cast<unsigned char>(j);
}
conn1->Send(buf, i + 1, options);
conn2->Send(buf, i + 1, options);
@@ -321,31 +335,31 @@
}
protected:
- talk_base::Thread* main_;
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> ss_;
- talk_base::SocketServerScope ss_scope_;
- talk_base::Network network_;
- talk_base::BasicPacketSocketFactory socket_factory_;
- talk_base::scoped_ptr<talk_base::AsyncPacketSocket> socket_;
+ rtc::Thread* main_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
+ rtc::SocketServerScope ss_scope_;
+ rtc::Network network_;
+ rtc::BasicPacketSocketFactory socket_factory_;
+ rtc::scoped_ptr<rtc::AsyncPacketSocket> socket_;
cricket::TestTurnServer turn_server_;
- talk_base::scoped_ptr<TurnPort> turn_port_;
- talk_base::scoped_ptr<UDPPort> udp_port_;
+ rtc::scoped_ptr<TurnPort> turn_port_;
+ rtc::scoped_ptr<UDPPort> udp_port_;
bool turn_ready_;
bool turn_error_;
bool turn_unknown_address_;
bool turn_create_permission_success_;
bool udp_ready_;
bool test_finish_;
- std::vector<talk_base::Buffer> turn_packets_;
- std::vector<talk_base::Buffer> udp_packets_;
- talk_base::PacketOptions options;
+ std::vector<rtc::Buffer> turn_packets_;
+ std::vector<rtc::Buffer> udp_packets_;
+ rtc::PacketOptions options;
};
// Do a normal TURN allocation.
TEST_F(TurnPortTest, TestTurnAllocate) {
CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
- EXPECT_EQ(0, turn_port_->SetOption(talk_base::Socket::OPT_SNDBUF, 10*1024));
+ EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10*1024));
turn_port_->PrepareAddress();
EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
ASSERT_EQ(1U, turn_port_->Candidates().size());
@@ -354,10 +368,11 @@
EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
}
+// Testing a normal UDP allocation using TCP connection.
TEST_F(TurnPortTest, TestTurnTcpAllocate) {
turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
- EXPECT_EQ(0, turn_port_->SetOption(talk_base::Socket::OPT_SNDBUF, 10*1024));
+ EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10*1024));
turn_port_->PrepareAddress();
EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
ASSERT_EQ(1U, turn_port_->Candidates().size());
@@ -366,6 +381,33 @@
EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
}
+// Testing turn port will attempt to create TCP socket on address resolution
+// failure.
+TEST_F(TurnPortTest, DISABLED_TestTurnTcpOnAddressResolveFailure) {
+ turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
+ CreateTurnPort(kTurnUsername, kTurnPassword, cricket::ProtocolAddress(
+ rtc::SocketAddress("www.webrtc-blah-blah.com", 3478),
+ cricket::PROTO_TCP));
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_error_, kTimeout);
+ // As VSS doesn't provide a DNS resolution, name resolve will fail. TurnPort
+ // will proceed in creating a TCP socket which will fail as there is no
+ // server on the above domain and error will be set to SOCKET_ERROR.
+ EXPECT_EQ(SOCKET_ERROR, turn_port_->error());
+}
+
+// In case of UDP on address resolve failure, TurnPort will not create socket
+// and return allocate failure.
+TEST_F(TurnPortTest, DISABLED_TestTurnUdpOnAdressResolveFailure) {
+ CreateTurnPort(kTurnUsername, kTurnPassword, cricket::ProtocolAddress(
+ rtc::SocketAddress("www.webrtc-blah-blah.com", 3478),
+ cricket::PROTO_UDP));
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_error_, kTimeout);
+ // Error from turn port will not be socket error.
+ EXPECT_NE(SOCKET_ERROR, turn_port_->error());
+}
+
// Try to do a TURN allocation with an invalid password.
TEST_F(TurnPortTest, TestTurnAllocateBadPassword) {
CreateTurnPort(kTurnUsername, "bad", kTurnUdpProtoAddr);
@@ -374,6 +416,80 @@
ASSERT_EQ(0U, turn_port_->Candidates().size());
}
+// Tests that a new local address is created after
+// STUN_ERROR_ALLOCATION_MISMATCH.
+TEST_F(TurnPortTest, TestTurnAllocateMismatch) {
+ // Do a normal allocation first.
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
+ rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
+
+ // Forces the socket server to assign the same port.
+ ss_->SetNextPortForTesting(first_addr.port());
+
+ turn_ready_ = false;
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+ turn_port_->PrepareAddress();
+
+ // Verifies that the new port has the same address.
+ EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
+
+ EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
+
+ // Verifies that the new port has a different address now.
+ EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
+}
+
+// Tests that a shared-socket-TurnPort creates its own socket after
+// STUN_ERROR_ALLOCATION_MISMATCH.
+TEST_F(TurnPortTest, TestSharedSocketAllocateMismatch) {
+ // Do a normal allocation first.
+ CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
+ rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
+
+ turn_ready_ = false;
+ CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+
+ // Verifies that the new port has the same address.
+ EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
+ EXPECT_TRUE(turn_port_->SharedSocket());
+
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
+
+ // Verifies that the new port has a different address now.
+ EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
+ EXPECT_FALSE(turn_port_->SharedSocket());
+}
+
+TEST_F(TurnPortTest, TestTurnTcpAllocateMismatch) {
+ turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
+
+ // Do a normal allocation first.
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
+ rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
+
+ // Forces the socket server to assign the same port.
+ ss_->SetNextPortForTesting(first_addr.port());
+
+ turn_ready_ = false;
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
+ turn_port_->PrepareAddress();
+
+ // Verifies that the new port has the same address.
+ EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
+
+ EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
+
+ // Verifies that the new port has a different address now.
+ EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
+}
+
// Do a TURN allocation and try to send a packet to it from the outside.
// The packet should be dropped. Then, try to send a packet from TURN to the
// outside. It should reach its destination. Finally, try again from the
@@ -408,6 +524,103 @@
ASSERT_EQ(0U, turn_port_->Candidates().size());
}
+// Test try-alternate-server feature.
+TEST_F(TurnPortTest, TestTurnAlternateServer) {
+ std::vector<rtc::SocketAddress> redirect_addresses;
+ redirect_addresses.push_back(kTurnAlternateUdpIntAddr);
+
+ cricket::TestTurnRedirector redirector(redirect_addresses);
+ turn_server_.AddInternalSocket(kTurnAlternateUdpIntAddr,
+ cricket::PROTO_UDP);
+ turn_server_.set_redirect_hook(&redirector);
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+
+ // Retrieve the address before we run the state machine.
+ const SocketAddress old_addr = turn_port_->server_address().address;
+
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
+ // Retrieve the address again, the turn port's address should be
+ // changed.
+ const SocketAddress new_addr = turn_port_->server_address().address;
+ EXPECT_NE(old_addr, new_addr);
+ ASSERT_EQ(1U, turn_port_->Candidates().size());
+ EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
+ turn_port_->Candidates()[0].address().ipaddr());
+ EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
+}
+
+// Test that we fail when we redirect to an address different from
+// current IP family.
+TEST_F(TurnPortTest, TestTurnAlternateServerV4toV6) {
+ std::vector<rtc::SocketAddress> redirect_addresses;
+ redirect_addresses.push_back(kTurnUdpIPv6IntAddr);
+
+ cricket::TestTurnRedirector redirector(redirect_addresses);
+ turn_server_.AddInternalSocket(kTurnAlternateUdpIntAddr,
+ cricket::PROTO_UDP);
+ turn_server_.set_redirect_hook(&redirector);
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_error_, kTimeout);
+}
+
+// Test that we fail to handle alternate-server response over TCP protocol.
+TEST_F(TurnPortTest, TestTurnAlternateServerTcp) {
+ std::vector<rtc::SocketAddress> redirect_addresses;
+ redirect_addresses.push_back(kTurnAlternateUdpIntAddr);
+
+ cricket::TestTurnRedirector redirector(redirect_addresses);
+ turn_server_.set_redirect_hook(&redirector);
+ turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
+
+ turn_server_.AddInternalSocket(kTurnAlternateUdpIntAddr, cricket::PROTO_TCP);
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_error_, kTimeout);
+}
+
+// Test try-alternate-server catches the case of pingpong.
+TEST_F(TurnPortTest, TestTurnAlternateServerPingPong) {
+ std::vector<rtc::SocketAddress> redirect_addresses;
+ redirect_addresses.push_back(kTurnAlternateUdpIntAddr);
+ redirect_addresses.push_back(kTurnUdpIntAddr);
+
+ cricket::TestTurnRedirector redirector(redirect_addresses);
+
+ turn_server_.AddInternalSocket(kTurnAlternateUdpIntAddr,
+ cricket::PROTO_UDP);
+ turn_server_.set_redirect_hook(&redirector);
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_error_, kTimeout);
+ ASSERT_EQ(0U, turn_port_->Candidates().size());
+ rtc::SocketAddress address;
+ // Verify that we have exhausted all alternate servers instead of
+ // failure caused by other errors.
+ EXPECT_FALSE(redirector.ShouldRedirect(address, &address));
+}
+
+// Test try-alternate-server catch the case of repeated server.
+TEST_F(TurnPortTest, TestTurnAlternateServerDetectRepetition) {
+ std::vector<rtc::SocketAddress> redirect_addresses;
+ redirect_addresses.push_back(kTurnAlternateUdpIntAddr);
+ redirect_addresses.push_back(kTurnAlternateUdpIntAddr);
+
+ cricket::TestTurnRedirector redirector(redirect_addresses);
+
+ turn_server_.AddInternalSocket(kTurnAlternateUdpIntAddr,
+ cricket::PROTO_UDP);
+ turn_server_.set_redirect_hook(&redirector);
+ CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
+
+ turn_port_->PrepareAddress();
+ EXPECT_TRUE_WAIT(turn_error_, kTimeout);
+ ASSERT_EQ(0U, turn_port_->Candidates().size());
+}
+
+
// Run TurnConnectionTest with one-time-use nonce feature.
// Here server will send a 438 STALE_NONCE error message for
// every TURN transaction.
@@ -466,16 +679,15 @@
int last_fd_count = GetFDCount();
// Need to supply unresolved address to kick off resolver.
CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
- cricket::ProtocolAddress(talk_base::SocketAddress(
+ cricket::ProtocolAddress(rtc::SocketAddress(
"stun.l.google.com", 3478), cricket::PROTO_UDP));
turn_port_->PrepareAddress();
ASSERT_TRUE_WAIT(turn_error_, kTimeout);
EXPECT_TRUE(turn_port_->Candidates().empty());
turn_port_.reset();
- talk_base::Thread::Current()->Post(this, MSG_TESTFINISH);
+ rtc::Thread::Current()->Post(this, MSG_TESTFINISH);
// Waiting for above message to be processed.
ASSERT_TRUE_WAIT(test_finish_, kTimeout);
EXPECT_EQ(last_fd_count, GetFDCount());
}
#endif
-
diff --git a/p2p/base/turnserver.cc b/p2p/base/turnserver.cc
index 4d7f39e..dbcbcd4 100644
--- a/p2p/base/turnserver.cc
+++ b/p2p/base/turnserver.cc
@@ -27,17 +27,17 @@
#include "talk/p2p/base/turnserver.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/messagedigest.h"
-#include "talk/base/socketadapters.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/asyncstuntcpsocket.h"
#include "talk/p2p/base/common.h"
#include "talk/p2p/base/packetsocketfactory.h"
#include "talk/p2p/base/stun.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/socketadapters.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -62,9 +62,9 @@
return ((msg_type & 0xC000) == 0x4000);
}
-// IDs used for posted messages.
+// IDs used for posted messages for TurnServer::Allocation.
enum {
- MSG_TIMEOUT,
+ MSG_ALLOCATION_TIMEOUT,
};
// Encapsulates a TURN allocation.
@@ -72,12 +72,12 @@
// handles TURN messages (via HandleTurnMessage) and channel data messages
// (via HandleChannelData) for this allocation when received by the server.
// The object self-deletes and informs the server if its lifetime timer expires.
-class TurnServer::Allocation : public talk_base::MessageHandler,
+class TurnServer::Allocation : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
Allocation(TurnServer* server_,
- talk_base::Thread* thread, const Connection& conn,
- talk_base::AsyncPacketSocket* server_socket,
+ rtc::Thread* thread, const Connection& conn,
+ rtc::AsyncPacketSocket* server_socket,
const std::string& key);
virtual ~Allocation();
@@ -105,33 +105,33 @@
void HandleCreatePermissionRequest(const TurnMessage* msg);
void HandleChannelBindRequest(const TurnMessage* msg);
- void OnExternalPacket(talk_base::AsyncPacketSocket* socket,
+ void OnExternalPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& addr,
+ const rtc::PacketTime& packet_time);
static int ComputeLifetime(const TurnMessage* msg);
- bool HasPermission(const talk_base::IPAddress& addr);
- void AddPermission(const talk_base::IPAddress& addr);
- Permission* FindPermission(const talk_base::IPAddress& addr) const;
+ bool HasPermission(const rtc::IPAddress& addr);
+ void AddPermission(const rtc::IPAddress& addr);
+ Permission* FindPermission(const rtc::IPAddress& addr) const;
Channel* FindChannel(int channel_id) const;
- Channel* FindChannel(const talk_base::SocketAddress& addr) const;
+ Channel* FindChannel(const rtc::SocketAddress& addr) const;
void SendResponse(TurnMessage* msg);
void SendBadRequestResponse(const TurnMessage* req);
void SendErrorResponse(const TurnMessage* req, int code,
const std::string& reason);
void SendExternal(const void* data, size_t size,
- const talk_base::SocketAddress& peer);
+ const rtc::SocketAddress& peer);
void OnPermissionDestroyed(Permission* perm);
void OnChannelDestroyed(Channel* channel);
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
TurnServer* server_;
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
Connection conn_;
- talk_base::scoped_ptr<talk_base::AsyncPacketSocket> external_socket_;
+ rtc::scoped_ptr<rtc::AsyncPacketSocket> external_socket_;
std::string key_;
std::string transaction_id_;
std::string username_;
@@ -143,44 +143,44 @@
// Encapsulates a TURN permission.
// The object is created when a create permission request is received by an
// allocation, and self-deletes when its lifetime timer expires.
-class TurnServer::Permission : public talk_base::MessageHandler {
+class TurnServer::Permission : public rtc::MessageHandler {
public:
- Permission(talk_base::Thread* thread, const talk_base::IPAddress& peer);
+ Permission(rtc::Thread* thread, const rtc::IPAddress& peer);
~Permission();
- const talk_base::IPAddress& peer() const { return peer_; }
+ const rtc::IPAddress& peer() const { return peer_; }
void Refresh();
sigslot::signal1<Permission*> SignalDestroyed;
private:
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
- talk_base::Thread* thread_;
- talk_base::IPAddress peer_;
+ rtc::Thread* thread_;
+ rtc::IPAddress peer_;
};
// Encapsulates a TURN channel binding.
// The object is created when a channel bind request is received by an
// allocation, and self-deletes when its lifetime timer expires.
-class TurnServer::Channel : public talk_base::MessageHandler {
+class TurnServer::Channel : public rtc::MessageHandler {
public:
- Channel(talk_base::Thread* thread, int id,
- const talk_base::SocketAddress& peer);
+ Channel(rtc::Thread* thread, int id,
+ const rtc::SocketAddress& peer);
~Channel();
int id() const { return id_; }
- const talk_base::SocketAddress& peer() const { return peer_; }
+ const rtc::SocketAddress& peer() const { return peer_; }
void Refresh();
sigslot::signal1<Channel*> SignalDestroyed;
private:
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
int id_;
- talk_base::SocketAddress peer_;
+ rtc::SocketAddress peer_;
};
static bool InitResponse(const StunMessage* req, StunMessage* resp) {
@@ -204,10 +204,11 @@
return true;
}
-TurnServer::TurnServer(talk_base::Thread* thread)
+TurnServer::TurnServer(rtc::Thread* thread)
: thread_(thread),
- nonce_key_(talk_base::CreateRandomString(kNonceKeySize)),
+ nonce_key_(rtc::CreateRandomString(kNonceKeySize)),
auth_hook_(NULL),
+ redirect_hook_(NULL),
enable_otu_nonce_(false) {
}
@@ -219,25 +220,25 @@
for (InternalSocketMap::iterator it = server_sockets_.begin();
it != server_sockets_.end(); ++it) {
- talk_base::AsyncPacketSocket* socket = it->first;
+ rtc::AsyncPacketSocket* socket = it->first;
delete socket;
}
for (ServerSocketMap::iterator it = server_listen_sockets_.begin();
it != server_listen_sockets_.end(); ++it) {
- talk_base::AsyncSocket* socket = it->first;
+ rtc::AsyncSocket* socket = it->first;
delete socket;
}
}
-void TurnServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket,
+void TurnServer::AddInternalSocket(rtc::AsyncPacketSocket* socket,
ProtocolType proto) {
ASSERT(server_sockets_.end() == server_sockets_.find(socket));
server_sockets_[socket] = proto;
socket->SignalReadPacket.connect(this, &TurnServer::OnInternalPacket);
}
-void TurnServer::AddInternalServerSocket(talk_base::AsyncSocket* socket,
+void TurnServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
ProtocolType proto) {
ASSERT(server_listen_sockets_.end() ==
server_listen_sockets_.find(socket));
@@ -246,21 +247,21 @@
}
void TurnServer::SetExternalSocketFactory(
- talk_base::PacketSocketFactory* factory,
- const talk_base::SocketAddress& external_addr) {
+ rtc::PacketSocketFactory* factory,
+ const rtc::SocketAddress& external_addr) {
external_socket_factory_.reset(factory);
external_addr_ = external_addr;
}
-void TurnServer::OnNewInternalConnection(talk_base::AsyncSocket* socket) {
+void TurnServer::OnNewInternalConnection(rtc::AsyncSocket* socket) {
ASSERT(server_listen_sockets_.find(socket) != server_listen_sockets_.end());
AcceptConnection(socket);
}
-void TurnServer::AcceptConnection(talk_base::AsyncSocket* server_socket) {
+void TurnServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
// Check if someone is trying to connect to us.
- talk_base::SocketAddress accept_addr;
- talk_base::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr);
+ rtc::SocketAddress accept_addr;
+ rtc::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr);
if (accepted_socket != NULL) {
ProtocolType proto = server_listen_sockets_[server_socket];
cricket::AsyncStunTCPSocket* tcp_socket =
@@ -272,15 +273,15 @@
}
}
-void TurnServer::OnInternalSocketClose(talk_base::AsyncPacketSocket* socket,
+void TurnServer::OnInternalSocketClose(rtc::AsyncPacketSocket* socket,
int err) {
DestroyInternalSocket(socket);
}
-void TurnServer::OnInternalPacket(talk_base::AsyncPacketSocket* socket,
+void TurnServer::OnInternalPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketTime& packet_time) {
+ const rtc::SocketAddress& addr,
+ const rtc::PacketTime& packet_time) {
// Fail if the packet is too small to even contain a channel header.
if (size < TURN_CHANNEL_HEADER_SIZE) {
return;
@@ -288,7 +289,7 @@
InternalSocketMap::iterator iter = server_sockets_.find(socket);
ASSERT(iter != server_sockets_.end());
Connection conn(addr, iter->second, socket);
- uint16 msg_type = talk_base::GetBE16(data);
+ uint16 msg_type = rtc::GetBE16(data);
if (!IsTurnChannelData(msg_type)) {
// This is a STUN message.
HandleStunMessage(&conn, data, size);
@@ -304,7 +305,7 @@
void TurnServer::HandleStunMessage(Connection* conn, const char* data,
size_t size) {
TurnMessage msg;
- talk_base::ByteBuffer buf(data, size);
+ rtc::ByteBuffer buf(data, size);
if (!msg.Read(&buf) || (buf.Length() > 0)) {
LOG(LS_WARNING) << "Received invalid STUN message";
return;
@@ -316,6 +317,15 @@
return;
}
+ if (redirect_hook_ != NULL && msg.type() == STUN_ALLOCATE_REQUEST) {
+ rtc::SocketAddress address;
+ if (redirect_hook_->ShouldRedirect(conn->src(), &address)) {
+ SendErrorResponseWithAlternateServer(
+ conn, &msg, address);
+ return;
+ }
+ }
+
// Look up the key that we'll use to validate the M-I. If we have an
// existing allocation, the key will already be cached.
Allocation* allocation = FindAllocation(conn);
@@ -334,7 +344,6 @@
}
if (!allocation && msg.type() == STUN_ALLOCATE_REQUEST) {
- // This is a new allocate request.
HandleAllocateRequest(conn, &msg, key);
} else if (allocation &&
(msg.type() != STUN_ALLOCATE_REQUEST ||
@@ -474,10 +483,10 @@
std::string TurnServer::GenerateNonce() const {
// Generate a nonce of the form hex(now + HMAC-MD5(nonce_key_, now))
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
std::string input(reinterpret_cast<const char*>(&now), sizeof(now));
- std::string nonce = talk_base::hex_encode(input.c_str(), input.size());
- nonce += talk_base::ComputeHmac(talk_base::DIGEST_MD5, nonce_key_, input);
+ std::string nonce = rtc::hex_encode(input.c_str(), input.size());
+ nonce += rtc::ComputeHmac(rtc::DIGEST_MD5, nonce_key_, input);
ASSERT(nonce.size() == kNonceSize);
return nonce;
}
@@ -491,20 +500,20 @@
// Decode the timestamp.
uint32 then;
char* p = reinterpret_cast<char*>(&then);
- size_t len = talk_base::hex_decode(p, sizeof(then),
+ size_t len = rtc::hex_decode(p, sizeof(then),
nonce.substr(0, sizeof(then) * 2));
if (len != sizeof(then)) {
return false;
}
// Verify the HMAC.
- if (nonce.substr(sizeof(then) * 2) != talk_base::ComputeHmac(
- talk_base::DIGEST_MD5, nonce_key_, std::string(p, sizeof(then)))) {
+ if (nonce.substr(sizeof(then) * 2) != rtc::ComputeHmac(
+ rtc::DIGEST_MD5, nonce_key_, std::string(p, sizeof(then)))) {
return false;
}
// Validate the timestamp.
- return talk_base::TimeSince(then) < kNonceTimeout;
+ return rtc::TimeSince(then) < kNonceTimeout;
}
TurnServer::Allocation* TurnServer::FindAllocation(Connection* conn) {
@@ -515,7 +524,7 @@
TurnServer::Allocation* TurnServer::CreateAllocation(Connection* conn,
int proto,
const std::string& key) {
- talk_base::AsyncPacketSocket* external_socket = (external_socket_factory_) ?
+ rtc::AsyncPacketSocket* external_socket = (external_socket_factory_) ?
external_socket_factory_->CreateUdpSocket(external_addr_, 0, 0) : NULL;
if (!external_socket) {
return NULL;
@@ -551,8 +560,19 @@
SendStun(conn, &resp);
}
+void TurnServer::SendErrorResponseWithAlternateServer(
+ Connection* conn, const StunMessage* msg,
+ const rtc::SocketAddress& addr) {
+ TurnMessage resp;
+ InitErrorResponse(msg, STUN_ERROR_TRY_ALTERNATE,
+ STUN_ERROR_REASON_TRY_ALTERNATE_SERVER, &resp);
+ VERIFY(resp.AddAttribute(new StunAddressAttribute(
+ STUN_ATTR_ALTERNATE_SERVER, addr)));
+ SendStun(conn, &resp);
+}
+
void TurnServer::SendStun(Connection* conn, StunMessage* msg) {
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
// Add a SOFTWARE attribute if one is set.
if (!software_.empty()) {
VERIFY(msg->AddAttribute(
@@ -563,14 +583,14 @@
}
void TurnServer::Send(Connection* conn,
- const talk_base::ByteBuffer& buf) {
- talk_base::PacketOptions options;
+ const rtc::ByteBuffer& buf) {
+ rtc::PacketOptions options;
conn->socket()->SendTo(buf.Data(), buf.Length(), conn->src(), options);
}
void TurnServer::OnAllocationDestroyed(Allocation* allocation) {
// Removing the internal socket if the connection is not udp.
- talk_base::AsyncPacketSocket* socket = allocation->conn()->socket();
+ rtc::AsyncPacketSocket* socket = allocation->conn()->socket();
InternalSocketMap::iterator iter = server_sockets_.find(socket);
ASSERT(iter != server_sockets_.end());
// Skip if the socket serving this allocation is UDP, as this will be shared
@@ -584,18 +604,20 @@
allocations_.erase(it);
}
-void TurnServer::DestroyInternalSocket(talk_base::AsyncPacketSocket* socket) {
+void TurnServer::DestroyInternalSocket(rtc::AsyncPacketSocket* socket) {
InternalSocketMap::iterator iter = server_sockets_.find(socket);
if (iter != server_sockets_.end()) {
- talk_base::AsyncPacketSocket* socket = iter->first;
- delete socket;
+ rtc::AsyncPacketSocket* socket = iter->first;
+ // We must destroy the socket async to avoid invalidating the sigslot
+ // callback list iterator inside a sigslot callback.
+ rtc::Thread::Current()->Dispose(socket);
server_sockets_.erase(iter);
}
}
-TurnServer::Connection::Connection(const talk_base::SocketAddress& src,
+TurnServer::Connection::Connection(const rtc::SocketAddress& src,
ProtocolType proto,
- talk_base::AsyncPacketSocket* socket)
+ rtc::AsyncPacketSocket* socket)
: src_(src),
dst_(socket->GetRemoteAddress()),
proto_(proto),
@@ -620,9 +642,9 @@
}
TurnServer::Allocation::Allocation(TurnServer* server,
- talk_base::Thread* thread,
+ rtc::Thread* thread,
const Connection& conn,
- talk_base::AsyncPacketSocket* socket,
+ rtc::AsyncPacketSocket* socket,
const std::string& key)
: server_(server),
thread_(thread),
@@ -642,7 +664,7 @@
it != perms_.end(); ++it) {
delete *it;
}
- thread_->Clear(this, MSG_TIMEOUT);
+ thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
LOG_J(LS_INFO, this) << "Allocation destroyed";
}
@@ -687,7 +709,7 @@
// Figure out the lifetime and start the allocation timer.
int lifetime_secs = ComputeLifetime(msg);
- thread_->PostDelayed(lifetime_secs * 1000, this, MSG_TIMEOUT);
+ thread_->PostDelayed(lifetime_secs * 1000, this, MSG_ALLOCATION_TIMEOUT);
LOG_J(LS_INFO, this) << "Created allocation, lifetime=" << lifetime_secs;
@@ -714,8 +736,8 @@
int lifetime_secs = ComputeLifetime(msg);
// Reset the expiration timer.
- thread_->Clear(this, MSG_TIMEOUT);
- thread_->PostDelayed(lifetime_secs * 1000, this, MSG_TIMEOUT);
+ thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
+ thread_->PostDelayed(lifetime_secs * 1000, this, MSG_ALLOCATION_TIMEOUT);
LOG_J(LS_INFO, this) << "Refreshed allocation, lifetime=" << lifetime_secs;
@@ -823,7 +845,7 @@
void TurnServer::Allocation::HandleChannelData(const char* data, size_t size) {
// Extract the channel number from the data.
- uint16 channel_id = talk_base::GetBE16(data);
+ uint16 channel_id = rtc::GetBE16(data);
Channel* channel = FindChannel(channel_id);
if (channel) {
// Send the data to the peer address.
@@ -836,15 +858,15 @@
}
void TurnServer::Allocation::OnExternalPacket(
- talk_base::AsyncPacketSocket* socket,
+ rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& addr,
- const talk_base::PacketTime& packet_time) {
+ const rtc::SocketAddress& addr,
+ const rtc::PacketTime& packet_time) {
ASSERT(external_socket_.get() == socket);
Channel* channel = FindChannel(addr);
if (channel) {
// There is a channel bound to this address. Send as a channel message.
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
buf.WriteUInt16(channel->id());
buf.WriteUInt16(static_cast<uint16>(size));
buf.WriteBytes(data, size);
@@ -854,7 +876,7 @@
TurnMessage msg;
msg.SetType(TURN_DATA_INDICATION);
msg.SetTransactionID(
- talk_base::CreateRandomString(kStunTransactionIdLength));
+ rtc::CreateRandomString(kStunTransactionIdLength));
VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
STUN_ATTR_XOR_PEER_ADDRESS, addr)));
VERIFY(msg.AddAttribute(new StunByteStringAttribute(
@@ -876,11 +898,11 @@
return lifetime;
}
-bool TurnServer::Allocation::HasPermission(const talk_base::IPAddress& addr) {
+bool TurnServer::Allocation::HasPermission(const rtc::IPAddress& addr) {
return (FindPermission(addr) != NULL);
}
-void TurnServer::Allocation::AddPermission(const talk_base::IPAddress& addr) {
+void TurnServer::Allocation::AddPermission(const rtc::IPAddress& addr) {
Permission* perm = FindPermission(addr);
if (!perm) {
perm = new Permission(thread_, addr);
@@ -893,7 +915,7 @@
}
TurnServer::Permission* TurnServer::Allocation::FindPermission(
- const talk_base::IPAddress& addr) const {
+ const rtc::IPAddress& addr) const {
for (PermissionList::const_iterator it = perms_.begin();
it != perms_.end(); ++it) {
if ((*it)->peer() == addr)
@@ -912,7 +934,7 @@
}
TurnServer::Channel* TurnServer::Allocation::FindChannel(
- const talk_base::SocketAddress& addr) const {
+ const rtc::SocketAddress& addr) const {
for (ChannelList::const_iterator it = channels_.begin();
it != channels_.end(); ++it) {
if ((*it)->peer() == addr)
@@ -937,13 +959,13 @@
}
void TurnServer::Allocation::SendExternal(const void* data, size_t size,
- const talk_base::SocketAddress& peer) {
- talk_base::PacketOptions options;
+ const rtc::SocketAddress& peer) {
+ rtc::PacketOptions options;
external_socket_->SendTo(data, size, peer, options);
}
-void TurnServer::Allocation::OnMessage(talk_base::Message* msg) {
- ASSERT(msg->message_id == MSG_TIMEOUT);
+void TurnServer::Allocation::OnMessage(rtc::Message* msg) {
+ ASSERT(msg->message_id == MSG_ALLOCATION_TIMEOUT);
SignalDestroyed(this);
delete this;
}
@@ -961,44 +983,44 @@
channels_.erase(it);
}
-TurnServer::Permission::Permission(talk_base::Thread* thread,
- const talk_base::IPAddress& peer)
+TurnServer::Permission::Permission(rtc::Thread* thread,
+ const rtc::IPAddress& peer)
: thread_(thread), peer_(peer) {
Refresh();
}
TurnServer::Permission::~Permission() {
- thread_->Clear(this, MSG_TIMEOUT);
+ thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
}
void TurnServer::Permission::Refresh() {
- thread_->Clear(this, MSG_TIMEOUT);
- thread_->PostDelayed(kPermissionTimeout, this, MSG_TIMEOUT);
+ thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
+ thread_->PostDelayed(kPermissionTimeout, this, MSG_ALLOCATION_TIMEOUT);
}
-void TurnServer::Permission::OnMessage(talk_base::Message* msg) {
- ASSERT(msg->message_id == MSG_TIMEOUT);
+void TurnServer::Permission::OnMessage(rtc::Message* msg) {
+ ASSERT(msg->message_id == MSG_ALLOCATION_TIMEOUT);
SignalDestroyed(this);
delete this;
}
-TurnServer::Channel::Channel(talk_base::Thread* thread, int id,
- const talk_base::SocketAddress& peer)
+TurnServer::Channel::Channel(rtc::Thread* thread, int id,
+ const rtc::SocketAddress& peer)
: thread_(thread), id_(id), peer_(peer) {
Refresh();
}
TurnServer::Channel::~Channel() {
- thread_->Clear(this, MSG_TIMEOUT);
+ thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
}
void TurnServer::Channel::Refresh() {
- thread_->Clear(this, MSG_TIMEOUT);
- thread_->PostDelayed(kChannelTimeout, this, MSG_TIMEOUT);
+ thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
+ thread_->PostDelayed(kChannelTimeout, this, MSG_ALLOCATION_TIMEOUT);
}
-void TurnServer::Channel::OnMessage(talk_base::Message* msg) {
- ASSERT(msg->message_id == MSG_TIMEOUT);
+void TurnServer::Channel::OnMessage(rtc::Message* msg) {
+ ASSERT(msg->message_id == MSG_ALLOCATION_TIMEOUT);
SignalDestroyed(this);
delete this;
}
diff --git a/p2p/base/turnserver.h b/p2p/base/turnserver.h
index 2c33cdb..553d00c 100644
--- a/p2p/base/turnserver.h
+++ b/p2p/base/turnserver.h
@@ -33,13 +33,13 @@
#include <set>
#include <string>
-#include "talk/base/asyncpacketsocket.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socketaddress.h"
#include "talk/p2p/base/portinterface.h"
+#include "webrtc/base/asyncpacketsocket.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/socketaddress.h"
-namespace talk_base {
+namespace rtc {
class ByteBuffer;
class PacketSocketFactory;
class Thread;
@@ -63,13 +63,21 @@
std::string* key) = 0;
};
+// An interface enables Turn Server to control redirection behavior.
+class TurnRedirectInterface {
+ public:
+ virtual bool ShouldRedirect(const rtc::SocketAddress& address,
+ rtc::SocketAddress* out) = 0;
+ virtual ~TurnRedirectInterface() {}
+};
+
// The core TURN server class. Give it a socket to listen on via
// AddInternalServerSocket, and a factory to create external sockets via
// SetExternalSocketFactory, and it's ready to go.
// Not yet wired up: TCP support.
class TurnServer : public sigslot::has_slots<> {
public:
- explicit TurnServer(talk_base::Thread* thread);
+ explicit TurnServer(rtc::Thread* thread);
~TurnServer();
// Gets/sets the realm value to use for the server.
@@ -83,54 +91,58 @@
// Sets the authentication callback; does not take ownership.
void set_auth_hook(TurnAuthInterface* auth_hook) { auth_hook_ = auth_hook; }
+ void set_redirect_hook(TurnRedirectInterface* redirect_hook) {
+ redirect_hook_ = redirect_hook;
+ }
+
void set_enable_otu_nonce(bool enable) { enable_otu_nonce_ = enable; }
// Starts listening for packets from internal clients.
- void AddInternalSocket(talk_base::AsyncPacketSocket* socket,
+ void AddInternalSocket(rtc::AsyncPacketSocket* socket,
ProtocolType proto);
// Starts listening for the connections on this socket. When someone tries
// to connect, the connection will be accepted and a new internal socket
// will be added.
- void AddInternalServerSocket(talk_base::AsyncSocket* socket,
+ void AddInternalServerSocket(rtc::AsyncSocket* socket,
ProtocolType proto);
// Specifies the factory to use for creating external sockets.
- void SetExternalSocketFactory(talk_base::PacketSocketFactory* factory,
- const talk_base::SocketAddress& address);
+ void SetExternalSocketFactory(rtc::PacketSocketFactory* factory,
+ const rtc::SocketAddress& address);
private:
// Encapsulates the client's connection to the server.
class Connection {
public:
Connection() : proto_(PROTO_UDP), socket_(NULL) {}
- Connection(const talk_base::SocketAddress& src,
+ Connection(const rtc::SocketAddress& src,
ProtocolType proto,
- talk_base::AsyncPacketSocket* socket);
- const talk_base::SocketAddress& src() const { return src_; }
- talk_base::AsyncPacketSocket* socket() { return socket_; }
+ rtc::AsyncPacketSocket* socket);
+ const rtc::SocketAddress& src() const { return src_; }
+ rtc::AsyncPacketSocket* socket() { return socket_; }
bool operator==(const Connection& t) const;
bool operator<(const Connection& t) const;
std::string ToString() const;
private:
- talk_base::SocketAddress src_;
- talk_base::SocketAddress dst_;
+ rtc::SocketAddress src_;
+ rtc::SocketAddress dst_;
cricket::ProtocolType proto_;
- talk_base::AsyncPacketSocket* socket_;
+ rtc::AsyncPacketSocket* socket_;
};
class Allocation;
class Permission;
class Channel;
typedef std::map<Connection, Allocation*> AllocationMap;
- void OnInternalPacket(talk_base::AsyncPacketSocket* socket, const char* data,
- size_t size, const talk_base::SocketAddress& address,
- const talk_base::PacketTime& packet_time);
+ void OnInternalPacket(rtc::AsyncPacketSocket* socket, const char* data,
+ size_t size, const rtc::SocketAddress& address,
+ const rtc::PacketTime& packet_time);
- void OnNewInternalConnection(talk_base::AsyncSocket* socket);
+ void OnNewInternalConnection(rtc::AsyncSocket* socket);
// Accept connections on this server socket.
- void AcceptConnection(talk_base::AsyncSocket* server_socket);
- void OnInternalSocketClose(talk_base::AsyncPacketSocket* socket, int err);
+ void AcceptConnection(rtc::AsyncSocket* server_socket);
+ void OnInternalSocketClose(rtc::AsyncPacketSocket* socket, int err);
void HandleStunMessage(Connection* conn, const char* data, size_t size);
void HandleBindingRequest(Connection* conn, const StunMessage* msg);
@@ -155,30 +167,38 @@
const StunMessage* req,
int code,
const std::string& reason);
+
+ void SendErrorResponseWithAlternateServer(Connection* conn,
+ const StunMessage* req,
+ const rtc::SocketAddress& addr);
+
void SendStun(Connection* conn, StunMessage* msg);
- void Send(Connection* conn, const talk_base::ByteBuffer& buf);
+ void Send(Connection* conn, const rtc::ByteBuffer& buf);
void OnAllocationDestroyed(Allocation* allocation);
- void DestroyInternalSocket(talk_base::AsyncPacketSocket* socket);
+ void DestroyInternalSocket(rtc::AsyncPacketSocket* socket);
- typedef std::map<talk_base::AsyncPacketSocket*,
+ typedef std::map<rtc::AsyncPacketSocket*,
ProtocolType> InternalSocketMap;
- typedef std::map<talk_base::AsyncSocket*,
+ typedef std::map<rtc::AsyncSocket*,
ProtocolType> ServerSocketMap;
- talk_base::Thread* thread_;
+ rtc::Thread* thread_;
std::string nonce_key_;
std::string realm_;
std::string software_;
TurnAuthInterface* auth_hook_;
+ TurnRedirectInterface* redirect_hook_;
// otu - one-time-use. Server will respond with 438 if it's
// sees the same nonce in next transaction.
bool enable_otu_nonce_;
+
InternalSocketMap server_sockets_;
ServerSocketMap server_listen_sockets_;
- talk_base::scoped_ptr<talk_base::PacketSocketFactory>
+ rtc::scoped_ptr<rtc::PacketSocketFactory>
external_socket_factory_;
- talk_base::SocketAddress external_addr_;
+ rtc::SocketAddress external_addr_;
+
AllocationMap allocations_;
};
diff --git a/p2p/client/autoportallocator.h b/p2p/client/autoportallocator.h
index 4ec324b..ed87162 100644
--- a/p2p/client/autoportallocator.h
+++ b/p2p/client/autoportallocator.h
@@ -25,22 +25,22 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef TALK_EXAMPLES_LOGIN_AUTOPORTALLOCATOR_H_
-#define TALK_EXAMPLES_LOGIN_AUTOPORTALLOCATOR_H_
+#ifndef TALK_P2P_CLIENT_AUTOPORTALLOCATOR_H_
+#define TALK_P2P_CLIENT_AUTOPORTALLOCATOR_H_
#include <string>
#include <vector>
-#include "talk/base/sigslot.h"
#include "talk/p2p/client/httpportallocator.h"
#include "talk/xmpp/jingleinfotask.h"
#include "talk/xmpp/xmppclient.h"
+#include "webrtc/base/sigslot.h"
// This class sets the relay and stun servers using XmppClient.
// It enables the client to traverse Proxy and NAT.
class AutoPortAllocator : public cricket::HttpPortAllocator {
public:
- AutoPortAllocator(talk_base::NetworkManager* network_manager,
+ AutoPortAllocator(rtc::NetworkManager* network_manager,
const std::string& user_agent)
: cricket::HttpPortAllocator(network_manager, user_agent) {
}
@@ -59,11 +59,11 @@
void OnJingleInfo(
const std::string& token,
const std::vector<std::string>& relay_hosts,
- const std::vector<talk_base::SocketAddress>& stun_hosts) {
+ const std::vector<rtc::SocketAddress>& stun_hosts) {
SetRelayToken(token);
SetStunHosts(stun_hosts);
SetRelayHosts(relay_hosts);
}
};
-#endif // TALK_EXAMPLES_LOGIN_AUTOPORTALLOCATOR_H_
+#endif // TALK_P2P_CLIENT_AUTOPORTALLOCATOR_H_
diff --git a/p2p/client/basicportallocator.cc b/p2p/client/basicportallocator.cc
index 762726f..0ec13e7 100644
--- a/p2p/client/basicportallocator.cc
+++ b/p2p/client/basicportallocator.cc
@@ -30,9 +30,6 @@
#include <string>
#include <vector>
-#include "talk/base/common.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/common.h"
#include "talk/p2p/base/port.h"
@@ -41,21 +38,24 @@
#include "talk/p2p/base/tcpport.h"
#include "talk/p2p/base/turnport.h"
#include "talk/p2p/base/udpport.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
-using talk_base::CreateRandomId;
-using talk_base::CreateRandomString;
+using rtc::CreateRandomId;
+using rtc::CreateRandomString;
namespace {
-const uint32 MSG_CONFIG_START = 1;
-const uint32 MSG_CONFIG_READY = 2;
-const uint32 MSG_ALLOCATE = 3;
-const uint32 MSG_ALLOCATION_PHASE = 4;
-const uint32 MSG_SHAKE = 5;
-const uint32 MSG_SEQUENCEOBJECTS_CREATED = 6;
-const uint32 MSG_CONFIG_STOP = 7;
-
-const uint32 ALLOCATE_DELAY = 250;
+enum {
+ MSG_CONFIG_START,
+ MSG_CONFIG_READY,
+ MSG_ALLOCATE,
+ MSG_ALLOCATION_PHASE,
+ MSG_SHAKE,
+ MSG_SEQUENCEOBJECTS_CREATED,
+ MSG_CONFIG_STOP,
+};
const int PHASE_UDP = 0;
const int PHASE_RELAY = 1;
@@ -84,7 +84,7 @@
// Performs the allocation of ports, in a sequenced (timed) manner, for a given
// network and IP address.
-class AllocationSequence : public talk_base::MessageHandler,
+class AllocationSequence : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
enum State {
@@ -97,7 +97,7 @@
};
AllocationSequence(BasicPortAllocatorSession* session,
- talk_base::Network* network,
+ rtc::Network* network,
PortConfiguration* config,
uint32 flags);
~AllocationSequence();
@@ -108,7 +108,7 @@
// Disables the phases for a new sequence that this one already covers for an
// equivalent network setup.
- void DisableEquivalentPhases(talk_base::Network* network,
+ void DisableEquivalentPhases(rtc::Network* network,
PortConfiguration* config, uint32* flags);
// Starts and stops the sequence. When started, it will continue allocating
@@ -117,7 +117,7 @@
void Stop();
// MessageHandler
- void OnMessage(talk_base::Message* msg);
+ void OnMessage(rtc::Message* msg);
void EnableProtocol(ProtocolType proto);
bool ProtocolEnabled(ProtocolType proto) const;
@@ -143,35 +143,31 @@
void CreateGturnPort(const RelayServerConfig& config);
void CreateTurnPort(const RelayServerConfig& config);
- void OnReadPacket(talk_base::AsyncPacketSocket* socket,
+ void OnReadPacket(rtc::AsyncPacketSocket* socket,
const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time);
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time);
void OnPortDestroyed(PortInterface* port);
- void OnResolvedTurnServerAddress(
- TurnPort* port, const talk_base::SocketAddress& server_address,
- const talk_base::SocketAddress& resolved_server_address);
BasicPortAllocatorSession* session_;
- talk_base::Network* network_;
- talk_base::IPAddress ip_;
+ rtc::Network* network_;
+ rtc::IPAddress ip_;
PortConfiguration* config_;
State state_;
uint32 flags_;
ProtocolList protocols_;
- talk_base::scoped_ptr<talk_base::AsyncPacketSocket> udp_socket_;
+ rtc::scoped_ptr<rtc::AsyncPacketSocket> udp_socket_;
// There will be only one udp port per AllocationSequence.
UDPPort* udp_port_;
- // Keeping a map for turn ports keyed with server addresses.
- std::map<talk_base::SocketAddress, Port*> turn_ports_;
+ std::vector<TurnPort*> turn_ports_;
int phase_;
};
// BasicPortAllocator
BasicPortAllocator::BasicPortAllocator(
- talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory)
+ rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory)
: network_manager_(network_manager),
socket_factory_(socket_factory) {
ASSERT(socket_factory_ != NULL);
@@ -179,32 +175,32 @@
}
BasicPortAllocator::BasicPortAllocator(
- talk_base::NetworkManager* network_manager)
+ rtc::NetworkManager* network_manager)
: network_manager_(network_manager),
socket_factory_(NULL) {
Construct();
}
BasicPortAllocator::BasicPortAllocator(
- talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory,
- const talk_base::SocketAddress& stun_address)
+ rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory,
+ const ServerAddresses& stun_servers)
: network_manager_(network_manager),
socket_factory_(socket_factory),
- stun_address_(stun_address) {
+ stun_servers_(stun_servers) {
ASSERT(socket_factory_ != NULL);
Construct();
}
BasicPortAllocator::BasicPortAllocator(
- talk_base::NetworkManager* network_manager,
- const talk_base::SocketAddress& stun_address,
- const talk_base::SocketAddress& relay_address_udp,
- const talk_base::SocketAddress& relay_address_tcp,
- const talk_base::SocketAddress& relay_address_ssl)
+ rtc::NetworkManager* network_manager,
+ const ServerAddresses& stun_servers,
+ const rtc::SocketAddress& relay_address_udp,
+ const rtc::SocketAddress& relay_address_tcp,
+ const rtc::SocketAddress& relay_address_ssl)
: network_manager_(network_manager),
socket_factory_(NULL),
- stun_address_(stun_address) {
+ stun_servers_(stun_servers) {
RelayServerConfig config(RELAY_GTURN);
if (!relay_address_udp.IsNil())
@@ -230,10 +226,11 @@
PortAllocatorSession *BasicPortAllocator::CreateSessionInternal(
const std::string& content_name, int component,
const std::string& ice_ufrag, const std::string& ice_pwd) {
- return new BasicPortAllocatorSession(this, content_name, component,
- ice_ufrag, ice_pwd);
+ return new BasicPortAllocatorSession(
+ this, content_name, component, ice_ufrag, ice_pwd);
}
+
// BasicPortAllocatorSession
BasicPortAllocatorSession::BasicPortAllocatorSession(
BasicPortAllocator *allocator,
@@ -277,10 +274,10 @@
}
void BasicPortAllocatorSession::StartGettingPorts() {
- network_thread_ = talk_base::Thread::Current();
+ network_thread_ = rtc::Thread::Current();
if (!socket_factory_) {
owned_socket_factory_.reset(
- new talk_base::BasicPacketSocketFactory(network_thread_));
+ new rtc::BasicPacketSocketFactory(network_thread_));
socket_factory_ = owned_socket_factory_.get();
}
@@ -292,7 +289,7 @@
}
void BasicPortAllocatorSession::StopGettingPorts() {
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
running_ = false;
network_thread_->Clear(this, MSG_ALLOCATE);
for (uint32 i = 0; i < sequences_.size(); ++i)
@@ -300,33 +297,33 @@
network_thread_->Post(this, MSG_CONFIG_STOP);
}
-void BasicPortAllocatorSession::OnMessage(talk_base::Message *message) {
+void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
switch (message->message_id) {
case MSG_CONFIG_START:
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
GetPortConfigurations();
break;
case MSG_CONFIG_READY:
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
break;
case MSG_ALLOCATE:
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
OnAllocate();
break;
case MSG_SHAKE:
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
OnShake();
break;
case MSG_SEQUENCEOBJECTS_CREATED:
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
OnAllocationSequenceObjectsCreated();
break;
case MSG_CONFIG_STOP:
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
OnConfigStop();
break;
default:
@@ -335,7 +332,7 @@
}
void BasicPortAllocatorSession::GetPortConfigurations() {
- PortConfiguration* config = new PortConfiguration(allocator_->stun_address(),
+ PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
username(),
password());
@@ -358,7 +355,7 @@
}
void BasicPortAllocatorSession::OnConfigStop() {
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
// If any of the allocated ports have not completed the candidates allocation,
// mark those as error. Since session doesn't need any new candidates
@@ -389,7 +386,7 @@
}
void BasicPortAllocatorSession::AllocatePorts() {
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
network_thread_->Post(this, MSG_ALLOCATE);
}
@@ -398,15 +395,13 @@
DoAllocate();
allocation_started_ = true;
- if (running_)
- network_thread_->PostDelayed(ALLOCATE_DELAY, this, MSG_ALLOCATE);
}
// For each network, see if we have a sequence that covers it already. If not,
// create a new sequence to create the appropriate ports.
void BasicPortAllocatorSession::DoAllocate() {
bool done_signal_needed = false;
- std::vector<talk_base::Network*> networks;
+ std::vector<rtc::Network*> networks;
allocator_->network_manager()->GetNetworks(&networks);
if (networks.empty()) {
LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
@@ -426,7 +421,7 @@
}
// Disables phases that are not specified in this config.
- if (!config || config->stun_address.IsNil()) {
+ if (!config || config->StunServers().empty()) {
// No STUN ports specified in this config.
sequence_flags |= PORTALLOCATOR_DISABLE_STUN;
}
@@ -436,7 +431,11 @@
}
if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
+#ifdef USE_WEBRTC_DEV_BRANCH
+ networks[i]->GetBestIP().family() == AF_INET6) {
+#else // USE_WEBRTC_DEV_BRANCH
networks[i]->ip().family() == AF_INET6) {
+#endif // USE_WEBRTC_DEV_BRANCH
// Skip IPv6 networks unless the flag's been set.
continue;
}
@@ -476,7 +475,7 @@
}
void BasicPortAllocatorSession::DisableEquivalentPhases(
- talk_base::Network* network, PortConfiguration* config, uint32* flags) {
+ rtc::Network* network, PortConfiguration* config, uint32* flags) {
for (uint32 i = 0; i < sequences_.size() &&
(*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES; ++i) {
sequences_[i]->DisableEquivalentPhases(network, config, flags);
@@ -493,7 +492,7 @@
port->set_content_name(content_name());
port->set_component(component_);
port->set_generation(generation());
- if (allocator_->proxy().type != talk_base::PROXY_NONE)
+ if (allocator_->proxy().type != rtc::PROXY_NONE)
port->set_proxy(allocator_->user_agent(), allocator_->proxy());
port->set_send_retransmit_count_attribute((allocator_->flags() &
PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
@@ -523,7 +522,7 @@
void BasicPortAllocatorSession::OnCandidateReady(
Port* port, const Candidate& c) {
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
PortData* data = FindPort(port);
ASSERT(data != NULL);
// Discarding any candidate signal if port allocation status is
@@ -534,8 +533,10 @@
// Send candidates whose protocol is enabled.
std::vector<Candidate> candidates;
ProtocolType pvalue;
+ bool candidate_allowed_to_send = CheckCandidateFilter(c);
if (StringToProto(c.protocol().c_str(), &pvalue) &&
- data->sequence()->ProtocolEnabled(pvalue)) {
+ data->sequence()->ProtocolEnabled(pvalue) &&
+ candidate_allowed_to_send) {
candidates.push_back(c);
}
@@ -546,14 +547,16 @@
// Moving to READY state as we have atleast one candidate from the port.
// Since this port has atleast one candidate we should forward this port
// to listners, to allow connections from this port.
- if (!data->ready()) {
+ // Also we should make sure that candidate gathered from this port is allowed
+ // to send outside.
+ if (!data->ready() && candidate_allowed_to_send) {
data->set_ready();
SignalPortReady(this, port);
}
}
void BasicPortAllocatorSession::OnPortComplete(Port* port) {
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
PortData* data = FindPort(port);
ASSERT(data != NULL);
@@ -568,7 +571,7 @@
}
void BasicPortAllocatorSession::OnPortError(Port* port) {
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
PortData* data = FindPort(port);
ASSERT(data != NULL);
// We might have already given up on this port and stopped it.
@@ -592,6 +595,8 @@
const std::vector<Candidate>& potentials = it->port()->Candidates();
for (size_t i = 0; i < potentials.size(); ++i) {
+ if (!CheckCandidateFilter(potentials[i]))
+ continue;
ProtocolType pvalue;
if (!StringToProto(potentials[i].protocol().c_str(), &pvalue))
continue;
@@ -606,6 +611,31 @@
}
}
+bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) {
+ uint32 filter = allocator_->candidate_filter();
+ bool allowed = false;
+ if (filter & CF_RELAY) {
+ allowed |= (c.type() == RELAY_PORT_TYPE);
+ }
+
+ if (filter & CF_REFLEXIVE) {
+ // We allow host candidates if the filter allows server-reflexive candidates
+ // and the candidate is a public IP. Because we don't generate
+ // server-reflexive candidates if they have the same IP as the host
+ // candidate (i.e. when the host candidate is a public IP), filtering to
+ // only server-reflexive candidates won't work right when the host
+ // candidates have public IPs.
+ allowed |= (c.type() == STUN_PORT_TYPE) ||
+ (c.type() == LOCAL_PORT_TYPE && !c.address().IsPrivateIP());
+ }
+
+ if (filter & CF_HOST) {
+ allowed |= (c.type() == LOCAL_PORT_TYPE);
+ }
+
+ return allowed;
+}
+
void BasicPortAllocatorSession::OnPortAllocationComplete(
AllocationSequence* seq) {
// Send candidate allocation complete signal if all ports are done.
@@ -640,7 +670,7 @@
void BasicPortAllocatorSession::OnPortDestroyed(
PortInterface* port) {
- ASSERT(talk_base::Thread::Current() == network_thread_);
+ ASSERT(rtc::Thread::Current() == network_thread_);
for (std::vector<PortData>::iterator iter = ports_.begin();
iter != ports_.end(); ++iter) {
if (port == iter->port()) {
@@ -697,12 +727,17 @@
// AllocationSequence
AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
- talk_base::Network* network,
+ rtc::Network* network,
PortConfiguration* config,
uint32 flags)
: session_(session),
network_(network),
+
+#ifdef USE_WEBRTC_DEV_BRANCH
+ ip_(network->GetBestIP()),
+#else // USE_WEBRTC_DEV_BRANCH
ip_(network->ip()),
+#endif // USE_WEBRTC_DEV_BRANCH
config_(config),
state_(kInit),
flags_(flags),
@@ -722,7 +757,7 @@
if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
- talk_base::SocketAddress(ip_, 0), session_->allocator()->min_port(),
+ rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
session_->allocator()->max_port()));
if (udp_socket_) {
udp_socket_->SignalReadPacket.connect(
@@ -743,9 +778,13 @@
session_->network_thread()->Clear(this);
}
-void AllocationSequence::DisableEquivalentPhases(talk_base::Network* network,
+void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
PortConfiguration* config, uint32* flags) {
+#ifdef USE_WEBRTC_DEV_BRANCH
+ if (!((network == network_) && (ip_ == network->GetBestIP()))) {
+#else // USE_WEBRTC_DEV_BRANCH
if (!((network == network_) && (ip_ == network->ip()))) {
+#endif // USE_WEBRTC_DEV_BRANCH
// Different network setup; nothing is equivalent.
return;
}
@@ -757,8 +796,8 @@
*flags |= PORTALLOCATOR_DISABLE_TCP;
if (config_ && config) {
- if (config_->stun_address == config->stun_address) {
- // Already got this STUN server covered.
+ if (config_->StunServers() == config->StunServers()) {
+ // Already got this STUN servers covered.
*flags |= PORTALLOCATOR_DISABLE_STUN;
}
if (!config_->relays.empty()) {
@@ -785,8 +824,8 @@
}
}
-void AllocationSequence::OnMessage(talk_base::Message* msg) {
- ASSERT(talk_base::Thread::Current() == session_->network_thread());
+void AllocationSequence::OnMessage(rtc::Message* msg) {
+ ASSERT(rtc::Thread::Current() == session_->network_thread());
ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
const char* const PHASE_NAMES[kNumPhases] = {
@@ -882,15 +921,15 @@
// If STUN is not disabled, setting stun server address to port.
if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
- // If config has stun_address, use it to get server reflexive candidate
+ // If config has stun_servers, use it to get server reflexive candidate
// otherwise use first TURN server which supports UDP.
- if (config_ && !config_->stun_address.IsNil()) {
+ if (config_ && !config_->StunServers().empty()) {
LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
<< "STUN candidate generation.";
- port->set_server_addr(config_->stun_address);
+ port->set_server_addresses(config_->StunServers());
} else if (config_ &&
config_->SupportsProtocol(RELAY_TURN, PROTO_UDP)) {
- port->set_server_addr(config_->GetFirstRelayServerAddress(
+ port->set_server_addresses(config_->GetRelayServerAddresses(
RELAY_TURN, PROTO_UDP));
LOG(LS_INFO) << "AllocationSequence: TURN Server address will be "
<< " used for generating STUN candidate.";
@@ -935,8 +974,8 @@
// If BasicPortAllocatorSession::OnAllocate left STUN ports enabled then we
// ought to have an address for them here.
- ASSERT(config_ && !config_->stun_address.IsNil());
- if (!(config_ && !config_->stun_address.IsNil())) {
+ ASSERT(config_ && !config_->StunServers().empty());
+ if (!(config_ && !config_->StunServers().empty())) {
LOG(LS_WARNING)
<< "AllocationSequence: No STUN server configured, skipping.";
return;
@@ -948,7 +987,7 @@
session_->allocator()->min_port(),
session_->allocator()->max_port(),
session_->username(), session_->password(),
- config_->stun_address);
+ config_->StunServers());
if (port) {
session_->AddAllocatedPort(port, this, true);
// Since StunPort is not created using shared socket, |port| will not be
@@ -1022,26 +1061,17 @@
TurnPort* port = NULL;
// Shared socket mode must be enabled only for UDP based ports. Hence
// don't pass shared socket for ports which will create TCP sockets.
+ // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
+ // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
relay_port->proto == PROTO_UDP) {
port = TurnPort::Create(session_->network_thread(),
session_->socket_factory(),
network_, udp_socket_.get(),
session_->username(), session_->password(),
- *relay_port, config.credentials);
- // If we are using shared socket for TURN and udp ports, we need to
- // find a way to demux the packets to the correct port when received.
- // Mapping against server_address is one way of doing this. When packet
- // is received the remote_address will be checked against the map.
- // If server address is not resolved, a signal will be sent from the port
- // after the address is resolved. The map entry will updated with the
- // resolved address when the signal is received from the port.
- if ((*relay_port).address.IsUnresolved()) {
- // If server address is not resolved then listen for signal from port.
- port->SignalResolvedServerAddress.connect(
- this, &AllocationSequence::OnResolvedTurnServerAddress);
- }
- turn_ports_[(*relay_port).address] = port;
+ *relay_port, config.credentials, config.priority);
+
+ turn_ports_.push_back(port);
// Listen to the port destroyed signal, to allow AllocationSequence to
// remove entrt from it's map.
port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
@@ -1053,7 +1083,7 @@
session_->allocator()->max_port(),
session_->username(),
session_->password(),
- *relay_port, config.credentials);
+ *relay_port, config.credentials, config.priority);
}
ASSERT(port != NULL);
session_->AddAllocatedPort(port, this, true);
@@ -1061,65 +1091,77 @@
}
void AllocationSequence::OnReadPacket(
- talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
- const talk_base::SocketAddress& remote_addr,
- const talk_base::PacketTime& packet_time) {
+ rtc::AsyncPacketSocket* socket, const char* data, size_t size,
+ const rtc::SocketAddress& remote_addr,
+ const rtc::PacketTime& packet_time) {
ASSERT(socket == udp_socket_.get());
- // If the packet is received from one of the TURN server in the config, then
- // pass down the packet to that port, otherwise it will be handed down to
- // the local udp port.
- Port* port = NULL;
- std::map<talk_base::SocketAddress, Port*>::iterator iter =
- turn_ports_.find(remote_addr);
- if (iter != turn_ports_.end()) {
- port = iter->second;
- } else if (udp_port_) {
- port = udp_port_;
+
+ bool turn_port_found = false;
+
+ // Try to find the TurnPort that matches the remote address. Note that the
+ // message could be a STUN binding response if the TURN server is also used as
+ // a STUN server. We don't want to parse every message here to check if it is
+ // a STUN binding response, so we pass the message to TurnPort regardless of
+ // the message type. The TurnPort will just ignore the message since it will
+ // not find any request by transaction ID.
+ for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
+ it != turn_ports_.end(); ++it) {
+ TurnPort* port = *it;
+ if (port->server_address().address == remote_addr) {
+ port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
+ turn_port_found = true;
+ break;
+ }
}
- ASSERT(port != NULL);
- if (port) {
- port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
+
+ if (udp_port_) {
+ const ServerAddresses& stun_servers = udp_port_->server_addresses();
+
+ // Pass the packet to the UdpPort if there is no matching TurnPort, or if
+ // the TURN server is also a STUN server.
+ if (!turn_port_found ||
+ stun_servers.find(remote_addr) != stun_servers.end()) {
+ udp_port_->HandleIncomingPacket(
+ socket, data, size, remote_addr, packet_time);
+ }
}
}
void AllocationSequence::OnPortDestroyed(PortInterface* port) {
if (udp_port_ == port) {
udp_port_ = NULL;
- } else {
- std::map<talk_base::SocketAddress, Port*>::iterator iter;
- for (iter = turn_ports_.begin(); iter != turn_ports_.end(); ++iter) {
- if (iter->second == port) {
- turn_ports_.erase(iter);
- break;
- }
- }
- }
-}
-
-void AllocationSequence::OnResolvedTurnServerAddress(
- TurnPort* port, const talk_base::SocketAddress& server_address,
- const talk_base::SocketAddress& resolved_server_address) {
- std::map<talk_base::SocketAddress, Port*>::iterator iter;
- iter = turn_ports_.find(server_address);
- if (iter == turn_ports_.end()) {
- LOG(LS_INFO) << "TurnPort entry is not found in the map.";
return;
}
- ASSERT(iter->second == port);
- // Remove old entry and then insert using the resolved address as key.
- turn_ports_.erase(iter);
- turn_ports_[resolved_server_address] = port;
+ turn_ports_.erase(std::find(turn_ports_.begin(), turn_ports_.end(), port));
}
// PortConfiguration
PortConfiguration::PortConfiguration(
- const talk_base::SocketAddress& stun_address,
+ const rtc::SocketAddress& stun_address,
const std::string& username,
const std::string& password)
- : stun_address(stun_address),
+ : stun_address(stun_address), username(username), password(password) {
+ if (!stun_address.IsNil())
+ stun_servers.insert(stun_address);
+}
+
+PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
+ const std::string& username,
+ const std::string& password)
+ : stun_servers(stun_servers),
username(username),
password(password) {
+ if (!stun_servers.empty())
+ stun_address = *(stun_servers.begin());
+}
+
+ServerAddresses PortConfiguration::StunServers() {
+ if (!stun_address.IsNil() &&
+ stun_servers.find(stun_address) == stun_servers.end()) {
+ stun_servers.insert(stun_address);
+ }
+ return stun_servers;
}
void PortConfiguration::AddRelay(const RelayServerConfig& config) {
@@ -1148,14 +1190,15 @@
return false;
}
-talk_base::SocketAddress PortConfiguration::GetFirstRelayServerAddress(
+ServerAddresses PortConfiguration::GetRelayServerAddresses(
RelayType turn_type, ProtocolType type) const {
+ ServerAddresses servers;
for (size_t i = 0; i < relays.size(); ++i) {
if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
- return relays[i].ports.front().address;
+ servers.insert(relays[i].ports.front().address);
}
}
- return talk_base::SocketAddress();
+ return servers;
}
} // namespace cricket
diff --git a/p2p/client/basicportallocator.h b/p2p/client/basicportallocator.h
index 8a60c42..d424772 100644
--- a/p2p/client/basicportallocator.h
+++ b/p2p/client/basicportallocator.h
@@ -31,12 +31,12 @@
#include <string>
#include <vector>
-#include "talk/base/messagequeue.h"
-#include "talk/base/network.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/port.h"
#include "talk/p2p/base/portallocator.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -54,36 +54,37 @@
typedef std::vector<ProtocolAddress> PortList;
struct RelayServerConfig {
- RelayServerConfig(RelayType type) : type(type) {}
+ RelayServerConfig(RelayType type) : type(type), priority(0) {}
RelayType type;
PortList ports;
RelayCredentials credentials;
+ int priority;
};
class BasicPortAllocator : public PortAllocator {
public:
- BasicPortAllocator(talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory);
- explicit BasicPortAllocator(talk_base::NetworkManager* network_manager);
- BasicPortAllocator(talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory,
- const talk_base::SocketAddress& stun_server);
- BasicPortAllocator(talk_base::NetworkManager* network_manager,
- const talk_base::SocketAddress& stun_server,
- const talk_base::SocketAddress& relay_server_udp,
- const talk_base::SocketAddress& relay_server_tcp,
- const talk_base::SocketAddress& relay_server_ssl);
+ BasicPortAllocator(rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory);
+ explicit BasicPortAllocator(rtc::NetworkManager* network_manager);
+ BasicPortAllocator(rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory,
+ const ServerAddresses& stun_servers);
+ BasicPortAllocator(rtc::NetworkManager* network_manager,
+ const ServerAddresses& stun_servers,
+ const rtc::SocketAddress& relay_server_udp,
+ const rtc::SocketAddress& relay_server_tcp,
+ const rtc::SocketAddress& relay_server_ssl);
virtual ~BasicPortAllocator();
- talk_base::NetworkManager* network_manager() { return network_manager_; }
+ rtc::NetworkManager* network_manager() { return network_manager_; }
// If socket_factory() is set to NULL each PortAllocatorSession
// creates its own socket factory.
- talk_base::PacketSocketFactory* socket_factory() { return socket_factory_; }
+ rtc::PacketSocketFactory* socket_factory() { return socket_factory_; }
- const talk_base::SocketAddress& stun_address() const {
- return stun_address_;
+ const ServerAddresses& stun_servers() const {
+ return stun_servers_;
}
const std::vector<RelayServerConfig>& relays() const {
@@ -102,9 +103,9 @@
private:
void Construct();
- talk_base::NetworkManager* network_manager_;
- talk_base::PacketSocketFactory* socket_factory_;
- const talk_base::SocketAddress stun_address_;
+ rtc::NetworkManager* network_manager_;
+ rtc::PacketSocketFactory* socket_factory_;
+ const ServerAddresses stun_servers_;
std::vector<RelayServerConfig> relays_;
bool allow_tcp_listen_;
};
@@ -113,7 +114,7 @@
class AllocationSequence;
class BasicPortAllocatorSession : public PortAllocatorSession,
- public talk_base::MessageHandler {
+ public rtc::MessageHandler {
public:
BasicPortAllocatorSession(BasicPortAllocator* allocator,
const std::string& content_name,
@@ -123,8 +124,8 @@
~BasicPortAllocatorSession();
virtual BasicPortAllocator* allocator() { return allocator_; }
- talk_base::Thread* network_thread() { return network_thread_; }
- talk_base::PacketSocketFactory* socket_factory() { return socket_factory_; }
+ rtc::Thread* network_thread() { return network_thread_; }
+ rtc::PacketSocketFactory* socket_factory() { return socket_factory_; }
virtual void StartGettingPorts();
virtual void StopGettingPorts();
@@ -139,7 +140,7 @@
virtual void ConfigReady(PortConfiguration* config);
// MessageHandler. Can be overriden if message IDs do not conflict.
- virtual void OnMessage(talk_base::Message *message);
+ virtual void OnMessage(rtc::Message *message);
private:
class PortData {
@@ -159,7 +160,6 @@
void set_ready() { ASSERT(state_ == STATE_INIT); state_ = STATE_READY; }
void set_complete() {
- ASSERT(state_ == STATE_READY);
state_ = STATE_COMPLETE;
}
void set_error() {
@@ -186,7 +186,7 @@
void DoAllocate();
void OnNetworksChanged();
void OnAllocationSequenceObjectsCreated();
- void DisableEquivalentPhases(talk_base::Network* network,
+ void DisableEquivalentPhases(rtc::Network* network,
PortConfiguration* config, uint32* flags);
void AddAllocatedPort(Port* port, AllocationSequence* seq,
bool prepare_address);
@@ -200,10 +200,12 @@
void OnPortAllocationComplete(AllocationSequence* seq);
PortData* FindPort(Port* port);
+ bool CheckCandidateFilter(const Candidate& c);
+
BasicPortAllocator* allocator_;
- talk_base::Thread* network_thread_;
- talk_base::scoped_ptr<talk_base::PacketSocketFactory> owned_socket_factory_;
- talk_base::PacketSocketFactory* socket_factory_;
+ rtc::Thread* network_thread_;
+ rtc::scoped_ptr<rtc::PacketSocketFactory> owned_socket_factory_;
+ rtc::PacketSocketFactory* socket_factory_;
bool allocation_started_;
bool network_manager_started_;
bool running_; // set when StartGetAllPorts is called
@@ -216,18 +218,28 @@
};
// Records configuration information useful in creating ports.
-struct PortConfiguration : public talk_base::MessageData {
- talk_base::SocketAddress stun_address;
+struct PortConfiguration : public rtc::MessageData {
+ // TODO(jiayl): remove |stun_address| when Chrome is updated.
+ rtc::SocketAddress stun_address;
+ ServerAddresses stun_servers;
std::string username;
std::string password;
typedef std::vector<RelayServerConfig> RelayList;
RelayList relays;
- PortConfiguration(const talk_base::SocketAddress& stun_address,
+ // TODO(jiayl): remove this ctor when Chrome is updated.
+ PortConfiguration(const rtc::SocketAddress& stun_address,
const std::string& username,
const std::string& password);
+ PortConfiguration(const ServerAddresses& stun_servers,
+ const std::string& username,
+ const std::string& password);
+
+ // TODO(jiayl): remove when |stun_address| is removed.
+ ServerAddresses StunServers();
+
// Adds another relay server, with the given ports and modifier, to the list.
void AddRelay(const RelayServerConfig& config);
@@ -235,9 +247,9 @@
bool SupportsProtocol(const RelayServerConfig& relay,
ProtocolType type) const;
bool SupportsProtocol(RelayType turn_type, ProtocolType type) const;
- // Helper method returns the first server address for the matching
- // RelayType and Protocol type.
- talk_base::SocketAddress GetFirstRelayServerAddress(
+ // Helper method returns the server addresses for the matching RelayType and
+ // Protocol type.
+ ServerAddresses GetRelayServerAddresses(
RelayType turn_type, ProtocolType type) const;
};
diff --git a/p2p/client/connectivitychecker.cc b/p2p/client/connectivitychecker.cc
index 1b59943..723c5a1 100644
--- a/p2p/client/connectivitychecker.cc
+++ b/p2p/client/connectivitychecker.cc
@@ -1,24 +1,48 @@
-// Copyright 2011 Google Inc. All Rights Reserved.
-
+/*
+ * libjingle
+ * Copyright 2011, Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
#include <string>
#include "talk/p2p/client/connectivitychecker.h"
-#include "talk/base/asynchttprequest.h"
-#include "talk/base/autodetectproxy.h"
-#include "talk/base/helpers.h"
-#include "talk/base/httpcommon.h"
-#include "talk/base/httpcommon-inl.h"
-#include "talk/base/logging.h"
-#include "talk/base/proxydetect.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/candidate.h"
-#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/common.h"
+#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/port.h"
#include "talk/p2p/base/relayport.h"
#include "talk/p2p/base/stunport.h"
+#include "webrtc/base/asynchttprequest.h"
+#include "webrtc/base/autodetectproxy.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/httpcommon-inl.h"
+#include "webrtc/base/httpcommon.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/proxydetect.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -37,7 +61,7 @@
class TestHttpPortAllocator : public HttpPortAllocator {
public:
- TestHttpPortAllocator(talk_base::NetworkManager* network_manager,
+ TestHttpPortAllocator(rtc::NetworkManager* network_manager,
const std::string& user_agent,
const std::string& relay_token) :
HttpPortAllocator(network_manager, user_agent) {
@@ -61,9 +85,9 @@
}
void TestHttpPortAllocatorSession::OnRequestDone(
- talk_base::SignalThread* data) {
- talk_base::AsyncHttpRequest* request =
- static_cast<talk_base::AsyncHttpRequest*>(data);
+ rtc::SignalThread* data) {
+ rtc::AsyncHttpRequest* request =
+ static_cast<rtc::AsyncHttpRequest*>(data);
// Tell the checker that the request is complete.
SignalRequestDone(request);
@@ -73,7 +97,7 @@
}
ConnectivityChecker::ConnectivityChecker(
- talk_base::Thread* worker,
+ rtc::Thread* worker,
const std::string& jid,
const std::string& session_id,
const std::string& user_agent,
@@ -115,13 +139,13 @@
}
void ConnectivityChecker::Start() {
- main_ = talk_base::Thread::Current();
+ main_ = rtc::Thread::Current();
worker_->Post(this, MSG_START);
started_ = true;
}
void ConnectivityChecker::CleanUp() {
- ASSERT(worker_ == talk_base::Thread::Current());
+ ASSERT(worker_ == rtc::Thread::Current());
if (proxy_detect_) {
proxy_detect_->Release();
proxy_detect_ = NULL;
@@ -137,14 +161,14 @@
ports_.clear();
}
-bool ConnectivityChecker::AddNic(const talk_base::IPAddress& ip,
- const talk_base::SocketAddress& proxy_addr) {
+bool ConnectivityChecker::AddNic(const rtc::IPAddress& ip,
+ const rtc::SocketAddress& proxy_addr) {
NicMap::iterator i = nics_.find(NicId(ip, proxy_addr));
if (i != nics_.end()) {
// Already have it.
return false;
}
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
NicInfo info;
info.ip = ip;
info.proxy_info = GetProxyInfo();
@@ -153,13 +177,13 @@
return true;
}
-void ConnectivityChecker::SetProxyInfo(const talk_base::ProxyInfo& proxy_info) {
+void ConnectivityChecker::SetProxyInfo(const rtc::ProxyInfo& proxy_info) {
port_allocator_->set_proxy(user_agent_, proxy_info);
AllocatePorts();
}
-talk_base::ProxyInfo ConnectivityChecker::GetProxyInfo() const {
- talk_base::ProxyInfo proxy_info;
+rtc::ProxyInfo ConnectivityChecker::GetProxyInfo() const {
+ rtc::ProxyInfo proxy_info;
if (proxy_detect_) {
proxy_info = proxy_detect_->proxy();
}
@@ -172,10 +196,10 @@
network_manager_->StartUpdating();
}
-void ConnectivityChecker::OnMessage(talk_base::Message *msg) {
+void ConnectivityChecker::OnMessage(rtc::Message *msg) {
switch (msg->message_id) {
case MSG_START:
- ASSERT(worker_ == talk_base::Thread::Current());
+ ASSERT(worker_ == rtc::Thread::Current());
worker_->PostDelayed(timeout_ms_, this, MSG_TIMEOUT);
CheckNetworks();
break;
@@ -188,7 +212,7 @@
main_->Post(this, MSG_SIGNAL_RESULTS);
break;
case MSG_SIGNAL_RESULTS:
- ASSERT(main_ == talk_base::Thread::Current());
+ ASSERT(main_ == rtc::Thread::Current());
SignalCheckDone(this);
break;
default:
@@ -196,32 +220,37 @@
}
}
-void ConnectivityChecker::OnProxyDetect(talk_base::SignalThread* thread) {
- ASSERT(worker_ == talk_base::Thread::Current());
- if (proxy_detect_->proxy().type != talk_base::PROXY_NONE) {
+void ConnectivityChecker::OnProxyDetect(rtc::SignalThread* thread) {
+ ASSERT(worker_ == rtc::Thread::Current());
+ if (proxy_detect_->proxy().type != rtc::PROXY_NONE) {
SetProxyInfo(proxy_detect_->proxy());
}
}
-void ConnectivityChecker::OnRequestDone(talk_base::AsyncHttpRequest* request) {
- ASSERT(worker_ == talk_base::Thread::Current());
+void ConnectivityChecker::OnRequestDone(rtc::AsyncHttpRequest* request) {
+ ASSERT(worker_ == rtc::Thread::Current());
// Since we don't know what nic were actually used for the http request,
// for now, just use the first one.
- std::vector<talk_base::Network*> networks;
+ std::vector<rtc::Network*> networks;
network_manager_->GetNetworks(&networks);
if (networks.empty()) {
LOG(LS_ERROR) << "No networks while registering http start.";
return;
}
- talk_base::ProxyInfo proxy_info = request->proxy();
- NicMap::iterator i = nics_.find(NicId(networks[0]->ip(), proxy_info.address));
+ rtc::ProxyInfo proxy_info = request->proxy();
+ NicMap::iterator i =
+#ifdef USE_WEBRTC_DEV_BRANCH
+ nics_.find(NicId(networks[0]->GetBestIP(), proxy_info.address));
+#else // USE_WEBRTC_DEV_BRANCH
+ nics_.find(NicId(networks[0]->ip(), proxy_info.address));
+#endif // USE_WEBRTC_DEV_BRANCH
if (i != nics_.end()) {
int port = request->port();
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
NicInfo* nic_info = &i->second;
- if (port == talk_base::HTTP_DEFAULT_PORT) {
+ if (port == rtc::HTTP_DEFAULT_PORT) {
nic_info->http.rtt = now - nic_info->http.start_time_ms;
- } else if (port == talk_base::HTTP_SECURE_PORT) {
+ } else if (port == rtc::HTTP_SECURE_PORT) {
nic_info->https.rtt = now - nic_info->https.start_time_ms;
} else {
LOG(LS_ERROR) << "Got response with unknown port: " << port;
@@ -233,8 +262,8 @@
void ConnectivityChecker::OnConfigReady(
const std::string& username, const std::string& password,
- const PortConfiguration* config, const talk_base::ProxyInfo& proxy_info) {
- ASSERT(worker_ == talk_base::Thread::Current());
+ const PortConfiguration* config, const rtc::ProxyInfo& proxy_info) {
+ ASSERT(worker_ == rtc::Thread::Current());
// Since we send requests on both HTTP and HTTPS we will get two
// configs per nic. Results from the second will overwrite the
@@ -244,10 +273,14 @@
}
void ConnectivityChecker::OnRelayPortComplete(Port* port) {
- ASSERT(worker_ == talk_base::Thread::Current());
+ ASSERT(worker_ == rtc::Thread::Current());
RelayPort* relay_port = reinterpret_cast<RelayPort*>(port);
const ProtocolAddress* address = relay_port->ServerAddress(0);
- talk_base::IPAddress ip = port->Network()->ip();
+#ifdef USE_WEBRTC_DEV_BRANCH
+ rtc::IPAddress ip = port->Network()->GetBestIP();
+#else // USE_WEBRTC_DEV_BRANCH
+ rtc::IPAddress ip = port->Network()->ip();
+#endif // USE_WEBRTC_DEV_BRANCH
NicMap::iterator i = nics_.find(NicId(ip, port->proxy().address));
if (i != nics_.end()) {
// We have it already, add the new information.
@@ -269,7 +302,7 @@
}
if (connect_info) {
connect_info->rtt =
- talk_base::TimeSince(connect_info->start_time_ms);
+ rtc::TimeSince(connect_info->start_time_ms);
}
}
} else {
@@ -278,17 +311,23 @@
}
void ConnectivityChecker::OnStunPortComplete(Port* port) {
- ASSERT(worker_ == talk_base::Thread::Current());
+ ASSERT(worker_ == rtc::Thread::Current());
const std::vector<Candidate> candidates = port->Candidates();
Candidate c = candidates[0];
- talk_base::IPAddress ip = port->Network()->ip();
+#ifdef USE_WEBRTC_DEV_BRANCH
+ rtc::IPAddress ip = port->Network()->GetBestIP();
+#else // USE_WEBRTC_DEV_BRANCH
+ rtc::IPAddress ip = port->Network()->ip();
+#endif // USE_WEBRTC_DEV_BRANCH
NicMap::iterator i = nics_.find(NicId(ip, port->proxy().address));
if (i != nics_.end()) {
// We have it already, add the new information.
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
NicInfo* nic_info = &i->second;
nic_info->external_address = c.address();
- nic_info->stun_server_address = static_cast<StunPort*>(port)->server_addr();
+
+ nic_info->stun_server_addresses =
+ static_cast<StunPort*>(port)->server_addresses();
nic_info->stun.rtt = now - nic_info->stun.start_time_ms;
} else {
LOG(LS_ERROR) << "Got stun address for non-existing nic";
@@ -296,25 +335,31 @@
}
void ConnectivityChecker::OnStunPortError(Port* port) {
- ASSERT(worker_ == talk_base::Thread::Current());
+ ASSERT(worker_ == rtc::Thread::Current());
LOG(LS_ERROR) << "Stun address error.";
- talk_base::IPAddress ip = port->Network()->ip();
+#ifdef USE_WEBRTC_DEV_BRANCH
+ rtc::IPAddress ip = port->Network()->GetBestIP();
+#else // USE_WEBRTC_DEV_BRANCH
+ rtc::IPAddress ip = port->Network()->ip();
+#endif // USE_WEBRTC_DEV_BRANCH
NicMap::iterator i = nics_.find(NicId(ip, port->proxy().address));
if (i != nics_.end()) {
// We have it already, add the new information.
NicInfo* nic_info = &i->second;
- nic_info->stun_server_address = static_cast<StunPort*>(port)->server_addr();
+
+ nic_info->stun_server_addresses =
+ static_cast<StunPort*>(port)->server_addresses();
}
}
void ConnectivityChecker::OnRelayPortError(Port* port) {
- ASSERT(worker_ == talk_base::Thread::Current());
+ ASSERT(worker_ == rtc::Thread::Current());
LOG(LS_ERROR) << "Relay address error.";
}
void ConnectivityChecker::OnNetworksChanged() {
- ASSERT(worker_ == talk_base::Thread::Current());
- std::vector<talk_base::Network*> networks;
+ ASSERT(worker_ == rtc::Thread::Current());
+ std::vector<rtc::Network*> networks;
network_manager_->GetNetworks(&networks);
if (networks.empty()) {
LOG(LS_ERROR) << "Machine has no networks; nothing to do";
@@ -324,7 +369,7 @@
}
HttpPortAllocator* ConnectivityChecker::CreatePortAllocator(
- talk_base::NetworkManager* network_manager,
+ rtc::NetworkManager* network_manager,
const std::string& user_agent,
const std::string& relay_token) {
return new TestHttpPortAllocator(network_manager, user_agent, relay_token);
@@ -332,27 +377,44 @@
StunPort* ConnectivityChecker::CreateStunPort(
const std::string& username, const std::string& password,
- const PortConfiguration* config, talk_base::Network* network) {
- return StunPort::Create(worker_, socket_factory_.get(),
- network, network->ip(), 0, 0,
- username, password, config->stun_address);
+ const PortConfiguration* config, rtc::Network* network) {
+ return StunPort::Create(worker_,
+ socket_factory_.get(),
+ network,
+#ifdef USE_WEBRTC_DEV_BRANCH
+ network->GetBestIP(),
+#else // USE_WEBRTC_DEV_BRANCH
+ network->ip(),
+#endif // USE_WEBRTC_DEV_BRANCH
+ 0,
+ 0,
+ username,
+ password,
+ config->stun_servers);
}
RelayPort* ConnectivityChecker::CreateRelayPort(
const std::string& username, const std::string& password,
- const PortConfiguration* config, talk_base::Network* network) {
- return RelayPort::Create(worker_, socket_factory_.get(),
- network, network->ip(),
+ const PortConfiguration* config, rtc::Network* network) {
+ return RelayPort::Create(worker_,
+ socket_factory_.get(),
+ network,
+#ifdef USE_WEBRTC_DEV_BRANCH
+ network->GetBestIP(),
+#else // USE_WEBRTC_DEV_BRANCH
+ network->ip(),
+#endif // USE_WEBRTC_DEV_BRANCH
port_allocator_->min_port(),
port_allocator_->max_port(),
- username, password);
+ username,
+ password);
}
void ConnectivityChecker::CreateRelayPorts(
const std::string& username, const std::string& password,
- const PortConfiguration* config, const talk_base::ProxyInfo& proxy_info) {
+ const PortConfiguration* config, const rtc::ProxyInfo& proxy_info) {
PortConfiguration::RelayList::const_iterator relay;
- std::vector<talk_base::Network*> networks;
+ std::vector<rtc::Network*> networks;
network_manager_->GetNetworks(&networks);
if (networks.empty()) {
LOG(LS_ERROR) << "Machine has no networks; no relay ports created.";
@@ -361,13 +423,17 @@
for (relay = config->relays.begin();
relay != config->relays.end(); ++relay) {
for (uint32 i = 0; i < networks.size(); ++i) {
- NicMap::iterator iter = nics_.find(NicId(networks[i]->ip(),
- proxy_info.address));
+ NicMap::iterator iter =
+#ifdef USE_WEBRTC_DEV_BRANCH
+ nics_.find(NicId(networks[i]->GetBestIP(), proxy_info.address));
+#else // USE_WEBRTC_DEV_BRANCH
+ nics_.find(NicId(networks[i]->ip(), proxy_info.address));
+#endif // USE_WEBRTC_DEV_BRANCH
if (iter != nics_.end()) {
// TODO: Now setting the same start time for all protocols.
// This might affect accuracy, but since we are mainly looking for
// connect failures or number that stick out, this is good enough.
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
NicInfo* nic_info = &iter->second;
nic_info->udp.start_time_ms = now;
nic_info->tcp.start_time_ms = now;
@@ -405,19 +471,25 @@
}
void ConnectivityChecker::AllocatePorts() {
- const std::string username = talk_base::CreateRandomString(ICE_UFRAG_LENGTH);
- const std::string password = talk_base::CreateRandomString(ICE_PWD_LENGTH);
- PortConfiguration config(stun_address_, username, password);
- std::vector<talk_base::Network*> networks;
+ const std::string username = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
+ const std::string password = rtc::CreateRandomString(ICE_PWD_LENGTH);
+ ServerAddresses stun_servers;
+ stun_servers.insert(stun_address_);
+ PortConfiguration config(stun_servers, username, password);
+ std::vector<rtc::Network*> networks;
network_manager_->GetNetworks(&networks);
if (networks.empty()) {
LOG(LS_ERROR) << "Machine has no networks; no ports will be allocated";
return;
}
- talk_base::ProxyInfo proxy_info = GetProxyInfo();
+ rtc::ProxyInfo proxy_info = GetProxyInfo();
bool allocate_relay_ports = false;
for (uint32 i = 0; i < networks.size(); ++i) {
+#ifdef USE_WEBRTC_DEV_BRANCH
+ if (AddNic(networks[i]->GetBestIP(), proxy_info.address)) {
+#else // USE_WEBRTC_DEV_BRANCH
if (AddNic(networks[i]->ip(), proxy_info.address)) {
+#endif // USE_WEBRTC_DEV_BRANCH
Port* port = CreateStunPort(username, password, &config, networks[i]);
if (port) {
@@ -447,9 +519,9 @@
void ConnectivityChecker::InitiateProxyDetection() {
// Only start if we haven't been started before.
if (!proxy_detect_) {
- proxy_detect_ = new talk_base::AutoDetectProxy(user_agent_);
- talk_base::Url<char> host_url("/", "relay.google.com",
- talk_base::HTTP_DEFAULT_PORT);
+ proxy_detect_ = new rtc::AutoDetectProxy(user_agent_);
+ rtc::Url<char> host_url("/", "relay.google.com",
+ rtc::HTTP_DEFAULT_PORT);
host_url.set_secure(true);
proxy_detect_->set_server_url(host_url.url());
proxy_detect_->SignalWorkDone.connect(
@@ -465,8 +537,8 @@
port_allocator_->CreateSessionInternal(
"connectivity checker test content",
ICE_CANDIDATE_COMPONENT_RTP,
- talk_base::CreateRandomString(ICE_UFRAG_LENGTH),
- talk_base::CreateRandomString(ICE_PWD_LENGTH)));
+ rtc::CreateRandomString(ICE_UFRAG_LENGTH),
+ rtc::CreateRandomString(ICE_PWD_LENGTH)));
allocator_session->set_proxy(port_allocator_->proxy());
allocator_session->SignalConfigReady.connect(
this, &ConnectivityChecker::OnConfigReady);
@@ -474,12 +546,12 @@
this, &ConnectivityChecker::OnRequestDone);
// Try both http and https.
- RegisterHttpStart(talk_base::HTTP_SECURE_PORT);
+ RegisterHttpStart(rtc::HTTP_SECURE_PORT);
allocator_session->SendSessionRequest("relay.l.google.com",
- talk_base::HTTP_SECURE_PORT);
- RegisterHttpStart(talk_base::HTTP_DEFAULT_PORT);
+ rtc::HTTP_SECURE_PORT);
+ RegisterHttpStart(rtc::HTTP_DEFAULT_PORT);
allocator_session->SendSessionRequest("relay.l.google.com",
- talk_base::HTTP_DEFAULT_PORT);
+ rtc::HTTP_DEFAULT_PORT);
sessions_.push_back(allocator_session);
}
@@ -487,20 +559,25 @@
void ConnectivityChecker::RegisterHttpStart(int port) {
// Since we don't know what nic were actually used for the http request,
// for now, just use the first one.
- std::vector<talk_base::Network*> networks;
+ std::vector<rtc::Network*> networks;
network_manager_->GetNetworks(&networks);
if (networks.empty()) {
LOG(LS_ERROR) << "No networks while registering http start.";
return;
}
- talk_base::ProxyInfo proxy_info = GetProxyInfo();
- NicMap::iterator i = nics_.find(NicId(networks[0]->ip(), proxy_info.address));
+ rtc::ProxyInfo proxy_info = GetProxyInfo();
+ NicMap::iterator i =
+#ifdef USE_WEBRTC_DEV_BRANCH
+ nics_.find(NicId(networks[0]->GetBestIP(), proxy_info.address));
+#else // USE_WEBRTC_DEV_BRANCH
+ nics_.find(NicId(networks[0]->ip(), proxy_info.address));
+#endif // USE_WEBRTC_DEV_BRANCH
if (i != nics_.end()) {
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
NicInfo* nic_info = &i->second;
- if (port == talk_base::HTTP_DEFAULT_PORT) {
+ if (port == rtc::HTTP_DEFAULT_PORT) {
nic_info->http.start_time_ms = now;
- } else if (port == talk_base::HTTP_SECURE_PORT) {
+ } else if (port == rtc::HTTP_SECURE_PORT) {
nic_info->https.start_time_ms = now;
} else {
LOG(LS_ERROR) << "Registering start time for unknown port: " << port;
@@ -510,4 +587,4 @@
}
}
-} // namespace talk_base
+} // namespace rtc
diff --git a/p2p/client/connectivitychecker.h b/p2p/client/connectivitychecker.h
index 95b736d..d4cda1e 100644
--- a/p2p/client/connectivitychecker.h
+++ b/p2p/client/connectivitychecker.h
@@ -7,17 +7,17 @@
#include <map>
#include <string>
-#include "talk/base/network.h"
-#include "talk/base/basictypes.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/proxyinfo.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/socketaddress.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/client/httpportallocator.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/proxyinfo.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/socketaddress.h"
-namespace talk_base {
+namespace rtc {
class AsyncHttpRequest;
class AutoDetectProxy;
class BasicPacketSocketFactory;
@@ -60,13 +60,13 @@
// Identifier for a network interface and proxy address pair.
struct NicId {
- NicId(const talk_base::IPAddress& ip,
- const talk_base::SocketAddress& proxy_address)
+ NicId(const rtc::IPAddress& ip,
+ const rtc::SocketAddress& proxy_address)
: ip(ip),
proxy_address(proxy_address) {
}
- talk_base::IPAddress ip;
- talk_base::SocketAddress proxy_address;
+ rtc::IPAddress ip;
+ rtc::SocketAddress proxy_address;
};
// Comparator implementation identifying unique network interface and
@@ -93,11 +93,11 @@
// Contains information of a network interface and proxy address pair.
struct NicInfo {
NicInfo() {}
- talk_base::IPAddress ip;
- talk_base::ProxyInfo proxy_info;
- talk_base::SocketAddress external_address;
- talk_base::SocketAddress stun_server_address;
- talk_base::SocketAddress media_server_address;
+ rtc::IPAddress ip;
+ rtc::ProxyInfo proxy_info;
+ rtc::SocketAddress external_address;
+ ServerAddresses stun_server_addresses;
+ rtc::SocketAddress media_server_address;
ConnectInfo stun;
ConnectInfo http;
ConnectInfo https;
@@ -119,7 +119,7 @@
int component,
const std::string& ice_ufrag,
const std::string& ice_pwd,
- const std::vector<talk_base::SocketAddress>& stun_hosts,
+ const std::vector<rtc::SocketAddress>& stun_hosts,
const std::vector<std::string>& relay_hosts,
const std::string& relay_token,
const std::string& user_agent)
@@ -127,30 +127,30 @@
allocator, content_name, component, ice_ufrag, ice_pwd, stun_hosts,
relay_hosts, relay_token, user_agent) {
}
- void set_proxy(const talk_base::ProxyInfo& proxy) {
+ void set_proxy(const rtc::ProxyInfo& proxy) {
proxy_ = proxy;
}
void ConfigReady(PortConfiguration* config);
- void OnRequestDone(talk_base::SignalThread* data);
+ void OnRequestDone(rtc::SignalThread* data);
sigslot::signal4<const std::string&, const std::string&,
const PortConfiguration*,
- const talk_base::ProxyInfo&> SignalConfigReady;
- sigslot::signal1<talk_base::AsyncHttpRequest*> SignalRequestDone;
+ const rtc::ProxyInfo&> SignalConfigReady;
+ sigslot::signal1<rtc::AsyncHttpRequest*> SignalRequestDone;
private:
- talk_base::ProxyInfo proxy_;
+ rtc::ProxyInfo proxy_;
};
// Runs a request/response check on all network interface and proxy
// address combinations. The check is considered done either when all
// checks has been successful or when the check times out.
class ConnectivityChecker
- : public talk_base::MessageHandler, public sigslot::has_slots<> {
+ : public rtc::MessageHandler, public sigslot::has_slots<> {
public:
- ConnectivityChecker(talk_base::Thread* worker,
+ ConnectivityChecker(rtc::Thread* worker,
const std::string& jid,
const std::string& session_id,
const std::string& user_agent,
@@ -163,7 +163,7 @@
virtual void Start();
// MessageHandler implementation.
- virtual void OnMessage(talk_base::Message *msg);
+ virtual void OnMessage(rtc::Message *msg);
// Instruct checker to stop and wait until that's done.
// Virtual for gMock.
@@ -179,7 +179,7 @@
timeout_ms_ = timeout;
}
- void set_stun_address(const talk_base::SocketAddress& stun_address) {
+ void set_stun_address(const rtc::SocketAddress& stun_address) {
stun_address_ = stun_address;
}
@@ -200,72 +200,72 @@
protected:
// Can be overridden for test.
- virtual talk_base::NetworkManager* CreateNetworkManager() {
- return new talk_base::BasicNetworkManager();
+ virtual rtc::NetworkManager* CreateNetworkManager() {
+ return new rtc::BasicNetworkManager();
}
- virtual talk_base::BasicPacketSocketFactory* CreateSocketFactory(
- talk_base::Thread* thread) {
- return new talk_base::BasicPacketSocketFactory(thread);
+ virtual rtc::BasicPacketSocketFactory* CreateSocketFactory(
+ rtc::Thread* thread) {
+ return new rtc::BasicPacketSocketFactory(thread);
}
virtual HttpPortAllocator* CreatePortAllocator(
- talk_base::NetworkManager* network_manager,
+ rtc::NetworkManager* network_manager,
const std::string& user_agent,
const std::string& relay_token);
virtual StunPort* CreateStunPort(
const std::string& username, const std::string& password,
- const PortConfiguration* config, talk_base::Network* network);
+ const PortConfiguration* config, rtc::Network* network);
virtual RelayPort* CreateRelayPort(
const std::string& username, const std::string& password,
- const PortConfiguration* config, talk_base::Network* network);
+ const PortConfiguration* config, rtc::Network* network);
virtual void InitiateProxyDetection();
- virtual void SetProxyInfo(const talk_base::ProxyInfo& info);
- virtual talk_base::ProxyInfo GetProxyInfo() const;
+ virtual void SetProxyInfo(const rtc::ProxyInfo& info);
+ virtual rtc::ProxyInfo GetProxyInfo() const;
- talk_base::Thread* worker() {
+ rtc::Thread* worker() {
return worker_;
}
private:
- bool AddNic(const talk_base::IPAddress& ip,
- const talk_base::SocketAddress& proxy_address);
+ bool AddNic(const rtc::IPAddress& ip,
+ const rtc::SocketAddress& proxy_address);
void AllocatePorts();
void AllocateRelayPorts();
void CheckNetworks();
void CreateRelayPorts(
const std::string& username, const std::string& password,
- const PortConfiguration* config, const talk_base::ProxyInfo& proxy_info);
+ const PortConfiguration* config, const rtc::ProxyInfo& proxy_info);
// Must be called by the worker thread.
void CleanUp();
- void OnRequestDone(talk_base::AsyncHttpRequest* request);
+ void OnRequestDone(rtc::AsyncHttpRequest* request);
void OnRelayPortComplete(Port* port);
void OnStunPortComplete(Port* port);
void OnRelayPortError(Port* port);
void OnStunPortError(Port* port);
void OnNetworksChanged();
- void OnProxyDetect(talk_base::SignalThread* thread);
+ void OnProxyDetect(rtc::SignalThread* thread);
void OnConfigReady(
const std::string& username, const std::string& password,
- const PortConfiguration* config, const talk_base::ProxyInfo& proxy);
+ const PortConfiguration* config, const rtc::ProxyInfo& proxy);
void OnConfigWithProxyReady(const PortConfiguration*);
void RegisterHttpStart(int port);
- talk_base::Thread* worker_;
+ rtc::Thread* worker_;
std::string jid_;
std::string session_id_;
std::string user_agent_;
std::string relay_token_;
std::string connection_;
- talk_base::AutoDetectProxy* proxy_detect_;
- talk_base::scoped_ptr<talk_base::NetworkManager> network_manager_;
- talk_base::scoped_ptr<talk_base::BasicPacketSocketFactory> socket_factory_;
- talk_base::scoped_ptr<HttpPortAllocator> port_allocator_;
+ rtc::AutoDetectProxy* proxy_detect_;
+ rtc::scoped_ptr<rtc::NetworkManager> network_manager_;
+ rtc::scoped_ptr<rtc::BasicPacketSocketFactory> socket_factory_;
+ rtc::scoped_ptr<HttpPortAllocator> port_allocator_;
NicMap nics_;
std::vector<Port*> ports_;
std::vector<PortAllocatorSession*> sessions_;
uint32 timeout_ms_;
- talk_base::SocketAddress stun_address_;
- talk_base::Thread* main_;
+ rtc::SocketAddress stun_address_;
+ rtc::Thread* main_;
bool started_;
};
diff --git a/p2p/client/connectivitychecker_unittest.cc b/p2p/client/connectivitychecker_unittest.cc
index c62120b..187505a 100644
--- a/p2p/client/connectivitychecker_unittest.cc
+++ b/p2p/client/connectivitychecker_unittest.cc
@@ -1,28 +1,52 @@
-// Copyright 2011 Google Inc. All Rights Reserved.
-
+/*
+ * libjingle
+ * Copyright 2011, Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
#include <string>
-#include "talk/base/asynchttprequest.h"
-#include "talk/base/gunit.h"
-#include "talk/base/fakenetwork.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/socketaddress.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/relayport.h"
#include "talk/p2p/base/stunport.h"
#include "talk/p2p/client/connectivitychecker.h"
#include "talk/p2p/client/httpportallocator.h"
+#include "webrtc/base/asynchttprequest.h"
+#include "webrtc/base/fakenetwork.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/socketaddress.h"
namespace cricket {
-static const talk_base::SocketAddress kClientAddr1("11.11.11.11", 0);
-static const talk_base::SocketAddress kClientAddr2("22.22.22.22", 0);
-static const talk_base::SocketAddress kExternalAddr("33.33.33.33", 3333);
-static const talk_base::SocketAddress kStunAddr("44.44.44.44", 4444);
-static const talk_base::SocketAddress kRelayAddr("55.55.55.55", 5555);
-static const talk_base::SocketAddress kProxyAddr("66.66.66.66", 6666);
-static const talk_base::ProxyType kProxyType = talk_base::PROXY_HTTPS;
+static const rtc::SocketAddress kClientAddr1("11.11.11.11", 0);
+static const rtc::SocketAddress kClientAddr2("22.22.22.22", 0);
+static const rtc::SocketAddress kExternalAddr("33.33.33.33", 3333);
+static const rtc::SocketAddress kStunAddr("44.44.44.44", 4444);
+static const rtc::SocketAddress kRelayAddr("55.55.55.55", 5555);
+static const rtc::SocketAddress kProxyAddr("66.66.66.66", 6666);
+static const rtc::ProxyType kProxyType = rtc::PROXY_HTTPS;
static const char kRelayHost[] = "relay.google.com";
static const char kRelayToken[] =
"CAESFwoOb2phQGdvb2dsZS5jb20Q043h47MmGhBTB1rbfIXkhuarDCZe+xF6";
@@ -42,9 +66,9 @@
// Fake implementation to mock away real network usage.
class FakeRelayPort : public RelayPort {
public:
- FakeRelayPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network, const talk_base::IPAddress& ip,
+ FakeRelayPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network, const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username, const std::string& password)
: RelayPort(thread, factory, network, ip, min_port, max_port,
@@ -60,21 +84,21 @@
// Fake implementation to mock away real network usage.
class FakeStunPort : public StunPort {
public:
- FakeStunPort(talk_base::Thread* thread,
- talk_base::PacketSocketFactory* factory,
- talk_base::Network* network,
- const talk_base::IPAddress& ip,
+ FakeStunPort(rtc::Thread* thread,
+ rtc::PacketSocketFactory* factory,
+ rtc::Network* network,
+ const rtc::IPAddress& ip,
int min_port, int max_port,
const std::string& username, const std::string& password,
- const talk_base::SocketAddress& server_addr)
+ const ServerAddresses& server_addr)
: StunPort(thread, factory, network, ip, min_port, max_port,
username, password, server_addr) {
}
// Just set external address and signal that we are done.
virtual void PrepareAddress() {
- AddAddress(kExternalAddr, kExternalAddr, talk_base::SocketAddress(), "udp",
- STUN_PORT_TYPE, ICE_TYPE_PREFERENCE_SRFLX, true);
+ AddAddress(kExternalAddr, kExternalAddr, rtc::SocketAddress(), "udp", "",
+ STUN_PORT_TYPE, ICE_TYPE_PREFERENCE_SRFLX, 0, true);
SignalPortComplete(this);
}
};
@@ -88,7 +112,7 @@
const std::string& content_name,
int component,
const std::string& ice_ufrag, const std::string& ice_pwd,
- const std::vector<talk_base::SocketAddress>& stun_hosts,
+ const std::vector<rtc::SocketAddress>& stun_hosts,
const std::vector<std::string>& relay_hosts,
const std::string& relay_token,
const std::string& agent)
@@ -108,16 +132,16 @@
// Pass results to the real implementation.
void FakeReceiveSessionResponse(const std::string& host, int port) {
- talk_base::AsyncHttpRequest* response = CreateAsyncHttpResponse(port);
+ rtc::AsyncHttpRequest* response = CreateAsyncHttpResponse(port);
TestHttpPortAllocatorSession::OnRequestDone(response);
response->Destroy(true);
}
private:
// Helper method for creating a response to a relay session request.
- talk_base::AsyncHttpRequest* CreateAsyncHttpResponse(int port) {
- talk_base::AsyncHttpRequest* request =
- new talk_base::AsyncHttpRequest(kBrowserAgent);
+ rtc::AsyncHttpRequest* CreateAsyncHttpResponse(int port) {
+ rtc::AsyncHttpRequest* request =
+ new rtc::AsyncHttpRequest(kBrowserAgent);
std::stringstream ss;
ss << "username=" << kUserName << std::endl
<< "password=" << kPassword << std::endl
@@ -127,10 +151,10 @@
<< "relay.tcp_port=" << kRelayTcpPort << std::endl
<< "relay.ssltcp_port=" << kRelaySsltcpPort << std::endl;
request->response().document.reset(
- new talk_base::MemoryStream(ss.str().c_str()));
+ new rtc::MemoryStream(ss.str().c_str()));
request->response().set_success();
request->set_port(port);
- request->set_secure(port == talk_base::HTTP_SECURE_PORT);
+ request->set_secure(port == rtc::HTTP_SECURE_PORT);
return request;
}
};
@@ -138,7 +162,7 @@
// Fake implementation for creating fake http sessions.
class FakeHttpPortAllocator : public HttpPortAllocator {
public:
- FakeHttpPortAllocator(talk_base::NetworkManager* network_manager,
+ FakeHttpPortAllocator(rtc::NetworkManager* network_manager,
const std::string& user_agent)
: HttpPortAllocator(network_manager, user_agent) {
}
@@ -146,7 +170,7 @@
virtual PortAllocatorSession* CreateSessionInternal(
const std::string& content_name, int component,
const std::string& ice_ufrag, const std::string& ice_pwd) {
- std::vector<talk_base::SocketAddress> stun_hosts;
+ std::vector<rtc::SocketAddress> stun_hosts;
stun_hosts.push_back(kStunAddr);
std::vector<std::string> relay_hosts;
relay_hosts.push_back(kRelayHost);
@@ -164,7 +188,7 @@
class ConnectivityCheckerForTest : public ConnectivityChecker {
public:
- ConnectivityCheckerForTest(talk_base::Thread* worker,
+ ConnectivityCheckerForTest(rtc::Thread* worker,
const std::string& jid,
const std::string& session_id,
const std::string& user_agent,
@@ -179,7 +203,7 @@
proxy_initiated_(false) {
}
- talk_base::FakeNetworkManager* network_manager() const {
+ rtc::FakeNetworkManager* network_manager() const {
return network_manager_;
}
@@ -189,19 +213,19 @@
protected:
// Overridden methods for faking a real network.
- virtual talk_base::NetworkManager* CreateNetworkManager() {
- network_manager_ = new talk_base::FakeNetworkManager();
+ virtual rtc::NetworkManager* CreateNetworkManager() {
+ network_manager_ = new rtc::FakeNetworkManager();
return network_manager_;
}
- virtual talk_base::BasicPacketSocketFactory* CreateSocketFactory(
- talk_base::Thread* thread) {
+ virtual rtc::BasicPacketSocketFactory* CreateSocketFactory(
+ rtc::Thread* thread) {
// Create socket factory, for simplicity, let it run on the current thread.
socket_factory_ =
- new talk_base::BasicPacketSocketFactory(talk_base::Thread::Current());
+ new rtc::BasicPacketSocketFactory(rtc::Thread::Current());
return socket_factory_;
}
virtual HttpPortAllocator* CreatePortAllocator(
- talk_base::NetworkManager* network_manager,
+ rtc::NetworkManager* network_manager,
const std::string& user_agent,
const std::string& relay_token) {
fake_port_allocator_ =
@@ -210,20 +234,36 @@
}
virtual StunPort* CreateStunPort(
const std::string& username, const std::string& password,
- const PortConfiguration* config, talk_base::Network* network) {
- return new FakeStunPort(worker(), socket_factory_,
- network, network->ip(),
- kMinPort, kMaxPort,
- username, password,
- config->stun_address);
+ const PortConfiguration* config, rtc::Network* network) {
+ return new FakeStunPort(worker(),
+ socket_factory_,
+ network,
+#ifdef USE_WEBRTC_DEV_BRANCH
+ network->GetBestIP(),
+#else // USE_WEBRTC_DEV_BRANCH
+ network->ip(),
+#endif // USE_WEBRTC_DEV_BRANCH
+ kMinPort,
+ kMaxPort,
+ username,
+ password,
+ config->stun_servers);
}
virtual RelayPort* CreateRelayPort(
const std::string& username, const std::string& password,
- const PortConfiguration* config, talk_base::Network* network) {
- return new FakeRelayPort(worker(), socket_factory_,
- network, network->ip(),
- kMinPort, kMaxPort,
- username, password);
+ const PortConfiguration* config, rtc::Network* network) {
+ return new FakeRelayPort(worker(),
+ socket_factory_,
+ network,
+#ifdef USE_WEBRTC_DEV_BRANCH
+ network->GetBestIP(),
+#else // USE_WEBRTC_DEV_BRANCH
+ network->ip(),
+#endif // USE_WEBRTC_DEV_BRANCH
+ kMinPort,
+ kMaxPort,
+ username,
+ password);
}
virtual void InitiateProxyDetection() {
if (!proxy_initiated_) {
@@ -234,27 +274,28 @@
}
}
- virtual talk_base::ProxyInfo GetProxyInfo() const {
+ virtual rtc::ProxyInfo GetProxyInfo() const {
return proxy_info_;
}
private:
- talk_base::BasicPacketSocketFactory* socket_factory_;
+ rtc::BasicPacketSocketFactory* socket_factory_;
FakeHttpPortAllocator* fake_port_allocator_;
- talk_base::FakeNetworkManager* network_manager_;
- talk_base::ProxyInfo proxy_info_;
+ rtc::FakeNetworkManager* network_manager_;
+ rtc::ProxyInfo proxy_info_;
bool proxy_initiated_;
};
class ConnectivityCheckerTest : public testing::Test {
protected:
void VerifyNic(const NicInfo& info,
- const talk_base::SocketAddress& local_address) {
+ const rtc::SocketAddress& local_address) {
// Verify that the external address has been set.
EXPECT_EQ(kExternalAddr, info.external_address);
// Verify that the stun server address has been set.
- EXPECT_EQ(kStunAddr, info.stun_server_address);
+ EXPECT_EQ(1U, info.stun_server_addresses.size());
+ EXPECT_EQ(kStunAddr, *(info.stun_server_addresses.begin()));
// Verify that the media server address has been set. Don't care
// about port since it is different for different protocols.
@@ -282,7 +323,7 @@
// combinations of ip/proxy are created and that all protocols are
// tested on each combination.
TEST_F(ConnectivityCheckerTest, TestStart) {
- ConnectivityCheckerForTest connectivity_checker(talk_base::Thread::Current(),
+ ConnectivityCheckerForTest connectivity_checker(rtc::Thread::Current(),
kJid,
kSessionId,
kBrowserAgent,
@@ -294,7 +335,7 @@
connectivity_checker.network_manager()->AddInterface(kClientAddr2);
connectivity_checker.Start();
- talk_base::Thread::Current()->ProcessMessages(1000);
+ rtc::Thread::Current()->ProcessMessages(1000);
NicMap nics = connectivity_checker.GetResults();
@@ -303,7 +344,7 @@
EXPECT_EQ(4U, nics.size());
// First verify interfaces without proxy.
- talk_base::SocketAddress nilAddress;
+ rtc::SocketAddress nilAddress;
// First lookup the address of the first nic combined with no proxy.
NicMap::iterator i = nics.find(NicId(kClientAddr1.ipaddr(), nilAddress));
@@ -332,7 +373,7 @@
// Tests that nothing bad happens if thera are no network interfaces
// available to check.
TEST_F(ConnectivityCheckerTest, TestStartNoNetwork) {
- ConnectivityCheckerForTest connectivity_checker(talk_base::Thread::Current(),
+ ConnectivityCheckerForTest connectivity_checker(rtc::Thread::Current(),
kJid,
kSessionId,
kBrowserAgent,
@@ -340,7 +381,7 @@
kConnection);
connectivity_checker.Initialize();
connectivity_checker.Start();
- talk_base::Thread::Current()->ProcessMessages(1000);
+ rtc::Thread::Current()->ProcessMessages(1000);
NicMap nics = connectivity_checker.GetResults();
diff --git a/p2p/client/fakeportallocator.h b/p2p/client/fakeportallocator.h
index 5375e50..e1a04dd 100644
--- a/p2p/client/fakeportallocator.h
+++ b/p2p/client/fakeportallocator.h
@@ -1,17 +1,40 @@
-// Copyright 2010 Google Inc. All Rights Reserved,
-//
-// Author: Justin Uberti (juberti@google.com)
+/*
+ * libjingle
+ * Copyright 2010, Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
#ifndef TALK_P2P_CLIENT_FAKEPORTALLOCATOR_H_
#define TALK_P2P_CLIENT_FAKEPORTALLOCATOR_H_
#include <string>
-#include "talk/base/scoped_ptr.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/portallocator.h"
#include "talk/p2p/base/udpport.h"
+#include "webrtc/base/scoped_ptr.h"
-namespace talk_base {
+namespace rtc {
class SocketFactory;
class Thread;
}
@@ -20,8 +43,8 @@
class FakePortAllocatorSession : public PortAllocatorSession {
public:
- FakePortAllocatorSession(talk_base::Thread* worker_thread,
- talk_base::PacketSocketFactory* factory,
+ FakePortAllocatorSession(rtc::Thread* worker_thread,
+ rtc::PacketSocketFactory* factory,
const std::string& content_name,
int component,
const std::string& ice_ufrag,
@@ -31,18 +54,26 @@
worker_thread_(worker_thread),
factory_(factory),
network_("network", "unittest",
- talk_base::IPAddress(INADDR_LOOPBACK), 8),
+ rtc::IPAddress(INADDR_LOOPBACK), 8),
port_(), running_(false),
port_config_count_(0) {
- network_.AddIP(talk_base::IPAddress(INADDR_LOOPBACK));
+ network_.AddIP(rtc::IPAddress(INADDR_LOOPBACK));
}
virtual void StartGettingPorts() {
if (!port_) {
- port_.reset(cricket::UDPPort::Create(worker_thread_, factory_,
- &network_, network_.ip(), 0, 0,
- username(),
- password()));
+ port_.reset(cricket::UDPPort::Create(worker_thread_,
+ factory_,
+ &network_,
+#ifdef USE_WEBRTC_DEV_BRANCH
+ network_.GetBestIP(),
+#else // USE_WEBRTC_DEV_BRANCH
+ network_.ip(),
+#endif // USE_WEBRTC_DEV_BRANCH
+ 0,
+ 0,
+ username(),
+ password()));
AddPort(port_.get());
}
++port_config_count_;
@@ -67,21 +98,21 @@
}
private:
- talk_base::Thread* worker_thread_;
- talk_base::PacketSocketFactory* factory_;
- talk_base::Network network_;
- talk_base::scoped_ptr<cricket::Port> port_;
+ rtc::Thread* worker_thread_;
+ rtc::PacketSocketFactory* factory_;
+ rtc::Network network_;
+ rtc::scoped_ptr<cricket::Port> port_;
bool running_;
int port_config_count_;
};
class FakePortAllocator : public cricket::PortAllocator {
public:
- FakePortAllocator(talk_base::Thread* worker_thread,
- talk_base::PacketSocketFactory* factory)
+ FakePortAllocator(rtc::Thread* worker_thread,
+ rtc::PacketSocketFactory* factory)
: worker_thread_(worker_thread), factory_(factory) {
if (factory_ == NULL) {
- owned_factory_.reset(new talk_base::BasicPacketSocketFactory(
+ owned_factory_.reset(new rtc::BasicPacketSocketFactory(
worker_thread_));
factory_ = owned_factory_.get();
}
@@ -97,9 +128,9 @@
}
private:
- talk_base::Thread* worker_thread_;
- talk_base::PacketSocketFactory* factory_;
- talk_base::scoped_ptr<talk_base::BasicPacketSocketFactory> owned_factory_;
+ rtc::Thread* worker_thread_;
+ rtc::PacketSocketFactory* factory_;
+ rtc::scoped_ptr<rtc::BasicPacketSocketFactory> owned_factory_;
};
} // namespace cricket
diff --git a/p2p/client/httpportallocator.cc b/p2p/client/httpportallocator.cc
index b881d43..31c9b51 100644
--- a/p2p/client/httpportallocator.cc
+++ b/p2p/client/httpportallocator.cc
@@ -30,14 +30,14 @@
#include <algorithm>
#include <map>
-#include "talk/base/asynchttprequest.h"
-#include "talk/base/basicdefs.h"
-#include "talk/base/common.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/nethelpers.h"
-#include "talk/base/signalthread.h"
-#include "talk/base/stringencode.h"
+#include "webrtc/base/asynchttprequest.h"
+#include "webrtc/base/basicdefs.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/nethelpers.h"
+#include "webrtc/base/signalthread.h"
+#include "webrtc/base/stringencode.h"
namespace {
@@ -95,22 +95,22 @@
const char HttpPortAllocatorBase::kCreateSessionURL[] = "/create_session";
HttpPortAllocatorBase::HttpPortAllocatorBase(
- talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory,
+ rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory,
const std::string &user_agent)
: BasicPortAllocator(network_manager, socket_factory), agent_(user_agent) {
relay_hosts_.push_back("relay.google.com");
stun_hosts_.push_back(
- talk_base::SocketAddress("stun.l.google.com", 19302));
+ rtc::SocketAddress("stun.l.google.com", 19302));
}
HttpPortAllocatorBase::HttpPortAllocatorBase(
- talk_base::NetworkManager* network_manager,
+ rtc::NetworkManager* network_manager,
const std::string &user_agent)
: BasicPortAllocator(network_manager), agent_(user_agent) {
relay_hosts_.push_back("relay.google.com");
stun_hosts_.push_back(
- talk_base::SocketAddress("stun.l.google.com", 19302));
+ rtc::SocketAddress("stun.l.google.com", 19302));
}
HttpPortAllocatorBase::~HttpPortAllocatorBase() {
@@ -124,7 +124,7 @@
int component,
const std::string& ice_ufrag,
const std::string& ice_pwd,
- const std::vector<talk_base::SocketAddress>& stun_hosts,
+ const std::vector<rtc::SocketAddress>& stun_hosts,
const std::vector<std::string>& relay_hosts,
const std::string& relay_token,
const std::string& user_agent)
@@ -142,7 +142,13 @@
// but for now is done here and added to the initial config. Note any later
// configs will have unresolved stun ips and will be discarded by the
// AllocationSequence.
- PortConfiguration* config = new PortConfiguration(stun_hosts_[0],
+ ServerAddresses hosts;
+ for (std::vector<rtc::SocketAddress>::iterator it = stun_hosts_.begin();
+ it != stun_hosts_.end(); ++it) {
+ hosts.insert(*it);
+ }
+
+ PortConfiguration* config = new PortConfiguration(hosts,
username(),
password());
ConfigReady(config);
@@ -174,7 +180,7 @@
LOG(LS_WARNING) << "No relay auth token found.";
}
- SendSessionRequest(host, talk_base::HTTP_SECURE_PORT);
+ SendSessionRequest(host, rtc::HTTP_SECURE_PORT);
}
std::string HttpPortAllocatorSessionBase::GetSessionRequestUrl() {
@@ -182,8 +188,8 @@
if (allocator()->flags() & PORTALLOCATOR_ENABLE_SHARED_UFRAG) {
ASSERT(!username().empty());
ASSERT(!password().empty());
- url = url + "?username=" + talk_base::s_url_encode(username()) +
- "&password=" + talk_base::s_url_encode(password());
+ url = url + "?username=" + rtc::s_url_encode(username()) +
+ "&password=" + rtc::s_url_encode(password());
}
return url;
}
@@ -206,21 +212,27 @@
std::string relay_tcp_port = map["relay.tcp_port"];
std::string relay_ssltcp_port = map["relay.ssltcp_port"];
- PortConfiguration* config = new PortConfiguration(stun_hosts_[0],
+ ServerAddresses hosts;
+ for (std::vector<rtc::SocketAddress>::iterator it = stun_hosts_.begin();
+ it != stun_hosts_.end(); ++it) {
+ hosts.insert(*it);
+ }
+
+ PortConfiguration* config = new PortConfiguration(hosts,
map["username"],
map["password"]);
RelayServerConfig relay_config(RELAY_GTURN);
if (!relay_udp_port.empty()) {
- talk_base::SocketAddress address(relay_ip, atoi(relay_udp_port.c_str()));
+ rtc::SocketAddress address(relay_ip, atoi(relay_udp_port.c_str()));
relay_config.ports.push_back(ProtocolAddress(address, PROTO_UDP));
}
if (!relay_tcp_port.empty()) {
- talk_base::SocketAddress address(relay_ip, atoi(relay_tcp_port.c_str()));
+ rtc::SocketAddress address(relay_ip, atoi(relay_tcp_port.c_str()));
relay_config.ports.push_back(ProtocolAddress(address, PROTO_TCP));
}
if (!relay_ssltcp_port.empty()) {
- talk_base::SocketAddress address(relay_ip, atoi(relay_ssltcp_port.c_str()));
+ rtc::SocketAddress address(relay_ip, atoi(relay_ssltcp_port.c_str()));
relay_config.ports.push_back(ProtocolAddress(address, PROTO_SSLTCP));
}
config->AddRelay(relay_config);
@@ -230,14 +242,14 @@
// HttpPortAllocator
HttpPortAllocator::HttpPortAllocator(
- talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory,
+ rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory,
const std::string &user_agent)
: HttpPortAllocatorBase(network_manager, socket_factory, user_agent) {
}
HttpPortAllocator::HttpPortAllocator(
- talk_base::NetworkManager* network_manager,
+ rtc::NetworkManager* network_manager,
const std::string &user_agent)
: HttpPortAllocatorBase(network_manager, user_agent) {
}
@@ -261,7 +273,7 @@
int component,
const std::string& ice_ufrag,
const std::string& ice_pwd,
- const std::vector<talk_base::SocketAddress>& stun_hosts,
+ const std::vector<rtc::SocketAddress>& stun_hosts,
const std::vector<std::string>& relay_hosts,
const std::string& relay,
const std::string& agent)
@@ -271,7 +283,7 @@
}
HttpPortAllocatorSession::~HttpPortAllocatorSession() {
- for (std::list<talk_base::AsyncHttpRequest*>::iterator it = requests_.begin();
+ for (std::list<rtc::AsyncHttpRequest*>::iterator it = requests_.begin();
it != requests_.end(); ++it) {
(*it)->Destroy(true);
}
@@ -280,15 +292,15 @@
void HttpPortAllocatorSession::SendSessionRequest(const std::string& host,
int port) {
// Initiate an HTTP request to create a session through the chosen host.
- talk_base::AsyncHttpRequest* request =
- new talk_base::AsyncHttpRequest(user_agent());
+ rtc::AsyncHttpRequest* request =
+ new rtc::AsyncHttpRequest(user_agent());
request->SignalWorkDone.connect(this,
&HttpPortAllocatorSession::OnRequestDone);
- request->set_secure(port == talk_base::HTTP_SECURE_PORT);
+ request->set_secure(port == rtc::HTTP_SECURE_PORT);
request->set_proxy(allocator()->proxy());
- request->response().document.reset(new talk_base::MemoryStream);
- request->request().verb = talk_base::HV_GET;
+ request->response().document.reset(new rtc::MemoryStream);
+ request->request().verb = rtc::HV_GET;
request->request().path = GetSessionRequestUrl();
request->request().addHeader("X-Talk-Google-Relay-Auth", relay_token(), true);
request->request().addHeader("X-Stream-Type", "video_rtp", true);
@@ -300,12 +312,12 @@
requests_.push_back(request);
}
-void HttpPortAllocatorSession::OnRequestDone(talk_base::SignalThread* data) {
- talk_base::AsyncHttpRequest* request =
- static_cast<talk_base::AsyncHttpRequest*>(data);
+void HttpPortAllocatorSession::OnRequestDone(rtc::SignalThread* data) {
+ rtc::AsyncHttpRequest* request =
+ static_cast<rtc::AsyncHttpRequest*>(data);
// Remove the request from the list of active requests.
- std::list<talk_base::AsyncHttpRequest*>::iterator it =
+ std::list<rtc::AsyncHttpRequest*>::iterator it =
std::find(requests_.begin(), requests_.end(), request);
if (it != requests_.end()) {
requests_.erase(it);
@@ -319,8 +331,8 @@
}
LOG(LS_INFO) << "HTTPPortAllocator: request succeeded";
- talk_base::MemoryStream* stream =
- static_cast<talk_base::MemoryStream*>(request->response().document.get());
+ rtc::MemoryStream* stream =
+ static_cast<rtc::MemoryStream*>(request->response().document.get());
stream->Rewind();
size_t length;
stream->GetSize(&length);
diff --git a/p2p/client/httpportallocator.h b/p2p/client/httpportallocator.h
index a0ef3b7..7ace943 100644
--- a/p2p/client/httpportallocator.h
+++ b/p2p/client/httpportallocator.h
@@ -36,7 +36,7 @@
class HttpPortAllocatorTest_TestSessionRequestUrl_Test;
-namespace talk_base {
+namespace rtc {
class AsyncHttpRequest;
class SignalThread;
}
@@ -51,10 +51,10 @@
// Records the URL that we will GET in order to create a session.
static const char kCreateSessionURL[];
- HttpPortAllocatorBase(talk_base::NetworkManager* network_manager,
+ HttpPortAllocatorBase(rtc::NetworkManager* network_manager,
const std::string& user_agent);
- HttpPortAllocatorBase(talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory,
+ HttpPortAllocatorBase(rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory,
const std::string& user_agent);
virtual ~HttpPortAllocatorBase();
@@ -66,7 +66,7 @@
const std::string& ice_ufrag,
const std::string& ice_pwd) = 0;
- void SetStunHosts(const std::vector<talk_base::SocketAddress>& hosts) {
+ void SetStunHosts(const std::vector<rtc::SocketAddress>& hosts) {
if (!hosts.empty()) {
stun_hosts_ = hosts;
}
@@ -78,7 +78,7 @@
}
void SetRelayToken(const std::string& relay) { relay_token_ = relay; }
- const std::vector<talk_base::SocketAddress>& stun_hosts() const {
+ const std::vector<rtc::SocketAddress>& stun_hosts() const {
return stun_hosts_;
}
@@ -95,7 +95,7 @@
}
private:
- std::vector<talk_base::SocketAddress> stun_hosts_;
+ std::vector<rtc::SocketAddress> stun_hosts_;
std::vector<std::string> relay_hosts_;
std::string relay_token_;
std::string agent_;
@@ -111,7 +111,7 @@
int component,
const std::string& ice_ufrag,
const std::string& ice_pwd,
- const std::vector<talk_base::SocketAddress>& stun_hosts,
+ const std::vector<rtc::SocketAddress>& stun_hosts,
const std::vector<std::string>& relay_hosts,
const std::string& relay,
const std::string& agent);
@@ -141,7 +141,7 @@
private:
std::vector<std::string> relay_hosts_;
- std::vector<talk_base::SocketAddress> stun_hosts_;
+ std::vector<rtc::SocketAddress> stun_hosts_;
std::string relay_token_;
std::string agent_;
int attempts_;
@@ -149,10 +149,10 @@
class HttpPortAllocator : public HttpPortAllocatorBase {
public:
- HttpPortAllocator(talk_base::NetworkManager* network_manager,
+ HttpPortAllocator(rtc::NetworkManager* network_manager,
const std::string& user_agent);
- HttpPortAllocator(talk_base::NetworkManager* network_manager,
- talk_base::PacketSocketFactory* socket_factory,
+ HttpPortAllocator(rtc::NetworkManager* network_manager,
+ rtc::PacketSocketFactory* socket_factory,
const std::string& user_agent);
virtual ~HttpPortAllocator();
virtual PortAllocatorSession* CreateSessionInternal(
@@ -169,7 +169,7 @@
int component,
const std::string& ice_ufrag,
const std::string& ice_pwd,
- const std::vector<talk_base::SocketAddress>& stun_hosts,
+ const std::vector<rtc::SocketAddress>& stun_hosts,
const std::vector<std::string>& relay_hosts,
const std::string& relay,
const std::string& agent);
@@ -179,10 +179,10 @@
protected:
// Protected for diagnostics.
- virtual void OnRequestDone(talk_base::SignalThread* request);
+ virtual void OnRequestDone(rtc::SignalThread* request);
private:
- std::list<talk_base::AsyncHttpRequest*> requests_;
+ std::list<rtc::AsyncHttpRequest*> requests_;
};
} // namespace cricket
diff --git a/p2p/client/portallocator_unittest.cc b/p2p/client/portallocator_unittest.cc
index 44a8f27..e793064 100644
--- a/p2p/client/portallocator_unittest.cc
+++ b/p2p/client/portallocator_unittest.cc
@@ -25,19 +25,6 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/fakenetwork.h"
-#include "talk/base/firewallsocketserver.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/natserver.h"
-#include "talk/base/natsocketfactory.h"
-#include "talk/base/network.h"
-#include "talk/base/physicalsocketserver.h"
-#include "talk/base/socketaddress.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/thread.h"
-#include "talk/base/virtualsocketserver.h"
#include "talk/p2p/base/basicpacketsocketfactory.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/p2ptransportchannel.h"
@@ -47,15 +34,30 @@
#include "talk/p2p/base/testturnserver.h"
#include "talk/p2p/client/basicportallocator.h"
#include "talk/p2p/client/httpportallocator.h"
+#include "webrtc/base/fakenetwork.h"
+#include "webrtc/base/firewallsocketserver.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/natserver.h"
+#include "webrtc/base/natsocketfactory.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/physicalsocketserver.h"
+#include "webrtc/base/socketaddress.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/virtualsocketserver.h"
-using talk_base::SocketAddress;
-using talk_base::Thread;
+using cricket::ServerAddresses;
+using rtc::SocketAddress;
+using rtc::Thread;
static const SocketAddress kClientAddr("11.11.11.11", 0);
+static const SocketAddress kPrivateAddr("192.168.1.11", 0);
static const SocketAddress kClientIPv6Addr(
"2401:fa00:4:1000:be30:5bff:fee5:c3", 0);
static const SocketAddress kClientAddr2("22.22.22.22", 0);
-static const SocketAddress kNatAddr("77.77.77.77", talk_base::NAT_SERVER_PORT);
+static const SocketAddress kNatAddr("77.77.77.77", rtc::NAT_SERVER_PORT);
static const SocketAddress kRemoteClientAddr("22.22.22.22", 0);
static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
@@ -96,17 +98,17 @@
class PortAllocatorTest : public testing::Test, public sigslot::has_slots<> {
public:
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
PortAllocatorTest()
- : pss_(new talk_base::PhysicalSocketServer),
- vss_(new talk_base::VirtualSocketServer(pss_.get())),
- fss_(new talk_base::FirewallSocketServer(vss_.get())),
+ : pss_(new rtc::PhysicalSocketServer),
+ vss_(new rtc::VirtualSocketServer(pss_.get())),
+ fss_(new rtc::FirewallSocketServer(vss_.get())),
ss_scope_(fss_.get()),
nat_factory_(vss_.get(), kNatAddr),
nat_socket_factory_(&nat_factory_),
@@ -115,10 +117,13 @@
kRelayTcpIntAddr, kRelayTcpExtAddr,
kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
turn_server_(Thread::Current(), kTurnUdpIntAddr, kTurnUdpExtAddr),
- allocator_(new cricket::BasicPortAllocator(
- &network_manager_, kStunAddr,
- kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr)),
candidate_allocation_done_(false) {
+ cricket::ServerAddresses stun_servers;
+ stun_servers.insert(kStunAddr);
+ allocator_.reset(new cricket::BasicPortAllocator(
+ &network_manager_,
+ stun_servers,
+ kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr));
allocator_->set_step_delay(cricket::kMinimumStepDelay);
}
@@ -128,9 +133,32 @@
bool SetPortRange(int min_port, int max_port) {
return allocator_->SetPortRange(min_port, max_port);
}
- talk_base::NATServer* CreateNatServer(const SocketAddress& addr,
- talk_base::NATType type) {
- return new talk_base::NATServer(type, vss_.get(), addr, vss_.get(), addr);
+ void ResetWithNatServer(const rtc::SocketAddress& stun_server) {
+ nat_server_.reset(new rtc::NATServer(
+ rtc::NAT_OPEN_CONE, vss_.get(), kNatAddr, vss_.get(), kNatAddr));
+
+ ServerAddresses stun_servers;
+ stun_servers.insert(stun_server);
+ allocator_.reset(new cricket::BasicPortAllocator(
+ &network_manager_, &nat_socket_factory_, stun_servers));
+ allocator().set_step_delay(cricket::kMinimumStepDelay);
+ }
+
+ void AddTurnServers(const rtc::SocketAddress& udp_turn,
+ const rtc::SocketAddress& tcp_turn) {
+ cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
+ cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
+ relay_server.credentials = credentials;
+
+ if (!udp_turn.IsNil()) {
+ relay_server.ports.push_back(cricket::ProtocolAddress(
+ kTurnUdpIntAddr, cricket::PROTO_UDP, false));
+ }
+ if (!tcp_turn.IsNil()) {
+ relay_server.ports.push_back(cricket::ProtocolAddress(
+ kTurnTcpIntAddr, cricket::PROTO_TCP, false));
+ }
+ allocator_->AddRelay(relay_server);
}
bool CreateSession(int component) {
@@ -181,7 +209,7 @@
((addr.port() == 0 && (c.address().port() != 0)) ||
(c.address().port() == addr.port())));
}
- static bool CheckPort(const talk_base::SocketAddress& addr,
+ static bool CheckPort(const rtc::SocketAddress& addr,
int min_port, int max_port) {
return (addr.port() >= min_port && addr.port() <= max_port);
}
@@ -203,10 +231,10 @@
int send_buffer_size;
if (expected == -1) {
EXPECT_EQ(SOCKET_ERROR,
- (*it)->GetOption(talk_base::Socket::OPT_SNDBUF,
+ (*it)->GetOption(rtc::Socket::OPT_SNDBUF,
&send_buffer_size));
} else {
- EXPECT_EQ(0, (*it)->GetOption(talk_base::Socket::OPT_SNDBUF,
+ EXPECT_EQ(0, (*it)->GetOption(rtc::Socket::OPT_SNDBUF,
&send_buffer_size));
ASSERT_EQ(expected, send_buffer_size);
}
@@ -245,18 +273,19 @@
return false;
}
- talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
- talk_base::scoped_ptr<talk_base::VirtualSocketServer> vss_;
- talk_base::scoped_ptr<talk_base::FirewallSocketServer> fss_;
- talk_base::SocketServerScope ss_scope_;
- talk_base::NATSocketFactory nat_factory_;
- talk_base::BasicPacketSocketFactory nat_socket_factory_;
+ rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
+ rtc::scoped_ptr<rtc::VirtualSocketServer> vss_;
+ rtc::scoped_ptr<rtc::FirewallSocketServer> fss_;
+ rtc::SocketServerScope ss_scope_;
+ rtc::scoped_ptr<rtc::NATServer> nat_server_;
+ rtc::NATSocketFactory nat_factory_;
+ rtc::BasicPacketSocketFactory nat_socket_factory_;
cricket::TestStunServer stun_server_;
cricket::TestRelayServer relay_server_;
cricket::TestTurnServer turn_server_;
- talk_base::FakeNetworkManager network_manager_;
- talk_base::scoped_ptr<cricket::BasicPortAllocator> allocator_;
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session_;
+ rtc::FakeNetworkManager network_manager_;
+ rtc::scoped_ptr<cricket::BasicPortAllocator> allocator_;
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session_;
std::vector<cricket::PortInterface*> ports_;
std::vector<cricket::Candidate> candidates_;
bool candidate_allocation_done_;
@@ -265,7 +294,7 @@
// Tests that we can init the port allocator and create a session.
TEST_F(PortAllocatorTest, TestBasic) {
EXPECT_EQ(&network_manager_, allocator().network_manager());
- EXPECT_EQ(kStunAddr, allocator().stun_address());
+ EXPECT_EQ(kStunAddr, *allocator().stun_servers().begin());
ASSERT_EQ(1u, allocator().relays().size());
EXPECT_EQ(cricket::RELAY_GTURN, allocator().relays()[0].type);
// Empty relay credentials are used for GTURN.
@@ -280,6 +309,19 @@
EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
}
+// Tests that we allocator session not trying to allocate ports for every 250ms.
+TEST_F(PortAllocatorTest, TestNoNetworkInterface) {
+ EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
+ session_->StartGettingPorts();
+ // Waiting for one second to make sure BasicPortAllocatorSession has not
+ // called OnAllocate multiple times. In old behavior it's called every 250ms.
+ // When there are no network interfaces, each execution of OnAllocate will
+ // result in SignalCandidatesAllocationDone signal.
+ rtc::Thread::Current()->ProcessMessages(1000);
+ EXPECT_TRUE(candidate_allocation_done_);
+ EXPECT_EQ(0U, candidates_.size());
+}
+
// Tests that we can get all the desired addresses successfully.
TEST_F(PortAllocatorTest, TestGetAllPortsWithMinimumStepDelay) {
AddInterface(kClientAddr);
@@ -391,7 +433,7 @@
TEST_F(PortAllocatorTest, TestGetAllPortsNoAdapters) {
EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
session_->StartGettingPorts();
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
// Without network adapter, we should not get any candidate.
EXPECT_EQ(0U, candidates_.size());
EXPECT_TRUE(candidate_allocation_done_);
@@ -407,7 +449,7 @@
cricket::PORTALLOCATOR_DISABLE_RELAY |
cricket::PORTALLOCATOR_DISABLE_TCP);
session_->StartGettingPorts();
- talk_base::Thread::Current()->ProcessMessages(100);
+ rtc::Thread::Current()->ProcessMessages(100);
EXPECT_EQ(0U, candidates_.size());
EXPECT_TRUE(candidate_allocation_done_);
}
@@ -474,7 +516,7 @@
// Testing STUN timeout.
TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpAllowed) {
- fss_->AddRule(false, talk_base::FP_UDP, talk_base::FD_ANY, kClientAddr);
+ fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr);
AddInterface(kClientAddr);
EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
session_->StartGettingPorts();
@@ -521,7 +563,7 @@
// Test to verify ICE restart process.
TEST_F(PortAllocatorTest, TestGetAllPortsRestarts) {
AddInterface(kClientAddr);
- EXPECT_TRUE(CreateSession(1));
+ EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
session_->StartGettingPorts();
EXPECT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
EXPECT_EQ(4U, ports_.size());
@@ -529,13 +571,80 @@
// TODO - Extend this to verify ICE restart.
}
+// Test ICE candidate filter mechanism with options Relay/Host/Reflexive.
+TEST_F(PortAllocatorTest, TestCandidateFilterWithRelayOnly) {
+ AddInterface(kClientAddr);
+ allocator().set_candidate_filter(cricket::CF_RELAY);
+ EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
+ session_->StartGettingPorts();
+ EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
+ // Using GTURN, we will have 4 candidates.
+ EXPECT_EQ(4U, candidates_.size());
+ EXPECT_EQ(1U, ports_.size()); // Only Relay port will be in ready state.
+ for (size_t i = 0; i < candidates_.size(); ++i) {
+ EXPECT_EQ(std::string(cricket::RELAY_PORT_TYPE), candidates_[i].type());
+ }
+}
+
+TEST_F(PortAllocatorTest, TestCandidateFilterWithHostOnly) {
+ AddInterface(kClientAddr);
+ allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
+ cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
+ allocator().set_candidate_filter(cricket::CF_HOST);
+ EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
+ session_->StartGettingPorts();
+ EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
+ EXPECT_EQ(2U, candidates_.size()); // Host UDP/TCP candidates only.
+ EXPECT_EQ(2U, ports_.size()); // UDP/TCP ports only.
+ for (size_t i = 0; i < candidates_.size(); ++i) {
+ EXPECT_EQ(std::string(cricket::LOCAL_PORT_TYPE), candidates_[i].type());
+ }
+}
+
+// Host is behind the NAT.
+TEST_F(PortAllocatorTest, TestCandidateFilterWithReflexiveOnly) {
+ AddInterface(kPrivateAddr);
+ ResetWithNatServer(kStunAddr);
+
+ allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
+ cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
+ allocator().set_candidate_filter(cricket::CF_REFLEXIVE);
+ EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
+ session_->StartGettingPorts();
+ EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
+ // Host is behind NAT, no private address will be exposed. Hence only UDP
+ // port with STUN candidate will be sent outside.
+ EXPECT_EQ(1U, candidates_.size()); // Only STUN candidate.
+ EXPECT_EQ(1U, ports_.size()); // Only UDP port will be in ready state.
+ for (size_t i = 0; i < candidates_.size(); ++i) {
+ EXPECT_EQ(std::string(cricket::STUN_PORT_TYPE), candidates_[i].type());
+ }
+}
+
+// Host is not behind the NAT.
+TEST_F(PortAllocatorTest, TestCandidateFilterWithReflexiveOnlyAndNoNAT) {
+ AddInterface(kClientAddr);
+ allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
+ cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
+ allocator().set_candidate_filter(cricket::CF_REFLEXIVE);
+ EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
+ session_->StartGettingPorts();
+ EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
+ // Host has a public address, both UDP and TCP candidates will be exposed.
+ EXPECT_EQ(2U, candidates_.size()); // Local UDP + TCP candidate.
+ EXPECT_EQ(2U, ports_.size()); // UDP and TCP ports will be in ready state.
+ for (size_t i = 0; i < candidates_.size(); ++i) {
+ EXPECT_EQ(std::string(cricket::LOCAL_PORT_TYPE), candidates_[i].type());
+ }
+}
+
TEST_F(PortAllocatorTest, TestBasicMuxFeatures) {
AddInterface(kClientAddr);
allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE);
// Session ID - session1.
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session1(
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session1(
CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTP));
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session2(
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session2(
CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTCP));
session1->StartGettingPorts();
session2->StartGettingPorts();
@@ -543,7 +652,7 @@
ASSERT_EQ_WAIT(14U, candidates_.size(), kDefaultAllocationTimeout);
EXPECT_EQ(8U, ports_.size());
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session3(
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session3(
CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTP));
session3->StartGettingPorts();
// Already allocated candidates and ports will be sent to the newly
@@ -560,7 +669,7 @@
AddInterface(kClientAddr);
allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE);
// Session ID - session1.
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session1(
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session1(
CreateSession("session1", kContentName,
cricket::ICE_CANDIDATE_COMPONENT_RTP,
kIceUfrag0, kIcePwd0));
@@ -569,7 +678,7 @@
EXPECT_EQ(4U, ports_.size());
// Allocate a different session with sid |session1| and different ice_ufrag.
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session2(
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session2(
CreateSession("session1", kContentName,
cricket::ICE_CANDIDATE_COMPONENT_RTP,
"TestIceUfrag", kIcePwd0));
@@ -584,7 +693,7 @@
// Allocating a different session with sid |session1| and
// different ice_pwd.
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session3(
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session3(
CreateSession("session1", kContentName,
cricket::ICE_CANDIDATE_COMPONENT_RTP,
kIceUfrag0, "TestIcePwd"));
@@ -597,7 +706,7 @@
EXPECT_NE(candidates_[8].address(), candidates_[15].address());
// Allocating a session with by changing both ice_ufrag and ice_pwd.
- talk_base::scoped_ptr<cricket::PortAllocatorSession> session4(
+ rtc::scoped_ptr<cricket::PortAllocatorSession> session4(
CreateSession("session1", kContentName,
cricket::ICE_CANDIDATE_COMPONENT_RTP,
"TestIceUfrag", "TestIcePwd"));
@@ -681,11 +790,8 @@
// local candidates as client behind a nat.
TEST_F(PortAllocatorTest, TestSharedSocketWithNat) {
AddInterface(kClientAddr);
- talk_base::scoped_ptr<talk_base::NATServer> nat_server(
- CreateNatServer(kNatAddr, talk_base::NAT_OPEN_CONE));
- allocator_.reset(new cricket::BasicPortAllocator(
- &network_manager_, &nat_socket_factory_, kStunAddr));
- allocator_->set_step_delay(cricket::kMinimumStepDelay);
+ ResetWithNatServer(kStunAddr);
+
allocator_->set_flags(allocator().flags() |
cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
@@ -697,7 +803,7 @@
cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
EXPECT_PRED5(CheckCandidate, candidates_[1],
cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
- talk_base::SocketAddress(kNatAddr.ipaddr(), 0));
+ rtc::SocketAddress(kNatAddr.ipaddr(), 0));
EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
EXPECT_EQ(3U, candidates_.size());
}
@@ -707,14 +813,8 @@
turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
AddInterface(kClientAddr);
allocator_.reset(new cricket::BasicPortAllocator(&network_manager_));
- cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
- cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
- relay_server.credentials = credentials;
- relay_server.ports.push_back(cricket::ProtocolAddress(
- kTurnUdpIntAddr, cricket::PROTO_UDP, false));
- relay_server.ports.push_back(cricket::ProtocolAddress(
- kTurnTcpIntAddr, cricket::PROTO_TCP, false));
- allocator_->AddRelay(relay_server);
+
+ AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr);
allocator_->set_step_delay(cricket::kMinimumStepDelay);
allocator_->set_flags(allocator().flags() |
@@ -731,10 +831,10 @@
cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
EXPECT_PRED5(CheckCandidate, candidates_[1],
cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
- talk_base::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
+ rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
EXPECT_PRED5(CheckCandidate, candidates_[2],
cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
- talk_base::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
+ rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
EXPECT_EQ(3U, candidates_.size());
}
@@ -742,7 +842,7 @@
// Testing DNS resolve for the TURN server, this will test AllocationSequence
// handling the unresolved address signal from TurnPort.
TEST_F(PortAllocatorTest, TestSharedSocketWithServerAddressResolve) {
- turn_server_.AddInternalSocket(talk_base::SocketAddress("127.0.0.1", 3478),
+ turn_server_.AddInternalSocket(rtc::SocketAddress("127.0.0.1", 3478),
cricket::PROTO_UDP);
AddInterface(kClientAddr);
allocator_.reset(new cricket::BasicPortAllocator(&network_manager_));
@@ -750,7 +850,7 @@
cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
relay_server.credentials = credentials;
relay_server.ports.push_back(cricket::ProtocolAddress(
- talk_base::SocketAddress("localhost", 3478),
+ rtc::SocketAddress("localhost", 3478),
cricket::PROTO_UDP, false));
allocator_->AddRelay(relay_server);
@@ -771,18 +871,10 @@
// stun and turn candidates.
TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurn) {
AddInterface(kClientAddr);
- talk_base::scoped_ptr<talk_base::NATServer> nat_server(
- CreateNatServer(kNatAddr, talk_base::NAT_OPEN_CONE));
- allocator_.reset(new cricket::BasicPortAllocator(
- &network_manager_, &nat_socket_factory_, kStunAddr));
- cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
- cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
- relay_server.credentials = credentials;
- relay_server.ports.push_back(cricket::ProtocolAddress(
- kTurnUdpIntAddr, cricket::PROTO_UDP, false));
- allocator_->AddRelay(relay_server);
+ ResetWithNatServer(kStunAddr);
- allocator_->set_step_delay(cricket::kMinimumStepDelay);
+ AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
+
allocator_->set_flags(allocator().flags() |
cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
@@ -797,10 +889,49 @@
cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
EXPECT_PRED5(CheckCandidate, candidates_[1],
cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
- talk_base::SocketAddress(kNatAddr.ipaddr(), 0));
+ rtc::SocketAddress(kNatAddr.ipaddr(), 0));
EXPECT_PRED5(CheckCandidate, candidates_[2],
cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
- talk_base::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
+ rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
+ EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
+ EXPECT_EQ(3U, candidates_.size());
+ // Local port will be created first and then TURN port.
+ EXPECT_EQ(2U, ports_[0]->Candidates().size());
+ EXPECT_EQ(1U, ports_[1]->Candidates().size());
+}
+
+// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled and the TURN
+// server is also used as the STUN server, we should get 'local', 'stun', and
+// 'relay' candidates.
+TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurnAsStun) {
+ AddInterface(kClientAddr);
+ ResetWithNatServer(kTurnUdpIntAddr);
+ AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
+
+ // Must set the step delay to 0 to make sure the relay allocation phase is
+ // started before the STUN candidates are obtained, so that the STUN binding
+ // response is processed when both StunPort and TurnPort exist to reproduce
+ // webrtc issue 3537.
+ allocator_->set_step_delay(0);
+ allocator_->set_flags(allocator().flags() |
+ cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
+ cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
+ cricket::PORTALLOCATOR_DISABLE_TCP);
+
+ EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
+ session_->StartGettingPorts();
+
+ ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
+ EXPECT_PRED5(CheckCandidate, candidates_[0],
+ cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
+ EXPECT_PRED5(CheckCandidate, candidates_[1],
+ cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
+ rtc::SocketAddress(kNatAddr.ipaddr(), 0));
+ EXPECT_PRED5(CheckCandidate, candidates_[2],
+ cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
+ rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
+ EXPECT_EQ(candidates_[2].related_address(), candidates_[1].address());
+
EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
EXPECT_EQ(3U, candidates_.size());
// Local port will be created first and then TURN port.
@@ -817,7 +948,7 @@
cricket::PORTALLOCATOR_DISABLE_TCP |
cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
- fss_->AddRule(false, talk_base::FP_UDP, talk_base::FD_ANY, kClientAddr);
+ fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr);
AddInterface(kClientAddr);
EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
session_->StartGettingPorts();
@@ -863,13 +994,13 @@
// Test that the httpportallocator correctly maintains its lists of stun and
// relay servers, by never allowing an empty list.
TEST(HttpPortAllocatorTest, TestHttpPortAllocatorHostLists) {
- talk_base::FakeNetworkManager network_manager;
+ rtc::FakeNetworkManager network_manager;
cricket::HttpPortAllocator alloc(&network_manager, "unit test agent");
EXPECT_EQ(1U, alloc.relay_hosts().size());
EXPECT_EQ(1U, alloc.stun_hosts().size());
std::vector<std::string> relay_servers;
- std::vector<talk_base::SocketAddress> stun_servers;
+ std::vector<rtc::SocketAddress> stun_servers;
alloc.SetRelayHosts(relay_servers);
alloc.SetStunHosts(stun_servers);
@@ -879,9 +1010,10 @@
relay_servers.push_back("1.unittest.corp.google.com");
relay_servers.push_back("2.unittest.corp.google.com");
stun_servers.push_back(
- talk_base::SocketAddress("1.unittest.corp.google.com", 0));
+ rtc::SocketAddress("1.unittest.corp.google.com", 0));
stun_servers.push_back(
- talk_base::SocketAddress("2.unittest.corp.google.com", 0));
+ rtc::SocketAddress("2.unittest.corp.google.com", 0));
+
alloc.SetRelayHosts(relay_servers);
alloc.SetStunHosts(stun_servers);
EXPECT_EQ(2U, alloc.relay_hosts().size());
@@ -890,12 +1022,12 @@
// Test that the HttpPortAllocator uses correct URL to create sessions.
TEST(HttpPortAllocatorTest, TestSessionRequestUrl) {
- talk_base::FakeNetworkManager network_manager;
+ rtc::FakeNetworkManager network_manager;
cricket::HttpPortAllocator alloc(&network_manager, "unit test agent");
// Disable PORTALLOCATOR_ENABLE_SHARED_UFRAG.
alloc.set_flags(alloc.flags() & ~cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
- talk_base::scoped_ptr<cricket::HttpPortAllocatorSessionBase> session(
+ rtc::scoped_ptr<cricket::HttpPortAllocatorSessionBase> session(
static_cast<cricket::HttpPortAllocatorSession*>(
alloc.CreateSessionInternal(
"test content", 0, kIceUfrag0, kIcePwd0)));
@@ -910,19 +1042,19 @@
url = session->GetSessionRequestUrl();
LOG(LS_INFO) << "url: " << url;
std::vector<std::string> parts;
- talk_base::split(url, '?', &parts);
+ rtc::split(url, '?', &parts);
ASSERT_EQ(2U, parts.size());
std::vector<std::string> args_parts;
- talk_base::split(parts[1], '&', &args_parts);
+ rtc::split(parts[1], '&', &args_parts);
std::map<std::string, std::string> args;
for (std::vector<std::string>::iterator it = args_parts.begin();
it != args_parts.end(); ++it) {
std::vector<std::string> parts;
- talk_base::split(*it, '=', &parts);
+ rtc::split(*it, '=', &parts);
ASSERT_EQ(2U, parts.size());
- args[talk_base::s_url_decode(parts[0])] = talk_base::s_url_decode(parts[1]);
+ args[rtc::s_url_decode(parts[0])] = rtc::s_url_decode(parts[1]);
}
EXPECT_EQ(kIceUfrag0, args["username"]);
diff --git a/p2p/client/sessionmanagertask.h b/p2p/client/sessionmanagertask.h
index d7d9733..e16d9d6 100644
--- a/p2p/client/sessionmanagertask.h
+++ b/p2p/client/sessionmanagertask.h
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _SESSIONMANAGERTASK_H_
-#define _SESSIONMANAGERTASK_H_
+#ifndef TALK_P2P_CLIENT_SESSIONMANAGERTASK_H_
+#define TALK_P2P_CLIENT_SESSIONMANAGERTASK_H_
#include "talk/p2p/base/sessionmanager.h"
#include "talk/p2p/client/sessionsendtask.h"
@@ -90,4 +90,4 @@
} // namespace cricket
-#endif // _SESSIONMANAGERTASK_H_
+#endif // TALK_P2P_CLIENT_SESSIONMANAGERTASK_H_
diff --git a/p2p/client/sessionsendtask.h b/p2p/client/sessionsendtask.h
index 6c7508a..c8734d2 100644
--- a/p2p/client/sessionsendtask.h
+++ b/p2p/client/sessionsendtask.h
@@ -28,12 +28,12 @@
#ifndef TALK_P2P_CLIENT_SESSIONSENDTASK_H_
#define TALK_P2P_CLIENT_SESSIONSENDTASK_H_
-#include "talk/base/common.h"
+#include "talk/p2p/base/sessionmanager.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/xmppclient.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
-#include "talk/p2p/base/sessionmanager.h"
+#include "webrtc/base/common.h"
namespace cricket {
@@ -137,7 +137,7 @@
private:
SessionManager *session_manager_;
- talk_base::scoped_ptr<buzz::XmlElement> stanza_;
+ rtc::scoped_ptr<buzz::XmlElement> stanza_;
};
}
diff --git a/p2p/client/socketmonitor.cc b/p2p/client/socketmonitor.cc
index e0c75d4..1924c70 100644
--- a/p2p/client/socketmonitor.cc
+++ b/p2p/client/socketmonitor.cc
@@ -27,7 +27,7 @@
#include "talk/p2p/client/socketmonitor.h"
-#include "talk/base/common.h"
+#include "webrtc/base/common.h"
namespace cricket {
@@ -39,8 +39,8 @@
};
SocketMonitor::SocketMonitor(TransportChannel* channel,
- talk_base::Thread* worker_thread,
- talk_base::Thread* monitor_thread) {
+ rtc::Thread* worker_thread,
+ rtc::Thread* monitor_thread) {
channel_ = channel;
channel_thread_ = worker_thread;
monitoring_thread_ = monitor_thread;
@@ -63,11 +63,11 @@
channel_thread_->Post(this, MSG_MONITOR_STOP);
}
-void SocketMonitor::OnMessage(talk_base::Message *message) {
- talk_base::CritScope cs(&crit_);
+void SocketMonitor::OnMessage(rtc::Message *message) {
+ rtc::CritScope cs(&crit_);
switch (message->message_id) {
case MSG_MONITOR_START:
- ASSERT(talk_base::Thread::Current() == channel_thread_);
+ ASSERT(rtc::Thread::Current() == channel_thread_);
if (!monitoring_) {
monitoring_ = true;
PollSocket(true);
@@ -75,7 +75,7 @@
break;
case MSG_MONITOR_STOP:
- ASSERT(talk_base::Thread::Current() == channel_thread_);
+ ASSERT(rtc::Thread::Current() == channel_thread_);
if (monitoring_) {
monitoring_ = false;
channel_thread_->Clear(this);
@@ -83,12 +83,12 @@
break;
case MSG_MONITOR_POLL:
- ASSERT(talk_base::Thread::Current() == channel_thread_);
+ ASSERT(rtc::Thread::Current() == channel_thread_);
PollSocket(true);
break;
case MSG_MONITOR_SIGNAL: {
- ASSERT(talk_base::Thread::Current() == monitoring_thread_);
+ ASSERT(rtc::Thread::Current() == monitoring_thread_);
std::vector<ConnectionInfo> infos = connection_infos_;
crit_.Leave();
SignalUpdate(this, infos);
@@ -99,8 +99,8 @@
}
void SocketMonitor::PollSocket(bool poll) {
- ASSERT(talk_base::Thread::Current() == channel_thread_);
- talk_base::CritScope cs(&crit_);
+ ASSERT(rtc::Thread::Current() == channel_thread_);
+ rtc::CritScope cs(&crit_);
// Gather connection infos
channel_->GetStats(&connection_infos_);
diff --git a/p2p/client/socketmonitor.h b/p2p/client/socketmonitor.h
index f24ad66..87b11cf 100644
--- a/p2p/client/socketmonitor.h
+++ b/p2p/client/socketmonitor.h
@@ -30,38 +30,38 @@
#include <vector>
-#include "talk/base/criticalsection.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
#include "talk/p2p/base/transportchannel.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
namespace cricket {
-class SocketMonitor : public talk_base::MessageHandler,
+class SocketMonitor : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
SocketMonitor(TransportChannel* channel,
- talk_base::Thread* worker_thread,
- talk_base::Thread* monitor_thread);
+ rtc::Thread* worker_thread,
+ rtc::Thread* monitor_thread);
~SocketMonitor();
void Start(int cms);
void Stop();
- talk_base::Thread* monitor_thread() { return monitoring_thread_; }
+ rtc::Thread* monitor_thread() { return monitoring_thread_; }
sigslot::signal2<SocketMonitor*,
const std::vector<ConnectionInfo>&> SignalUpdate;
protected:
- void OnMessage(talk_base::Message* message);
+ void OnMessage(rtc::Message* message);
void PollSocket(bool poll);
std::vector<ConnectionInfo> connection_infos_;
TransportChannel* channel_;
- talk_base::Thread* channel_thread_;
- talk_base::Thread* monitoring_thread_;
- talk_base::CriticalSection crit_;
+ rtc::Thread* channel_thread_;
+ rtc::Thread* monitoring_thread_;
+ rtc::CriticalSection crit_;
uint32 rate_;
bool monitoring_;
};
diff --git a/session/media/audiomonitor.cc b/session/media/audiomonitor.cc
index c3a2eb0..aa4a87d 100644
--- a/session/media/audiomonitor.cc
+++ b/session/media/audiomonitor.cc
@@ -25,9 +25,9 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+#include <assert.h>
#include "talk/session/media/audiomonitor.h"
#include "talk/session/media/voicechannel.h"
-#include <assert.h>
namespace cricket {
@@ -37,7 +37,7 @@
const uint32 MSG_MONITOR_SIGNAL = 4;
AudioMonitor::AudioMonitor(VoiceChannel *voice_channel,
- talk_base::Thread *monitor_thread) {
+ rtc::Thread *monitor_thread) {
voice_channel_ = voice_channel;
monitoring_thread_ = monitor_thread;
monitoring_ = false;
@@ -59,12 +59,12 @@
voice_channel_->worker_thread()->Post(this, MSG_MONITOR_STOP);
}
-void AudioMonitor::OnMessage(talk_base::Message *message) {
- talk_base::CritScope cs(&crit_);
+void AudioMonitor::OnMessage(rtc::Message *message) {
+ rtc::CritScope cs(&crit_);
switch (message->message_id) {
case MSG_MONITOR_START:
- assert(talk_base::Thread::Current() == voice_channel_->worker_thread());
+ assert(rtc::Thread::Current() == voice_channel_->worker_thread());
if (!monitoring_) {
monitoring_ = true;
PollVoiceChannel();
@@ -72,7 +72,7 @@
break;
case MSG_MONITOR_STOP:
- assert(talk_base::Thread::Current() == voice_channel_->worker_thread());
+ assert(rtc::Thread::Current() == voice_channel_->worker_thread());
if (monitoring_) {
monitoring_ = false;
voice_channel_->worker_thread()->Clear(this);
@@ -80,13 +80,13 @@
break;
case MSG_MONITOR_POLL:
- assert(talk_base::Thread::Current() == voice_channel_->worker_thread());
+ assert(rtc::Thread::Current() == voice_channel_->worker_thread());
PollVoiceChannel();
break;
case MSG_MONITOR_SIGNAL:
{
- assert(talk_base::Thread::Current() == monitoring_thread_);
+ assert(rtc::Thread::Current() == monitoring_thread_);
AudioInfo info = audio_info_;
crit_.Leave();
SignalUpdate(this, info);
@@ -97,8 +97,8 @@
}
void AudioMonitor::PollVoiceChannel() {
- talk_base::CritScope cs(&crit_);
- assert(talk_base::Thread::Current() == voice_channel_->worker_thread());
+ rtc::CritScope cs(&crit_);
+ assert(rtc::Thread::Current() == voice_channel_->worker_thread());
// Gather connection infos
audio_info_.input_level = voice_channel_->GetInputLevel_w();
@@ -114,7 +114,7 @@
return voice_channel_;
}
-talk_base::Thread *AudioMonitor::monitor_thread() {
+rtc::Thread *AudioMonitor::monitor_thread() {
return monitoring_thread_;
}
diff --git a/session/media/audiomonitor.h b/session/media/audiomonitor.h
index 5aff8fd..e5585a4 100644
--- a/session/media/audiomonitor.h
+++ b/session/media/audiomonitor.h
@@ -28,10 +28,10 @@
#ifndef TALK_SESSION_MEDIA_AUDIOMONITOR_H_
#define TALK_SESSION_MEDIA_AUDIOMONITOR_H_
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
-#include "talk/p2p/base/port.h"
#include <vector>
+#include "talk/p2p/base/port.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -44,28 +44,28 @@
StreamList active_streams; // ssrcs contributing to output_level
};
-class AudioMonitor : public talk_base::MessageHandler,
+class AudioMonitor : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
- AudioMonitor(VoiceChannel* voice_channel, talk_base::Thread *monitor_thread);
+ AudioMonitor(VoiceChannel* voice_channel, rtc::Thread *monitor_thread);
~AudioMonitor();
void Start(int cms);
void Stop();
VoiceChannel* voice_channel();
- talk_base::Thread *monitor_thread();
+ rtc::Thread *monitor_thread();
sigslot::signal2<AudioMonitor*, const AudioInfo&> SignalUpdate;
protected:
- void OnMessage(talk_base::Message *message);
+ void OnMessage(rtc::Message *message);
void PollVoiceChannel();
AudioInfo audio_info_;
VoiceChannel* voice_channel_;
- talk_base::Thread* monitoring_thread_;
- talk_base::CriticalSection crit_;
+ rtc::Thread* monitoring_thread_;
+ rtc::CriticalSection crit_;
uint32 rate_;
bool monitoring_;
};
diff --git a/session/media/bundlefilter.cc b/session/media/bundlefilter.cc
index 0d7927c..1d2a031 100755
--- a/session/media/bundlefilter.cc
+++ b/session/media/bundlefilter.cc
@@ -27,8 +27,8 @@
#include "talk/session/media/bundlefilter.h"
-#include "talk/base/logging.h"
#include "talk/media/base/rtputils.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -47,6 +47,10 @@
// |streams_| is empty, we will allow all rtcp packets pass through provided
// that they are valid rtcp packets in case that they are for early media.
if (!rtcp) {
+ // It may not be a RTP packet (e.g. SCTP).
+ if (!IsRtpPacket(data, len))
+ return false;
+
int payload_type = 0;
if (!GetRtpPayloadType(data, len, &payload_type)) {
return false;
diff --git a/session/media/bundlefilter.h b/session/media/bundlefilter.h
index 34bc330..a498041 100755
--- a/session/media/bundlefilter.h
+++ b/session/media/bundlefilter.h
@@ -31,8 +31,8 @@
#include <set>
#include <vector>
-#include "talk/base/basictypes.h"
#include "talk/media/base/streamparams.h"
+#include "webrtc/base/basictypes.h"
namespace cricket {
diff --git a/session/media/bundlefilter_unittest.cc b/session/media/bundlefilter_unittest.cc
index 0386666..806d6ba 100755
--- a/session/media/bundlefilter_unittest.cc
+++ b/session/media/bundlefilter_unittest.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
#include "talk/session/media/bundlefilter.h"
+#include "webrtc/base/gunit.h"
using cricket::StreamParams;
@@ -105,6 +105,15 @@
0x81, 0xCE, 0x00, 0x0C, 0x00, 0x00, 0x11, 0x11, 0x00, 0x00, 0x11, 0x11,
};
+// An SCTP packet.
+static const unsigned char kSctpPacket[] = {
+ 0x00, 0x01, 0x00, 0x01,
+ 0xff, 0xff, 0xff, 0xff,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x03, 0x00, 0x00, 0x04,
+ 0x00, 0x00, 0x00, 0x00,
+};
+
TEST(BundleFilterTest, AddRemoveStreamTest) {
cricket::BundleFilter bundle_filter;
EXPECT_FALSE(bundle_filter.HasStreams());
@@ -194,3 +203,11 @@
reinterpret_cast<const char*>(kRtcpPacketSrSsrc2),
sizeof(kRtcpPacketSrSsrc2), true));
}
+
+TEST(BundleFilterTest, InvalidRtpPacket) {
+ cricket::BundleFilter bundle_filter;
+ EXPECT_TRUE(bundle_filter.AddStream(StreamParams::CreateLegacy(kSsrc1)));
+ EXPECT_FALSE(bundle_filter.DemuxPacket(
+ reinterpret_cast<const char*>(kSctpPacket),
+ sizeof(kSctpPacket), false));
+}
diff --git a/session/media/call.cc b/session/media/call.cc
index 91fe146..4fbdd0f 100644
--- a/session/media/call.cc
+++ b/session/media/call.cc
@@ -26,16 +26,16 @@
*/
#include <string>
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
-#include "talk/base/window.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/screencastid.h"
#include "talk/p2p/base/parsing.h"
#include "talk/session/media/call.h"
#include "talk/session/media/currentspeakermonitor.h"
#include "talk/session/media/mediasessionclient.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/window.h"
namespace cricket {
@@ -92,9 +92,8 @@
}
Call::Call(MediaSessionClient* session_client)
- : id_(talk_base::CreateRandomId()),
+ : id_(rtc::CreateRandomId()),
session_client_(session_client),
- local_renderer_(NULL),
has_video_(false),
has_data_(false),
muted_(false),
@@ -110,7 +109,7 @@
RemoveSession(session);
session_client_->session_manager()->DestroySession(session);
}
- talk_base::Thread::Current()->Clear(this);
+ rtc::Thread::Current()->Clear(this);
}
Session* Call::InitiateSession(const buzz::Jid& to,
@@ -207,13 +206,6 @@
return session->SendInfoMessage(elems, session->remote_name());
}
-void Call::SetLocalRenderer(VideoRenderer* renderer) {
- local_renderer_ = renderer;
- if (session_client_->GetFocus() == this) {
- session_client_->channel_manager()->SetLocalRenderer(renderer);
- }
-}
-
void Call::SetVideoRenderer(Session* session, uint32 ssrc,
VideoRenderer* renderer) {
VideoChannel* video_channel = GetVideoChannel(session);
@@ -226,7 +218,7 @@
}
}
-void Call::OnMessage(talk_base::Message* message) {
+void Call::OnMessage(rtc::Message* message) {
switch (message->message_id) {
case MSG_CHECKAUTODESTROY:
// If no more sessions for this call, delete it
@@ -390,7 +382,7 @@
SignalRemoveSession(this, session);
// The call auto destroys when the last session is removed
- talk_base::Thread::Current()->Post(this, MSG_CHECKAUTODESTROY);
+ rtc::Thread::Current()->Post(this, MSG_CHECKAUTODESTROY);
}
VoiceChannel* Call::GetVoiceChannel(Session* session) const {
@@ -418,8 +410,6 @@
for (it = media_session_map_.begin(); it != media_session_map_.end(); ++it) {
EnableSessionChannels(it->second.session, enable);
}
- session_client_->channel_manager()->SetLocalRenderer(
- (enable) ? local_renderer_ : NULL);
}
void Call::EnableSessionChannels(Session* session, bool enable) {
@@ -458,7 +448,7 @@
bool Call::SendData(Session* session,
const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result) {
DataChannel* data_channel = GetDataChannel(session);
if (!data_channel) {
@@ -493,7 +483,7 @@
bool Call::StartScreencast(Session* session,
const std::string& streamid, uint32 ssrc,
- const ScreencastId& screencastid, int fps) {
+ const ScreencastId& screenid, int fps) {
MediaSessionMap::iterator it = media_session_map_.find(session->id());
if (it == media_session_map_.end()) {
return false;
@@ -506,12 +496,19 @@
return false;
}
- VideoCapturer *capturer = video_channel->AddScreencast(ssrc, screencastid);
- if (capturer == NULL) {
+ VideoCapturer* capturer = session_client_->channel_manager()->
+ CreateScreenCapturer(screenid);
+ if (!capturer) {
LOG(LS_WARNING) << "Could not create screencast capturer.";
return false;
}
+ if (!video_channel->AddScreencast(ssrc, capturer)) {
+ delete capturer;
+ LOG(LS_WARNING) << "Could not add screencast capturer.";
+ return false;
+ }
+
VideoFormat format = ScreencastFormatFromFps(fps);
if (!session_client_->channel_manager()->StartVideoCapture(
capturer, format)) {
@@ -617,7 +614,7 @@
void Call::SendVideoStreamUpdate(
Session* session, VideoContentDescription* video) {
// Takes the ownership of |video|.
- talk_base::scoped_ptr<VideoContentDescription> description(video);
+ rtc::scoped_ptr<VideoContentDescription> description(video);
const ContentInfo* video_info =
GetFirstVideoContent(session->local_description());
if (video_info == NULL) {
@@ -652,7 +649,7 @@
// Post a message to play the next tone or at least clear the playing_dtmf_
// bit.
- talk_base::Thread::Current()->PostDelayed(kDTMFDelay, this, MSG_PLAYDTMF);
+ rtc::Thread::Current()->PostDelayed(kDTMFDelay, this, MSG_PLAYDTMF);
}
}
@@ -794,7 +791,7 @@
void Call::OnDataReceived(DataChannel* channel,
const ReceiveDataParams& params,
- const talk_base::Buffer& payload) {
+ const rtc::Buffer& payload) {
SignalDataReceived(this, params, payload);
}
diff --git a/session/media/call.h b/session/media/call.h
index 063447a..be9397e 100644
--- a/session/media/call.h
+++ b/session/media/call.h
@@ -33,7 +33,6 @@
#include <string>
#include <vector>
-#include "talk/base/messagequeue.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/screencastid.h"
#include "talk/media/base/streamparams.h"
@@ -45,6 +44,7 @@
#include "talk/session/media/mediamessages.h"
#include "talk/session/media/mediasession.h"
#include "talk/xmpp/jid.h"
+#include "webrtc/base/messagequeue.h"
namespace cricket {
@@ -80,7 +80,7 @@
Call* call_;
};
-class Call : public talk_base::MessageHandler, public sigslot::has_slots<> {
+class Call : public rtc::MessageHandler, public sigslot::has_slots<> {
public:
explicit Call(MediaSessionClient* session_client);
~Call();
@@ -96,7 +96,6 @@
void Terminate();
bool SendViewRequest(Session* session,
const ViewRequest& view_request);
- void SetLocalRenderer(VideoRenderer* renderer);
void SetVideoRenderer(Session* session, uint32 ssrc,
VideoRenderer* renderer);
void StartConnectionMonitor(Session* session, int cms);
@@ -110,12 +109,12 @@
void MuteVideo(bool mute);
bool SendData(Session* session,
const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result);
void PressDTMF(int event);
bool StartScreencast(Session* session,
const std::string& stream_name, uint32 ssrc,
- const ScreencastId& screencastid, int fps);
+ const ScreencastId& screenid, int fps);
bool StopScreencast(Session* session,
const std::string& stream_name, uint32 ssrc);
@@ -187,12 +186,12 @@
const MediaStreams&> SignalMediaStreamsUpdate;
sigslot::signal3<Call*,
const ReceiveDataParams&,
- const talk_base::Buffer&> SignalDataReceived;
+ const rtc::Buffer&> SignalDataReceived;
AudioSourceProxy* GetAudioSourceProxy();
private:
- void OnMessage(talk_base::Message* message);
+ void OnMessage(rtc::Message* message);
void OnSessionState(BaseSession* base_session, BaseSession::State state);
void OnSessionError(BaseSession* base_session, Session::Error error);
void OnSessionInfoMessage(
@@ -219,7 +218,7 @@
void OnMediaMonitor(VideoChannel* channel, const VideoMediaInfo& info);
void OnDataReceived(DataChannel* channel,
const ReceiveDataParams& params,
- const talk_base::Buffer& payload);
+ const rtc::Buffer& payload);
MediaStreams* GetMediaStreams(Session* session) const;
void UpdateRemoteMediaStreams(Session* session,
const ContentInfos& updated_contents,
@@ -284,7 +283,6 @@
MediaSessionMap media_session_map_;
std::map<std::string, CurrentSpeakerMonitor*> speaker_monitor_map_;
- VideoRenderer* local_renderer_;
bool has_video_;
bool has_data_;
bool muted_;
@@ -300,7 +298,7 @@
VoiceMediaInfo last_voice_media_info_;
- talk_base::scoped_ptr<AudioSourceProxy> audio_source_proxy_;
+ rtc::scoped_ptr<AudioSourceProxy> audio_source_proxy_;
friend class MediaSessionClient;
};
diff --git a/session/media/channel.cc b/session/media/channel.cc
index 575c759..3615da8 100644
--- a/session/media/channel.cc
+++ b/session/media/channel.cc
@@ -27,23 +27,22 @@
#include "talk/session/media/channel.h"
-#include "talk/base/bind.h"
-#include "talk/base/buffer.h"
-#include "talk/base/byteorder.h"
-#include "talk/base/common.h"
-#include "talk/base/dscp.h"
-#include "talk/base/logging.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/rtputils.h"
#include "talk/p2p/base/transportchannel.h"
#include "talk/session/media/channelmanager.h"
#include "talk/session/media/mediamessages.h"
#include "talk/session/media/typingmonitor.h"
-
+#include "webrtc/base/bind.h"
+#include "webrtc/base/buffer.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/dscp.h"
+#include "webrtc/base/logging.h"
namespace cricket {
-using talk_base::Bind;
+using rtc::Bind;
enum {
MSG_EARLYMEDIATIMEOUT = 1,
@@ -73,35 +72,21 @@
}
}
-// TODO(hellner): use the device manager for creation of screen capturers when
-// the cl enabling it has landed.
-class NullScreenCapturerFactory : public VideoChannel::ScreenCapturerFactory {
- public:
- VideoCapturer* CreateScreenCapturer(const ScreencastId& window) {
- return NULL;
- }
+struct PacketMessageData : public rtc::MessageData {
+ rtc::Buffer packet;
+ rtc::DiffServCodePoint dscp;
};
-
-VideoChannel::ScreenCapturerFactory* CreateScreenCapturerFactory() {
- return new NullScreenCapturerFactory();
-}
-
-struct PacketMessageData : public talk_base::MessageData {
- talk_base::Buffer packet;
- talk_base::DiffServCodePoint dscp;
-};
-
-struct ScreencastEventMessageData : public talk_base::MessageData {
- ScreencastEventMessageData(uint32 s, talk_base::WindowEvent we)
+struct ScreencastEventMessageData : public rtc::MessageData {
+ ScreencastEventMessageData(uint32 s, rtc::WindowEvent we)
: ssrc(s),
event(we) {
}
uint32 ssrc;
- talk_base::WindowEvent event;
+ rtc::WindowEvent event;
};
-struct VoiceChannelErrorMessageData : public talk_base::MessageData {
+struct VoiceChannelErrorMessageData : public rtc::MessageData {
VoiceChannelErrorMessageData(uint32 in_ssrc,
VoiceMediaChannel::Error in_error)
: ssrc(in_ssrc),
@@ -111,7 +96,7 @@
VoiceMediaChannel::Error error;
};
-struct VideoChannelErrorMessageData : public talk_base::MessageData {
+struct VideoChannelErrorMessageData : public rtc::MessageData {
VideoChannelErrorMessageData(uint32 in_ssrc,
VideoMediaChannel::Error in_error)
: ssrc(in_ssrc),
@@ -121,7 +106,7 @@
VideoMediaChannel::Error error;
};
-struct DataChannelErrorMessageData : public talk_base::MessageData {
+struct DataChannelErrorMessageData : public rtc::MessageData {
DataChannelErrorMessageData(uint32 in_ssrc,
DataMediaChannel::Error in_error)
: ssrc(in_ssrc),
@@ -144,7 +129,7 @@
return (!rtcp) ? "RTP" : "RTCP";
}
-static bool ValidPacket(bool rtcp, const talk_base::Buffer* packet) {
+static bool ValidPacket(bool rtcp, const rtc::Buffer* packet) {
// Check the packet size. We could check the header too if needed.
return (packet &&
packet->length() >= (!rtcp ? kMinRtpPacketLen : kMinRtcpPacketLen) &&
@@ -166,7 +151,7 @@
return static_cast<const MediaContentDescription*>(cinfo->description);
}
-BaseChannel::BaseChannel(talk_base::Thread* thread,
+BaseChannel::BaseChannel(rtc::Thread* thread,
MediaEngineInterface* media_engine,
MediaChannel* media_channel, BaseSession* session,
const std::string& content_name, bool rtcp)
@@ -189,12 +174,12 @@
dtls_keyed_(false),
secure_required_(false),
rtp_abs_sendtime_extn_id_(-1) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
LOG(LS_INFO) << "Created channel for " << content_name;
}
BaseChannel::~BaseChannel() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
Deinit();
StopConnectionMonitor();
FlushRtcpMessages(); // Send any outstanding RTCP packets.
@@ -296,7 +281,7 @@
void BaseChannel::StartConnectionMonitor(int cms) {
socket_monitor_.reset(new SocketMonitor(transport_channel_,
worker_thread(),
- talk_base::Thread::Current()));
+ rtc::Thread::Current()));
socket_monitor_->SignalUpdate.connect(
this, &BaseChannel::OnConnectionMonitorUpdate);
socket_monitor_->Start(cms);
@@ -343,17 +328,17 @@
was_ever_writable();
}
-bool BaseChannel::SendPacket(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
+bool BaseChannel::SendPacket(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
return SendPacket(false, packet, dscp);
}
-bool BaseChannel::SendRtcp(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
+bool BaseChannel::SendRtcp(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
return SendPacket(true, packet, dscp);
}
-int BaseChannel::SetOption(SocketType type, talk_base::Socket::Option opt,
+int BaseChannel::SetOption(SocketType type, rtc::Socket::Option opt,
int value) {
TransportChannel* channel = NULL;
switch (type) {
@@ -379,15 +364,15 @@
void BaseChannel::OnChannelRead(TransportChannel* channel,
const char* data, size_t len,
- const talk_base::PacketTime& packet_time,
+ const rtc::PacketTime& packet_time,
int flags) {
// OnChannelRead gets called from P2PSocket; now pass data to MediaEngine
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// When using RTCP multiplexing we might get RTCP packets on the RTP
// transport. We feed RTP traffic into the demuxer to determine if it is RTCP.
bool rtcp = PacketIsRtcp(channel, data, len);
- talk_base::Buffer packet(data, len);
+ rtc::Buffer packet(data, len);
HandlePacket(rtcp, &packet, packet_time);
}
@@ -421,8 +406,8 @@
rtcp_mux_filter_.DemuxRtcp(data, static_cast<int>(len)));
}
-bool BaseChannel::SendPacket(bool rtcp, talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp) {
+bool BaseChannel::SendPacket(bool rtcp, rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp) {
// SendPacket gets called from MediaEngine, typically on an encoder thread.
// If the thread is not our worker thread, we will post to our worker
// so that the real work happens on our worker. This avoids us having to
@@ -430,7 +415,7 @@
// SRTP and the inner workings of the transport channels.
// The only downside is that we can't return a proper failure code if
// needed. Since UDP is unreliable anyway, this should be a non-issue.
- if (talk_base::Thread::Current() != worker_thread_) {
+ if (rtc::Thread::Current() != worker_thread_) {
// Avoid a copy by transferring the ownership of the packet data.
int message_id = (!rtcp) ? MSG_RTPPACKET : MSG_RTCPPACKET;
PacketMessageData* data = new PacketMessageData;
@@ -460,11 +445,11 @@
// Signal to the media sink before protecting the packet.
{
- talk_base::CritScope cs(&signal_send_packet_cs_);
+ rtc::CritScope cs(&signal_send_packet_cs_);
SignalSendPacketPreCrypto(packet->data(), packet->length(), rtcp);
}
- talk_base::PacketOptions options(dscp);
+ rtc::PacketOptions options(dscp);
// Protect if needed.
if (srtp_filter_.IsActive()) {
bool res;
@@ -534,7 +519,7 @@
// Signal to the media sink after protecting the packet.
{
- talk_base::CritScope cs(&signal_send_packet_cs_);
+ rtc::CritScope cs(&signal_send_packet_cs_);
SignalSendPacketPostCrypto(packet->data(), packet->length(), rtcp);
}
@@ -551,7 +536,7 @@
return true;
}
-bool BaseChannel::WantsPacket(bool rtcp, talk_base::Buffer* packet) {
+bool BaseChannel::WantsPacket(bool rtcp, rtc::Buffer* packet) {
// Protect ourselves against crazy data.
if (!ValidPacket(rtcp, packet)) {
LOG(LS_ERROR) << "Dropping incoming " << content_name_ << " "
@@ -564,8 +549,8 @@
return bundle_filter_.DemuxPacket(packet->data(), packet->length(), rtcp);
}
-void BaseChannel::HandlePacket(bool rtcp, talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time) {
+void BaseChannel::HandlePacket(bool rtcp, rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time) {
if (!WantsPacket(rtcp, packet)) {
return;
}
@@ -577,7 +562,7 @@
// Signal to the media sink before unprotecting the packet.
{
- talk_base::CritScope cs(&signal_recv_packet_cs_);
+ rtc::CritScope cs(&signal_recv_packet_cs_);
SignalRecvPacketPostCrypto(packet->data(), packet->length(), rtcp);
}
@@ -628,7 +613,7 @@
// Signal to the media sink after unprotecting the packet.
{
- talk_base::CritScope cs(&signal_recv_packet_cs_);
+ rtc::CritScope cs(&signal_recv_packet_cs_);
SignalRecvPacketPreCrypto(packet->data(), packet->length(), rtcp);
}
@@ -669,7 +654,7 @@
}
void BaseChannel::EnableMedia_w() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (enabled_)
return;
@@ -679,7 +664,7 @@
}
void BaseChannel::DisableMedia_w() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (!enabled_)
return;
@@ -689,7 +674,7 @@
}
bool BaseChannel::MuteStream_w(uint32 ssrc, bool mute) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
bool ret = media_channel()->MuteStream(ssrc, mute);
if (ret) {
if (mute)
@@ -701,12 +686,12 @@
}
bool BaseChannel::IsStreamMuted_w(uint32 ssrc) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
return muted_streams_.find(ssrc) != muted_streams_.end();
}
void BaseChannel::ChannelWritable_w() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (writable_)
return;
@@ -832,13 +817,13 @@
&dtls_buffer[offset], SRTP_MASTER_KEY_SALT_LEN);
std::vector<unsigned char> *send_key, *recv_key;
- talk_base::SSLRole role;
+ rtc::SSLRole role;
if (!channel->GetSslRole(&role)) {
LOG(LS_WARNING) << "GetSslRole failed";
return false;
}
- if (role == talk_base::SSL_SERVER) {
+ if (role == rtc::SSL_SERVER) {
send_key = &server_write_key;
recv_key = &client_write_key;
} else {
@@ -873,7 +858,7 @@
}
void BaseChannel::ChannelNotWritable_w() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
if (!writable_)
return;
@@ -898,6 +883,42 @@
return true;
}
+bool BaseChannel::SetRecvRtpHeaderExtensions_w(
+ const MediaContentDescription* content,
+ MediaChannel* media_channel,
+ std::string* error_desc) {
+ if (content->rtp_header_extensions_set()) {
+ if (!media_channel->SetRecvRtpHeaderExtensions(
+ content->rtp_header_extensions())) {
+ std::ostringstream desc;
+ desc << "Failed to set receive rtp header extensions for "
+ << MediaTypeToString(content->type()) << " content.";
+ SafeSetError(desc.str(), error_desc);
+ return false;
+ }
+ }
+ return true;
+}
+
+bool BaseChannel::SetSendRtpHeaderExtensions_w(
+ const MediaContentDescription* content,
+ MediaChannel* media_channel,
+ std::string* error_desc) {
+ if (content->rtp_header_extensions_set()) {
+ if (!media_channel->SetSendRtpHeaderExtensions(
+ content->rtp_header_extensions())) {
+ std::ostringstream desc;
+ desc << "Failed to set send rtp header extensions for "
+ << MediaTypeToString(content->type()) << " content.";
+ SafeSetError(desc.str(), error_desc);
+ return false;
+ } else {
+ MaybeCacheRtpAbsSendTimeHeaderExtension(content->rtp_header_extensions());
+ }
+ }
+ return true;
+}
+
bool BaseChannel::SetSrtp_w(const std::vector<CryptoParams>& cryptos,
ContentAction action,
ContentSource src,
@@ -986,7 +1007,7 @@
}
bool BaseChannel::AddRecvStream_w(const StreamParams& sp) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
if (!media_channel()->AddRecvStream(sp))
return false;
@@ -994,7 +1015,7 @@
}
bool BaseChannel::RemoveRecvStream_w(uint32 ssrc) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
bundle_filter_.RemoveStream(ssrc);
return media_channel()->RemoveRecvStream(ssrc);
}
@@ -1154,22 +1175,16 @@
std::string* error_desc) {
// Cache secure_required_ for belt and suspenders check on SendPacket
secure_required_ = content->crypto_required() != CT_NONE;
- bool ret = UpdateLocalStreams_w(content->streams(), action, error_desc);
+ // Set local RTP header extensions.
+ bool ret = SetRecvRtpHeaderExtensions_w(content, media_channel(), error_desc);
// Set local SRTP parameters (what we will encrypt with).
ret &= SetSrtp_w(content->cryptos(), action, CS_LOCAL, error_desc);
// Set local RTCP mux parameters.
ret &= SetRtcpMux_w(content->rtcp_mux(), action, CS_LOCAL, error_desc);
- // Set local RTP header extensions.
- if (content->rtp_header_extensions_set()) {
- if (!media_channel()->SetRecvRtpHeaderExtensions(
- content->rtp_header_extensions())) {
- std::ostringstream desc;
- desc << "Failed to set receive rtp header extensions for "
- << MediaTypeToString(content->type()) << " content.";
- SafeSetError(desc.str(), error_desc);
- ret = false;
- }
- }
+
+ // Call UpdateLocalStreams_w last to make sure as many settings as possible
+ // are already set when creating streams.
+ ret &= UpdateLocalStreams_w(content->streams(), action, error_desc);
set_local_content_direction(content->direction());
return ret;
}
@@ -1177,25 +1192,12 @@
bool BaseChannel::SetBaseRemoteContent_w(const MediaContentDescription* content,
ContentAction action,
std::string* error_desc) {
- bool ret = UpdateRemoteStreams_w(content->streams(), action, error_desc);
+ // Set remote RTP header extensions.
+ bool ret = SetSendRtpHeaderExtensions_w(content, media_channel(), error_desc);
// Set remote SRTP parameters (what the other side will encrypt with).
ret &= SetSrtp_w(content->cryptos(), action, CS_REMOTE, error_desc);
// Set remote RTCP mux parameters.
ret &= SetRtcpMux_w(content->rtcp_mux(), action, CS_REMOTE, error_desc);
- // Set remote RTP header extensions.
- if (content->rtp_header_extensions_set()) {
- if (!media_channel()->SetSendRtpHeaderExtensions(
- content->rtp_header_extensions())) {
- std::ostringstream desc;
- desc << "Failed to set send rtp header extensions for "
- << MediaTypeToString(content->type()) << " content.";
- SafeSetError(desc.str(), error_desc);
- ret = false;
- } else {
- MaybeCacheRtpAbsSendTimeHeaderExtension(content->rtp_header_extensions());
- }
- }
-
if (!media_channel()->SetMaxSendBandwidth(content->bandwidth())) {
std::ostringstream desc;
desc << "Failed to set max send bandwidth for "
@@ -1203,6 +1205,10 @@
SafeSetError(desc.str(), error_desc);
ret = false;
}
+
+ // Call UpdateRemoteStreams_w last to make sure as many settings as possible
+ // are already set when creating streams.
+ ret &= UpdateRemoteStreams_w(content->streams(), action, error_desc);
set_remote_content_direction(content->direction());
return ret;
}
@@ -1215,7 +1221,7 @@
send_time_extension ? send_time_extension->id : -1;
}
-void BaseChannel::OnMessage(talk_base::Message *pmsg) {
+void BaseChannel::OnMessage(rtc::Message *pmsg) {
switch (pmsg->message_id) {
case MSG_RTPPACKET:
case MSG_RTCPPACKET: {
@@ -1234,16 +1240,16 @@
void BaseChannel::FlushRtcpMessages() {
// Flush all remaining RTCP messages. This should only be called in
// destructor.
- ASSERT(talk_base::Thread::Current() == worker_thread_);
- talk_base::MessageList rtcp_messages;
+ ASSERT(rtc::Thread::Current() == worker_thread_);
+ rtc::MessageList rtcp_messages;
worker_thread_->Clear(this, MSG_RTCPPACKET, &rtcp_messages);
- for (talk_base::MessageList::iterator it = rtcp_messages.begin();
+ for (rtc::MessageList::iterator it = rtcp_messages.begin();
it != rtcp_messages.end(); ++it) {
worker_thread_->Send(this, MSG_RTCPPACKET, it->pdata);
}
}
-VoiceChannel::VoiceChannel(talk_base::Thread* thread,
+VoiceChannel::VoiceChannel(rtc::Thread* thread,
MediaEngineInterface* media_engine,
VoiceMediaChannel* media_channel,
BaseSession* session,
@@ -1344,7 +1350,7 @@
void VoiceChannel::StartMediaMonitor(int cms) {
media_monitor_.reset(new VoiceMediaMonitor(media_channel(), worker_thread(),
- talk_base::Thread::Current()));
+ rtc::Thread::Current()));
media_monitor_->SignalUpdate.connect(
this, &VoiceChannel::OnMediaMonitorUpdate);
media_monitor_->Start(cms);
@@ -1359,7 +1365,7 @@
}
void VoiceChannel::StartAudioMonitor(int cms) {
- audio_monitor_.reset(new AudioMonitor(this, talk_base::Thread::Current()));
+ audio_monitor_.reset(new AudioMonitor(this, rtc::Thread::Current()));
audio_monitor_
->SignalUpdate.connect(this, &VoiceChannel::OnAudioMonitorUpdate);
audio_monitor_->Start(cms);
@@ -1410,7 +1416,7 @@
void VoiceChannel::OnChannelRead(TransportChannel* channel,
const char* data, size_t len,
- const talk_base::PacketTime& packet_time,
+ const rtc::PacketTime& packet_time,
int flags) {
BaseChannel::OnChannelRead(channel, data, len, packet_time, flags);
@@ -1449,7 +1455,7 @@
bool VoiceChannel::SetLocalContent_w(const MediaContentDescription* content,
ContentAction action,
std::string* error_desc) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
LOG(LS_INFO) << "Setting local voice description";
const AudioContentDescription* audio =
@@ -1487,7 +1493,7 @@
bool VoiceChannel::SetRemoteContent_w(const MediaContentDescription* content,
ContentAction action,
std::string* error_desc) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
LOG(LS_INFO) << "Setting remote voice description";
const AudioContentDescription* audio =
@@ -1538,12 +1544,12 @@
}
bool VoiceChannel::SetRingbackTone_w(const void* buf, int len) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
return media_channel()->SetRingbackTone(static_cast<const char*>(buf), len);
}
bool VoiceChannel::PlayRingbackTone_w(uint32 ssrc, bool play, bool loop) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
if (play) {
LOG(LS_INFO) << "Playing ringback tone, loop=" << loop;
} else {
@@ -1574,7 +1580,7 @@
media_channel(), options));
}
-void VoiceChannel::OnMessage(talk_base::Message *pmsg) {
+void VoiceChannel::OnMessage(rtc::Message *pmsg) {
switch (pmsg->message_id) {
case MSG_EARLYMEDIATIMEOUT:
HandleEarlyMediaTimeout();
@@ -1642,7 +1648,7 @@
GetSupportedAudioCryptoSuites(ciphers);
}
-VideoChannel::VideoChannel(talk_base::Thread* thread,
+VideoChannel::VideoChannel(rtc::Thread* thread,
MediaEngineInterface* media_engine,
VideoMediaChannel* media_channel,
BaseSession* session,
@@ -1653,8 +1659,7 @@
rtcp),
voice_channel_(voice_channel),
renderer_(NULL),
- screencapture_factory_(CreateScreenCapturerFactory()),
- previous_we_(talk_base::WE_CLOSE) {
+ previous_we_(rtc::WE_CLOSE) {
}
bool VideoChannel::Init() {
@@ -1708,10 +1713,9 @@
return InvokeOnWorker(Bind(&VideoChannel::ApplyViewRequest_w, this, request));
}
-VideoCapturer* VideoChannel::AddScreencast(
- uint32 ssrc, const ScreencastId& id) {
- return worker_thread()->Invoke<VideoCapturer*>(Bind(
- &VideoChannel::AddScreencast_w, this, ssrc, id));
+bool VideoChannel::AddScreencast(uint32 ssrc, VideoCapturer* capturer) {
+ return worker_thread()->Invoke<bool>(Bind(
+ &VideoChannel::AddScreencast_w, this, ssrc, capturer));
}
bool VideoChannel::SetCapturer(uint32 ssrc, VideoCapturer* capturer) {
@@ -1753,13 +1757,6 @@
return true;
}
-void VideoChannel::SetScreenCaptureFactory(
- ScreenCapturerFactory* screencapture_factory) {
- worker_thread()->Invoke<void>(Bind(
- &VideoChannel::SetScreenCaptureFactory_w,
- this, screencapture_factory));
-}
-
void VideoChannel::ChangeState() {
// Render incoming data if we're the active call, and we have the local
// content. We receive data on the default channel and multiplexed streams.
@@ -1788,7 +1785,7 @@
void VideoChannel::StartMediaMonitor(int cms) {
media_monitor_.reset(new VideoMediaMonitor(media_channel(), worker_thread(),
- talk_base::Thread::Current()));
+ rtc::Thread::Current()));
media_monitor_->SignalUpdate.connect(
this, &VideoChannel::OnMediaMonitorUpdate);
media_monitor_->Start(cms);
@@ -1809,7 +1806,7 @@
bool VideoChannel::SetLocalContent_w(const MediaContentDescription* content,
ContentAction action,
std::string* error_desc) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
LOG(LS_INFO) << "Setting local video description";
const VideoContentDescription* video =
@@ -1856,7 +1853,7 @@
bool VideoChannel::SetRemoteContent_w(const MediaContentDescription* content,
ContentAction action,
std::string* error_desc) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
LOG(LS_INFO) << "Setting remote video description";
const VideoContentDescription* video =
@@ -1939,20 +1936,13 @@
return ret;
}
-VideoCapturer* VideoChannel::AddScreencast_w(
- uint32 ssrc, const ScreencastId& id) {
+bool VideoChannel::AddScreencast_w(uint32 ssrc, VideoCapturer* capturer) {
if (screencast_capturers_.find(ssrc) != screencast_capturers_.end()) {
- return NULL;
+ return false;
}
- VideoCapturer* screen_capturer =
- screencapture_factory_->CreateScreenCapturer(id);
- if (!screen_capturer) {
- return NULL;
- }
- screen_capturer->SignalStateChange.connect(this,
- &VideoChannel::OnStateChange);
- screencast_capturers_[ssrc] = screen_capturer;
- return screen_capturer;
+ capturer->SignalStateChange.connect(this, &VideoChannel::OnStateChange);
+ screencast_capturers_[ssrc] = capturer;
+ return true;
}
bool VideoChannel::RemoveScreencast_w(uint32 ssrc) {
@@ -1982,18 +1972,9 @@
data->screencast_max_pixels = capturer->screencast_max_pixels();
}
-void VideoChannel::SetScreenCaptureFactory_w(
- ScreenCapturerFactory* screencapture_factory) {
- if (screencapture_factory == NULL) {
- screencapture_factory_.reset(CreateScreenCapturerFactory());
- } else {
- screencapture_factory_.reset(screencapture_factory);
- }
-}
-
void VideoChannel::OnScreencastWindowEvent_s(uint32 ssrc,
- talk_base::WindowEvent we) {
- ASSERT(signaling_thread() == talk_base::Thread::Current());
+ rtc::WindowEvent we) {
+ ASSERT(signaling_thread() == rtc::Thread::Current());
SignalScreencastWindowEvent(ssrc, we);
}
@@ -2002,7 +1983,7 @@
media_channel(), options));
}
-void VideoChannel::OnMessage(talk_base::Message *pmsg) {
+void VideoChannel::OnMessage(rtc::Message *pmsg) {
switch (pmsg->message_id) {
case MSG_SCREENCASTWINDOWEVENT: {
const ScreencastEventMessageData* data =
@@ -2038,7 +2019,7 @@
}
void VideoChannel::OnScreencastWindowEvent(uint32 ssrc,
- talk_base::WindowEvent event) {
+ rtc::WindowEvent event) {
ScreencastEventMessageData* pdata =
new ScreencastEventMessageData(ssrc, event);
signaling_thread()->Post(this, MSG_SCREENCASTWINDOWEVENT, pdata);
@@ -2047,13 +2028,13 @@
void VideoChannel::OnStateChange(VideoCapturer* capturer, CaptureState ev) {
// Map capturer events to window events. In the future we may want to simply
// pass these events up directly.
- talk_base::WindowEvent we;
+ rtc::WindowEvent we;
if (ev == CS_STOPPED) {
- we = talk_base::WE_CLOSE;
+ we = rtc::WE_CLOSE;
} else if (ev == CS_PAUSED) {
- we = talk_base::WE_MINIMIZE;
- } else if (ev == CS_RUNNING && previous_we_ == talk_base::WE_MINIMIZE) {
- we = talk_base::WE_RESTORE;
+ we = rtc::WE_MINIMIZE;
+ } else if (ev == CS_RUNNING && previous_we_ == rtc::WE_MINIMIZE) {
+ we = rtc::WE_RESTORE;
} else {
return;
}
@@ -2116,7 +2097,7 @@
GetSupportedVideoCryptoSuites(ciphers);
}
-DataChannel::DataChannel(talk_base::Thread* thread,
+DataChannel::DataChannel(rtc::Thread* thread,
DataMediaChannel* media_channel,
BaseSession* session,
const std::string& content_name,
@@ -2157,7 +2138,7 @@
}
bool DataChannel::SendData(const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result) {
return InvokeOnWorker(Bind(&DataMediaChannel::SendData,
media_channel(), params, payload, result));
@@ -2168,21 +2149,11 @@
return GetFirstDataContent(sdesc);
}
-
-static bool IsRtpPacket(const talk_base::Buffer* packet) {
- int version;
- if (!GetRtpVersion(packet->data(), packet->length(), &version)) {
- return false;
- }
-
- return version == 2;
-}
-
-bool DataChannel::WantsPacket(bool rtcp, talk_base::Buffer* packet) {
+bool DataChannel::WantsPacket(bool rtcp, rtc::Buffer* packet) {
if (data_channel_type_ == DCT_SCTP) {
// TODO(pthatcher): Do this in a more robust way by checking for
// SCTP or DTLS.
- return !IsRtpPacket(packet);
+ return !IsRtpPacket(packet->data(), packet->length());
} else if (data_channel_type_ == DCT_RTP) {
return BaseChannel::WantsPacket(rtcp, packet);
}
@@ -2223,7 +2194,7 @@
bool DataChannel::SetLocalContent_w(const MediaContentDescription* content,
ContentAction action,
std::string* error_desc) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
LOG(LS_INFO) << "Setting local data description";
const DataContentDescription* data =
@@ -2277,7 +2248,7 @@
bool DataChannel::SetRemoteContent_w(const MediaContentDescription* content,
ContentAction action,
std::string* error_desc) {
- ASSERT(worker_thread() == talk_base::Thread::Current());
+ ASSERT(worker_thread() == rtc::Thread::Current());
const DataContentDescription* data =
static_cast<const DataContentDescription*>(content);
@@ -2366,7 +2337,7 @@
LOG(LS_INFO) << "Changing data state, recv=" << recv << " send=" << send;
}
-void DataChannel::OnMessage(talk_base::Message *pmsg) {
+void DataChannel::OnMessage(rtc::Message *pmsg) {
switch (pmsg->message_id) {
case MSG_READYTOSENDDATA: {
DataChannelReadyToSendMessageData* data =
@@ -2391,8 +2362,8 @@
break;
}
case MSG_STREAMCLOSEDREMOTELY: {
- talk_base::TypedMessageData<uint32>* data =
- static_cast<talk_base::TypedMessageData<uint32>*>(pmsg->pdata);
+ rtc::TypedMessageData<uint32>* data =
+ static_cast<rtc::TypedMessageData<uint32>*>(pmsg->pdata);
SignalStreamClosedRemotely(data->data());
delete data;
break;
@@ -2410,7 +2381,7 @@
void DataChannel::StartMediaMonitor(int cms) {
media_monitor_.reset(new DataMediaMonitor(media_channel(), worker_thread(),
- talk_base::Thread::Current()));
+ rtc::Thread::Current()));
media_monitor_->SignalUpdate.connect(
this, &DataChannel::OnMediaMonitorUpdate);
media_monitor_->Start(cms);
@@ -2484,8 +2455,8 @@
}
void DataChannel::OnStreamClosedRemotely(uint32 sid) {
- talk_base::TypedMessageData<uint32>* message =
- new talk_base::TypedMessageData<uint32>(sid);
+ rtc::TypedMessageData<uint32>* message =
+ new rtc::TypedMessageData<uint32>(sid);
signaling_thread()->Post(this, MSG_STREAMCLOSEDREMOTELY, message);
}
diff --git a/session/media/channel.h b/session/media/channel.h
index d48a64e..6da29a4 100644
--- a/session/media/channel.h
+++ b/session/media/channel.h
@@ -31,14 +31,8 @@
#include <string>
#include <vector>
-#include "talk/base/asyncudpsocket.h"
-#include "talk/base/criticalsection.h"
-#include "talk/base/network.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/window.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/mediaengine.h"
-#include "talk/media/base/screencastid.h"
#include "talk/media/base/streamparams.h"
#include "talk/media/base/videocapturer.h"
#include "talk/p2p/base/session.h"
@@ -49,6 +43,11 @@
#include "talk/session/media/mediasession.h"
#include "talk/session/media/rtcpmuxfilter.h"
#include "talk/session/media/srtpfilter.h"
+#include "webrtc/base/asyncudpsocket.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/network.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/window.h"
namespace cricket {
@@ -73,10 +72,10 @@
// NetworkInterface.
class BaseChannel
- : public talk_base::MessageHandler, public sigslot::has_slots<>,
+ : public rtc::MessageHandler, public sigslot::has_slots<>,
public MediaChannel::NetworkInterface {
public:
- BaseChannel(talk_base::Thread* thread, MediaEngineInterface* media_engine,
+ BaseChannel(rtc::Thread* thread, MediaEngineInterface* media_engine,
MediaChannel* channel, BaseSession* session,
const std::string& content_name, bool rtcp);
virtual ~BaseChannel();
@@ -86,7 +85,7 @@
// done.
void Deinit();
- talk_base::Thread* worker_thread() const { return worker_thread_; }
+ rtc::Thread* worker_thread() const { return worker_thread_; }
BaseSession* session() const { return session_; }
const std::string& content_name() { return content_name_; }
TransportChannel* transport_channel() const {
@@ -151,7 +150,7 @@
void RegisterSendSink(T* sink,
void (T::*OnPacket)(const void*, size_t, bool),
SinkType type) {
- talk_base::CritScope cs(&signal_send_packet_cs_);
+ rtc::CritScope cs(&signal_send_packet_cs_);
if (SINK_POST_CRYPTO == type) {
SignalSendPacketPostCrypto.disconnect(sink);
SignalSendPacketPostCrypto.connect(sink, OnPacket);
@@ -163,7 +162,7 @@
void UnregisterSendSink(sigslot::has_slots<>* sink,
SinkType type) {
- talk_base::CritScope cs(&signal_send_packet_cs_);
+ rtc::CritScope cs(&signal_send_packet_cs_);
if (SINK_POST_CRYPTO == type) {
SignalSendPacketPostCrypto.disconnect(sink);
} else {
@@ -172,7 +171,7 @@
}
bool HasSendSinks(SinkType type) {
- talk_base::CritScope cs(&signal_send_packet_cs_);
+ rtc::CritScope cs(&signal_send_packet_cs_);
if (SINK_POST_CRYPTO == type) {
return !SignalSendPacketPostCrypto.is_empty();
} else {
@@ -184,7 +183,7 @@
void RegisterRecvSink(T* sink,
void (T::*OnPacket)(const void*, size_t, bool),
SinkType type) {
- talk_base::CritScope cs(&signal_recv_packet_cs_);
+ rtc::CritScope cs(&signal_recv_packet_cs_);
if (SINK_POST_CRYPTO == type) {
SignalRecvPacketPostCrypto.disconnect(sink);
SignalRecvPacketPostCrypto.connect(sink, OnPacket);
@@ -196,7 +195,7 @@
void UnregisterRecvSink(sigslot::has_slots<>* sink,
SinkType type) {
- talk_base::CritScope cs(&signal_recv_packet_cs_);
+ rtc::CritScope cs(&signal_recv_packet_cs_);
if (SINK_POST_CRYPTO == type) {
SignalRecvPacketPostCrypto.disconnect(sink);
} else {
@@ -205,7 +204,7 @@
}
bool HasRecvSinks(SinkType type) {
- talk_base::CritScope cs(&signal_recv_packet_cs_);
+ rtc::CritScope cs(&signal_recv_packet_cs_);
if (SINK_POST_CRYPTO == type) {
return !SignalRecvPacketPostCrypto.is_empty();
} else {
@@ -244,35 +243,35 @@
}
bool IsReadyToReceive() const;
bool IsReadyToSend() const;
- talk_base::Thread* signaling_thread() { return session_->signaling_thread(); }
+ rtc::Thread* signaling_thread() { return session_->signaling_thread(); }
SrtpFilter* srtp_filter() { return &srtp_filter_; }
bool rtcp() const { return rtcp_; }
void FlushRtcpMessages();
// NetworkInterface implementation, called by MediaEngine
- virtual bool SendPacket(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp);
- virtual bool SendRtcp(talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp);
- virtual int SetOption(SocketType type, talk_base::Socket::Option o, int val);
+ virtual bool SendPacket(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp);
+ virtual bool SendRtcp(rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp);
+ virtual int SetOption(SocketType type, rtc::Socket::Option o, int val);
// From TransportChannel
void OnWritableState(TransportChannel* channel);
virtual void OnChannelRead(TransportChannel* channel,
const char* data,
size_t len,
- const talk_base::PacketTime& packet_time,
+ const rtc::PacketTime& packet_time,
int flags);
void OnReadyToSend(TransportChannel* channel);
bool PacketIsRtcp(const TransportChannel* channel, const char* data,
size_t len);
- bool SendPacket(bool rtcp, talk_base::Buffer* packet,
- talk_base::DiffServCodePoint dscp);
- virtual bool WantsPacket(bool rtcp, talk_base::Buffer* packet);
- void HandlePacket(bool rtcp, talk_base::Buffer* packet,
- const talk_base::PacketTime& packet_time);
+ bool SendPacket(bool rtcp, rtc::Buffer* packet,
+ rtc::DiffServCodePoint dscp);
+ virtual bool WantsPacket(bool rtcp, rtc::Buffer* packet);
+ void HandlePacket(bool rtcp, rtc::Buffer* packet,
+ const rtc::PacketTime& packet_time);
// Apply the new local/remote session description.
void OnNewLocalDescription(BaseSession* session, ContentAction action);
@@ -324,6 +323,13 @@
void MaybeCacheRtpAbsSendTimeHeaderExtension(
const std::vector<RtpHeaderExtension>& extensions);
+ bool SetRecvRtpHeaderExtensions_w(const MediaContentDescription* content,
+ MediaChannel* media_channel,
+ std::string* error_desc);
+ bool SetSendRtpHeaderExtensions_w(const MediaContentDescription* content,
+ MediaChannel* media_channel,
+ std::string* error_desc);
+
bool CheckSrtpConfig(const std::vector<CryptoParams>& cryptos,
bool* dtls,
std::string* error_desc);
@@ -337,7 +343,7 @@
std::string* error_desc);
// From MessageHandler
- virtual void OnMessage(talk_base::Message* pmsg);
+ virtual void OnMessage(rtc::Message* pmsg);
// Handled in derived classes
// Get the SRTP ciphers to use for RTP media
@@ -356,10 +362,10 @@
sigslot::signal3<const void*, size_t, bool> SignalSendPacketPostCrypto;
sigslot::signal3<const void*, size_t, bool> SignalRecvPacketPreCrypto;
sigslot::signal3<const void*, size_t, bool> SignalRecvPacketPostCrypto;
- talk_base::CriticalSection signal_send_packet_cs_;
- talk_base::CriticalSection signal_recv_packet_cs_;
+ rtc::CriticalSection signal_send_packet_cs_;
+ rtc::CriticalSection signal_recv_packet_cs_;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* worker_thread_;
MediaEngineInterface* media_engine_;
BaseSession* session_;
MediaChannel* media_channel_;
@@ -373,7 +379,7 @@
SrtpFilter srtp_filter_;
RtcpMuxFilter rtcp_mux_filter_;
BundleFilter bundle_filter_;
- talk_base::scoped_ptr<SocketMonitor> socket_monitor_;
+ rtc::scoped_ptr<SocketMonitor> socket_monitor_;
bool enabled_;
bool writable_;
bool rtp_ready_to_send_;
@@ -392,7 +398,7 @@
// and input/output level monitoring.
class VoiceChannel : public BaseChannel {
public:
- VoiceChannel(talk_base::Thread* thread, MediaEngineInterface* media_engine,
+ VoiceChannel(rtc::Thread* thread, MediaEngineInterface* media_engine,
VoiceMediaChannel* channel, BaseSession* session,
const std::string& content_name, bool rtcp);
~VoiceChannel();
@@ -463,7 +469,7 @@
// overrides from BaseChannel
virtual void OnChannelRead(TransportChannel* channel,
const char* data, size_t len,
- const talk_base::PacketTime& packet_time,
+ const rtc::PacketTime& packet_time,
int flags);
virtual void ChangeState();
virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
@@ -480,7 +486,7 @@
bool SetOutputScaling_w(uint32 ssrc, double left, double right);
bool GetStats_w(VoiceMediaInfo* stats);
- virtual void OnMessage(talk_base::Message* pmsg);
+ virtual void OnMessage(rtc::Message* pmsg);
virtual void GetSrtpCiphers(std::vector<std::string>* ciphers) const;
virtual void OnConnectionMonitorUpdate(
SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos);
@@ -493,23 +499,15 @@
static const int kEarlyMediaTimeout = 1000;
bool received_media_;
- talk_base::scoped_ptr<VoiceMediaMonitor> media_monitor_;
- talk_base::scoped_ptr<AudioMonitor> audio_monitor_;
- talk_base::scoped_ptr<TypingMonitor> typing_monitor_;
+ rtc::scoped_ptr<VoiceMediaMonitor> media_monitor_;
+ rtc::scoped_ptr<AudioMonitor> audio_monitor_;
+ rtc::scoped_ptr<TypingMonitor> typing_monitor_;
};
// VideoChannel is a specialization for video.
class VideoChannel : public BaseChannel {
public:
- // Make screen capturer virtual so that it can be overriden in testing.
- // E.g. used to test that window events are triggered correctly.
- class ScreenCapturerFactory {
- public:
- virtual VideoCapturer* CreateScreenCapturer(const ScreencastId& window) = 0;
- virtual ~ScreenCapturerFactory() {}
- };
-
- VideoChannel(talk_base::Thread* thread, MediaEngineInterface* media_engine,
+ VideoChannel(rtc::Thread* thread, MediaEngineInterface* media_engine,
VideoMediaChannel* channel, BaseSession* session,
const std::string& content_name, bool rtcp,
VoiceChannel* voice_channel);
@@ -521,7 +519,8 @@
// TODO(pthatcher): Refactor to use a "capture id" instead of an
// ssrc here as the "key".
- VideoCapturer* AddScreencast(uint32 ssrc, const ScreencastId& id);
+ // Passes ownership of the capturer to the channel.
+ bool AddScreencast(uint32 ssrc, VideoCapturer* capturer);
bool SetCapturer(uint32 ssrc, VideoCapturer* capturer);
bool RemoveScreencast(uint32 ssrc);
// True if we've added a screencast. Doesn't matter if the capturer
@@ -538,16 +537,13 @@
void StartMediaMonitor(int cms);
void StopMediaMonitor();
sigslot::signal2<VideoChannel*, const VideoMediaInfo&> SignalMediaMonitor;
- sigslot::signal2<uint32, talk_base::WindowEvent> SignalScreencastWindowEvent;
+ sigslot::signal2<uint32, rtc::WindowEvent> SignalScreencastWindowEvent;
bool SendIntraFrame();
bool RequestIntraFrame();
sigslot::signal3<VideoChannel*, uint32, VideoMediaChannel::Error>
SignalMediaError;
- void SetScreenCaptureFactory(
- ScreenCapturerFactory* screencapture_factory);
-
// Configuration and setting.
bool SetChannelOptions(const VideoOptions& options);
@@ -572,23 +568,21 @@
std::string* error_desc);
bool ApplyViewRequest_w(const ViewRequest& request);
- VideoCapturer* AddScreencast_w(uint32 ssrc, const ScreencastId& id);
+ bool AddScreencast_w(uint32 ssrc, VideoCapturer* capturer);
bool RemoveScreencast_w(uint32 ssrc);
- void OnScreencastWindowEvent_s(uint32 ssrc, talk_base::WindowEvent we);
+ void OnScreencastWindowEvent_s(uint32 ssrc, rtc::WindowEvent we);
bool IsScreencasting_w() const;
void GetScreencastDetails_w(ScreencastDetailsData* d) const;
- void SetScreenCaptureFactory_w(
- ScreenCapturerFactory* screencapture_factory);
bool GetStats_w(VideoMediaInfo* stats);
- virtual void OnMessage(talk_base::Message* pmsg);
+ virtual void OnMessage(rtc::Message* pmsg);
virtual void GetSrtpCiphers(std::vector<std::string>* ciphers) const;
virtual void OnConnectionMonitorUpdate(
SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos);
virtual void OnMediaMonitorUpdate(
VideoMediaChannel* media_channel, const VideoMediaInfo& info);
virtual void OnScreencastWindowEvent(uint32 ssrc,
- talk_base::WindowEvent event);
+ rtc::WindowEvent event);
virtual void OnStateChange(VideoCapturer* capturer, CaptureState ev);
bool GetLocalSsrc(const VideoCapturer* capturer, uint32* ssrc);
@@ -597,17 +591,16 @@
VoiceChannel* voice_channel_;
VideoRenderer* renderer_;
- talk_base::scoped_ptr<ScreenCapturerFactory> screencapture_factory_;
ScreencastMap screencast_capturers_;
- talk_base::scoped_ptr<VideoMediaMonitor> media_monitor_;
+ rtc::scoped_ptr<VideoMediaMonitor> media_monitor_;
- talk_base::WindowEvent previous_we_;
+ rtc::WindowEvent previous_we_;
};
// DataChannel is a specialization for data.
class DataChannel : public BaseChannel {
public:
- DataChannel(talk_base::Thread* thread,
+ DataChannel(rtc::Thread* thread,
DataMediaChannel* media_channel,
BaseSession* session,
const std::string& content_name,
@@ -616,7 +609,7 @@
bool Init();
virtual bool SendData(const SendDataParams& params,
- const talk_base::Buffer& payload,
+ const rtc::Buffer& payload,
SendDataResult* result);
void StartMediaMonitor(int cms);
@@ -634,7 +627,7 @@
SignalMediaError;
sigslot::signal3<DataChannel*,
const ReceiveDataParams&,
- const talk_base::Buffer&>
+ const rtc::Buffer&>
SignalDataReceived;
// Signal for notifying when the channel becomes ready to send data.
// That occurs when the channel is enabled, the transport is writable,
@@ -650,9 +643,9 @@
}
private:
- struct SendDataMessageData : public talk_base::MessageData {
+ struct SendDataMessageData : public rtc::MessageData {
SendDataMessageData(const SendDataParams& params,
- const talk_base::Buffer* payload,
+ const rtc::Buffer* payload,
SendDataResult* result)
: params(params),
payload(payload),
@@ -661,12 +654,12 @@
}
const SendDataParams& params;
- const talk_base::Buffer* payload;
+ const rtc::Buffer* payload;
SendDataResult* result;
bool succeeded;
};
- struct DataReceivedMessageData : public talk_base::MessageData {
+ struct DataReceivedMessageData : public rtc::MessageData {
// We copy the data because the data will become invalid after we
// handle DataMediaChannel::SignalDataReceived but before we fire
// SignalDataReceived.
@@ -676,10 +669,10 @@
payload(data, len) {
}
const ReceiveDataParams params;
- const talk_base::Buffer payload;
+ const rtc::Buffer payload;
};
- typedef talk_base::TypedMessageData<bool> DataChannelReadyToSendMessageData;
+ typedef rtc::TypedMessageData<bool> DataChannelReadyToSendMessageData;
// overrides from BaseChannel
virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
@@ -699,9 +692,9 @@
ContentAction action,
std::string* error_desc);
virtual void ChangeState();
- virtual bool WantsPacket(bool rtcp, talk_base::Buffer* packet);
+ virtual bool WantsPacket(bool rtcp, rtc::Buffer* packet);
- virtual void OnMessage(talk_base::Message* pmsg);
+ virtual void OnMessage(rtc::Message* pmsg);
virtual void GetSrtpCiphers(std::vector<std::string>* ciphers) const;
virtual void OnConnectionMonitorUpdate(
SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos);
@@ -715,7 +708,7 @@
void OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode, SrtpFilter::Error error);
void OnStreamClosedRemotely(uint32 sid);
- talk_base::scoped_ptr<DataMediaMonitor> media_monitor_;
+ rtc::scoped_ptr<DataMediaMonitor> media_monitor_;
// TODO(pthatcher): Make a separate SctpDataChannel and
// RtpDataChannel instead of using this.
DataChannelType data_channel_type_;
diff --git a/session/media/channel_unittest.cc b/session/media/channel_unittest.cc
index c22361d..625b802 100644
--- a/session/media/channel_unittest.cc
+++ b/session/media/channel_unittest.cc
@@ -23,17 +23,9 @@
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/signalthread.h"
-#include "talk/base/ssladapter.h"
-#include "talk/base/sslidentity.h"
-#include "talk/base/window.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/fakertp.h"
+#include "talk/media/base/fakescreencapturerfactory.h"
#include "talk/media/base/fakevideocapturer.h"
#include "talk/media/base/mediachannel.h"
#include "talk/media/base/rtpdump.h"
@@ -45,9 +37,18 @@
#include "talk/session/media/mediarecorder.h"
#include "talk/session/media/mediasessionclient.h"
#include "talk/session/media/typingmonitor.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/signalthread.h"
+#include "webrtc/base/ssladapter.h"
+#include "webrtc/base/sslidentity.h"
+#include "webrtc/base/window.h"
#define MAYBE_SKIP_TEST(feature) \
- if (!(talk_base::SSLStreamAdapter::feature())) { \
+ if (!(rtc::SSLStreamAdapter::feature())) { \
LOG(LS_INFO) << "Feature disabled... skipping"; \
return; \
}
@@ -60,7 +61,7 @@
using cricket::ScreencastId;
using cricket::StreamParams;
using cricket::TransportChannel;
-using talk_base::WindowId;
+using rtc::WindowId;
static const cricket::AudioCodec kPcmuCodec(0, "PCMU", 64000, 8000, 1, 0);
static const cricket::AudioCodec kPcmaCodec(8, "PCMA", 64000, 8000, 1, 0);
@@ -88,49 +89,6 @@
typedef MediaInfoT MediaInfo;
};
-class FakeScreenCaptureFactory
- : public cricket::VideoChannel::ScreenCapturerFactory,
- public sigslot::has_slots<> {
- public:
- FakeScreenCaptureFactory()
- : window_capturer_(NULL),
- capture_state_(cricket::CS_STOPPED) {}
-
- virtual cricket::VideoCapturer* CreateScreenCapturer(
- const ScreencastId& window) {
- if (window_capturer_ != NULL) {
- // Class is only designed to handle one fake screencapturer.
- ADD_FAILURE();
- return NULL;
- }
- window_capturer_ = new cricket::FakeVideoCapturer;
- window_capturer_->SignalDestroyed.connect(
- this,
- &FakeScreenCaptureFactory::OnWindowCapturerDestroyed);
- window_capturer_->SignalStateChange.connect(
- this,
- &FakeScreenCaptureFactory::OnStateChange);
- return window_capturer_;
- }
-
- cricket::FakeVideoCapturer* window_capturer() { return window_capturer_; }
-
- cricket::CaptureState capture_state() { return capture_state_; }
-
- private:
- void OnWindowCapturerDestroyed(cricket::FakeVideoCapturer* capturer) {
- if (capturer == window_capturer_) {
- window_capturer_ = NULL;
- }
- }
- void OnStateChange(cricket::VideoCapturer*, cricket::CaptureState state) {
- capture_state_ = state;
- }
-
- cricket::FakeVideoCapturer* window_capturer_;
- cricket::CaptureState capture_state_;
-};
-
// Controls how long we wait for a session to send messages that we
// expect, in milliseconds. We put it high to avoid flaky tests.
static const int kEventTimeout = 5000;
@@ -157,9 +115,9 @@
};
-talk_base::StreamInterface* Open(const std::string& path) {
- return talk_base::Filesystem::OpenFile(
- talk_base::Pathname(path), "wb");
+rtc::StreamInterface* Open(const std::string& path) {
+ return rtc::Filesystem::OpenFile(
+ rtc::Pathname(path), "wb");
}
// Base class for Voice/VideoChannel tests
@@ -186,38 +144,38 @@
}
static void SetUpTestCase() {
- talk_base::InitializeSSL();
+ rtc::InitializeSSL();
}
static void TearDownTestCase() {
- talk_base::CleanupSSL();
+ rtc::CleanupSSL();
}
void CreateChannels(int flags1, int flags2) {
CreateChannels(new typename T::MediaChannel(NULL),
new typename T::MediaChannel(NULL),
- flags1, flags2, talk_base::Thread::Current());
+ flags1, flags2, rtc::Thread::Current());
}
void CreateChannels(int flags) {
CreateChannels(new typename T::MediaChannel(NULL),
new typename T::MediaChannel(NULL),
- flags, talk_base::Thread::Current());
+ flags, rtc::Thread::Current());
}
void CreateChannels(int flags1, int flags2,
- talk_base::Thread* thread) {
+ rtc::Thread* thread) {
CreateChannels(new typename T::MediaChannel(NULL),
new typename T::MediaChannel(NULL),
flags1, flags2, thread);
}
void CreateChannels(int flags,
- talk_base::Thread* thread) {
+ rtc::Thread* thread) {
CreateChannels(new typename T::MediaChannel(NULL),
new typename T::MediaChannel(NULL),
flags, thread);
}
void CreateChannels(
typename T::MediaChannel* ch1, typename T::MediaChannel* ch2,
- int flags1, int flags2, talk_base::Thread* thread) {
+ int flags1, int flags2, rtc::Thread* thread) {
media_channel1_ = ch1;
media_channel2_ = ch2;
channel1_.reset(CreateChannel(thread, &media_engine_, ch1, &session1_,
@@ -246,11 +204,11 @@
CopyContent(local_media_content2_, &remote_media_content2_);
if (flags1 & DTLS) {
- identity1_.reset(talk_base::SSLIdentity::Generate("session1"));
+ identity1_.reset(rtc::SSLIdentity::Generate("session1"));
session1_.set_ssl_identity(identity1_.get());
}
if (flags2 & DTLS) {
- identity2_.reset(talk_base::SSLIdentity::Generate("session2"));
+ identity2_.reset(rtc::SSLIdentity::Generate("session2"));
session2_.set_ssl_identity(identity2_.get());
}
@@ -271,7 +229,7 @@
void CreateChannels(
typename T::MediaChannel* ch1, typename T::MediaChannel* ch2,
- int flags, talk_base::Thread* thread) {
+ int flags, rtc::Thread* thread) {
media_channel1_ = ch1;
media_channel2_ = ch2;
@@ -304,7 +262,7 @@
}
}
- typename T::Channel* CreateChannel(talk_base::Thread* thread,
+ typename T::Channel* CreateChannel(rtc::Thread* thread,
cricket::MediaEngineInterface* engine,
typename T::MediaChannel* ch,
cricket::BaseSession* session,
@@ -470,17 +428,17 @@
std::string CreateRtpData(uint32 ssrc, int sequence_number, int pl_type) {
std::string data(rtp_packet_);
// Set SSRC in the rtp packet copy.
- talk_base::SetBE32(const_cast<char*>(data.c_str()) + 8, ssrc);
- talk_base::SetBE16(const_cast<char*>(data.c_str()) + 2, sequence_number);
+ rtc::SetBE32(const_cast<char*>(data.c_str()) + 8, ssrc);
+ rtc::SetBE16(const_cast<char*>(data.c_str()) + 2, sequence_number);
if (pl_type >= 0) {
- talk_base::Set8(const_cast<char*>(data.c_str()), 1, pl_type);
+ rtc::Set8(const_cast<char*>(data.c_str()), 1, pl_type);
}
return data;
}
std::string CreateRtcpData(uint32 ssrc) {
std::string data(rtcp_packet_);
// Set SSRC in the rtcp packet copy.
- talk_base::SetBE32(const_cast<char*>(data.c_str()) + 4, ssrc);
+ rtc::SetBE32(const_cast<char*>(data.c_str()) + 4, ssrc);
return data;
}
@@ -520,7 +478,7 @@
return sdesc;
}
- class CallThread : public talk_base::SignalThread {
+ class CallThread : public rtc::SignalThread {
public:
typedef bool (ChannelTest<T>::*Method)();
CallThread(ChannelTest<T>* obj, Method method, bool* result)
@@ -1077,7 +1035,7 @@
};
CreateChannels(new LastWordMediaChannel(), new LastWordMediaChannel(),
RTCP | RTCP_MUX, RTCP | RTCP_MUX,
- talk_base::Thread::Current());
+ rtc::Thread::Current());
EXPECT_TRUE(SendInitiate());
EXPECT_TRUE(SendAccept());
EXPECT_TRUE(SendTerminate());
@@ -1533,10 +1491,10 @@
EXPECT_FALSE(channel1_->HasSendSinks(cricket::SINK_PRE_CRYPTO));
EXPECT_FALSE(channel1_->HasRecvSinks(cricket::SINK_PRE_CRYPTO));
- talk_base::Pathname path;
- EXPECT_TRUE(talk_base::Filesystem::GetTemporaryFolder(path, true, NULL));
+ rtc::Pathname path;
+ EXPECT_TRUE(rtc::Filesystem::GetTemporaryFolder(path, true, NULL));
path.SetFilename("sink-test.rtpdump");
- talk_base::scoped_ptr<cricket::RtpDumpSink> sink(
+ rtc::scoped_ptr<cricket::RtpDumpSink> sink(
new cricket::RtpDumpSink(Open(path.pathname())));
sink->set_packet_filter(cricket::PF_ALL);
EXPECT_TRUE(sink->Enable(true));
@@ -1562,27 +1520,27 @@
sink.reset(); // This will close the file.
// Read the recorded file and verify two packets.
- talk_base::scoped_ptr<talk_base::StreamInterface> stream(
- talk_base::Filesystem::OpenFile(path, "rb"));
+ rtc::scoped_ptr<rtc::StreamInterface> stream(
+ rtc::Filesystem::OpenFile(path, "rb"));
cricket::RtpDumpReader reader(stream.get());
cricket::RtpDumpPacket packet;
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
std::string read_packet(reinterpret_cast<const char*>(&packet.data[0]),
packet.data.size());
EXPECT_EQ(rtp_packet_, read_packet);
- EXPECT_EQ(talk_base::SR_SUCCESS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, reader.ReadPacket(&packet));
size_t len = 0;
packet.GetRtpHeaderLen(&len);
EXPECT_EQ(len, packet.data.size());
EXPECT_EQ(0, memcmp(&packet.data[0], rtp_packet_.c_str(), len));
- EXPECT_EQ(talk_base::SR_EOS, reader.ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, reader.ReadPacket(&packet));
// Delete the file for media recording.
stream.reset();
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(path));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(path));
}
void TestSetContentFailure() {
@@ -1597,12 +1555,12 @@
new cricket::AudioContentDescription());
sdesc_loc->AddContent(cricket::CN_VIDEO, cricket::NS_JINGLE_RTP,
new cricket::VideoContentDescription());
- EXPECT_TRUE(session1_.set_local_description(sdesc_loc));
+ session1_.set_local_description(sdesc_loc);
sdesc_rem->AddContent(cricket::CN_AUDIO, cricket::NS_JINGLE_RTP,
new cricket::AudioContentDescription());
sdesc_rem->AddContent(cricket::CN_VIDEO, cricket::NS_JINGLE_RTP,
new cricket::VideoContentDescription());
- EXPECT_TRUE(session1_.set_remote_description(sdesc_rem));
+ session1_.set_remote_description(sdesc_rem);
// Test failures in SetLocalContent.
media_channel1_->set_fail_set_recv_codecs(true);
@@ -1630,7 +1588,7 @@
// Set up the initial session description.
cricket::SessionDescription* sdesc = CreateSessionDescriptionWithStream(1);
- EXPECT_TRUE(session1_.set_local_description(sdesc));
+ session1_.set_local_description(sdesc);
session1_.SetError(cricket::BaseSession::ERROR_NONE, "");
session1_.SetState(cricket::Session::STATE_SENTINITIATE);
@@ -1639,7 +1597,7 @@
// Update the local description and set the state again.
sdesc = CreateSessionDescriptionWithStream(2);
- EXPECT_TRUE(session1_.set_local_description(sdesc));
+ session1_.set_local_description(sdesc);
session1_.SetState(cricket::Session::STATE_SENTINITIATE);
EXPECT_EQ(cricket::BaseSession::ERROR_NONE, session1_.error());
@@ -1652,7 +1610,7 @@
// Set up the initial session description.
cricket::SessionDescription* sdesc = CreateSessionDescriptionWithStream(1);
- EXPECT_TRUE(session1_.set_remote_description(sdesc));
+ session1_.set_remote_description(sdesc);
session1_.SetError(cricket::BaseSession::ERROR_NONE, "");
session1_.SetState(cricket::Session::STATE_RECEIVEDINITIATE);
@@ -1660,7 +1618,7 @@
EXPECT_TRUE(media_channel1_->HasRecvStream(1));
sdesc = CreateSessionDescriptionWithStream(2);
- EXPECT_TRUE(session1_.set_remote_description(sdesc));
+ session1_.set_remote_description(sdesc);
session1_.SetState(cricket::Session::STATE_RECEIVEDINITIATE);
EXPECT_EQ(cricket::BaseSession::ERROR_NONE, session1_.error());
EXPECT_FALSE(media_channel1_->HasRecvStream(1));
@@ -1672,7 +1630,7 @@
// Set up the initial session description.
cricket::SessionDescription* sdesc = CreateSessionDescriptionWithStream(1);
- EXPECT_TRUE(session1_.set_remote_description(sdesc));
+ session1_.set_remote_description(sdesc);
session1_.SetError(cricket::BaseSession::ERROR_NONE, "");
session1_.SetState(cricket::Session::STATE_RECEIVEDINITIATE);
@@ -1681,7 +1639,7 @@
// Send PRANSWER
sdesc = CreateSessionDescriptionWithStream(2);
- EXPECT_TRUE(session1_.set_local_description(sdesc));
+ session1_.set_local_description(sdesc);
session1_.SetState(cricket::Session::STATE_SENTPRACCEPT);
EXPECT_EQ(cricket::BaseSession::ERROR_NONE, session1_.error());
@@ -1690,7 +1648,7 @@
// Send ACCEPT
sdesc = CreateSessionDescriptionWithStream(3);
- EXPECT_TRUE(session1_.set_local_description(sdesc));
+ session1_.set_local_description(sdesc);
session1_.SetState(cricket::Session::STATE_SENTACCEPT);
EXPECT_EQ(cricket::BaseSession::ERROR_NONE, session1_.error());
@@ -1704,7 +1662,7 @@
// Set up the initial session description.
cricket::SessionDescription* sdesc = CreateSessionDescriptionWithStream(1);
- EXPECT_TRUE(session1_.set_local_description(sdesc));
+ session1_.set_local_description(sdesc);
session1_.SetError(cricket::BaseSession::ERROR_NONE, "");
session1_.SetState(cricket::Session::STATE_SENTINITIATE);
@@ -1713,7 +1671,7 @@
// Receive PRANSWER
sdesc = CreateSessionDescriptionWithStream(2);
- EXPECT_TRUE(session1_.set_remote_description(sdesc));
+ session1_.set_remote_description(sdesc);
session1_.SetState(cricket::Session::STATE_RECEIVEDPRACCEPT);
EXPECT_EQ(cricket::BaseSession::ERROR_NONE, session1_.error());
@@ -1722,7 +1680,7 @@
// Receive ACCEPT
sdesc = CreateSessionDescriptionWithStream(3);
- EXPECT_TRUE(session1_.set_remote_description(sdesc));
+ session1_.set_remote_description(sdesc);
session1_.SetState(cricket::Session::STATE_RECEIVEDACCEPT);
EXPECT_EQ(cricket::BaseSession::ERROR_NONE, session1_.error());
@@ -1796,7 +1754,7 @@
// The next 1 sec failures will not trigger an error.
EXPECT_FALSE(media_channel2_->SendRtp(kBadPacket, sizeof(kBadPacket)));
// Wait for a while to ensure no message comes in.
- talk_base::Thread::Current()->ProcessMessages(210);
+ rtc::Thread::Current()->ProcessMessages(210);
EXPECT_EQ(T::MediaChannel::ERROR_NONE, error_);
// The error will be triggered again.
EXPECT_FALSE(media_channel2_->SendRtp(kBadPacket, sizeof(kBadPacket)));
@@ -1808,7 +1766,7 @@
channel2_->transport_channel();
transport_channel->SignalReadPacket(
transport_channel, reinterpret_cast<const char*>(kBadPacket),
- sizeof(kBadPacket), talk_base::PacketTime(), 0);
+ sizeof(kBadPacket), rtc::PacketTime(), 0);
EXPECT_EQ_WAIT(T::MediaChannel::ERROR_PLAY_SRTP_ERROR, error_, 500);
}
@@ -1863,14 +1821,14 @@
// The media channels are owned by the voice channel objects below.
typename T::MediaChannel* media_channel1_;
typename T::MediaChannel* media_channel2_;
- talk_base::scoped_ptr<typename T::Channel> channel1_;
- talk_base::scoped_ptr<typename T::Channel> channel2_;
+ rtc::scoped_ptr<typename T::Channel> channel1_;
+ rtc::scoped_ptr<typename T::Channel> channel2_;
typename T::Content local_media_content1_;
typename T::Content local_media_content2_;
typename T::Content remote_media_content1_;
typename T::Content remote_media_content2_;
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity1_;
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity2_;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity1_;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity2_;
// The RTP and RTCP packets to send in the tests.
std::string rtp_packet_;
std::string rtcp_packet_;
@@ -1895,7 +1853,7 @@
if (flags & SECURE) {
audio->AddCrypto(cricket::CryptoParams(
1, cricket::CS_AES_CM_128_HMAC_SHA1_32,
- "inline:" + talk_base::CreateRandomString(40), ""));
+ "inline:" + rtc::CreateRandomString(40), ""));
}
}
@@ -1956,7 +1914,7 @@
// override to add NULL parameter
template<>
cricket::VideoChannel* ChannelTest<VideoTraits>::CreateChannel(
- talk_base::Thread* thread, cricket::MediaEngineInterface* engine,
+ rtc::Thread* thread, cricket::MediaEngineInterface* engine,
cricket::FakeVideoMediaChannel* ch, cricket::BaseSession* session,
bool rtcp) {
cricket::VideoChannel* channel = new cricket::VideoChannel(
@@ -1985,7 +1943,7 @@
if (flags & SECURE) {
video->AddCrypto(cricket::CryptoParams(
1, cricket::CS_AES_CM_128_HMAC_SHA1_80,
- "inline:" + talk_base::CreateRandomString(40), ""));
+ "inline:" + rtc::CreateRandomString(40), ""));
}
}
@@ -2214,7 +2172,7 @@
// Typing doesn't mute automatically unless typing monitor has been installed
media_channel1_->TriggerError(0, e);
- talk_base::Thread::Current()->ProcessMessages(0);
+ rtc::Thread::Current()->ProcessMessages(0);
EXPECT_EQ(e, error_);
EXPECT_FALSE(media_channel1_->IsStreamMuted(0));
EXPECT_FALSE(mute_callback_recved_);
@@ -2223,7 +2181,7 @@
o.mute_period = 1500;
channel1_->StartTypingMonitor(o);
media_channel1_->TriggerError(0, e);
- talk_base::Thread::Current()->ProcessMessages(0);
+ rtc::Thread::Current()->ProcessMessages(0);
EXPECT_TRUE(media_channel1_->IsStreamMuted(0));
EXPECT_TRUE(mute_callback_recved_);
}
@@ -2469,28 +2427,31 @@
TEST_F(VideoChannelTest, TestScreencastEvents) {
const int kTimeoutMs = 500;
TestInit();
- FakeScreenCaptureFactory* screencapture_factory =
- new FakeScreenCaptureFactory();
- channel1_->SetScreenCaptureFactory(screencapture_factory);
cricket::ScreencastEventCatcher catcher;
channel1_->SignalScreencastWindowEvent.connect(
&catcher,
&cricket::ScreencastEventCatcher::OnEvent);
- EXPECT_TRUE(channel1_->AddScreencast(0, ScreencastId(WindowId(0))) != NULL);
- ASSERT_TRUE(screencapture_factory->window_capturer() != NULL);
- EXPECT_EQ_WAIT(cricket::CS_STOPPED, screencapture_factory->capture_state(),
+
+ rtc::scoped_ptr<cricket::FakeScreenCapturerFactory>
+ screen_capturer_factory(new cricket::FakeScreenCapturerFactory());
+ cricket::VideoCapturer* screen_capturer = screen_capturer_factory->Create(
+ ScreencastId(WindowId(0)));
+ ASSERT_TRUE(screen_capturer != NULL);
+
+ EXPECT_TRUE(channel1_->AddScreencast(0, screen_capturer));
+ EXPECT_EQ_WAIT(cricket::CS_STOPPED, screen_capturer_factory->capture_state(),
kTimeoutMs);
- screencapture_factory->window_capturer()->SignalStateChange(
- screencapture_factory->window_capturer(), cricket::CS_PAUSED);
- EXPECT_EQ_WAIT(talk_base::WE_MINIMIZE, catcher.event(), kTimeoutMs);
- screencapture_factory->window_capturer()->SignalStateChange(
- screencapture_factory->window_capturer(), cricket::CS_RUNNING);
- EXPECT_EQ_WAIT(talk_base::WE_RESTORE, catcher.event(), kTimeoutMs);
- screencapture_factory->window_capturer()->SignalStateChange(
- screencapture_factory->window_capturer(), cricket::CS_STOPPED);
- EXPECT_EQ_WAIT(talk_base::WE_CLOSE, catcher.event(), kTimeoutMs);
+
+ screen_capturer->SignalStateChange(screen_capturer, cricket::CS_PAUSED);
+ EXPECT_EQ_WAIT(rtc::WE_MINIMIZE, catcher.event(), kTimeoutMs);
+
+ screen_capturer->SignalStateChange(screen_capturer, cricket::CS_RUNNING);
+ EXPECT_EQ_WAIT(rtc::WE_RESTORE, catcher.event(), kTimeoutMs);
+
+ screen_capturer->SignalStateChange(screen_capturer, cricket::CS_STOPPED);
+ EXPECT_EQ_WAIT(rtc::WE_CLOSE, catcher.event(), kTimeoutMs);
+
EXPECT_TRUE(channel1_->RemoveScreencast(0));
- ASSERT_TRUE(screencapture_factory->window_capturer() == NULL);
}
TEST_F(VideoChannelTest, TestUpdateStreamsInLocalContent) {
@@ -2748,7 +2709,7 @@
// Override to avoid engine channel parameter.
template<>
cricket::DataChannel* ChannelTest<DataTraits>::CreateChannel(
- talk_base::Thread* thread, cricket::MediaEngineInterface* engine,
+ rtc::Thread* thread, cricket::MediaEngineInterface* engine,
cricket::FakeDataMediaChannel* ch, cricket::BaseSession* session,
bool rtcp) {
cricket::DataChannel* channel = new cricket::DataChannel(
@@ -2771,7 +2732,7 @@
if (flags & SECURE) {
data->AddCrypto(cricket::CryptoParams(
1, cricket::CS_AES_CM_128_HMAC_SHA1_32,
- "inline:" + talk_base::CreateRandomString(40), ""));
+ "inline:" + rtc::CreateRandomString(40), ""));
}
}
@@ -2929,7 +2890,7 @@
unsigned char data[] = {
'f', 'o', 'o'
};
- talk_base::Buffer payload(data, 3);
+ rtc::Buffer payload(data, 3);
cricket::SendDataResult result;
ASSERT_TRUE(media_channel1_->SendData(params, payload, &result));
EXPECT_EQ(params.ssrc,
diff --git a/session/media/channelmanager.cc b/session/media/channelmanager.cc
index 88316b5..199bc86 100644
--- a/session/media/channelmanager.cc
+++ b/session/media/channelmanager.cc
@@ -33,12 +33,6 @@
#include <algorithm>
-#include "talk/base/bind.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/sigslotrepeater.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/capturemanager.h"
#include "talk/media/base/hybriddataengine.h"
#include "talk/media/base/rtpdataengine.h"
@@ -49,6 +43,12 @@
#endif
#include "talk/session/media/soundclip.h"
#include "talk/session/media/srtpfilter.h"
+#include "webrtc/base/bind.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/sigslotrepeater.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
@@ -56,11 +56,11 @@
MSG_VIDEOCAPTURESTATE = 1,
};
-using talk_base::Bind;
+using rtc::Bind;
static const int kNotSetOutputVolume = -1;
-struct CaptureStateParams : public talk_base::MessageData {
+struct CaptureStateParams : public rtc::MessageData {
CaptureStateParams(cricket::VideoCapturer* c, cricket::CaptureState s)
: capturer(c),
state(s) {}
@@ -77,7 +77,7 @@
}
#if !defined(DISABLE_MEDIA_ENGINE_FACTORY)
-ChannelManager::ChannelManager(talk_base::Thread* worker_thread) {
+ChannelManager::ChannelManager(rtc::Thread* worker_thread) {
Construct(MediaEngineFactory::Create(),
ConstructDataEngine(),
cricket::DeviceManagerFactory::Create(),
@@ -90,13 +90,13 @@
DataEngineInterface* dme,
DeviceManagerInterface* dm,
CaptureManager* cm,
- talk_base::Thread* worker_thread) {
+ rtc::Thread* worker_thread) {
Construct(me, dme, dm, cm, worker_thread);
}
ChannelManager::ChannelManager(MediaEngineInterface* me,
DeviceManagerInterface* dm,
- talk_base::Thread* worker_thread) {
+ rtc::Thread* worker_thread) {
Construct(me,
ConstructDataEngine(),
dm,
@@ -108,19 +108,19 @@
DataEngineInterface* dme,
DeviceManagerInterface* dm,
CaptureManager* cm,
- talk_base::Thread* worker_thread) {
+ rtc::Thread* worker_thread) {
media_engine_.reset(me);
data_media_engine_.reset(dme);
device_manager_.reset(dm);
capture_manager_.reset(cm);
initialized_ = false;
- main_thread_ = talk_base::Thread::Current();
+ main_thread_ = rtc::Thread::Current();
worker_thread_ = worker_thread;
// Get the default audio options from the media engine.
audio_options_ = media_engine_->GetAudioOptions();
audio_in_device_ = DeviceManagerInterface::kDefaultDeviceName;
audio_out_device_ = DeviceManagerInterface::kDefaultDeviceName;
- audio_delay_offset_ = MediaEngineInterface::kDefaultAudioDelayOffset;
+ audio_delay_offset_ = kDefaultAudioDelayOffset;
audio_output_volume_ = kNotSetOutputVolume;
local_renderer_ = NULL;
capturing_ = false;
@@ -137,6 +137,12 @@
this, &ChannelManager::OnVideoCaptureStateChange);
capture_manager_->SignalCapturerStateChange.connect(
this, &ChannelManager::OnVideoCaptureStateChange);
+
+ if (worker_thread_ != rtc::Thread::Current()) {
+ // Do not allow invoking calls to other threads on the worker thread.
+ worker_thread_->Invoke<bool>(
+ rtc::Bind(&rtc::Thread::SetAllowBlockingCalls, worker_thread_, false));
+ }
}
ChannelManager::~ChannelManager() {
@@ -217,11 +223,7 @@
}
ASSERT(worker_thread_ != NULL);
- ASSERT(worker_thread_->RunningForChannelManager());
- // TODO(fischman): remove the if below (and
- // Thread::RunningForChannelManager()) once the ASSERT above has stuck for a
- // month (2014/06/22).
- if (worker_thread_ && worker_thread_->RunningForChannelManager()) {
+ if (worker_thread_) {
if (media_engine_->Init(worker_thread_)) {
initialized_ = true;
@@ -281,10 +283,6 @@
if (default_video_encoder_config_.max_codec.id != 0) {
SetDefaultVideoEncoderConfig(default_video_encoder_config_);
}
- // And the local renderer.
- if (local_renderer_) {
- SetLocalRenderer(local_renderer_);
- }
}
}
return initialized_;
@@ -301,7 +299,7 @@
}
void ChannelManager::Terminate_w() {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
// Need to destroy the voice/video channels
while (!video_channels_.empty()) {
DestroyVideoChannel_w(video_channels_.back());
@@ -474,7 +472,7 @@
Soundclip* ChannelManager::CreateSoundclip_w() {
ASSERT(initialized_);
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
SoundclipMedia* soundclip_media = media_engine_->CreateSoundclip();
if (!soundclip_media) {
@@ -560,7 +558,7 @@
bool ChannelManager::SetAudioOptions_w(
const AudioOptions& options, int delay_offset,
const Device* in_dev, const Device* out_dev) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
ASSERT(initialized_);
// Set audio options
@@ -595,7 +593,7 @@
}
bool ChannelManager::SetEngineAudioOptions_w(const AudioOptions& options) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
ASSERT(initialized_);
return media_engine_->SetAudioOptions(options);
@@ -714,8 +712,13 @@
return capturer;
}
+VideoCapturer* ChannelManager::CreateScreenCapturer(
+ const ScreencastId& screenid) {
+ return device_manager_->CreateScreenCapturer(screenid);
+}
+
bool ChannelManager::SetCaptureDevice_w(const Device* cam_device) {
- ASSERT(worker_thread_ == talk_base::Thread::Current());
+ ASSERT(worker_thread_ == rtc::Thread::Current());
ASSERT(initialized_);
if (!cam_device) {
@@ -749,19 +752,6 @@
return ret;
}
-bool ChannelManager::SetLocalRenderer(VideoRenderer* renderer) {
- bool ret = true;
- if (initialized_) {
- ret = worker_thread_->Invoke<bool>(
- Bind(&MediaEngineInterface::SetLocalRenderer,
- media_engine_.get(), renderer));
- }
- if (ret) {
- local_renderer_ = renderer;
- }
- return ret;
-}
-
void ChannelManager::SetVoiceLogging(int level, const char* filter) {
if (initialized_) {
worker_thread_->Invoke<void>(
@@ -904,7 +894,7 @@
new CaptureStateParams(capturer, result));
}
-void ChannelManager::OnMessage(talk_base::Message* message) {
+void ChannelManager::OnMessage(rtc::Message* message) {
switch (message->message_id) {
case MSG_VIDEOCAPTURESTATE: {
CaptureStateParams* data =
@@ -966,7 +956,7 @@
Bind(&MediaEngineInterface::GetStartCaptureFormat, media_engine_.get()));
}
-bool ChannelManager::StartAecDump(talk_base::PlatformFile file) {
+bool ChannelManager::StartAecDump(rtc::PlatformFile file) {
return worker_thread_->Invoke<bool>(
Bind(&MediaEngineInterface::StartAecDump, media_engine_.get(), file));
}
diff --git a/session/media/channelmanager.h b/session/media/channelmanager.h
index e8d6c0e..fa79014 100644
--- a/session/media/channelmanager.h
+++ b/session/media/channelmanager.h
@@ -31,17 +31,19 @@
#include <string>
#include <vector>
-#include "talk/base/criticalsection.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/sigslotrepeater.h"
-#include "talk/base/thread.h"
#include "talk/media/base/capturemanager.h"
#include "talk/media/base/mediaengine.h"
#include "talk/p2p/base/session.h"
#include "talk/session/media/voicechannel.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/sigslotrepeater.h"
+#include "webrtc/base/thread.h"
namespace cricket {
+const int kDefaultAudioDelayOffset = 0;
+
class Soundclip;
class VideoProcessor;
class VoiceChannel;
@@ -55,12 +57,12 @@
// voice or just video channels.
// ChannelManager also allows the application to discover what devices it has
// using device manager.
-class ChannelManager : public talk_base::MessageHandler,
+class ChannelManager : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
#if !defined(DISABLE_MEDIA_ENGINE_FACTORY)
// Creates the channel manager, and specifies the worker thread to use.
- explicit ChannelManager(talk_base::Thread* worker);
+ explicit ChannelManager(rtc::Thread* worker);
#endif
// For testing purposes. Allows the media engine and data media
@@ -70,17 +72,17 @@
DataEngineInterface* dme,
DeviceManagerInterface* dm,
CaptureManager* cm,
- talk_base::Thread* worker);
+ rtc::Thread* worker);
// Same as above, but gives an easier default DataEngine.
ChannelManager(MediaEngineInterface* me,
DeviceManagerInterface* dm,
- talk_base::Thread* worker);
+ rtc::Thread* worker);
~ChannelManager();
// Accessors for the worker thread, allowing it to be set after construction,
// but before Init. set_worker_thread will return false if called after Init.
- talk_base::Thread* worker_thread() const { return worker_thread_; }
- bool set_worker_thread(talk_base::Thread* thread) {
+ rtc::Thread* worker_thread() const { return worker_thread_; }
+ bool set_worker_thread(rtc::Thread* thread) {
if (initialized_) return false;
worker_thread_ = thread;
return true;
@@ -157,6 +159,8 @@
bool GetVideoCaptureDevice(Device* device);
// Create capturer based on what has been set in SetCaptureDevice().
VideoCapturer* CreateVideoCapturer();
+ // Create capturer from a screen.
+ VideoCapturer* CreateScreenCapturer(const ScreencastId& screenid);
bool SetCaptureDevice(const std::string& cam_device);
bool SetDefaultVideoEncoderConfig(const VideoEncoderConfig& config);
// RTX will be enabled/disabled in engines that support it. The supporting
@@ -166,8 +170,6 @@
// Starts/stops the local microphone and enables polling of the input level.
bool SetLocalMonitor(bool enable);
bool monitoring() const { return monitoring_; }
- // Sets the local renderer where to renderer the local camera.
- bool SetLocalRenderer(VideoRenderer* renderer);
bool capturing() const { return capturing_; }
// Configures the logging output of the mediaengine(s).
@@ -218,7 +220,7 @@
const VideoFormat& max_format);
// Starts AEC dump using existing file.
- bool StartAecDump(talk_base::PlatformFile file);
+ bool StartAecDump(rtc::PlatformFile file);
sigslot::repeater0<> SignalDevicesChange;
sigslot::signal2<VideoCapturer*, CaptureState> SignalVideoCaptureStateChange;
@@ -240,6 +242,9 @@
const AudioOptions& options,
int delay_offset);
int audio_delay_offset() const { return audio_delay_offset_; }
+ // This is here so that ChannelManager subclasses can set the video
+ // capturer factories to use.
+ DeviceManagerInterface* device_manager() { return device_manager_.get(); }
private:
typedef std::vector<VoiceChannel*> VoiceChannels;
@@ -251,7 +256,7 @@
DataEngineInterface* dme,
DeviceManagerInterface* dm,
CaptureManager* cm,
- talk_base::Thread* worker_thread);
+ rtc::Thread* worker_thread);
void Terminate_w();
VoiceChannel* CreateVoiceChannel_w(
BaseSession* session, const std::string& content_name, bool rtcp);
@@ -277,15 +282,15 @@
bool UnregisterVideoProcessor_w(VideoCapturer* capturer,
VideoProcessor* processor);
bool IsScreencastRunning_w() const;
- virtual void OnMessage(talk_base::Message *message);
+ virtual void OnMessage(rtc::Message *message);
- talk_base::scoped_ptr<MediaEngineInterface> media_engine_;
- talk_base::scoped_ptr<DataEngineInterface> data_media_engine_;
- talk_base::scoped_ptr<DeviceManagerInterface> device_manager_;
- talk_base::scoped_ptr<CaptureManager> capture_manager_;
+ rtc::scoped_ptr<MediaEngineInterface> media_engine_;
+ rtc::scoped_ptr<DataEngineInterface> data_media_engine_;
+ rtc::scoped_ptr<DeviceManagerInterface> device_manager_;
+ rtc::scoped_ptr<CaptureManager> capture_manager_;
bool initialized_;
- talk_base::Thread* main_thread_;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* main_thread_;
+ rtc::Thread* worker_thread_;
VoiceChannels voice_channels_;
VideoChannels video_channels_;
diff --git a/session/media/channelmanager_unittest.cc b/session/media/channelmanager_unittest.cc
index cbf19f8..98f1400 100644
--- a/session/media/channelmanager_unittest.cc
+++ b/session/media/channelmanager_unittest.cc
@@ -23,17 +23,17 @@
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
#include "talk/media/base/fakecapturemanager.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/fakemediaprocessor.h"
#include "talk/media/base/nullvideorenderer.h"
-#include "talk/media/devices/fakedevicemanager.h"
#include "talk/media/base/testutils.h"
+#include "talk/media/devices/fakedevicemanager.h"
#include "talk/p2p/base/fakesession.h"
#include "talk/session/media/channelmanager.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -62,7 +62,7 @@
fdm_ = new cricket::FakeDeviceManager();
fcm_ = new cricket::FakeCaptureManager();
cm_ = new cricket::ChannelManager(
- fme_, fdme_, fdm_, fcm_, talk_base::Thread::Current());
+ fme_, fdme_, fdm_, fcm_, rtc::Thread::Current());
session_ = new cricket::FakeSession(true);
std::vector<std::string> in_device_list, out_device_list, vid_device_list;
@@ -87,7 +87,7 @@
fme_ = NULL;
}
- talk_base::Thread worker_;
+ rtc::Thread worker_;
cricket::FakeMediaEngine* fme_;
cricket::FakeDataEngine* fdme_;
cricket::FakeDeviceManager* fdm_;
@@ -99,7 +99,7 @@
// Test that we startup/shutdown properly.
TEST_F(ChannelManagerTest, StartupShutdown) {
EXPECT_FALSE(cm_->initialized());
- EXPECT_EQ(talk_base::Thread::Current(), cm_->worker_thread());
+ EXPECT_EQ(rtc::Thread::Current(), cm_->worker_thread());
EXPECT_TRUE(cm_->Init());
EXPECT_TRUE(cm_->initialized());
cm_->Terminate();
@@ -110,26 +110,17 @@
TEST_F(ChannelManagerTest, StartupShutdownOnThread) {
worker_.Start();
EXPECT_FALSE(cm_->initialized());
- EXPECT_EQ(talk_base::Thread::Current(), cm_->worker_thread());
+ EXPECT_EQ(rtc::Thread::Current(), cm_->worker_thread());
EXPECT_TRUE(cm_->set_worker_thread(&worker_));
EXPECT_EQ(&worker_, cm_->worker_thread());
EXPECT_TRUE(cm_->Init());
EXPECT_TRUE(cm_->initialized());
// Setting the worker thread while initialized should fail.
- EXPECT_FALSE(cm_->set_worker_thread(talk_base::Thread::Current()));
+ EXPECT_FALSE(cm_->set_worker_thread(rtc::Thread::Current()));
cm_->Terminate();
EXPECT_FALSE(cm_->initialized());
}
-// Test that we fail to startup if we're given an unstarted thread.
-// TODO(fischman): delete once Thread::RunningForChannelManager() is gone
-// (webrtc:3388).
-TEST_F(ChannelManagerTest, DISABLED_StartupShutdownOnUnstartedThread) {
- EXPECT_TRUE(cm_->set_worker_thread(&worker_));
- EXPECT_FALSE(cm_->Init());
- EXPECT_FALSE(cm_->initialized());
-}
-
// Test that we can create and destroy a voice and video channel.
TEST_F(ChannelManagerTest, CreateDestroyChannels) {
EXPECT_TRUE(cm_->Init());
@@ -276,7 +267,7 @@
EXPECT_EQ(options, set_options);
// At this point, the media engine should also be initialized.
EXPECT_EQ(options, fme_->audio_options());
- EXPECT_EQ(cricket::MediaEngineInterface::kDefaultAudioDelayOffset,
+ EXPECT_EQ(cricket::kDefaultAudioDelayOffset,
fme_->audio_delay_offset());
}
@@ -303,7 +294,7 @@
fme_->audio_in_device());
EXPECT_EQ(std::string(cricket::DeviceManagerInterface::kDefaultDeviceName),
fme_->audio_out_device());
- EXPECT_EQ(cricket::MediaEngineInterface::kDefaultAudioDelayOffset,
+ EXPECT_EQ(cricket::kDefaultAudioDelayOffset,
fme_->audio_delay_offset());
// Test setting specific values.
AudioOptions options;
@@ -315,7 +306,7 @@
EXPECT_TRUE(
fme_->audio_options().auto_gain_control.Get(&auto_gain_control));
EXPECT_TRUE(auto_gain_control);
- EXPECT_EQ(cricket::MediaEngineInterface::kDefaultAudioDelayOffset,
+ EXPECT_EQ(cricket::kDefaultAudioDelayOffset,
fme_->audio_delay_offset());
// Test setting bad values.
EXPECT_FALSE(cm_->SetAudioOptions("audio-in9", "audio-out2", options));
@@ -518,46 +509,30 @@
EXPECT_EQ(60, level);
}
-// Test that a value set before Init is applied properly.
-TEST_F(ChannelManagerTest, SetLocalRendererBeforeInit) {
- cricket::NullVideoRenderer renderer;
- EXPECT_TRUE(cm_->SetLocalRenderer(&renderer));
- EXPECT_TRUE(cm_->Init());
- EXPECT_EQ(&renderer, fme_->local_renderer());
-}
-
-// Test that a value set after init is passed through properly.
-TEST_F(ChannelManagerTest, SetLocalRenderer) {
- cricket::NullVideoRenderer renderer;
- EXPECT_TRUE(cm_->Init());
- EXPECT_TRUE(cm_->SetLocalRenderer(&renderer));
- EXPECT_EQ(&renderer, fme_->local_renderer());
-}
-
// Test that logging options set before Init are applied properly,
// and retained even after Init.
TEST_F(ChannelManagerTest, SetLoggingBeforeInit) {
- cm_->SetVoiceLogging(talk_base::LS_INFO, "test-voice");
- cm_->SetVideoLogging(talk_base::LS_VERBOSE, "test-video");
- EXPECT_EQ(talk_base::LS_INFO, fme_->voice_loglevel());
+ cm_->SetVoiceLogging(rtc::LS_INFO, "test-voice");
+ cm_->SetVideoLogging(rtc::LS_VERBOSE, "test-video");
+ EXPECT_EQ(rtc::LS_INFO, fme_->voice_loglevel());
EXPECT_STREQ("test-voice", fme_->voice_logfilter().c_str());
- EXPECT_EQ(talk_base::LS_VERBOSE, fme_->video_loglevel());
+ EXPECT_EQ(rtc::LS_VERBOSE, fme_->video_loglevel());
EXPECT_STREQ("test-video", fme_->video_logfilter().c_str());
EXPECT_TRUE(cm_->Init());
- EXPECT_EQ(talk_base::LS_INFO, fme_->voice_loglevel());
+ EXPECT_EQ(rtc::LS_INFO, fme_->voice_loglevel());
EXPECT_STREQ("test-voice", fme_->voice_logfilter().c_str());
- EXPECT_EQ(talk_base::LS_VERBOSE, fme_->video_loglevel());
+ EXPECT_EQ(rtc::LS_VERBOSE, fme_->video_loglevel());
EXPECT_STREQ("test-video", fme_->video_logfilter().c_str());
}
// Test that logging options set after Init are applied properly.
TEST_F(ChannelManagerTest, SetLogging) {
EXPECT_TRUE(cm_->Init());
- cm_->SetVoiceLogging(talk_base::LS_INFO, "test-voice");
- cm_->SetVideoLogging(talk_base::LS_VERBOSE, "test-video");
- EXPECT_EQ(talk_base::LS_INFO, fme_->voice_loglevel());
+ cm_->SetVoiceLogging(rtc::LS_INFO, "test-voice");
+ cm_->SetVideoLogging(rtc::LS_VERBOSE, "test-video");
+ EXPECT_EQ(rtc::LS_INFO, fme_->voice_loglevel());
EXPECT_STREQ("test-voice", fme_->voice_logfilter().c_str());
- EXPECT_EQ(talk_base::LS_VERBOSE, fme_->video_loglevel());
+ EXPECT_EQ(rtc::LS_VERBOSE, fme_->video_loglevel());
EXPECT_STREQ("test-video", fme_->video_logfilter().c_str());
}
diff --git a/session/media/currentspeakermonitor.cc b/session/media/currentspeakermonitor.cc
index 8965cde..472acfe 100644
--- a/session/media/currentspeakermonitor.cc
+++ b/session/media/currentspeakermonitor.cc
@@ -27,10 +27,10 @@
#include "talk/session/media/currentspeakermonitor.h"
-#include "talk/base/logging.h"
#include "talk/media/base/streamparams.h"
#include "talk/session/media/audiomonitor.h"
#include "talk/session/media/mediamessages.h"
+#include "webrtc/base/logging.h"
namespace cricket {
@@ -183,7 +183,7 @@
// We avoid over-switching by disabling switching for a period of time after
// a switch is done.
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
if (earliest_permitted_switch_time_ <= now &&
current_speaker_ssrc_ != loudest_speaker_ssrc) {
current_speaker_ssrc_ = loudest_speaker_ssrc;
diff --git a/session/media/currentspeakermonitor.h b/session/media/currentspeakermonitor.h
index 8e05c8e..0397a6d 100644
--- a/session/media/currentspeakermonitor.h
+++ b/session/media/currentspeakermonitor.h
@@ -33,8 +33,8 @@
#include <map>
-#include "talk/base/basictypes.h"
-#include "talk/base/sigslot.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/sigslot.h"
namespace cricket {
diff --git a/session/media/currentspeakermonitor_unittest.cc b/session/media/currentspeakermonitor_unittest.cc
index b65611f..63676f9 100644
--- a/session/media/currentspeakermonitor_unittest.cc
+++ b/session/media/currentspeakermonitor_unittest.cc
@@ -25,10 +25,10 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
#include "talk/session/media/call.h"
#include "talk/session/media/currentspeakermonitor.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/thread.h"
namespace cricket {
@@ -165,7 +165,7 @@
EXPECT_EQ(num_changes_, 1);
// Wait so the changes don't come so rapidly.
- talk_base::Thread::SleepMs(kSleepTimeBetweenSwitches);
+ rtc::Thread::SleepMs(kSleepTimeBetweenSwitches);
info.active_streams.push_back(std::make_pair(kSsrc1, 9));
info.active_streams.push_back(std::make_pair(kSsrc2, 1));
@@ -201,7 +201,7 @@
EXPECT_EQ(num_changes_, 1);
// Wait so the changes don't come so rapidly.
- talk_base::Thread::SleepMs(kSleepTimeBetweenSwitches);
+ rtc::Thread::SleepMs(kSleepTimeBetweenSwitches);
info.active_streams.push_back(std::make_pair(kSsrc1, 3));
info.active_streams.push_back(std::make_pair(kSsrc2, 0));
diff --git a/session/media/externalhmac.cc b/session/media/externalhmac.cc
index 470668d..82d316d 100644
--- a/session/media/externalhmac.cc
+++ b/session/media/externalhmac.cc
@@ -37,7 +37,7 @@
#include "third_party/libsrtp/include/srtp.h"
#endif // SRTP_RELATIVE_PATH
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
// Begin test case 0 */
static const uint8_t kExternalHmacTestCase0Key[20] = {
diff --git a/session/media/externalhmac.h b/session/media/externalhmac.h
index 287d968..0ab1919 100644
--- a/session/media/externalhmac.h
+++ b/session/media/externalhmac.h
@@ -46,7 +46,7 @@
// crypto_kernel_replace_auth_type function.
#if defined(HAVE_SRTP) && defined(ENABLE_EXTERNAL_AUTH)
-#include "talk/base/basictypes.h"
+#include "webrtc/base/basictypes.h"
#ifdef SRTP_RELATIVE_PATH
#include "auth.h" // NOLINT
#else
diff --git a/session/media/mediamessages.cc b/session/media/mediamessages.cc
index 45c6c79..6c9f681 100644
--- a/session/media/mediamessages.cc
+++ b/session/media/mediamessages.cc
@@ -31,12 +31,12 @@
#include "talk/session/media/mediamessages.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/parsing.h"
#include "talk/session/media/mediasessionclient.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
namespace cricket {
@@ -49,7 +49,7 @@
}
bool ParseSsrc(const std::string& string, uint32* ssrc) {
- return talk_base::FromString(string, ssrc);
+ return rtc::FromString(string, ssrc);
}
// Builds a <view> element according to the following spec:
diff --git a/session/media/mediamessages.h b/session/media/mediamessages.h
index dcb48a8..4a56e4b 100644
--- a/session/media/mediamessages.h
+++ b/session/media/mediamessages.h
@@ -39,11 +39,11 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
#include "talk/media/base/mediachannel.h" // For RtpHeaderExtension
#include "talk/media/base/streamparams.h"
#include "talk/p2p/base/parsing.h"
#include "talk/p2p/base/sessiondescription.h"
+#include "webrtc/base/basictypes.h"
namespace cricket {
diff --git a/session/media/mediamessages_unittest.cc b/session/media/mediamessages_unittest.cc
index c7c81c3..9ebd38c 100644
--- a/session/media/mediamessages_unittest.cc
+++ b/session/media/mediamessages_unittest.cc
@@ -30,11 +30,11 @@
#include <string>
#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/p2p/base/constants.h"
#include "talk/session/media/mediasessionclient.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
// Unit tests for mediamessages.cc.
@@ -161,7 +161,7 @@
return size;
}
- talk_base::scoped_ptr<cricket::SessionDescription> remote_description_;
+ rtc::scoped_ptr<cricket::SessionDescription> remote_description_;
};
} // anonymous namespace
@@ -170,7 +170,7 @@
TEST_F(MediaMessagesTest, ViewNoneToFromXml) {
buzz::XmlElement* expected_view_elem =
buzz::XmlElement::ForStr(kViewVideoNoneXml);
- talk_base::scoped_ptr<buzz::XmlElement> action_elem(
+ rtc::scoped_ptr<buzz::XmlElement> action_elem(
new buzz::XmlElement(QN_JINGLE));
EXPECT_FALSE(cricket::IsJingleViewRequest(action_elem.get()));
@@ -197,7 +197,7 @@
// Test serializing/deserializing an a simple vga <view> message.
TEST_F(MediaMessagesTest, ViewVgaToFromXml) {
- talk_base::scoped_ptr<buzz::XmlElement> action_elem(
+ rtc::scoped_ptr<buzz::XmlElement> action_elem(
new buzz::XmlElement(QN_JINGLE));
buzz::XmlElement* expected_view_elem1 =
buzz::XmlElement::ForStr(ViewVideoStaticVgaXml("1234"));
@@ -238,7 +238,7 @@
// Test deserializing bad view XML.
TEST_F(MediaMessagesTest, ParseBadViewXml) {
- talk_base::scoped_ptr<buzz::XmlElement> action_elem(
+ rtc::scoped_ptr<buzz::XmlElement> action_elem(
new buzz::XmlElement(QN_JINGLE));
buzz::XmlElement* view_elem =
buzz::XmlElement::ForStr(ViewVideoStaticVgaXml("not-an-ssrc"));
@@ -253,7 +253,7 @@
// Test serializing/deserializing typical streams xml.
TEST_F(MediaMessagesTest, StreamsToFromXml) {
- talk_base::scoped_ptr<buzz::XmlElement> expected_streams_elem(
+ rtc::scoped_ptr<buzz::XmlElement> expected_streams_elem(
buzz::XmlElement::ForStr(
StreamsXml(
StreamXml("nick1", "stream1", "101", "102",
@@ -267,7 +267,7 @@
expected_streams.push_back(CreateStream("nick2", "stream2", 201U, 202U,
"semantics2", "type2", "display2"));
- talk_base::scoped_ptr<buzz::XmlElement> actual_desc_elem(
+ rtc::scoped_ptr<buzz::XmlElement> actual_desc_elem(
new buzz::XmlElement(QN_JINGLE_RTP_CONTENT));
cricket::WriteJingleStreams(expected_streams, actual_desc_elem.get());
@@ -276,7 +276,7 @@
ASSERT_TRUE(actual_streams_elem != NULL);
EXPECT_EQ(expected_streams_elem->Str(), actual_streams_elem->Str());
- talk_base::scoped_ptr<buzz::XmlElement> expected_desc_elem(
+ rtc::scoped_ptr<buzz::XmlElement> expected_desc_elem(
new buzz::XmlElement(QN_JINGLE_RTP_CONTENT));
expected_desc_elem->AddElement(new buzz::XmlElement(
*expected_streams_elem));
@@ -293,14 +293,14 @@
// Test deserializing bad streams xml.
TEST_F(MediaMessagesTest, StreamsFromBadXml) {
- talk_base::scoped_ptr<buzz::XmlElement> streams_elem(
+ rtc::scoped_ptr<buzz::XmlElement> streams_elem(
buzz::XmlElement::ForStr(
StreamsXml(
StreamXml("nick1", "name1", "101", "not-an-ssrc",
"semantics1", "type1", "display1"),
StreamXml("nick2", "name2", "202", "not-an-ssrc",
"semantics2", "type2", "display2"))));
- talk_base::scoped_ptr<buzz::XmlElement> desc_elem(
+ rtc::scoped_ptr<buzz::XmlElement> desc_elem(
new buzz::XmlElement(QN_JINGLE_RTP_CONTENT));
desc_elem->AddElement(new buzz::XmlElement(*streams_elem));
@@ -312,7 +312,7 @@
// Test serializing/deserializing typical RTP Header Extension xml.
TEST_F(MediaMessagesTest, HeaderExtensionsToFromXml) {
- talk_base::scoped_ptr<buzz::XmlElement> expected_desc_elem(
+ rtc::scoped_ptr<buzz::XmlElement> expected_desc_elem(
buzz::XmlElement::ForStr(
HeaderExtensionsXml(
HeaderExtensionXml("abc", "123"),
@@ -322,7 +322,7 @@
expected_hdrexts.push_back(RtpHeaderExtension("abc", 123));
expected_hdrexts.push_back(RtpHeaderExtension("def", 456));
- talk_base::scoped_ptr<buzz::XmlElement> actual_desc_elem(
+ rtc::scoped_ptr<buzz::XmlElement> actual_desc_elem(
new buzz::XmlElement(QN_JINGLE_RTP_CONTENT));
cricket::WriteJingleRtpHeaderExtensions(expected_hdrexts, actual_desc_elem.get());
@@ -343,7 +343,7 @@
std::vector<cricket::RtpHeaderExtension> actual_hdrexts;
cricket::ParseError parse_error;
- talk_base::scoped_ptr<buzz::XmlElement> desc_elem(
+ rtc::scoped_ptr<buzz::XmlElement> desc_elem(
buzz::XmlElement::ForStr(
HeaderExtensionsXml(
HeaderExtensionXml("abc", "123"),
diff --git a/session/media/mediamonitor.cc b/session/media/mediamonitor.cc
index 844180e..565e145 100644
--- a/session/media/mediamonitor.cc
+++ b/session/media/mediamonitor.cc
@@ -25,9 +25,9 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/common.h"
#include "talk/session/media/channelmanager.h"
#include "talk/session/media/mediamonitor.h"
+#include "webrtc/base/common.h"
namespace cricket {
@@ -38,8 +38,8 @@
MSG_MONITOR_SIGNAL = 4
};
-MediaMonitor::MediaMonitor(talk_base::Thread* worker_thread,
- talk_base::Thread* monitor_thread)
+MediaMonitor::MediaMonitor(rtc::Thread* worker_thread,
+ rtc::Thread* monitor_thread)
: worker_thread_(worker_thread),
monitor_thread_(monitor_thread), monitoring_(false), rate_(0) {
}
@@ -62,12 +62,12 @@
rate_ = 0;
}
-void MediaMonitor::OnMessage(talk_base::Message* message) {
- talk_base::CritScope cs(&crit_);
+void MediaMonitor::OnMessage(rtc::Message* message) {
+ rtc::CritScope cs(&crit_);
switch (message->message_id) {
case MSG_MONITOR_START:
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (!monitoring_) {
monitoring_ = true;
PollMediaChannel();
@@ -75,7 +75,7 @@
break;
case MSG_MONITOR_STOP:
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
if (monitoring_) {
monitoring_ = false;
worker_thread_->Clear(this);
@@ -83,20 +83,20 @@
break;
case MSG_MONITOR_POLL:
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
PollMediaChannel();
break;
case MSG_MONITOR_SIGNAL:
- ASSERT(talk_base::Thread::Current() == monitor_thread_);
+ ASSERT(rtc::Thread::Current() == monitor_thread_);
Update();
break;
}
}
void MediaMonitor::PollMediaChannel() {
- talk_base::CritScope cs(&crit_);
- ASSERT(talk_base::Thread::Current() == worker_thread_);
+ rtc::CritScope cs(&crit_);
+ ASSERT(rtc::Thread::Current() == worker_thread_);
GetStats();
diff --git a/session/media/mediamonitor.h b/session/media/mediamonitor.h
index a9ce889..89740a8 100644
--- a/session/media/mediamonitor.h
+++ b/session/media/mediamonitor.h
@@ -30,33 +30,34 @@
#ifndef TALK_SESSION_MEDIA_MEDIAMONITOR_H_
#define TALK_SESSION_MEDIA_MEDIAMONITOR_H_
-#include "talk/base/criticalsection.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/thread.h"
#include "talk/media/base/mediachannel.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/thread_annotations.h"
namespace cricket {
// The base MediaMonitor class, independent of voice and video.
-class MediaMonitor : public talk_base::MessageHandler,
+class MediaMonitor : public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
- MediaMonitor(talk_base::Thread* worker_thread,
- talk_base::Thread* monitor_thread);
+ MediaMonitor(rtc::Thread* worker_thread,
+ rtc::Thread* monitor_thread);
~MediaMonitor();
void Start(uint32 milliseconds);
void Stop();
protected:
- void OnMessage(talk_base::Message *message);
+ void OnMessage(rtc::Message *message);
void PollMediaChannel();
virtual void GetStats() = 0;
virtual void Update() = 0;
- talk_base::CriticalSection crit_;
- talk_base::Thread* worker_thread_;
- talk_base::Thread* monitor_thread_;
+ rtc::CriticalSection crit_;
+ rtc::Thread* worker_thread_;
+ rtc::Thread* monitor_thread_;
bool monitoring_;
uint32 rate_;
};
@@ -65,8 +66,8 @@
template<class MC, class MI>
class MediaMonitorT : public MediaMonitor {
public:
- MediaMonitorT(MC* media_channel, talk_base::Thread* worker_thread,
- talk_base::Thread* monitor_thread)
+ MediaMonitorT(MC* media_channel, rtc::Thread* worker_thread,
+ rtc::Thread* monitor_thread)
: MediaMonitor(worker_thread, monitor_thread),
media_channel_(media_channel) {}
sigslot::signal2<MC*, const MI&> SignalUpdate;
@@ -77,7 +78,7 @@
media_info_.Clear();
media_channel_->GetStats(&media_info_);
}
- virtual void Update() {
+ virtual void Update() EXCLUSIVE_LOCKS_REQUIRED(crit_) {
MI stats(media_info_);
crit_.Leave();
SignalUpdate(media_channel_, stats);
diff --git a/session/media/mediarecorder.cc b/session/media/mediarecorder.cc
index 0aed63a..9ce84f3 100644
--- a/session/media/mediarecorder.cc
+++ b/session/media/mediarecorder.cc
@@ -31,10 +31,10 @@
#include <string>
-#include "talk/base/fileutils.h"
-#include "talk/base/logging.h"
-#include "talk/base/pathutils.h"
#include "talk/media/base/rtpdump.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/pathutils.h"
namespace cricket {
@@ -42,7 +42,7 @@
///////////////////////////////////////////////////////////////////////////
// Implementation of RtpDumpSink.
///////////////////////////////////////////////////////////////////////////
-RtpDumpSink::RtpDumpSink(talk_base::StreamInterface* stream)
+RtpDumpSink::RtpDumpSink(rtc::StreamInterface* stream)
: max_size_(INT_MAX),
recording_(false),
packet_filter_(PF_NONE) {
@@ -52,12 +52,12 @@
RtpDumpSink::~RtpDumpSink() {}
void RtpDumpSink::SetMaxSize(size_t size) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
max_size_ = size;
}
bool RtpDumpSink::Enable(bool enable) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
recording_ = enable;
@@ -75,7 +75,7 @@
}
void RtpDumpSink::OnPacket(const void* data, size_t size, bool rtcp) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
if (recording_ && writer_) {
size_t current_size;
@@ -91,7 +91,7 @@
}
void RtpDumpSink::set_packet_filter(int filter) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
packet_filter_ = filter;
if (writer_) {
writer_->set_packet_filter(packet_filter_);
@@ -99,7 +99,7 @@
}
void RtpDumpSink::Flush() {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
if (stream_) {
stream_->Flush();
}
@@ -111,7 +111,7 @@
MediaRecorder::MediaRecorder() {}
MediaRecorder::~MediaRecorder() {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
std::map<BaseChannel*, SinkPair*>::iterator itr;
for (itr = sinks_.begin(); itr != sinks_.end(); ++itr) {
delete itr->second;
@@ -119,15 +119,15 @@
}
bool MediaRecorder::AddChannel(VoiceChannel* channel,
- talk_base::StreamInterface* send_stream,
- talk_base::StreamInterface* recv_stream,
+ rtc::StreamInterface* send_stream,
+ rtc::StreamInterface* recv_stream,
int filter) {
return InternalAddChannel(channel, false, send_stream, recv_stream,
filter);
}
bool MediaRecorder::AddChannel(VideoChannel* channel,
- talk_base::StreamInterface* send_stream,
- talk_base::StreamInterface* recv_stream,
+ rtc::StreamInterface* send_stream,
+ rtc::StreamInterface* recv_stream,
int filter) {
return InternalAddChannel(channel, true, send_stream, recv_stream,
filter);
@@ -135,14 +135,14 @@
bool MediaRecorder::InternalAddChannel(BaseChannel* channel,
bool video_channel,
- talk_base::StreamInterface* send_stream,
- talk_base::StreamInterface* recv_stream,
+ rtc::StreamInterface* send_stream,
+ rtc::StreamInterface* recv_stream,
int filter) {
if (!channel) {
return false;
}
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
if (sinks_.end() != sinks_.find(channel)) {
return false; // The channel was added already.
}
@@ -161,7 +161,7 @@
void MediaRecorder::RemoveChannel(BaseChannel* channel,
SinkType type) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
std::map<BaseChannel*, SinkPair*>::iterator itr = sinks_.find(channel);
if (sinks_.end() != itr) {
channel->UnregisterSendSink(itr->second->send_sink.get(), type);
@@ -174,7 +174,7 @@
bool MediaRecorder::EnableChannel(
BaseChannel* channel, bool enable_send, bool enable_recv,
SinkType type) {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
std::map<BaseChannel*, SinkPair*>::iterator itr = sinks_.find(channel);
if (sinks_.end() == itr) {
return false;
@@ -213,7 +213,7 @@
}
void MediaRecorder::FlushSinks() {
- talk_base::CritScope cs(&critical_section_);
+ rtc::CritScope cs(&critical_section_);
std::map<BaseChannel*, SinkPair*>::iterator itr;
for (itr = sinks_.begin(); itr != sinks_.end(); ++itr) {
itr->second->send_sink->Flush();
diff --git a/session/media/mediarecorder.h b/session/media/mediarecorder.h
index df22e98..095f355 100644
--- a/session/media/mediarecorder.h
+++ b/session/media/mediarecorder.h
@@ -31,13 +31,13 @@
#include <map>
#include <string>
-#include "talk/base/criticalsection.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
#include "talk/session/media/channel.h"
#include "talk/session/media/mediasink.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
-namespace talk_base {
+namespace rtc {
class Pathname;
class FileStream;
}
@@ -54,7 +54,7 @@
class RtpDumpSink : public MediaSinkInterface, public sigslot::has_slots<> {
public:
// Takes ownership of stream.
- explicit RtpDumpSink(talk_base::StreamInterface* stream);
+ explicit RtpDumpSink(rtc::StreamInterface* stream);
virtual ~RtpDumpSink();
virtual void SetMaxSize(size_t size);
@@ -69,9 +69,9 @@
size_t max_size_;
bool recording_;
int packet_filter_;
- talk_base::scoped_ptr<talk_base::StreamInterface> stream_;
- talk_base::scoped_ptr<RtpDumpWriter> writer_;
- talk_base::CriticalSection critical_section_;
+ rtc::scoped_ptr<rtc::StreamInterface> stream_;
+ rtc::scoped_ptr<RtpDumpWriter> writer_;
+ rtc::CriticalSection critical_section_;
DISALLOW_COPY_AND_ASSIGN(RtpDumpSink);
};
@@ -82,12 +82,12 @@
virtual ~MediaRecorder();
bool AddChannel(VoiceChannel* channel,
- talk_base::StreamInterface* send_stream,
- talk_base::StreamInterface* recv_stream,
+ rtc::StreamInterface* send_stream,
+ rtc::StreamInterface* recv_stream,
int filter);
bool AddChannel(VideoChannel* channel,
- talk_base::StreamInterface* send_stream,
- talk_base::StreamInterface* recv_stream,
+ rtc::StreamInterface* send_stream,
+ rtc::StreamInterface* recv_stream,
int filter);
void RemoveChannel(BaseChannel* channel, SinkType type);
bool EnableChannel(BaseChannel* channel, bool enable_send, bool enable_recv,
@@ -98,18 +98,18 @@
struct SinkPair {
bool video_channel;
int filter;
- talk_base::scoped_ptr<RtpDumpSink> send_sink;
- talk_base::scoped_ptr<RtpDumpSink> recv_sink;
+ rtc::scoped_ptr<RtpDumpSink> send_sink;
+ rtc::scoped_ptr<RtpDumpSink> recv_sink;
};
bool InternalAddChannel(BaseChannel* channel,
bool video_channel,
- talk_base::StreamInterface* send_stream,
- talk_base::StreamInterface* recv_stream,
+ rtc::StreamInterface* send_stream,
+ rtc::StreamInterface* recv_stream,
int filter);
std::map<BaseChannel*, SinkPair*> sinks_;
- talk_base::CriticalSection critical_section_;
+ rtc::CriticalSection critical_section_;
DISALLOW_COPY_AND_ASSIGN(MediaRecorder);
};
diff --git a/session/media/mediarecorder_unittest.cc b/session/media/mediarecorder_unittest.cc
index 5155e6d..9feb22a 100644
--- a/session/media/mediarecorder_unittest.cc
+++ b/session/media/mediarecorder_unittest.cc
@@ -25,23 +25,23 @@
#include <string>
-#include "talk/base/bytebuffer.h"
-#include "talk/base/fileutils.h"
-#include "talk/base/gunit.h"
-#include "talk/base/pathutils.h"
-#include "talk/base/thread.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/media/base/rtpdump.h"
#include "talk/media/base/testutils.h"
#include "talk/p2p/base/fakesession.h"
#include "talk/session/media/channel.h"
#include "talk/session/media/mediarecorder.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/fileutils.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/pathutils.h"
+#include "webrtc/base/thread.h"
namespace cricket {
-talk_base::StreamInterface* Open(const std::string& path) {
- return talk_base::Filesystem::OpenFile(
- talk_base::Pathname(path), "wb");
+rtc::StreamInterface* Open(const std::string& path) {
+ return rtc::Filesystem::OpenFile(
+ rtc::Pathname(path), "wb");
}
/////////////////////////////////////////////////////////////////////////
@@ -50,7 +50,7 @@
class RtpDumpSinkTest : public testing::Test {
public:
virtual void SetUp() {
- EXPECT_TRUE(talk_base::Filesystem::GetTemporaryFolder(path_, true, NULL));
+ EXPECT_TRUE(rtc::Filesystem::GetTemporaryFolder(path_, true, NULL));
path_.SetFilename("sink-test.rtpdump");
sink_.reset(new RtpDumpSink(Open(path_.pathname())));
@@ -62,30 +62,30 @@
virtual void TearDown() {
stream_.reset();
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(path_));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(path_));
}
protected:
void OnRtpPacket(const RawRtpPacket& raw) {
- talk_base::ByteBuffer buf;
+ rtc::ByteBuffer buf;
raw.WriteToByteBuffer(RtpTestUtility::kDefaultSsrc, &buf);
sink_->OnPacket(buf.Data(), buf.Length(), false);
}
- talk_base::StreamResult ReadPacket(RtpDumpPacket* packet) {
+ rtc::StreamResult ReadPacket(RtpDumpPacket* packet) {
if (!stream_.get()) {
sink_.reset(); // This will close the file. So we can read it.
- stream_.reset(talk_base::Filesystem::OpenFile(path_, "rb"));
+ stream_.reset(rtc::Filesystem::OpenFile(path_, "rb"));
reader_.reset(new RtpDumpReader(stream_.get()));
}
return reader_->ReadPacket(packet);
}
- talk_base::Pathname path_;
- talk_base::scoped_ptr<RtpDumpSink> sink_;
- talk_base::ByteBuffer rtp_buf_[3];
- talk_base::scoped_ptr<talk_base::StreamInterface> stream_;
- talk_base::scoped_ptr<RtpDumpReader> reader_;
+ rtc::Pathname path_;
+ rtc::scoped_ptr<RtpDumpSink> sink_;
+ rtc::ByteBuffer rtp_buf_[3];
+ rtc::scoped_ptr<rtc::StreamInterface> stream_;
+ rtc::scoped_ptr<RtpDumpReader> reader_;
};
TEST_F(RtpDumpSinkTest, TestRtpDumpSink) {
@@ -97,7 +97,7 @@
// Enable the sink. The 2nd packet is written.
EXPECT_TRUE(sink_->Enable(true));
EXPECT_TRUE(sink_->IsEnabled());
- EXPECT_TRUE(talk_base::Filesystem::IsFile(path_.pathname()));
+ EXPECT_TRUE(rtc::Filesystem::IsFile(path_.pathname()));
OnRtpPacket(RtpTestUtility::kTestRawRtpPackets[1]);
// Disable the sink. The 3rd packet is not written.
@@ -107,10 +107,10 @@
// Read the recorded file and verify it contains only the 2nd packet.
RtpDumpPacket packet;
- EXPECT_EQ(talk_base::SR_SUCCESS, ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, ReadPacket(&packet));
EXPECT_TRUE(RtpTestUtility::VerifyPacket(
&packet, &RtpTestUtility::kTestRawRtpPackets[1], false));
- EXPECT_EQ(talk_base::SR_EOS, ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, ReadPacket(&packet));
}
TEST_F(RtpDumpSinkTest, TestRtpDumpSinkMaxSize) {
@@ -128,10 +128,10 @@
// Read the recorded file and verify that it contains only the first packet.
RtpDumpPacket packet;
- EXPECT_EQ(talk_base::SR_SUCCESS, ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, ReadPacket(&packet));
EXPECT_TRUE(RtpTestUtility::VerifyPacket(
&packet, &RtpTestUtility::kTestRawRtpPackets[0], false));
- EXPECT_EQ(talk_base::SR_EOS, ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, ReadPacket(&packet));
}
TEST_F(RtpDumpSinkTest, TestRtpDumpSinkFilter) {
@@ -158,13 +158,13 @@
// Read the recorded file and verify the header of the first packet and
// the whole packet for the second packet.
RtpDumpPacket packet;
- EXPECT_EQ(talk_base::SR_SUCCESS, ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, ReadPacket(&packet));
EXPECT_TRUE(RtpTestUtility::VerifyPacket(
&packet, &RtpTestUtility::kTestRawRtpPackets[0], true));
- EXPECT_EQ(talk_base::SR_SUCCESS, ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_SUCCESS, ReadPacket(&packet));
EXPECT_TRUE(RtpTestUtility::VerifyPacket(
&packet, &RtpTestUtility::kTestRawRtpPackets[1], false));
- EXPECT_EQ(talk_base::SR_EOS, ReadPacket(&packet));
+ EXPECT_EQ(rtc::SR_EOS, ReadPacket(&packet));
}
/////////////////////////////////////////////////////////////////////////
@@ -174,7 +174,7 @@
FakeVideoMediaChannel* video_media_channel,
int filter) {
// Create media recorder.
- talk_base::scoped_ptr<MediaRecorder> recorder(new MediaRecorder);
+ rtc::scoped_ptr<MediaRecorder> recorder(new MediaRecorder);
// Fail to EnableChannel before AddChannel.
EXPECT_FALSE(recorder->EnableChannel(channel, true, true, SINK_PRE_CRYPTO));
EXPECT_FALSE(channel->HasSendSinks(SINK_PRE_CRYPTO));
@@ -183,8 +183,8 @@
EXPECT_FALSE(channel->HasRecvSinks(SINK_POST_CRYPTO));
// Add the channel to the recorder.
- talk_base::Pathname path;
- EXPECT_TRUE(talk_base::Filesystem::GetTemporaryFolder(path, true, NULL));
+ rtc::Pathname path;
+ EXPECT_TRUE(rtc::Filesystem::GetTemporaryFolder(path, true, NULL));
path.SetFilename("send.rtpdump");
std::string send_file = path.pathname();
path.SetFilename("recv.rtpdump");
@@ -247,8 +247,8 @@
// Delete all files.
recorder.reset();
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(send_file));
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(recv_file));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(send_file));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(recv_file));
}
// Fisrt start recording header and then start recording media. Verify that
@@ -256,10 +256,10 @@
void TestRecordHeaderAndMedia(BaseChannel* channel,
FakeVideoMediaChannel* video_media_channel) {
// Create RTP header recorder.
- talk_base::scoped_ptr<MediaRecorder> header_recorder(new MediaRecorder);
+ rtc::scoped_ptr<MediaRecorder> header_recorder(new MediaRecorder);
- talk_base::Pathname path;
- EXPECT_TRUE(talk_base::Filesystem::GetTemporaryFolder(path, true, NULL));
+ rtc::Pathname path;
+ EXPECT_TRUE(rtc::Filesystem::GetTemporaryFolder(path, true, NULL));
path.SetFilename("send-header.rtpdump");
std::string send_header_file = path.pathname();
path.SetFilename("recv-header.rtpdump");
@@ -287,11 +287,11 @@
}
// Verify that header files are created.
- EXPECT_TRUE(talk_base::Filesystem::IsFile(send_header_file));
- EXPECT_TRUE(talk_base::Filesystem::IsFile(recv_header_file));
+ EXPECT_TRUE(rtc::Filesystem::IsFile(send_header_file));
+ EXPECT_TRUE(rtc::Filesystem::IsFile(recv_header_file));
// Create RTP header recorder.
- talk_base::scoped_ptr<MediaRecorder> recorder(new MediaRecorder);
+ rtc::scoped_ptr<MediaRecorder> recorder(new MediaRecorder);
path.SetFilename("send.rtpdump");
std::string send_file = path.pathname();
path.SetFilename("recv.rtpdump");
@@ -318,23 +318,23 @@
}
// Verify that media files are created.
- EXPECT_TRUE(talk_base::Filesystem::IsFile(send_file));
- EXPECT_TRUE(talk_base::Filesystem::IsFile(recv_file));
+ EXPECT_TRUE(rtc::Filesystem::IsFile(send_file));
+ EXPECT_TRUE(rtc::Filesystem::IsFile(recv_file));
// Delete all files.
header_recorder.reset();
recorder.reset();
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(send_header_file));
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(recv_header_file));
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(send_file));
- EXPECT_TRUE(talk_base::Filesystem::DeleteFile(recv_file));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(send_header_file));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(recv_header_file));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(send_file));
+ EXPECT_TRUE(rtc::Filesystem::DeleteFile(recv_file));
}
TEST(MediaRecorderTest, TestMediaRecorderVoiceChannel) {
// Create the voice channel.
FakeSession session(true);
FakeMediaEngine media_engine;
- VoiceChannel channel(talk_base::Thread::Current(), &media_engine,
+ VoiceChannel channel(rtc::Thread::Current(), &media_engine,
new FakeVoiceMediaChannel(NULL), &session, "", false);
EXPECT_TRUE(channel.Init());
TestMediaRecorder(&channel, NULL, PF_RTPPACKET);
@@ -347,7 +347,7 @@
FakeSession session(true);
FakeMediaEngine media_engine;
FakeVideoMediaChannel* media_channel = new FakeVideoMediaChannel(NULL);
- VideoChannel channel(talk_base::Thread::Current(), &media_engine,
+ VideoChannel channel(rtc::Thread::Current(), &media_engine,
media_channel, &session, "", false, NULL);
EXPECT_TRUE(channel.Init());
TestMediaRecorder(&channel, media_channel, PF_RTPPACKET);
diff --git a/session/media/mediasession.cc b/session/media/mediasession.cc
index 006975f..92dd257 100644
--- a/session/media/mediasession.cc
+++ b/session/media/mediasession.cc
@@ -32,16 +32,16 @@
#include <set>
#include <utility>
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/cryptoparams.h"
#include "talk/p2p/base/constants.h"
#include "talk/session/media/channelmanager.h"
#include "talk/session/media/srtpfilter.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stringutils.h"
#ifdef HAVE_SCTP
#include "talk/media/sctp/sctpdataengine.h"
@@ -55,7 +55,7 @@
namespace cricket {
-using talk_base::scoped_ptr;
+using rtc::scoped_ptr;
// RTP Profile names
// http://www.iana.org/assignments/rtp-parameters/rtp-parameters.xml
@@ -89,7 +89,7 @@
std::string key;
key.reserve(SRTP_MASTER_KEY_BASE64_LEN);
- if (!talk_base::CreateRandomString(SRTP_MASTER_KEY_BASE64_LEN, &key)) {
+ if (!rtc::CreateRandomString(SRTP_MASTER_KEY_BASE64_LEN, &key)) {
return false;
}
out->tag = tag;
@@ -236,7 +236,7 @@
// Generate a random string for the RTCP CNAME, as stated in RFC 6222.
// This string is only used for synchronization, and therefore is opaque.
do {
- if (!talk_base::CreateRandomString(16, cname)) {
+ if (!rtc::CreateRandomString(16, cname)) {
ASSERT(false);
return false;
}
@@ -254,7 +254,7 @@
for (int i = 0; i < num_ssrcs; i++) {
uint32 candidate;
do {
- candidate = talk_base::CreateRandomNonZeroId();
+ candidate = rtc::CreateRandomNonZeroId();
} while (GetStreamBySsrc(params_vec, candidate, NULL) ||
std::count(ssrcs->begin(), ssrcs->end(), candidate) > 0);
ssrcs->push_back(candidate);
@@ -270,7 +270,7 @@
return false;
}
while (true) {
- uint32 candidate = talk_base::CreateRandomNonZeroId() % kMaxSctpSid;
+ uint32 candidate = rtc::CreateRandomNonZeroId() % kMaxSctpSid;
if (!GetStreamBySsrc(params_vec, candidate, NULL)) {
*sid = candidate;
return true;
@@ -610,7 +610,7 @@
return false;
}
is_rtp = media_desc->protocol().empty() ||
- talk_base::starts_with(media_desc->protocol().data(),
+ rtc::starts_with(media_desc->protocol().data(),
kMediaProtocolRtpPrefix);
}
return is_rtp;
@@ -775,6 +775,11 @@
negotiated.SetParam(kCodecParamAssociatedPayloadType, apt_value);
}
negotiated.id = theirs->id;
+ // RFC3264: Although the answerer MAY list the formats in their desired
+ // order of preference, it is RECOMMENDED that unless there is a
+ // specific reason, the answerer list formats in the same relative order
+ // they were present in the offer.
+ negotiated.preference = theirs->preference;
negotiated_codecs->push_back(negotiated);
}
}
@@ -815,7 +820,7 @@
if (!FindMatchingCodec<C>(*offered_codecs, *it, NULL) && IsRtxCodec(*it)) {
C rtx_codec = *it;
int referenced_pl_type =
- talk_base::FromString<int>(0,
+ rtc::FromString<int>(0,
rtx_codec.params[kCodecParamAssociatedPayloadType]);
new_rtx_codecs.insert(std::pair<int, C>(referenced_pl_type,
rtx_codec));
@@ -838,7 +843,7 @@
if (rtx_it != new_rtx_codecs.end()) {
C& rtx_codec = rtx_it->second;
rtx_codec.params[kCodecParamAssociatedPayloadType] =
- talk_base::ToString(codec.id);
+ rtc::ToString(codec.id);
}
}
}
@@ -1135,8 +1140,6 @@
SessionDescription* MediaSessionDescriptionFactory::CreateOffer(
const MediaSessionOptions& options,
const SessionDescription* current_description) const {
- bool secure_transport = (transport_desc_factory_->secure() != SEC_DISABLED);
-
scoped_ptr<SessionDescription> offer(new SessionDescription());
StreamParamsVec current_streams;
@@ -1158,117 +1161,57 @@
GetRtpHdrExtsToOffer(current_description, &audio_rtp_extensions,
&video_rtp_extensions);
- // Handle m=audio.
- if (options.has_audio) {
- cricket::SecurePolicy sdes_policy =
- IsDtlsActive(CN_AUDIO, current_description) ?
- cricket::SEC_DISABLED : secure();
+ bool audio_added = false;
+ bool video_added = false;
+ bool data_added = false;
- scoped_ptr<AudioContentDescription> audio(new AudioContentDescription());
- std::vector<std::string> crypto_suites;
- GetSupportedAudioCryptoSuites(&crypto_suites);
- if (!CreateMediaContentOffer(
- options,
- audio_codecs,
- sdes_policy,
- GetCryptos(GetFirstAudioContentDescription(current_description)),
- crypto_suites,
- audio_rtp_extensions,
- add_legacy_,
- ¤t_streams,
- audio.get())) {
- return NULL;
- }
-
- audio->set_lang(lang_);
- SetMediaProtocol(secure_transport, audio.get());
- offer->AddContent(CN_AUDIO, NS_JINGLE_RTP, audio.release());
- if (!AddTransportOffer(CN_AUDIO, options.transport_options,
- current_description, offer.get())) {
- return NULL;
+ // Iterate through the contents of |current_description| to maintain the order
+ // of the m-lines in the new offer.
+ if (current_description) {
+ ContentInfos::const_iterator it = current_description->contents().begin();
+ for (; it != current_description->contents().end(); ++it) {
+ if (IsMediaContentOfType(&*it, MEDIA_TYPE_AUDIO)) {
+ if (!AddAudioContentForOffer(options, current_description,
+ audio_rtp_extensions, audio_codecs,
+ ¤t_streams, offer.get())) {
+ return NULL;
+ }
+ audio_added = true;
+ } else if (IsMediaContentOfType(&*it, MEDIA_TYPE_VIDEO)) {
+ if (!AddVideoContentForOffer(options, current_description,
+ video_rtp_extensions, video_codecs,
+ ¤t_streams, offer.get())) {
+ return NULL;
+ }
+ video_added = true;
+ } else if (IsMediaContentOfType(&*it, MEDIA_TYPE_DATA)) {
+ if (!AddDataContentForOffer(options, current_description, &data_codecs,
+ ¤t_streams, offer.get())) {
+ return NULL;
+ }
+ data_added = true;
+ } else {
+ ASSERT(false);
+ }
}
}
-
- // Handle m=video.
- if (options.has_video) {
- cricket::SecurePolicy sdes_policy =
- IsDtlsActive(CN_VIDEO, current_description) ?
- cricket::SEC_DISABLED : secure();
-
- scoped_ptr<VideoContentDescription> video(new VideoContentDescription());
- std::vector<std::string> crypto_suites;
- GetSupportedVideoCryptoSuites(&crypto_suites);
- if (!CreateMediaContentOffer(
- options,
- video_codecs,
- sdes_policy,
- GetCryptos(GetFirstVideoContentDescription(current_description)),
- crypto_suites,
- video_rtp_extensions,
- add_legacy_,
- ¤t_streams,
- video.get())) {
- return NULL;
- }
-
- video->set_bandwidth(options.video_bandwidth);
- SetMediaProtocol(secure_transport, video.get());
- offer->AddContent(CN_VIDEO, NS_JINGLE_RTP, video.release());
- if (!AddTransportOffer(CN_VIDEO, options.transport_options,
- current_description, offer.get())) {
- return NULL;
- }
+ // Append contents that are not in |current_description|.
+ if (!audio_added && options.has_audio &&
+ !AddAudioContentForOffer(options, current_description,
+ audio_rtp_extensions, audio_codecs,
+ ¤t_streams, offer.get())) {
+ return NULL;
}
-
- // Handle m=data.
- if (options.has_data()) {
- scoped_ptr<DataContentDescription> data(new DataContentDescription());
- bool is_sctp = (options.data_channel_type == DCT_SCTP);
-
- FilterDataCodecs(&data_codecs, is_sctp);
-
- cricket::SecurePolicy sdes_policy =
- IsDtlsActive(CN_DATA, current_description) ?
- cricket::SEC_DISABLED : secure();
- std::vector<std::string> crypto_suites;
- if (is_sctp) {
- // SDES doesn't make sense for SCTP, so we disable it, and we only
- // get SDES crypto suites for RTP-based data channels.
- sdes_policy = cricket::SEC_DISABLED;
- // Unlike SetMediaProtocol below, we need to set the protocol
- // before we call CreateMediaContentOffer. Otherwise,
- // CreateMediaContentOffer won't know this is SCTP and will
- // generate SSRCs rather than SIDs.
- data->set_protocol(
- secure_transport ? kMediaProtocolDtlsSctp : kMediaProtocolSctp);
- } else {
- GetSupportedDataCryptoSuites(&crypto_suites);
- }
-
- if (!CreateMediaContentOffer(
- options,
- data_codecs,
- sdes_policy,
- GetCryptos(GetFirstDataContentDescription(current_description)),
- crypto_suites,
- RtpHeaderExtensions(),
- add_legacy_,
- ¤t_streams,
- data.get())) {
- return NULL;
- }
-
- if (is_sctp) {
- offer->AddContent(CN_DATA, NS_JINGLE_DRAFT_SCTP, data.release());
- } else {
- data->set_bandwidth(options.data_bandwidth);
- SetMediaProtocol(secure_transport, data.get());
- offer->AddContent(CN_DATA, NS_JINGLE_RTP, data.release());
- }
- if (!AddTransportOffer(CN_DATA, options.transport_options,
- current_description, offer.get())) {
- return NULL;
- }
+ if (!video_added && options.has_video &&
+ !AddVideoContentForOffer(options, current_description,
+ video_rtp_extensions, video_codecs,
+ ¤t_streams, offer.get())) {
+ return NULL;
+ }
+ if (!data_added && options.has_data() &&
+ !AddDataContentForOffer(options, current_description, &data_codecs,
+ ¤t_streams, offer.get())) {
+ return NULL;
}
// Bundle the contents together, if we've been asked to do so, and update any
@@ -1304,168 +1247,27 @@
StreamParamsVec current_streams;
GetCurrentStreamParams(current_description, ¤t_streams);
- bool bundle_enabled =
- offer->HasGroup(GROUP_TYPE_BUNDLE) && options.bundle_enabled;
-
- // Handle m=audio.
- const ContentInfo* audio_content = GetFirstAudioContent(offer);
- if (audio_content) {
- scoped_ptr<TransportDescription> audio_transport(
- CreateTransportAnswer(audio_content->name, offer,
- options.transport_options,
- current_description));
- if (!audio_transport) {
- return NULL;
- }
-
- AudioCodecs audio_codecs = audio_codecs_;
- if (!options.vad_enabled) {
- StripCNCodecs(&audio_codecs);
- }
-
- scoped_ptr<AudioContentDescription> audio_answer(
- new AudioContentDescription());
- // Do not require or create SDES cryptos if DTLS is used.
- cricket::SecurePolicy sdes_policy =
- audio_transport->secure() ? cricket::SEC_DISABLED : secure();
- if (!CreateMediaContentAnswer(
- static_cast<const AudioContentDescription*>(
- audio_content->description),
- options,
- audio_codecs,
- sdes_policy,
- GetCryptos(GetFirstAudioContentDescription(current_description)),
- audio_rtp_extensions_,
- ¤t_streams,
- add_legacy_,
- bundle_enabled,
- audio_answer.get())) {
- return NULL; // Fails the session setup.
- }
-
- bool rejected = !options.has_audio || audio_content->rejected ||
- !IsMediaProtocolSupported(MEDIA_TYPE_AUDIO,
- audio_answer->protocol(),
- audio_transport->secure());
- if (!rejected) {
- AddTransportAnswer(audio_content->name, *(audio_transport.get()),
- answer.get());
- } else {
- // RFC 3264
- // The answer MUST contain the same number of m-lines as the offer.
- LOG(LS_INFO) << "Audio is not supported in the answer.";
- }
-
- answer->AddContent(audio_content->name, audio_content->type, rejected,
- audio_answer.release());
- } else {
- LOG(LS_INFO) << "Audio is not available in the offer.";
- }
-
- // Handle m=video.
- const ContentInfo* video_content = GetFirstVideoContent(offer);
- if (video_content) {
- scoped_ptr<TransportDescription> video_transport(
- CreateTransportAnswer(video_content->name, offer,
- options.transport_options,
- current_description));
- if (!video_transport) {
- return NULL;
- }
-
- scoped_ptr<VideoContentDescription> video_answer(
- new VideoContentDescription());
- // Do not require or create SDES cryptos if DTLS is used.
- cricket::SecurePolicy sdes_policy =
- video_transport->secure() ? cricket::SEC_DISABLED : secure();
- if (!CreateMediaContentAnswer(
- static_cast<const VideoContentDescription*>(
- video_content->description),
- options,
- video_codecs_,
- sdes_policy,
- GetCryptos(GetFirstVideoContentDescription(current_description)),
- video_rtp_extensions_,
- ¤t_streams,
- add_legacy_,
- bundle_enabled,
- video_answer.get())) {
- return NULL;
- }
- bool rejected = !options.has_video || video_content->rejected ||
- !IsMediaProtocolSupported(MEDIA_TYPE_VIDEO,
- video_answer->protocol(),
- video_transport->secure());
- if (!rejected) {
- if (!AddTransportAnswer(video_content->name, *(video_transport.get()),
- answer.get())) {
- return NULL;
+ if (offer) {
+ ContentInfos::const_iterator it = offer->contents().begin();
+ for (; it != offer->contents().end(); ++it) {
+ if (IsMediaContentOfType(&*it, MEDIA_TYPE_AUDIO)) {
+ if (!AddAudioContentForAnswer(offer, options, current_description,
+ ¤t_streams, answer.get())) {
+ return NULL;
+ }
+ } else if (IsMediaContentOfType(&*it, MEDIA_TYPE_VIDEO)) {
+ if (!AddVideoContentForAnswer(offer, options, current_description,
+ ¤t_streams, answer.get())) {
+ return NULL;
+ }
+ } else {
+ ASSERT(IsMediaContentOfType(&*it, MEDIA_TYPE_DATA));
+ if (!AddDataContentForAnswer(offer, options, current_description,
+ ¤t_streams, answer.get())) {
+ return NULL;
+ }
}
- video_answer->set_bandwidth(options.video_bandwidth);
- } else {
- // RFC 3264
- // The answer MUST contain the same number of m-lines as the offer.
- LOG(LS_INFO) << "Video is not supported in the answer.";
}
- answer->AddContent(video_content->name, video_content->type, rejected,
- video_answer.release());
- } else {
- LOG(LS_INFO) << "Video is not available in the offer.";
- }
-
- // Handle m=data.
- const ContentInfo* data_content = GetFirstDataContent(offer);
- if (data_content) {
- scoped_ptr<TransportDescription> data_transport(
- CreateTransportAnswer(data_content->name, offer,
- options.transport_options,
- current_description));
- if (!data_transport) {
- return NULL;
- }
- bool is_sctp = (options.data_channel_type == DCT_SCTP);
- std::vector<DataCodec> data_codecs(data_codecs_);
- FilterDataCodecs(&data_codecs, is_sctp);
-
- scoped_ptr<DataContentDescription> data_answer(
- new DataContentDescription());
- // Do not require or create SDES cryptos if DTLS is used.
- cricket::SecurePolicy sdes_policy =
- data_transport->secure() ? cricket::SEC_DISABLED : secure();
- if (!CreateMediaContentAnswer(
- static_cast<const DataContentDescription*>(
- data_content->description),
- options,
- data_codecs_,
- sdes_policy,
- GetCryptos(GetFirstDataContentDescription(current_description)),
- RtpHeaderExtensions(),
- ¤t_streams,
- add_legacy_,
- bundle_enabled,
- data_answer.get())) {
- return NULL; // Fails the session setup.
- }
-
- bool rejected = !options.has_data() || data_content->rejected ||
- !IsMediaProtocolSupported(MEDIA_TYPE_DATA,
- data_answer->protocol(),
- data_transport->secure());
- if (!rejected) {
- data_answer->set_bandwidth(options.data_bandwidth);
- if (!AddTransportAnswer(data_content->name, *(data_transport.get()),
- answer.get())) {
- return NULL;
- }
- } else {
- // RFC 3264
- // The answer MUST contain the same number of m-lines as the offer.
- LOG(LS_INFO) << "Data is not supported in the answer.";
- }
- answer->AddContent(data_content->name, data_content->type, rejected,
- data_answer.release());
- } else {
- LOG(LS_INFO) << "Data is not available in the offer.";
}
// If the offer supports BUNDLE, and we want to use it too, create a BUNDLE
@@ -1587,7 +1389,7 @@
return false;
const TransportDescription* current_tdesc =
GetTransportDescription(content_name, current_desc);
- talk_base::scoped_ptr<TransportDescription> new_tdesc(
+ rtc::scoped_ptr<TransportDescription> new_tdesc(
transport_desc_factory_->CreateOffer(transport_options, current_tdesc));
bool ret = (new_tdesc.get() != NULL &&
offer_desc->AddTransportInfo(TransportInfo(content_name, *new_tdesc)));
@@ -1627,6 +1429,320 @@
return true;
}
+bool MediaSessionDescriptionFactory::AddAudioContentForOffer(
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ const RtpHeaderExtensions& audio_rtp_extensions,
+ const AudioCodecs& audio_codecs,
+ StreamParamsVec* current_streams,
+ SessionDescription* desc) const {
+ cricket::SecurePolicy sdes_policy =
+ IsDtlsActive(CN_AUDIO, current_description) ?
+ cricket::SEC_DISABLED : secure();
+
+ scoped_ptr<AudioContentDescription> audio(new AudioContentDescription());
+ std::vector<std::string> crypto_suites;
+ GetSupportedAudioCryptoSuites(&crypto_suites);
+ if (!CreateMediaContentOffer(
+ options,
+ audio_codecs,
+ sdes_policy,
+ GetCryptos(GetFirstAudioContentDescription(current_description)),
+ crypto_suites,
+ audio_rtp_extensions,
+ add_legacy_,
+ current_streams,
+ audio.get())) {
+ return false;
+ }
+ audio->set_lang(lang_);
+
+ bool secure_transport = (transport_desc_factory_->secure() != SEC_DISABLED);
+ SetMediaProtocol(secure_transport, audio.get());
+
+ desc->AddContent(CN_AUDIO, NS_JINGLE_RTP, audio.release());
+ if (!AddTransportOffer(CN_AUDIO, options.transport_options,
+ current_description, desc)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool MediaSessionDescriptionFactory::AddVideoContentForOffer(
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ const RtpHeaderExtensions& video_rtp_extensions,
+ const VideoCodecs& video_codecs,
+ StreamParamsVec* current_streams,
+ SessionDescription* desc) const {
+ cricket::SecurePolicy sdes_policy =
+ IsDtlsActive(CN_VIDEO, current_description) ?
+ cricket::SEC_DISABLED : secure();
+
+ scoped_ptr<VideoContentDescription> video(new VideoContentDescription());
+ std::vector<std::string> crypto_suites;
+ GetSupportedVideoCryptoSuites(&crypto_suites);
+ if (!CreateMediaContentOffer(
+ options,
+ video_codecs,
+ sdes_policy,
+ GetCryptos(GetFirstVideoContentDescription(current_description)),
+ crypto_suites,
+ video_rtp_extensions,
+ add_legacy_,
+ current_streams,
+ video.get())) {
+ return false;
+ }
+
+ video->set_bandwidth(options.video_bandwidth);
+
+ bool secure_transport = (transport_desc_factory_->secure() != SEC_DISABLED);
+ SetMediaProtocol(secure_transport, video.get());
+ desc->AddContent(CN_VIDEO, NS_JINGLE_RTP, video.release());
+ if (!AddTransportOffer(CN_VIDEO, options.transport_options,
+ current_description, desc)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool MediaSessionDescriptionFactory::AddDataContentForOffer(
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ DataCodecs* data_codecs,
+ StreamParamsVec* current_streams,
+ SessionDescription* desc) const {
+ bool secure_transport = (transport_desc_factory_->secure() != SEC_DISABLED);
+
+ scoped_ptr<DataContentDescription> data(new DataContentDescription());
+ bool is_sctp = (options.data_channel_type == DCT_SCTP);
+
+ FilterDataCodecs(data_codecs, is_sctp);
+
+ cricket::SecurePolicy sdes_policy =
+ IsDtlsActive(CN_DATA, current_description) ?
+ cricket::SEC_DISABLED : secure();
+ std::vector<std::string> crypto_suites;
+ if (is_sctp) {
+ // SDES doesn't make sense for SCTP, so we disable it, and we only
+ // get SDES crypto suites for RTP-based data channels.
+ sdes_policy = cricket::SEC_DISABLED;
+ // Unlike SetMediaProtocol below, we need to set the protocol
+ // before we call CreateMediaContentOffer. Otherwise,
+ // CreateMediaContentOffer won't know this is SCTP and will
+ // generate SSRCs rather than SIDs.
+ data->set_protocol(
+ secure_transport ? kMediaProtocolDtlsSctp : kMediaProtocolSctp);
+ } else {
+ GetSupportedDataCryptoSuites(&crypto_suites);
+ }
+
+ if (!CreateMediaContentOffer(
+ options,
+ *data_codecs,
+ sdes_policy,
+ GetCryptos(GetFirstDataContentDescription(current_description)),
+ crypto_suites,
+ RtpHeaderExtensions(),
+ add_legacy_,
+ current_streams,
+ data.get())) {
+ return false;
+ }
+
+ if (is_sctp) {
+ desc->AddContent(CN_DATA, NS_JINGLE_DRAFT_SCTP, data.release());
+ } else {
+ data->set_bandwidth(options.data_bandwidth);
+ SetMediaProtocol(secure_transport, data.get());
+ desc->AddContent(CN_DATA, NS_JINGLE_RTP, data.release());
+ }
+ if (!AddTransportOffer(CN_DATA, options.transport_options,
+ current_description, desc)) {
+ return false;
+ }
+ return true;
+}
+
+bool MediaSessionDescriptionFactory::AddAudioContentForAnswer(
+ const SessionDescription* offer,
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ StreamParamsVec* current_streams,
+ SessionDescription* answer) const {
+ const ContentInfo* audio_content = GetFirstAudioContent(offer);
+
+ scoped_ptr<TransportDescription> audio_transport(
+ CreateTransportAnswer(audio_content->name, offer,
+ options.transport_options,
+ current_description));
+ if (!audio_transport) {
+ return false;
+ }
+
+ AudioCodecs audio_codecs = audio_codecs_;
+ if (!options.vad_enabled) {
+ StripCNCodecs(&audio_codecs);
+ }
+
+ bool bundle_enabled =
+ offer->HasGroup(GROUP_TYPE_BUNDLE) && options.bundle_enabled;
+ scoped_ptr<AudioContentDescription> audio_answer(
+ new AudioContentDescription());
+ // Do not require or create SDES cryptos if DTLS is used.
+ cricket::SecurePolicy sdes_policy =
+ audio_transport->secure() ? cricket::SEC_DISABLED : secure();
+ if (!CreateMediaContentAnswer(
+ static_cast<const AudioContentDescription*>(
+ audio_content->description),
+ options,
+ audio_codecs,
+ sdes_policy,
+ GetCryptos(GetFirstAudioContentDescription(current_description)),
+ audio_rtp_extensions_,
+ current_streams,
+ add_legacy_,
+ bundle_enabled,
+ audio_answer.get())) {
+ return false; // Fails the session setup.
+ }
+
+ bool rejected = !options.has_audio || audio_content->rejected ||
+ !IsMediaProtocolSupported(MEDIA_TYPE_AUDIO,
+ audio_answer->protocol(),
+ audio_transport->secure());
+ if (!rejected) {
+ AddTransportAnswer(audio_content->name, *(audio_transport.get()), answer);
+ } else {
+ // RFC 3264
+ // The answer MUST contain the same number of m-lines as the offer.
+ LOG(LS_INFO) << "Audio is not supported in the answer.";
+ }
+
+ answer->AddContent(audio_content->name, audio_content->type, rejected,
+ audio_answer.release());
+ return true;
+}
+
+bool MediaSessionDescriptionFactory::AddVideoContentForAnswer(
+ const SessionDescription* offer,
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ StreamParamsVec* current_streams,
+ SessionDescription* answer) const {
+ const ContentInfo* video_content = GetFirstVideoContent(offer);
+ scoped_ptr<TransportDescription> video_transport(
+ CreateTransportAnswer(video_content->name, offer,
+ options.transport_options,
+ current_description));
+ if (!video_transport) {
+ return false;
+ }
+
+ scoped_ptr<VideoContentDescription> video_answer(
+ new VideoContentDescription());
+ // Do not require or create SDES cryptos if DTLS is used.
+ cricket::SecurePolicy sdes_policy =
+ video_transport->secure() ? cricket::SEC_DISABLED : secure();
+ bool bundle_enabled =
+ offer->HasGroup(GROUP_TYPE_BUNDLE) && options.bundle_enabled;
+ if (!CreateMediaContentAnswer(
+ static_cast<const VideoContentDescription*>(
+ video_content->description),
+ options,
+ video_codecs_,
+ sdes_policy,
+ GetCryptos(GetFirstVideoContentDescription(current_description)),
+ video_rtp_extensions_,
+ current_streams,
+ add_legacy_,
+ bundle_enabled,
+ video_answer.get())) {
+ return false;
+ }
+ bool rejected = !options.has_video || video_content->rejected ||
+ !IsMediaProtocolSupported(MEDIA_TYPE_VIDEO,
+ video_answer->protocol(),
+ video_transport->secure());
+ if (!rejected) {
+ if (!AddTransportAnswer(video_content->name, *(video_transport.get()),
+ answer)) {
+ return false;
+ }
+ video_answer->set_bandwidth(options.video_bandwidth);
+ } else {
+ // RFC 3264
+ // The answer MUST contain the same number of m-lines as the offer.
+ LOG(LS_INFO) << "Video is not supported in the answer.";
+ }
+ answer->AddContent(video_content->name, video_content->type, rejected,
+ video_answer.release());
+ return true;
+}
+
+bool MediaSessionDescriptionFactory::AddDataContentForAnswer(
+ const SessionDescription* offer,
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ StreamParamsVec* current_streams,
+ SessionDescription* answer) const {
+ const ContentInfo* data_content = GetFirstDataContent(offer);
+ scoped_ptr<TransportDescription> data_transport(
+ CreateTransportAnswer(data_content->name, offer,
+ options.transport_options,
+ current_description));
+ if (!data_transport) {
+ return false;
+ }
+ bool is_sctp = (options.data_channel_type == DCT_SCTP);
+ std::vector<DataCodec> data_codecs(data_codecs_);
+ FilterDataCodecs(&data_codecs, is_sctp);
+
+ scoped_ptr<DataContentDescription> data_answer(
+ new DataContentDescription());
+ // Do not require or create SDES cryptos if DTLS is used.
+ cricket::SecurePolicy sdes_policy =
+ data_transport->secure() ? cricket::SEC_DISABLED : secure();
+ bool bundle_enabled =
+ offer->HasGroup(GROUP_TYPE_BUNDLE) && options.bundle_enabled;
+ if (!CreateMediaContentAnswer(
+ static_cast<const DataContentDescription*>(
+ data_content->description),
+ options,
+ data_codecs_,
+ sdes_policy,
+ GetCryptos(GetFirstDataContentDescription(current_description)),
+ RtpHeaderExtensions(),
+ current_streams,
+ add_legacy_,
+ bundle_enabled,
+ data_answer.get())) {
+ return false; // Fails the session setup.
+ }
+
+ bool rejected = !options.has_data() || data_content->rejected ||
+ !IsMediaProtocolSupported(MEDIA_TYPE_DATA,
+ data_answer->protocol(),
+ data_transport->secure());
+ if (!rejected) {
+ data_answer->set_bandwidth(options.data_bandwidth);
+ if (!AddTransportAnswer(data_content->name, *(data_transport.get()),
+ answer)) {
+ return false;
+ }
+ } else {
+ // RFC 3264
+ // The answer MUST contain the same number of m-lines as the offer.
+ LOG(LS_INFO) << "Data is not supported in the answer.";
+ }
+ answer->AddContent(data_content->name, data_content->type, rejected,
+ data_answer.release());
+ return true;
+}
+
bool IsMediaContent(const ContentInfo* content) {
return (content &&
(content->type == NS_JINGLE_RTP ||
diff --git a/session/media/mediasession.h b/session/media/mediasession.h
index 5041de0..93894cd 100644
--- a/session/media/mediasession.h
+++ b/session/media/mediasession.h
@@ -30,11 +30,10 @@
#ifndef TALK_SESSION_MEDIA_MEDIASESSION_H_
#define TALK_SESSION_MEDIA_MEDIASESSION_H_
+#include <algorithm>
#include <string>
#include <vector>
-#include <algorithm>
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/constants.h"
#include "talk/media/base/cryptoparams.h"
@@ -44,6 +43,7 @@
#include "talk/p2p/base/sessiondescription.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/transportdescriptionfactory.h"
+#include "webrtc/base/scoped_ptr.h"
namespace cricket {
@@ -460,6 +460,54 @@
const TransportDescription& transport_desc,
SessionDescription* answer_desc) const;
+ // Helpers for adding media contents to the SessionDescription. Returns true
+ // it succeeds or the media content is not needed, or false if there is any
+ // error.
+
+ bool AddAudioContentForOffer(
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ const RtpHeaderExtensions& audio_rtp_extensions,
+ const AudioCodecs& audio_codecs,
+ StreamParamsVec* current_streams,
+ SessionDescription* desc) const;
+
+ bool AddVideoContentForOffer(
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ const RtpHeaderExtensions& video_rtp_extensions,
+ const VideoCodecs& video_codecs,
+ StreamParamsVec* current_streams,
+ SessionDescription* desc) const;
+
+ bool AddDataContentForOffer(
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ DataCodecs* data_codecs,
+ StreamParamsVec* current_streams,
+ SessionDescription* desc) const;
+
+ bool AddAudioContentForAnswer(
+ const SessionDescription* offer,
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ StreamParamsVec* current_streams,
+ SessionDescription* answer) const;
+
+ bool AddVideoContentForAnswer(
+ const SessionDescription* offer,
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ StreamParamsVec* current_streams,
+ SessionDescription* answer) const;
+
+ bool AddDataContentForAnswer(
+ const SessionDescription* offer,
+ const MediaSessionOptions& options,
+ const SessionDescription* current_description,
+ StreamParamsVec* current_streams,
+ SessionDescription* answer) const;
+
AudioCodecs audio_codecs_;
RtpHeaderExtensions audio_rtp_extensions_;
VideoCodecs video_codecs_;
diff --git a/session/media/mediasession_unittest.cc b/session/media/mediasession_unittest.cc
index cf492a6..2d2e2c8 100644
--- a/session/media/mediasession_unittest.cc
+++ b/session/media/mediasession_unittest.cc
@@ -28,9 +28,6 @@
#include <string>
#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/fakesslidentity.h"
-#include "talk/base/messagedigest.h"
#include "talk/media/base/codec.h"
#include "talk/media/base/testutils.h"
#include "talk/p2p/base/constants.h"
@@ -38,6 +35,10 @@
#include "talk/p2p/base/transportinfo.h"
#include "talk/session/media/mediasession.h"
#include "talk/session/media/srtpfilter.h"
+#include "webrtc/base/fakesslidentity.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/messagedigest.h"
+#include "webrtc/base/ssladapter.h"
#ifdef HAVE_SRTP
#define ASSERT_CRYPTO(cd, s, cs) \
@@ -97,13 +98,13 @@
static const AudioCodec kAudioCodecs2[] = {
AudioCodec(126, "speex", 16000, 22000, 1, 3),
- AudioCodec(127, "iLBC", 8000, 13300, 1, 2),
- AudioCodec(0, "PCMU", 8000, 64000, 1, 1),
+ AudioCodec(0, "PCMU", 8000, 64000, 1, 2),
+ AudioCodec(127, "iLBC", 8000, 13300, 1, 1),
};
static const AudioCodec kAudioCodecsAnswer[] = {
- AudioCodec(102, "iLBC", 8000, 13300, 1, 2),
- AudioCodec(0, "PCMU", 8000, 64000, 1, 1),
+ AudioCodec(102, "iLBC", 8000, 13300, 1, 5),
+ AudioCodec(0, "PCMU", 8000, 64000, 1, 4),
};
static const VideoCodec kVideoCodecs1[] = {
@@ -117,7 +118,7 @@
};
static const VideoCodec kVideoCodecsAnswer[] = {
- VideoCodec(97, "H264", 320, 200, 30, 2)
+ VideoCodec(97, "H264", 320, 200, 30, 1)
};
static const DataCodec kDataCodecs1[] = {
@@ -182,6 +183,13 @@
static const char kDataTrack2[] = "data_2";
static const char kDataTrack3[] = "data_3";
+static bool IsMediaContentOfType(const ContentInfo* content,
+ MediaType media_type) {
+ const MediaContentDescription* mdesc =
+ static_cast<const MediaContentDescription*>(content->description);
+ return mdesc && mdesc->type() == media_type;
+}
+
class MediaSessionDescriptionFactoryTest : public testing::Test {
public:
MediaSessionDescriptionFactoryTest()
@@ -196,6 +204,14 @@
tdf2_.set_identity(&id2_);
}
+ static void SetUpTestCase() {
+ rtc::InitializeSSL();
+ }
+
+ static void TearDownTestCase() {
+ rtc::CleanupSSL();
+ }
+
// Create a video StreamParamsVec object with:
// - one video stream with 3 simulcast streams and FEC,
StreamParamsVec CreateComplexVideoStreamParamsVec() {
@@ -243,8 +259,8 @@
const std::string current_video_pwd = "current_video_pwd";
const std::string current_data_ufrag = "current_data_ufrag";
const std::string current_data_pwd = "current_data_pwd";
- talk_base::scoped_ptr<SessionDescription> current_desc;
- talk_base::scoped_ptr<SessionDescription> desc;
+ rtc::scoped_ptr<SessionDescription> current_desc;
+ rtc::scoped_ptr<SessionDescription> desc;
if (has_current_desc) {
current_desc.reset(new SessionDescription());
EXPECT_TRUE(current_desc->AddTransportInfo(
@@ -266,7 +282,7 @@
if (offer) {
desc.reset(f1_.CreateOffer(options, current_desc.get()));
} else {
- talk_base::scoped_ptr<SessionDescription> offer;
+ rtc::scoped_ptr<SessionDescription> offer;
offer.reset(f1_.CreateOffer(options, NULL));
desc.reset(f1_.CreateAnswer(offer.get(), options, current_desc.get()));
}
@@ -339,8 +355,8 @@
options.has_audio = true;
options.has_video = true;
options.data_channel_type = cricket::DCT_RTP;
- talk_base::scoped_ptr<SessionDescription> ref_desc;
- talk_base::scoped_ptr<SessionDescription> desc;
+ rtc::scoped_ptr<SessionDescription> ref_desc;
+ rtc::scoped_ptr<SessionDescription> desc;
if (offer) {
options.bundle_enabled = false;
ref_desc.reset(f1_.CreateOffer(options, NULL));
@@ -390,7 +406,7 @@
cricket::MediaContentDirection expected_direction_in_answer) {
MediaSessionOptions opts;
opts.has_video = true;
- talk_base::scoped_ptr<SessionDescription> offer(
+ rtc::scoped_ptr<SessionDescription> offer(
f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
ContentInfo* ac_offer= offer->GetContentByName("audio");
@@ -404,7 +420,7 @@
static_cast<VideoContentDescription*>(vc_offer->description);
vcd_offer->set_direction(direction_in_offer);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const AudioContentDescription* acd_answer =
GetFirstAudioContentDescription(answer.get());
@@ -432,14 +448,14 @@
MediaSessionDescriptionFactory f2_;
TransportDescriptionFactory tdf1_;
TransportDescriptionFactory tdf2_;
- talk_base::FakeSSLIdentity id1_;
- talk_base::FakeSSLIdentity id2_;
+ rtc::FakeSSLIdentity id1_;
+ rtc::FakeSSLIdentity id2_;
};
// Create a typical audio offer, and ensure it matches what we expect.
TEST_F(MediaSessionDescriptionFactoryTest, TestCreateAudioOffer) {
f1_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(
+ rtc::scoped_ptr<SessionDescription> offer(
f1_.CreateOffer(MediaSessionOptions(), NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* ac = offer->GetContentByName("audio");
@@ -463,7 +479,7 @@
MediaSessionOptions opts;
opts.has_video = true;
f1_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* ac = offer->GetContentByName("audio");
@@ -507,7 +523,7 @@
opts.has_video = true;
opts.data_channel_type = cricket::DCT_RTP;
opts.bundle_enabled = true;
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f2_.CreateOffer(opts, NULL));
const VideoContentDescription* vcd =
GetFirstVideoContentDescription(offer.get());
@@ -537,8 +553,8 @@
opts.has_video = false;
opts.data_channel_type = cricket::DCT_NONE;
opts.bundle_enabled = true;
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
MediaSessionOptions updated_opts;
@@ -546,7 +562,7 @@
updated_opts.has_video = true;
updated_opts.data_channel_type = cricket::DCT_RTP;
updated_opts.bundle_enabled = true;
- talk_base::scoped_ptr<SessionDescription> updated_offer(f1_.CreateOffer(
+ rtc::scoped_ptr<SessionDescription> updated_offer(f1_.CreateOffer(
updated_opts, answer.get()));
const AudioContentDescription* acd =
@@ -571,7 +587,7 @@
MediaSessionOptions opts;
opts.data_channel_type = cricket::DCT_RTP;
f1_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* ac = offer->GetContentByName("audio");
@@ -608,7 +624,7 @@
opts.bundle_enabled = true;
opts.data_channel_type = cricket::DCT_SCTP;
f1_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
EXPECT_TRUE(offer.get() != NULL);
EXPECT_TRUE(offer->GetContentByName("data") != NULL);
}
@@ -619,7 +635,7 @@
MediaSessionOptions opts;
opts.has_video = true;
f1_.set_add_legacy_streams(false);
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* ac = offer->GetContentByName("audio");
@@ -635,14 +651,54 @@
EXPECT_FALSE(acd->has_ssrcs()); // No StreamParams.
}
+// Verifies that the order of the media contents in the current
+// SessionDescription is preserved in the new SessionDescription.
+TEST_F(MediaSessionDescriptionFactoryTest, TestCreateOfferContentOrder) {
+ MediaSessionOptions opts;
+ opts.has_audio = false;
+ opts.has_video = false;
+ opts.data_channel_type = cricket::DCT_SCTP;
+
+ rtc::scoped_ptr<SessionDescription> offer1(f1_.CreateOffer(opts, NULL));
+ ASSERT_TRUE(offer1.get() != NULL);
+ EXPECT_EQ(1u, offer1->contents().size());
+ EXPECT_TRUE(IsMediaContentOfType(&offer1->contents()[0], MEDIA_TYPE_DATA));
+
+ opts.has_video = true;
+ rtc::scoped_ptr<SessionDescription> offer2(
+ f1_.CreateOffer(opts, offer1.get()));
+ ASSERT_TRUE(offer2.get() != NULL);
+ EXPECT_EQ(2u, offer2->contents().size());
+ EXPECT_TRUE(IsMediaContentOfType(&offer2->contents()[0], MEDIA_TYPE_DATA));
+ EXPECT_TRUE(IsMediaContentOfType(&offer2->contents()[1], MEDIA_TYPE_VIDEO));
+
+ opts.has_audio = true;
+ rtc::scoped_ptr<SessionDescription> offer3(
+ f1_.CreateOffer(opts, offer2.get()));
+ ASSERT_TRUE(offer3.get() != NULL);
+ EXPECT_EQ(3u, offer3->contents().size());
+ EXPECT_TRUE(IsMediaContentOfType(&offer3->contents()[0], MEDIA_TYPE_DATA));
+ EXPECT_TRUE(IsMediaContentOfType(&offer3->contents()[1], MEDIA_TYPE_VIDEO));
+ EXPECT_TRUE(IsMediaContentOfType(&offer3->contents()[2], MEDIA_TYPE_AUDIO));
+
+ // Verifies the default order is audio-video-data, so that the previous checks
+ // didn't pass by accident.
+ rtc::scoped_ptr<SessionDescription> offer4(f1_.CreateOffer(opts, NULL));
+ ASSERT_TRUE(offer4.get() != NULL);
+ EXPECT_EQ(3u, offer4->contents().size());
+ EXPECT_TRUE(IsMediaContentOfType(&offer4->contents()[0], MEDIA_TYPE_AUDIO));
+ EXPECT_TRUE(IsMediaContentOfType(&offer4->contents()[1], MEDIA_TYPE_VIDEO));
+ EXPECT_TRUE(IsMediaContentOfType(&offer4->contents()[2], MEDIA_TYPE_DATA));
+}
+
// Create a typical audio answer, and ensure it matches what we expect.
TEST_F(MediaSessionDescriptionFactoryTest, TestCreateAudioAnswer) {
f1_.set_secure(SEC_ENABLED);
f2_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(
+ rtc::scoped_ptr<SessionDescription> offer(
f1_.CreateOffer(MediaSessionOptions(), NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), MediaSessionOptions(), NULL));
const ContentInfo* ac = answer->GetContentByName("audio");
const ContentInfo* vc = answer->GetContentByName("video");
@@ -666,9 +722,9 @@
opts.has_video = true;
f1_.set_secure(SEC_ENABLED);
f2_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const ContentInfo* ac = answer->GetContentByName("audio");
const ContentInfo* vc = answer->GetContentByName("video");
@@ -699,9 +755,9 @@
opts.data_channel_type = cricket::DCT_RTP;
f1_.set_secure(SEC_ENABLED);
f2_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const ContentInfo* ac = answer->GetContentByName("audio");
const ContentInfo* vc = answer->GetContentByName("data");
@@ -727,6 +783,38 @@
EXPECT_EQ(std::string(cricket::kMediaProtocolSavpf), vcd->protocol());
}
+// Verifies that the order of the media contents in the offer is preserved in
+// the answer.
+TEST_F(MediaSessionDescriptionFactoryTest, TestCreateAnswerContentOrder) {
+ MediaSessionOptions opts;
+
+ // Creates a data only offer.
+ opts.has_audio = false;
+ opts.data_channel_type = cricket::DCT_SCTP;
+ rtc::scoped_ptr<SessionDescription> offer1(f1_.CreateOffer(opts, NULL));
+ ASSERT_TRUE(offer1.get() != NULL);
+
+ // Appends audio to the offer.
+ opts.has_audio = true;
+ rtc::scoped_ptr<SessionDescription> offer2(
+ f1_.CreateOffer(opts, offer1.get()));
+ ASSERT_TRUE(offer2.get() != NULL);
+
+ // Appends video to the offer.
+ opts.has_video = true;
+ rtc::scoped_ptr<SessionDescription> offer3(
+ f1_.CreateOffer(opts, offer2.get()));
+ ASSERT_TRUE(offer3.get() != NULL);
+
+ rtc::scoped_ptr<SessionDescription> answer(
+ f2_.CreateAnswer(offer3.get(), opts, NULL));
+ ASSERT_TRUE(answer.get() != NULL);
+ EXPECT_EQ(3u, answer->contents().size());
+ EXPECT_TRUE(IsMediaContentOfType(&answer->contents()[0], MEDIA_TYPE_DATA));
+ EXPECT_TRUE(IsMediaContentOfType(&answer->contents()[1], MEDIA_TYPE_AUDIO));
+ EXPECT_TRUE(IsMediaContentOfType(&answer->contents()[2], MEDIA_TYPE_VIDEO));
+}
+
// This test that the media direction is set to send/receive in an answer if
// the offer is send receive.
TEST_F(MediaSessionDescriptionFactoryTest, CreateAnswerToSendReceiveOffer) {
@@ -759,7 +847,7 @@
opts.has_audio = false;
f1_.set_secure(SEC_ENABLED);
f2_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ContentInfo* dc_offer= offer->GetContentByName("data");
ASSERT_TRUE(dc_offer != NULL);
DataContentDescription* dcd_offer =
@@ -768,7 +856,7 @@
std::string protocol = "a weird unknown protocol";
dcd_offer->set_protocol(protocol);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const ContentInfo* dc_answer = answer->GetContentByName("data");
@@ -788,13 +876,13 @@
tdf1_.set_secure(SEC_DISABLED);
tdf2_.set_secure(SEC_DISABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
const AudioContentDescription* offer_acd =
GetFirstAudioContentDescription(offer.get());
ASSERT_TRUE(offer_acd != NULL);
EXPECT_EQ(std::string(cricket::kMediaProtocolAvpf), offer_acd->protocol());
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const ContentInfo* ac_answer = answer->GetContentByName("audio");
@@ -818,9 +906,9 @@
f2_.set_audio_rtp_header_extensions(MAKE_VECTOR(kAudioRtpExtension2));
f2_.set_video_rtp_header_extensions(MAKE_VECTOR(kVideoRtpExtension2));
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
EXPECT_EQ(MAKE_VECTOR(kAudioRtpExtension1),
@@ -845,9 +933,9 @@
opts.data_channel_type = cricket::DCT_RTP;
f1_.set_add_legacy_streams(false);
f2_.set_add_legacy_streams(false);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const ContentInfo* ac = answer->GetContentByName("audio");
const ContentInfo* vc = answer->GetContentByName("video");
@@ -871,7 +959,7 @@
opts.has_video = true;
opts.data_channel_type = cricket::DCT_RTP;
f1_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* ac = offer->GetContentByName("audio");
@@ -912,8 +1000,8 @@
answer_opts.data_channel_type = cricket::DCT_RTP;
offer_opts.data_channel_type = cricket::DCT_RTP;
- talk_base::scoped_ptr<SessionDescription> offer;
- talk_base::scoped_ptr<SessionDescription> answer;
+ rtc::scoped_ptr<SessionDescription> offer;
+ rtc::scoped_ptr<SessionDescription> answer;
offer_opts.rtcp_mux_enabled = true;
answer_opts.rtcp_mux_enabled = true;
@@ -992,10 +1080,10 @@
TEST_F(MediaSessionDescriptionFactoryTest, TestCreateAudioAnswerToVideo) {
MediaSessionOptions opts;
opts.has_video = true;
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), MediaSessionOptions(), NULL));
const ContentInfo* ac = answer->GetContentByName("audio");
const ContentInfo* vc = answer->GetContentByName("video");
@@ -1009,10 +1097,10 @@
TEST_F(MediaSessionDescriptionFactoryTest, TestCreateNoDataAnswerToDataOffer) {
MediaSessionOptions opts;
opts.data_channel_type = cricket::DCT_RTP;
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), MediaSessionOptions(), NULL));
const ContentInfo* ac = answer->GetContentByName("audio");
const ContentInfo* dc = answer->GetContentByName("data");
@@ -1028,7 +1116,7 @@
MediaSessionOptions opts;
opts.has_video = true;
opts.data_channel_type = cricket::DCT_RTP;
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
ContentInfo* ac = offer->GetContentByName("audio");
@@ -1040,7 +1128,7 @@
ac->rejected = true;
vc->rejected = true;
dc->rejected = true;
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
ac = answer->GetContentByName("audio");
vc = answer->GetContentByName("video");
@@ -1069,7 +1157,7 @@
opts.AddStream(MEDIA_TYPE_DATA, kDataTrack2, kMediaStream1);
f1_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* ac = offer->GetContentByName("audio");
@@ -1139,7 +1227,7 @@
opts.AddStream(MEDIA_TYPE_AUDIO, kAudioTrack3, kMediaStream1);
opts.RemoveStream(MEDIA_TYPE_DATA, kDataTrack2);
opts.AddStream(MEDIA_TYPE_DATA, kDataTrack3, kMediaStream1);
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
updated_offer(f1_.CreateOffer(opts, offer.get()));
ASSERT_TRUE(updated_offer.get() != NULL);
@@ -1197,7 +1285,7 @@
MediaSessionOptions opts;
const int num_sim_layers = 3;
opts.AddVideoStream(kVideoTrack1, kMediaStream1, num_sim_layers);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* vc = offer->GetContentByName("video");
@@ -1226,7 +1314,7 @@
offer_opts.data_channel_type = cricket::DCT_RTP;
f1_.set_secure(SEC_ENABLED);
f2_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(offer_opts,
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(offer_opts,
NULL));
MediaSessionOptions opts;
@@ -1237,7 +1325,7 @@
opts.AddStream(MEDIA_TYPE_DATA, kDataTrack1, kMediaStream1);
opts.AddStream(MEDIA_TYPE_DATA, kDataTrack2, kMediaStream1);
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
answer(f2_.CreateAnswer(offer.get(), opts, NULL));
ASSERT_TRUE(answer.get() != NULL);
@@ -1305,7 +1393,7 @@
opts.AddStream(MEDIA_TYPE_VIDEO, kVideoTrack2, kMediaStream2);
opts.RemoveStream(MEDIA_TYPE_AUDIO, kAudioTrack2);
opts.RemoveStream(MEDIA_TYPE_DATA, kDataTrack2);
- talk_base::scoped_ptr<SessionDescription>
+ rtc::scoped_ptr<SessionDescription>
updated_answer(f2_.CreateAnswer(offer.get(), opts, answer.get()));
ASSERT_TRUE(updated_answer.get() != NULL);
@@ -1361,8 +1449,8 @@
opts.has_audio = true;
opts.has_video = true;
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const AudioContentDescription* acd =
@@ -1373,16 +1461,18 @@
GetFirstVideoContentDescription(answer.get());
EXPECT_EQ(MAKE_VECTOR(kVideoCodecsAnswer), vcd->codecs());
- talk_base::scoped_ptr<SessionDescription> updated_offer(
+ rtc::scoped_ptr<SessionDescription> updated_offer(
f2_.CreateOffer(opts, answer.get()));
// The expected audio codecs are the common audio codecs from the first
// offer/answer exchange plus the audio codecs only |f2_| offer, sorted in
// preference order.
+ // TODO(wu): |updated_offer| should not include the codec
+ // (i.e. |kAudioCodecs2[0]|) the other side doesn't support.
const AudioCodec kUpdatedAudioCodecOffer[] = {
- kAudioCodecs2[0],
kAudioCodecsAnswer[0],
kAudioCodecsAnswer[1],
+ kAudioCodecs2[0],
};
// The expected video codecs are the common video codecs from the first
@@ -1417,7 +1507,7 @@
// This creates rtx for H264 with the payload type |f1_| uses.
rtx_f1.params[cricket::kCodecParamAssociatedPayloadType] =
- talk_base::ToString<int>(kVideoCodecs1[1].id);
+ rtc::ToString<int>(kVideoCodecs1[1].id);
f1_codecs.push_back(rtx_f1);
f1_.set_video_codecs(f1_codecs);
@@ -1428,13 +1518,13 @@
// This creates rtx for H264 with the payload type |f2_| uses.
rtx_f2.params[cricket::kCodecParamAssociatedPayloadType] =
- talk_base::ToString<int>(kVideoCodecs2[0].id);
+ rtc::ToString<int>(kVideoCodecs2[0].id);
f2_codecs.push_back(rtx_f2);
f2_.set_video_codecs(f2_codecs);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const VideoContentDescription* vcd =
@@ -1450,10 +1540,10 @@
// are different from |f1_|.
expected_codecs[0].preference = f1_codecs[1].preference;
- talk_base::scoped_ptr<SessionDescription> updated_offer(
+ rtc::scoped_ptr<SessionDescription> updated_offer(
f2_.CreateOffer(opts, answer.get()));
ASSERT_TRUE(updated_offer);
- talk_base::scoped_ptr<SessionDescription> updated_answer(
+ rtc::scoped_ptr<SessionDescription> updated_answer(
f1_.CreateAnswer(updated_offer.get(), opts, answer.get()));
const VideoContentDescription* updated_vcd =
@@ -1475,7 +1565,7 @@
// This creates rtx for H264 with the payload type |f1_| uses.
rtx_f1.params[cricket::kCodecParamAssociatedPayloadType] =
- talk_base::ToString<int>(kVideoCodecs1[1].id);
+ rtc::ToString<int>(kVideoCodecs1[1].id);
f1_codecs.push_back(rtx_f1);
f1_.set_video_codecs(f1_codecs);
@@ -1483,8 +1573,8 @@
opts.has_audio = true;
opts.has_video = false;
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const AudioContentDescription* acd =
@@ -1504,14 +1594,14 @@
rtx_f2.id = 127;
rtx_f2.name = cricket::kRtxCodecName;
rtx_f2.params[cricket::kCodecParamAssociatedPayloadType] =
- talk_base::ToString<int>(used_pl_type);
+ rtc::ToString<int>(used_pl_type);
f2_codecs.push_back(rtx_f2);
f2_.set_video_codecs(f2_codecs);
- talk_base::scoped_ptr<SessionDescription> updated_offer(
+ rtc::scoped_ptr<SessionDescription> updated_offer(
f2_.CreateOffer(opts, answer.get()));
ASSERT_TRUE(updated_offer);
- talk_base::scoped_ptr<SessionDescription> updated_answer(
+ rtc::scoped_ptr<SessionDescription> updated_answer(
f1_.CreateAnswer(updated_offer.get(), opts, answer.get()));
const AudioContentDescription* updated_acd =
@@ -1526,7 +1616,7 @@
int new_h264_pl_type = updated_vcd->codecs()[0].id;
EXPECT_NE(used_pl_type, new_h264_pl_type);
VideoCodec rtx = updated_vcd->codecs()[1];
- int pt_referenced_by_rtx = talk_base::FromString<int>(
+ int pt_referenced_by_rtx = rtc::FromString<int>(
rtx.params[cricket::kCodecParamAssociatedPayloadType]);
EXPECT_EQ(new_h264_pl_type, pt_referenced_by_rtx);
}
@@ -1551,11 +1641,11 @@
// This creates rtx for H264 with the payload type |f2_| uses.
rtx_f2.SetParam(cricket::kCodecParamAssociatedPayloadType,
- talk_base::ToString<int>(kVideoCodecs2[0].id));
+ rtc::ToString<int>(kVideoCodecs2[0].id));
f2_codecs.push_back(rtx_f2);
f2_.set_video_codecs(f2_codecs);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
ASSERT_TRUE(offer.get() != NULL);
// kCodecParamAssociatedPayloadType will always be added to the offer when RTX
// is selected. Manually remove kCodecParamAssociatedPayloadType so that it
@@ -1574,7 +1664,7 @@
}
desc->set_codecs(codecs);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
const VideoContentDescription* vcd =
@@ -1600,8 +1690,8 @@
f2_.set_audio_rtp_header_extensions(MAKE_VECTOR(kAudioRtpExtension2));
f2_.set_video_rtp_header_extensions(MAKE_VECTOR(kVideoRtpExtension2));
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(opts, NULL));
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), opts, NULL));
EXPECT_EQ(MAKE_VECTOR(kAudioRtpExtensionAnswer),
@@ -1611,7 +1701,7 @@
GetFirstVideoContentDescription(
answer.get())->rtp_header_extensions());
- talk_base::scoped_ptr<SessionDescription> updated_offer(
+ rtc::scoped_ptr<SessionDescription> updated_offer(
f2_.CreateOffer(opts, answer.get()));
// The expected RTP header extensions in the new offer are the resulting
@@ -1657,7 +1747,7 @@
vcd->AddLegacyStream(2);
source.AddContent(cricket::CN_VIDEO, cricket::NS_JINGLE_RTP, vcd);
- talk_base::scoped_ptr<SessionDescription> copy(source.Copy());
+ rtc::scoped_ptr<SessionDescription> copy(source.Copy());
ASSERT_TRUE(copy.get() != NULL);
EXPECT_TRUE(copy->HasGroup(cricket::CN_AUDIO));
const ContentInfo* ac = copy->GetContentByName("audio");
@@ -1797,7 +1887,7 @@
tdf1_.set_secure(SEC_DISABLED);
tdf2_.set_secure(SEC_DISABLED);
- talk_base::scoped_ptr<SessionDescription> offer(
+ rtc::scoped_ptr<SessionDescription> offer(
f1_.CreateOffer(MediaSessionOptions(), NULL));
ASSERT_TRUE(offer.get() != NULL);
ContentInfo* offer_content = offer->GetContentByName("audio");
@@ -1806,7 +1896,7 @@
static_cast<AudioContentDescription*>(offer_content->description);
offer_audio_desc->set_protocol(cricket::kMediaProtocolDtlsSavpf);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), MediaSessionOptions(), NULL));
ASSERT_TRUE(answer != NULL);
ContentInfo* answer_content = answer->GetContentByName("audio");
@@ -1823,7 +1913,7 @@
tdf1_.set_secure(SEC_ENABLED);
tdf2_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(
+ rtc::scoped_ptr<SessionDescription> offer(
f1_.CreateOffer(MediaSessionOptions(), NULL));
ASSERT_TRUE(offer.get() != NULL);
ContentInfo* offer_content = offer->GetContentByName("audio");
@@ -1832,7 +1922,7 @@
static_cast<AudioContentDescription*>(offer_content->description);
offer_audio_desc->set_protocol(cricket::kMediaProtocolDtlsSavpf);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), MediaSessionOptions(), NULL));
ASSERT_TRUE(answer != NULL);
@@ -1856,7 +1946,7 @@
MediaSessionOptions options;
options.has_audio = true;
options.has_video = true;
- talk_base::scoped_ptr<SessionDescription> offer, answer;
+ rtc::scoped_ptr<SessionDescription> offer, answer;
const cricket::MediaContentDescription* audio_media_desc;
const cricket::MediaContentDescription* video_media_desc;
const cricket::TransportDescription* audio_trans_desc;
@@ -1957,10 +2047,10 @@
f2_.set_secure(SEC_REQUIRED);
tdf1_.set_secure(SEC_ENABLED);
- talk_base::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(options,
+ rtc::scoped_ptr<SessionDescription> offer(f1_.CreateOffer(options,
NULL));
ASSERT_TRUE(offer.get() != NULL);
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f2_.CreateAnswer(offer.get(), options, NULL));
EXPECT_TRUE(answer.get() == NULL);
}
@@ -1977,7 +2067,7 @@
options.has_video = true;
options.data_channel_type = cricket::DCT_RTP;
- talk_base::scoped_ptr<SessionDescription> offer, answer;
+ rtc::scoped_ptr<SessionDescription> offer, answer;
// Generate an offer with DTLS but without SDES.
offer.reset(f1_.CreateOffer(options, NULL));
@@ -2024,7 +2114,7 @@
MediaSessionOptions options;
options.has_audio = true;
options.has_video = true;
- talk_base::scoped_ptr<SessionDescription> offer(
+ rtc::scoped_ptr<SessionDescription> offer(
f1_.CreateOffer(options, NULL));
ASSERT_TRUE(offer.get() != NULL);
const ContentInfo* audio_content = offer->GetContentByName("audio");
@@ -2035,7 +2125,7 @@
ASSERT_TRUE(offer.get() != NULL);
audio_content = offer->GetContentByName("audio");
EXPECT_TRUE(VerifyNoCNCodecs(audio_content));
- talk_base::scoped_ptr<SessionDescription> answer(
+ rtc::scoped_ptr<SessionDescription> answer(
f1_.CreateAnswer(offer.get(), options, NULL));
ASSERT_TRUE(answer.get() != NULL);
audio_content = answer->GetContentByName("audio");
diff --git a/session/media/mediasessionclient.cc b/session/media/mediasessionclient.cc
index a5a652c..826909a 100644
--- a/session/media/mediasessionclient.cc
+++ b/session/media/mediasessionclient.cc
@@ -29,20 +29,20 @@
#include "talk/session/media/mediasessionclient.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/stringutils.h"
-#include "talk/media/base/cryptoparams.h"
#include "talk/media/base/capturemanager.h"
+#include "talk/media/base/cryptoparams.h"
#include "talk/media/sctp/sctpdataengine.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/parsing.h"
#include "talk/session/media/mediamessages.h"
#include "talk/session/media/srtpfilter.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlconstants.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlconstants.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
@@ -283,7 +283,7 @@
ParseError* error) {
if (!ssrc_str.empty()) {
uint32 ssrc;
- if (!talk_base::FromString(ssrc_str, &ssrc)) {
+ if (!rtc::FromString(ssrc_str, &ssrc)) {
return BadParse("Missing or invalid ssrc.", error);
}
@@ -361,7 +361,7 @@
MediaContentDescription* media) {
const buzz::XmlElement* bw_elem = GetXmlChild(parent_elem, LN_BANDWIDTH);
int bandwidth_kbps = -1;
- if (bw_elem && talk_base::FromString(bw_elem->BodyText(), &bandwidth_kbps)) {
+ if (bw_elem && rtc::FromString(bw_elem->BodyText(), &bandwidth_kbps)) {
if (bandwidth_kbps >= 0) {
media->set_bandwidth(bandwidth_kbps * 1000);
}
@@ -373,6 +373,7 @@
ParseError* error) {
AudioContentDescription* audio = new AudioContentDescription();
+ int preference = kMaxPayloadId;
if (content_elem->FirstElement()) {
for (const buzz::XmlElement* codec_elem =
content_elem->FirstNamed(QN_GINGLE_AUDIO_PAYLOADTYPE);
@@ -380,6 +381,7 @@
codec_elem = codec_elem->NextNamed(QN_GINGLE_AUDIO_PAYLOADTYPE)) {
AudioCodec codec;
if (ParseGingleAudioCodec(codec_elem, &codec)) {
+ codec.preference = preference--;
audio->AddCodec(codec);
}
}
@@ -406,12 +408,14 @@
ParseError* error) {
VideoContentDescription* video = new VideoContentDescription();
+ int preference = kMaxPayloadId;
for (const buzz::XmlElement* codec_elem =
content_elem->FirstNamed(QN_GINGLE_VIDEO_PAYLOADTYPE);
codec_elem != NULL;
codec_elem = codec_elem->NextNamed(QN_GINGLE_VIDEO_PAYLOADTYPE)) {
VideoCodec codec;
if (ParseGingleVideoCodec(codec_elem, &codec)) {
+ codec.preference = preference--;
video->AddCodec(codec);
}
}
@@ -565,12 +569,13 @@
bool ParseJingleAudioContent(const buzz::XmlElement* content_elem,
ContentDescription** content,
ParseError* error) {
- talk_base::scoped_ptr<AudioContentDescription> audio(
+ rtc::scoped_ptr<AudioContentDescription> audio(
new AudioContentDescription());
FeedbackParams content_feedback_params;
ParseFeedbackParams(content_elem, &content_feedback_params);
+ int preference = kMaxPayloadId;
for (const buzz::XmlElement* payload_elem =
content_elem->FirstNamed(QN_JINGLE_RTP_PAYLOADTYPE);
payload_elem != NULL;
@@ -578,6 +583,7 @@
AudioCodec codec;
if (ParseJingleAudioCodec(payload_elem, &codec)) {
AddFeedbackParams(content_feedback_params, &codec.feedback_params);
+ codec.preference = preference--;
audio->AddCodec(codec);
}
}
@@ -605,12 +611,13 @@
bool ParseJingleVideoContent(const buzz::XmlElement* content_elem,
ContentDescription** content,
ParseError* error) {
- talk_base::scoped_ptr<VideoContentDescription> video(
+ rtc::scoped_ptr<VideoContentDescription> video(
new VideoContentDescription());
FeedbackParams content_feedback_params;
ParseFeedbackParams(content_elem, &content_feedback_params);
+ int preference = kMaxPayloadId;
for (const buzz::XmlElement* payload_elem =
content_elem->FirstNamed(QN_JINGLE_RTP_PAYLOADTYPE);
payload_elem != NULL;
@@ -618,6 +625,7 @@
VideoCodec codec;
if (ParseJingleVideoCodec(payload_elem, &codec)) {
AddFeedbackParams(content_feedback_params, &codec.feedback_params);
+ codec.preference = preference--;
video->AddCodec(codec);
}
}
@@ -646,7 +654,7 @@
bool ParseJingleSctpDataContent(const buzz::XmlElement* content_elem,
ContentDescription** content,
ParseError* error) {
- talk_base::scoped_ptr<DataContentDescription> data(
+ rtc::scoped_ptr<DataContentDescription> data(
new DataContentDescription());
data->set_protocol(kMediaProtocolSctp);
@@ -658,7 +666,7 @@
stream.groupid = stream_elem->Attr(QN_NICK);
stream.id = stream_elem->Attr(QN_NAME);
uint32 sid;
- if (!talk_base::FromString(stream_elem->Attr(QN_SID), &sid)) {
+ if (!rtc::FromString(stream_elem->Attr(QN_SID), &sid)) {
return BadParse("Missing or invalid sid.", error);
}
if (sid > kMaxSctpSid) {
@@ -681,6 +689,7 @@
FeedbackParams content_feedback_params;
ParseFeedbackParams(content_elem, &content_feedback_params);
+ int preference = kMaxPayloadId;
for (const buzz::XmlElement* payload_elem =
content_elem->FirstNamed(QN_JINGLE_RTP_PAYLOADTYPE);
payload_elem != NULL;
@@ -688,6 +697,7 @@
DataCodec codec;
if (ParseJingleDataCodec(payload_elem, &codec)) {
AddFeedbackParams(content_feedback_params, &codec.feedback_params);
+ codec.preference = preference--;
data->AddCodec(codec);
}
}
@@ -1142,7 +1152,7 @@
}
} else {
return BadWrite("Unknown content type: " +
- talk_base::ToString<int>(media->type()), error);
+ rtc::ToString<int>(media->type()), error);
}
return true;
diff --git a/session/media/mediasessionclient.h b/session/media/mediasessionclient.h
index d0034ca..61d1f1d 100644
--- a/session/media/mediasessionclient.h
+++ b/session/media/mediasessionclient.h
@@ -28,14 +28,10 @@
#ifndef TALK_SESSION_MEDIA_MEDIASESSIONCLIENT_H_
#define TALK_SESSION_MEDIA_MEDIASESSIONCLIENT_H_
+#include <algorithm>
+#include <map>
#include <string>
#include <vector>
-#include <map>
-#include <algorithm>
-#include "talk/base/messagequeue.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/sigslotrepeater.h"
-#include "talk/base/thread.h"
#include "talk/media/base/cryptoparams.h"
#include "talk/p2p/base/session.h"
#include "talk/p2p/base/sessionclient.h"
@@ -44,6 +40,10 @@
#include "talk/session/media/call.h"
#include "talk/session/media/channelmanager.h"
#include "talk/session/media/mediasession.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/sigslotrepeater.h"
+#include "webrtc/base/thread.h"
namespace cricket {
diff --git a/session/media/mediasessionclient_unittest.cc b/session/media/mediasessionclient_unittest.cc
index 7cb1ec9..2998228 100644
--- a/session/media/mediasessionclient_unittest.cc
+++ b/session/media/mediasessionclient_unittest.cc
@@ -28,18 +28,19 @@
#include <string>
#include <vector>
-#include "talk/base/gunit.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/fakemediaengine.h"
+#include "talk/media/base/testutils.h"
#include "talk/media/devices/fakedevicemanager.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/client/basicportallocator.h"
#include "talk/session/media/mediasessionclient.h"
-#include "talk/xmllite/xmlbuilder.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/xmllite/xmlprinter.h"
+#include "webrtc/libjingle/xmllite/xmlbuilder.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlprinter.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
using cricket::AudioCodec;
using cricket::AudioContentDescription;
@@ -74,6 +75,29 @@
cricket::AudioCodec(106, "telephone-event", 8000, 0, 1, 1)
};
+// The codecs that our FakeMediaEngine will support with a different order of
+// supported codecs.
+static const cricket::AudioCodec kAudioCodecsDifferentPreference[] = {
+ cricket::AudioCodec(104, "ISAC", 32000, -1, 1, 17),
+ cricket::AudioCodec(97, "IPCMWB", 16000, 80000, 1, 14),
+ cricket::AudioCodec(9, "G722", 16000, 64000, 1, 13),
+ cricket::AudioCodec(119, "ISACLC", 16000, 40000, 1, 16),
+ cricket::AudioCodec(103, "ISAC", 16000, -1, 1, 18),
+ cricket::AudioCodec(99, "speex", 16000, 22000, 1, 15),
+ cricket::AudioCodec(100, "EG711U", 8000, 64000, 1, 9),
+ cricket::AudioCodec(101, "EG711A", 8000, 64000, 1, 8),
+ cricket::AudioCodec(0, "PCMU", 8000, 64000, 1, 7),
+ cricket::AudioCodec(8, "PCMA", 8000, 64000, 1, 6),
+ cricket::AudioCodec(102, "iLBC", 8000, 13300, 1, 12),
+ cricket::AudioCodec(3, "GSM", 8000, 13000, 1, 10),
+ cricket::AudioCodec(98, "speex", 8000, 11000, 1, 11),
+ cricket::AudioCodec(126, "CN", 32000, 0, 1, 5),
+ cricket::AudioCodec(105, "CN", 16000, 0, 1, 4),
+ cricket::AudioCodec(13, "CN", 8000, 0, 1, 3),
+ cricket::AudioCodec(117, "red", 8000, 0, 1, 2),
+ cricket::AudioCodec(106, "telephone-event", 8000, 0, 1, 1)
+};
+
static const cricket::VideoCodec kVideoCodecs[] = {
cricket::VideoCodec(96, "H264-SVC", 320, 200, 30, 1)
};
@@ -270,123 +294,6 @@
" </jingle> " \
"</iq> ");
-// Initiate string with a different order of supported codecs.
-// Should accept the supported ones, but with our desired order.
-const std::string kGingleInitiateDifferentPreference(
- "<iq xmlns='jabber:client' from='me@domain.com/resource' " \
- " to='user@domain.com/resource' type='set' id='123'> " \
- " <session xmlns='http://www.google.com/session' type='initiate'" \
- " id='abcdef' initiator='me@domain.com/resource'> " \
- " <description xmlns='http://www.google.com/session/phone'> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='104' name='ISAC' clockrate='32000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='97' name='IPCMWB' clockrate='16000' bitrate='80000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='9' name='G722' clockrate='16000' bitrate='64000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='119' name='ISACLC' clockrate='16000' bitrate='40000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='103' name='ISAC' clockrate='16000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='99' name='speex' clockrate='16000' bitrate='22000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='100' name='EG711U' clockrate='8000' bitrate='64000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='101' name='EG711A' clockrate='8000' bitrate='64000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='0' name='PCMU' clockrate='8000' bitrate='64000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='8' name='PCMA' clockrate='8000' bitrate='64000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='102' name='iLBC' clockrate='8000' bitrate='13300' />" \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='3' name='GSM' clockrate='8000' bitrate='13000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='98' name='speex' clockrate='8000' bitrate='11000' />" \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='126' name='CN' clockrate='32000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='105' name='CN' clockrate='16000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='13' name='CN' clockrate='8000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='117' name='red' clockrate='8000' /> " \
- " <payload-type xmlns='http://www.google.com/session/phone' " \
- " id='106' name='telephone-event' clockrate='8000' /> " \
- " </description> " \
- " </session> " \
- "</iq> ");
-
-const std::string kJingleInitiateDifferentPreference(
- "<iq xmlns='jabber:client' from='me@domain.com/resource' " \
- " to='user@domain.com/resource' type='set' id='123'> " \
- " <jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' " \
- " sid='abcdef' initiator='me@domain.com/resource'> " \
- " <content name='test audio'> " \
- " <description xmlns='urn:xmpp:jingle:apps:rtp:1' media='audio'> " \
- " <payload-type id='104' name='ISAC' clockrate='32000'/> " \
- " <payload-type " \
- " id='97' name='IPCMWB' clockrate='16000'> " \
- " <parameter name='bitrate' value='80000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='9' name='G722' clockrate='16000'> " \
- " <parameter name='bitrate' value='64000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='119' name='ISACLC' clockrate='16000'> " \
- " <parameter name='bitrate' value='40000'/> " \
- " </payload-type> " \
- " <payload-type id='103' name='ISAC' clockrate='16000'/> " \
- " <payload-type " \
- " id='99' name='speex' clockrate='16000'> " \
- " <parameter name='bitrate' value='22000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='100' name='EG711U' clockrate='8000'> " \
- " <parameter name='bitrate' value='64000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='101' name='EG711A' clockrate='8000'> " \
- " <parameter name='bitrate' value='64000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='0' name='PCMU' clockrate='8000'> " \
- " <parameter name='bitrate' value='64000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='8' name='PCMA' clockrate='8000'> " \
- " <parameter name='bitrate' value='64000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='102' name='iLBC' clockrate='8000'> " \
- " <parameter name='bitrate' value='13300'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='3' name='GSM' clockrate='8000'> " \
- " <parameter name='bitrate' value='13000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='98' name='speex' clockrate='8000'> " \
- " <parameter name='bitrate' value='11000'/> " \
- " </payload-type> " \
- " <payload-type " \
- " id='126' name='CN' clockrate='32000' /> " \
- " <payload-type " \
- " id='105' name='CN' clockrate='16000' /> " \
- " <payload-type " \
- " id='13' name='CN' clockrate='8000' /> " \
- " <payload-type " \
- " id='117' name='red' clockrate='8000' /> " \
- " <payload-type " \
- " id='106' name='telephone-event' clockrate='8000' /> " \
- " </description> " \
- " <transport xmlns=\"http://www.google.com/transport/p2p\"/> " \
- " </content> " \
- " </jingle> " \
- "</iq> ");
-
const std::string kJingleInitiateWithRtcpFb(
"<iq xmlns='jabber:client' from='me@domain.com/resource' " \
" to='user@domain.com/resource' type='set' id='123'> " \
@@ -1426,7 +1333,7 @@
}
private:
- talk_base::scoped_ptr<buzz::XmlElement> action_;
+ rtc::scoped_ptr<buzz::XmlElement> action_;
};
class GingleSessionTestParser : public MediaSessionTestParser {
@@ -1552,7 +1459,7 @@
public:
explicit MediaSessionClientTest(MediaSessionTestParser* parser,
cricket::SignalingProtocol initial_protocol) {
- nm_ = new talk_base::BasicNetworkManager();
+ nm_ = new rtc::BasicNetworkManager();
pa_ = new cricket::BasicPortAllocator(nm_);
sm_ = new cricket::SessionManager(pa_, NULL);
fme_ = new cricket::FakeMediaEngine();
@@ -1807,7 +1714,7 @@
buzz::XmlElement** element) {
*element = NULL;
- talk_base::scoped_ptr<buzz::XmlElement> el(
+ rtc::scoped_ptr<buzz::XmlElement> el(
buzz::XmlElement::ForStr(initiate_string));
client_->session_manager()->OnIncomingMessage(el.get());
ASSERT_TRUE(call_ != NULL);
@@ -1871,7 +1778,7 @@
buzz::XmlElement** element) {
*element = NULL;
- talk_base::scoped_ptr<buzz::XmlElement> el(
+ rtc::scoped_ptr<buzz::XmlElement> el(
buzz::XmlElement::ForStr(initiate_string));
client_->session_manager()->OnIncomingMessage(el.get());
ASSERT_TRUE(call_ != NULL);
@@ -1935,7 +1842,7 @@
}
void TestBadIncomingInitiate(const std::string& initiate_string) {
- talk_base::scoped_ptr<buzz::XmlElement> el(
+ rtc::scoped_ptr<buzz::XmlElement> el(
buzz::XmlElement::ForStr(initiate_string));
client_->session_manager()->OnIncomingMessage(el.get());
ASSERT_TRUE(call_ != NULL);
@@ -2127,7 +2034,7 @@
} else {
ASSERT_TRUE(bandwidth != NULL);
ASSERT_EQ("AS", bandwidth->Attr(buzz::QName("", "type")));
- ASSERT_EQ(talk_base::ToString(options.video_bandwidth / 1000),
+ ASSERT_EQ(rtc::ToString(options.video_bandwidth / 1000),
bandwidth->BodyText());
}
@@ -2439,7 +2346,7 @@
buzz::XmlElement** element) {
*element = NULL;
- talk_base::scoped_ptr<buzz::XmlElement> el(
+ rtc::scoped_ptr<buzz::XmlElement> el(
buzz::XmlElement::ForStr(initiate_string));
client_->session_manager()->OnIncomingMessage(el.get());
@@ -2486,7 +2393,7 @@
ClearStanzas();
// We need to insert the session ID into the session accept message.
- talk_base::scoped_ptr<buzz::XmlElement> el(
+ rtc::scoped_ptr<buzz::XmlElement> el(
buzz::XmlElement::ForStr(accept_string));
const std::string sid = call_->sessions()[0]->id();
if (initial_protocol_ == cricket::PROTOCOL_JINGLE) {
@@ -2544,12 +2451,12 @@
cricket::StreamParams stream;
stream.id = "test-stream";
stream.ssrcs.push_back(1001);
- talk_base::scoped_ptr<buzz::XmlElement> expected_stream_add(
+ rtc::scoped_ptr<buzz::XmlElement> expected_stream_add(
buzz::XmlElement::ForStr(
JingleOutboundStreamAdd(
call_->sessions()[0]->id(),
"video", stream.id, "1001")));
- talk_base::scoped_ptr<buzz::XmlElement> expected_stream_remove(
+ rtc::scoped_ptr<buzz::XmlElement> expected_stream_remove(
buzz::XmlElement::ForStr(
JingleOutboundStreamRemove(
call_->sessions()[0]->id(),
@@ -2582,7 +2489,7 @@
ASSERT_EQ(0U, last_streams_removed_.audio().size());
ASSERT_EQ(0U, last_streams_removed_.video().size());
- talk_base::scoped_ptr<buzz::XmlElement> accept_stanza(
+ rtc::scoped_ptr<buzz::XmlElement> accept_stanza(
buzz::XmlElement::ForStr(kJingleAcceptWithSsrcs));
SetJingleSid(accept_stanza.get());
client_->session_manager()->OnIncomingMessage(accept_stanza.get());
@@ -2598,7 +2505,7 @@
call_->sessions()[0]->SetState(cricket::Session::STATE_INPROGRESS);
- talk_base::scoped_ptr<buzz::XmlElement> streams_stanza(
+ rtc::scoped_ptr<buzz::XmlElement> streams_stanza(
buzz::XmlElement::ForStr(
JingleStreamAdd("video", "Bob", "video1", "ABC")));
SetJingleSid(streams_stanza.get());
@@ -2686,7 +2593,7 @@
cricket::StaticVideoView staticVideoView(
cricket::StreamSelector(5678U), 640, 480, 30);
viewRequest.static_video_views.push_back(staticVideoView);
- talk_base::scoped_ptr<buzz::XmlElement> expected_view_elem(
+ rtc::scoped_ptr<buzz::XmlElement> expected_view_elem(
buzz::XmlElement::ForStr(JingleView("5678", "640", "480", "30")));
SetJingleSid(expected_view_elem.get());
@@ -2793,6 +2700,8 @@
expected_data_fb_params_ = params_nack;
}
+ cricket::FakeMediaEngine* fme() { return fme_; }
+
private:
void OnSendStanza(cricket::SessionManager* manager,
const buzz::XmlElement* stanza) {
@@ -2822,7 +2731,7 @@
last_streams_removed_.CopyFrom(removed);
}
- talk_base::NetworkManager* nm_;
+ rtc::NetworkManager* nm_;
cricket::PortAllocator* pa_;
cricket::SessionManager* sm_;
cricket::FakeMediaEngine* fme_;
@@ -2855,8 +2764,8 @@
}
TEST(MediaSessionTest, JingleGoodInitiateWithRtcpFb) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
cricket::CallOptions options = VideoCallOptions();
options.data_channel_type = cricket::DCT_SCTP;
@@ -2866,32 +2775,32 @@
}
TEST(MediaSessionTest, JingleGoodVideoInitiate) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
kJingleVideoInitiate, VideoCallOptions(), elem.use());
test->TestCodecsOfVideoInitiate(elem.get());
}
TEST(MediaSessionTest, JingleGoodVideoInitiateWithBandwidth) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->ExpectVideoBandwidth(42000);
test->TestGoodIncomingInitiate(
kJingleVideoInitiateWithBandwidth, VideoCallOptions(), elem.use());
}
TEST(MediaSessionTest, JingleGoodVideoInitiateWithRtcpMux) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->ExpectVideoRtcpMux(true);
test->TestGoodIncomingInitiate(
kJingleVideoInitiateWithRtcpMux, VideoCallOptions(), elem.use());
}
TEST(MediaSessionTest, JingleGoodVideoInitiateWithRtpData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
cricket::CallOptions options = VideoCallOptions();
options.data_channel_type = cricket::DCT_RTP;
test->TestGoodIncomingInitiate(
@@ -2901,8 +2810,8 @@
}
TEST(MediaSessionTest, JingleGoodVideoInitiateWithSctpData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
cricket::CallOptions options = VideoCallOptions();
options.data_channel_type = cricket::DCT_SCTP;
test->TestGoodIncomingInitiate(kJingleVideoInitiateWithSctpData,
@@ -2911,8 +2820,8 @@
}
TEST(MediaSessionTest, JingleRejectAudio) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
cricket::CallOptions options = VideoCallOptions();
options.has_audio = false;
options.data_channel_type = cricket::DCT_RTP;
@@ -2920,118 +2829,122 @@
}
TEST(MediaSessionTest, JingleRejectVideo) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
cricket::CallOptions options = AudioCallOptions();
options.data_channel_type = cricket::DCT_RTP;
test->TestRejectOffer(kJingleVideoInitiateWithRtpData, options, elem.use());
}
TEST(MediaSessionTest, JingleRejectData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestRejectOffer(
kJingleVideoInitiateWithRtpData, VideoCallOptions(), elem.use());
}
TEST(MediaSessionTest, JingleRejectVideoAndData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestRejectOffer(
kJingleVideoInitiateWithRtpData, AudioCallOptions(), elem.use());
}
TEST(MediaSessionTest, JingleGoodInitiateAllSupportedAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
kJingleInitiate, AudioCallOptions(), elem.use());
test->TestHasAllSupportedAudioCodecs(elem.get());
}
+// Changes the codecs that our FakeMediaEngine will support with a different
+// preference order than the incoming offer.
+// Verifies the answer accepts the preference order of the remote peer.
TEST(MediaSessionTest, JingleGoodInitiateDifferentPreferenceAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ test->fme()->SetAudioCodecs(MAKE_VECTOR(kAudioCodecsDifferentPreference));
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
- kJingleInitiateDifferentPreference, AudioCallOptions(), elem.use());
+ kJingleInitiate, AudioCallOptions(), elem.use());
test->TestHasAllSupportedAudioCodecs(elem.get());
}
TEST(MediaSessionTest, JingleGoodInitiateSomeUnsupportedAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
kJingleInitiateSomeUnsupported, AudioCallOptions(), elem.use());
test->TestHasAudioCodecsFromInitiateSomeUnsupported(elem.get());
}
TEST(MediaSessionTest, JingleGoodInitiateDynamicAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
kJingleInitiateDynamicAudioCodecs, AudioCallOptions(), elem.use());
test->TestHasAudioCodecsFromInitiateDynamicAudioCodecs(elem.get());
}
TEST(MediaSessionTest, JingleGoodInitiateStaticAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
kJingleInitiateStaticAudioCodecs, AudioCallOptions(), elem.use());
test->TestHasAudioCodecsFromInitiateStaticAudioCodecs(elem.get());
}
TEST(MediaSessionTest, JingleBadInitiateNoAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(kJingleInitiateNoAudioCodecs);
}
TEST(MediaSessionTest, JingleBadInitiateNoSupportedAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(kJingleInitiateNoSupportedAudioCodecs);
}
TEST(MediaSessionTest, JingleBadInitiateWrongClockrates) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(kJingleInitiateWrongClockrates);
}
TEST(MediaSessionTest, JingleBadInitiateWrongChannels) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(kJingleInitiateWrongChannels);
}
TEST(MediaSessionTest, JingleBadInitiateNoPayloadTypes) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(kJingleInitiateNoPayloadTypes);
}
TEST(MediaSessionTest, JingleBadInitiateDynamicWithoutNames) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(kJingleInitiateDynamicWithoutNames);
}
TEST(MediaSessionTest, JingleGoodOutgoingInitiate) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestGoodOutgoingInitiate(AudioCallOptions());
}
TEST(MediaSessionTest, JingleGoodOutgoingInitiateWithBandwidth) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
cricket::CallOptions options = VideoCallOptions();
options.video_bandwidth = 42000;
test->TestGoodOutgoingInitiate(options);
}
TEST(MediaSessionTest, JingleGoodOutgoingInitiateWithRtcpMux) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
cricket::CallOptions options = VideoCallOptions();
options.rtcp_mux_enabled = true;
test->TestGoodOutgoingInitiate(options);
}
TEST(MediaSessionTest, JingleGoodOutgoingInitiateWithRtpData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
cricket::CallOptions options;
options.data_channel_type = cricket::DCT_RTP;
test->ExpectCrypto(cricket::SEC_ENABLED);
@@ -3039,7 +2952,7 @@
}
TEST(MediaSessionTest, JingleGoodOutgoingInitiateWithSctpData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
cricket::CallOptions options;
options.data_channel_type = cricket::DCT_SCTP;
test->TestGoodOutgoingInitiate(options);
@@ -3049,8 +2962,8 @@
// Offer has crypto but the session is not secured, just ignore it.
TEST(MediaSessionTest, JingleInitiateWithCryptoIsIgnoredWhenNotSecured) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
AddEncryption(kJingleVideoInitiate, kJingleCryptoOffer),
VideoCallOptions(),
@@ -3059,22 +2972,22 @@
// Offer has crypto required but the session is not secure, fail.
TEST(MediaSessionTest, JingleInitiateWithCryptoRequiredWhenNotSecured) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(AddEncryption(kJingleVideoInitiate,
kJingleRequiredCryptoOffer));
}
// Offer has no crypto but the session is secure required, fail.
TEST(MediaSessionTest, JingleInitiateWithNoCryptoFailsWhenSecureRequired) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->ExpectCrypto(cricket::SEC_REQUIRED);
test->TestBadIncomingInitiate(kJingleInitiate);
}
// Offer has crypto and session is secure, expect crypto in the answer.
TEST(MediaSessionTest, JingleInitiateWithCryptoWhenSecureEnabled) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->ExpectCrypto(cricket::SEC_ENABLED);
test->TestGoodIncomingInitiate(
AddEncryption(kJingleVideoInitiate, kJingleCryptoOffer),
@@ -3085,8 +2998,8 @@
// Offer has crypto and session is secure required, expect crypto in
// the answer.
TEST(MediaSessionTest, JingleInitiateWithCryptoWhenSecureRequired) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->ExpectCrypto(cricket::SEC_REQUIRED);
test->TestGoodIncomingInitiate(
AddEncryption(kJingleVideoInitiate, kJingleCryptoOffer),
@@ -3097,8 +3010,8 @@
// Offer has unsupported crypto and session is secure, no crypto in
// the answer.
TEST(MediaSessionTest, JingleInitiateWithUnsupportedCrypto) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
- talk_base::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->MakeSignalingSecure(cricket::SEC_ENABLED);
test->TestGoodIncomingInitiate(
AddEncryption(kJingleInitiate, kJingleUnsupportedCryptoOffer),
@@ -3108,14 +3021,14 @@
// Offer has unsupported REQUIRED crypto and session is not secure, fail.
TEST(MediaSessionTest, JingleInitiateWithRequiredUnsupportedCrypto) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestBadIncomingInitiate(
AddEncryption(kJingleInitiate, kJingleRequiredUnsupportedCryptoOffer));
}
// Offer has unsupported REQUIRED crypto and session is secure, fail.
TEST(MediaSessionTest, JingleInitiateWithRequiredUnsupportedCryptoWhenSecure) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->MakeSignalingSecure(cricket::SEC_ENABLED);
test->TestBadIncomingInitiate(
AddEncryption(kJingleInitiate, kJingleRequiredUnsupportedCryptoOffer));
@@ -3124,7 +3037,7 @@
// Offer has unsupported REQUIRED crypto and session is required secure, fail.
TEST(MediaSessionTest,
JingleInitiateWithRequiredUnsupportedCryptoWhenSecureRequired) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->MakeSignalingSecure(cricket::SEC_REQUIRED);
test->TestBadIncomingInitiate(
AddEncryption(kJingleInitiate, kJingleRequiredUnsupportedCryptoOffer));
@@ -3132,26 +3045,26 @@
TEST(MediaSessionTest, JingleGoodOutgoingInitiateWithCrypto) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->ExpectCrypto(cricket::SEC_ENABLED);
test->TestGoodOutgoingInitiate(AudioCallOptions());
}
TEST(MediaSessionTest, JingleGoodOutgoingInitiateWithCryptoRequired) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->ExpectCrypto(cricket::SEC_REQUIRED);
test->TestGoodOutgoingInitiate(AudioCallOptions());
}
TEST(MediaSessionTest, JingleIncomingAcceptWithSsrcs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
cricket::CallOptions options = VideoCallOptions();
options.is_muc = true;
test->TestIncomingAcceptWithSsrcs(kJingleAcceptWithSsrcs, options);
}
TEST(MediaSessionTest, JingleIncomingAcceptWithRtpDataSsrcs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
cricket::CallOptions options = VideoCallOptions();
options.is_muc = true;
options.data_channel_type = cricket::DCT_RTP;
@@ -3159,7 +3072,7 @@
}
TEST(MediaSessionTest, JingleIncomingAcceptWithSctpData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
cricket::CallOptions options = VideoCallOptions();
options.is_muc = true;
options.data_channel_type = cricket::DCT_SCTP;
@@ -3167,44 +3080,44 @@
}
TEST(MediaSessionTest, JingleStreamsUpdateAndView) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestStreamsUpdateAndViewRequests();
}
TEST(MediaSessionTest, JingleSendVideoStreamUpdate) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(JingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(JingleTest());
test->TestSendVideoStreamUpdate();
}
// Gingle tests
TEST(MediaSessionTest, GingleGoodVideoInitiate) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodIncomingInitiate(
kGingleVideoInitiate, VideoCallOptions(), elem.use());
test->TestCodecsOfVideoInitiate(elem.get());
}
TEST(MediaSessionTest, GingleGoodVideoInitiateWithBandwidth) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->ExpectVideoBandwidth(42000);
test->TestGoodIncomingInitiate(
kGingleVideoInitiateWithBandwidth, VideoCallOptions(), elem.use());
}
TEST(MediaSessionTest, GingleGoodInitiateAllSupportedAudioCodecs) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodIncomingInitiate(
kGingleInitiate, AudioCallOptions(), elem.use());
test->TestHasAllSupportedAudioCodecs(elem.get());
}
TEST(MediaSessionTest, GingleGoodInitiateAllSupportedAudioCodecsWithCrypto) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->ExpectCrypto(cricket::SEC_ENABLED);
test->TestGoodIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleCryptoOffer),
@@ -3213,79 +3126,83 @@
test->TestHasAllSupportedAudioCodecs(elem.get());
}
+// Changes the codecs that our FakeMediaEngine will support with a different
+// preference order than the incoming offer.
+// Verifies the answer accepts the preference order of the remote peer.
TEST(MediaSessionTest, GingleGoodInitiateDifferentPreferenceAudioCodecs) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ test->fme()->SetAudioCodecs(MAKE_VECTOR(kAudioCodecsDifferentPreference));
+ rtc::scoped_ptr<buzz::XmlElement> elem;
test->TestGoodIncomingInitiate(
- kGingleInitiateDifferentPreference, AudioCallOptions(), elem.use());
+ kGingleInitiate, AudioCallOptions(), elem.use());
test->TestHasAllSupportedAudioCodecs(elem.get());
}
TEST(MediaSessionTest, GingleGoodInitiateSomeUnsupportedAudioCodecs) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodIncomingInitiate(
kGingleInitiateSomeUnsupported, AudioCallOptions(), elem.use());
test->TestHasAudioCodecsFromInitiateSomeUnsupported(elem.get());
}
TEST(MediaSessionTest, GingleGoodInitiateDynamicAudioCodecs) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodIncomingInitiate(
kGingleInitiateDynamicAudioCodecs, AudioCallOptions(), elem.use());
test->TestHasAudioCodecsFromInitiateDynamicAudioCodecs(elem.get());
}
TEST(MediaSessionTest, GingleGoodInitiateStaticAudioCodecs) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodIncomingInitiate(
kGingleInitiateStaticAudioCodecs, AudioCallOptions(), elem.use());
test->TestHasAudioCodecsFromInitiateStaticAudioCodecs(elem.get());
}
TEST(MediaSessionTest, GingleGoodInitiateNoAudioCodecs) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodIncomingInitiate(
kGingleInitiateNoAudioCodecs, AudioCallOptions(), elem.use());
test->TestHasDefaultAudioCodecs(elem.get());
}
TEST(MediaSessionTest, GingleBadInitiateNoSupportedAudioCodecs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestBadIncomingInitiate(kGingleInitiateNoSupportedAudioCodecs);
}
TEST(MediaSessionTest, GingleBadInitiateWrongClockrates) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestBadIncomingInitiate(kGingleInitiateWrongClockrates);
}
TEST(MediaSessionTest, GingleBadInitiateWrongChannels) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestBadIncomingInitiate(kGingleInitiateWrongChannels);
}
TEST(MediaSessionTest, GingleBadInitiateNoPayloadTypes) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestBadIncomingInitiate(kGingleInitiateNoPayloadTypes);
}
TEST(MediaSessionTest, GingleBadInitiateDynamicWithoutNames) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestBadIncomingInitiate(kGingleInitiateDynamicWithoutNames);
}
TEST(MediaSessionTest, GingleGoodOutgoingInitiate) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodOutgoingInitiate(AudioCallOptions());
}
TEST(MediaSessionTest, GingleGoodOutgoingInitiateWithBandwidth) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
cricket::CallOptions options = VideoCallOptions();
options.video_bandwidth = 42000;
test->TestGoodOutgoingInitiate(options);
@@ -3295,8 +3212,8 @@
// Offer has crypto but the session is not secured, just ignore it.
TEST(MediaSessionTest, GingleInitiateWithCryptoIsIgnoredWhenNotSecured) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestGoodIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleCryptoOffer),
VideoCallOptions(),
@@ -3305,22 +3222,22 @@
// Offer has crypto required but the session is not secure, fail.
TEST(MediaSessionTest, GingleInitiateWithCryptoRequiredWhenNotSecured) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestBadIncomingInitiate(AddEncryption(kGingleInitiate,
kGingleRequiredCryptoOffer));
}
// Offer has no crypto but the session is secure required, fail.
TEST(MediaSessionTest, GingleInitiateWithNoCryptoFailsWhenSecureRequired) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->ExpectCrypto(cricket::SEC_REQUIRED);
test->TestBadIncomingInitiate(kGingleInitiate);
}
// Offer has crypto and session is secure, expect crypto in the answer.
TEST(MediaSessionTest, GingleInitiateWithCryptoWhenSecureEnabled) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->ExpectCrypto(cricket::SEC_ENABLED);
test->TestGoodIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleCryptoOffer),
@@ -3331,8 +3248,8 @@
// Offer has crypto and session is secure required, expect crypto in
// the answer.
TEST(MediaSessionTest, GingleInitiateWithCryptoWhenSecureRequired) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->ExpectCrypto(cricket::SEC_REQUIRED);
test->TestGoodIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleCryptoOffer),
@@ -3343,8 +3260,8 @@
// Offer has unsupported crypto and session is secure, no crypto in
// the answer.
TEST(MediaSessionTest, GingleInitiateWithUnsupportedCrypto) {
- talk_base::scoped_ptr<buzz::XmlElement> elem;
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<buzz::XmlElement> elem;
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->MakeSignalingSecure(cricket::SEC_ENABLED);
test->TestGoodIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleUnsupportedCryptoOffer),
@@ -3354,14 +3271,14 @@
// Offer has unsupported REQUIRED crypto and session is not secure, fail.
TEST(MediaSessionTest, GingleInitiateWithRequiredUnsupportedCrypto) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->TestBadIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleRequiredUnsupportedCryptoOffer));
}
// Offer has unsupported REQUIRED crypto and session is secure, fail.
TEST(MediaSessionTest, GingleInitiateWithRequiredUnsupportedCryptoWhenSecure) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->MakeSignalingSecure(cricket::SEC_ENABLED);
test->TestBadIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleRequiredUnsupportedCryptoOffer));
@@ -3370,33 +3287,33 @@
// Offer has unsupported REQUIRED crypto and session is required secure, fail.
TEST(MediaSessionTest,
GingleInitiateWithRequiredUnsupportedCryptoWhenSecureRequired) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->MakeSignalingSecure(cricket::SEC_REQUIRED);
test->TestBadIncomingInitiate(
AddEncryption(kGingleInitiate, kGingleRequiredUnsupportedCryptoOffer));
}
TEST(MediaSessionTest, GingleGoodOutgoingInitiateWithCrypto) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->ExpectCrypto(cricket::SEC_ENABLED);
test->TestGoodOutgoingInitiate(AudioCallOptions());
}
TEST(MediaSessionTest, GingleGoodOutgoingInitiateWithCryptoRequired) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
test->ExpectCrypto(cricket::SEC_REQUIRED);
test->TestGoodOutgoingInitiate(AudioCallOptions());
}
TEST(MediaSessionTest, GingleIncomingAcceptWithSsrcs) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
cricket::CallOptions options = VideoCallOptions();
options.is_muc = true;
test->TestIncomingAcceptWithSsrcs(kGingleAcceptWithSsrcs, options);
}
TEST(MediaSessionTest, GingleGoodOutgoingInitiateWithRtpData) {
- talk_base::scoped_ptr<MediaSessionClientTest> test(GingleTest());
+ rtc::scoped_ptr<MediaSessionClientTest> test(GingleTest());
cricket::CallOptions options;
options.data_channel_type = cricket::DCT_RTP;
test->ExpectCrypto(cricket::SEC_ENABLED);
diff --git a/session/media/planarfunctions_unittest.cc b/session/media/planarfunctions_unittest.cc
index 32cacf9..e453087 100644
--- a/session/media/planarfunctions_unittest.cc
+++ b/session/media/planarfunctions_unittest.cc
@@ -31,11 +31,11 @@
#include "libyuv/format_conversion.h"
#include "libyuv/mjpeg_decoder.h"
#include "libyuv/planar_functions.h"
-#include "talk/base/flags.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/testutils.h"
#include "talk/media/base/videocommon.h"
+#include "webrtc/base/flags.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
// Undefine macros for the windows build.
#undef max
@@ -512,12 +512,12 @@
int repeat_;
// Y, U, V and R, G, B channels of testing colors.
- talk_base::scoped_ptr<uint8[]> testing_color_y_;
- talk_base::scoped_ptr<uint8[]> testing_color_u_;
- talk_base::scoped_ptr<uint8[]> testing_color_v_;
- talk_base::scoped_ptr<uint8[]> testing_color_r_;
- talk_base::scoped_ptr<uint8[]> testing_color_g_;
- talk_base::scoped_ptr<uint8[]> testing_color_b_;
+ rtc::scoped_ptr<uint8[]> testing_color_y_;
+ rtc::scoped_ptr<uint8[]> testing_color_u_;
+ rtc::scoped_ptr<uint8[]> testing_color_v_;
+ rtc::scoped_ptr<uint8[]> testing_color_r_;
+ rtc::scoped_ptr<uint8[]> testing_color_g_;
+ rtc::scoped_ptr<uint8[]> testing_color_b_;
};
TEST_F(PlanarFunctionsTest, I420Copy) {
@@ -529,12 +529,12 @@
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1);
int block_size = 3;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> yuv_input(
+ rtc::scoped_ptr<uint8[]> yuv_input(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_pointer, u_pointer, v_pointer));
// Allocate space for the output image.
- talk_base::scoped_ptr<uint8[]> yuv_output(
+ rtc::scoped_ptr<uint8[]> yuv_output(
new uint8[I420_SIZE(kHeight, kWidth) + kAlignment]);
uint8 *y_output_pointer = ALIGNP(yuv_output.get(), kAlignment);
uint8 *u_output_pointer = y_output_pointer + y_size;
@@ -566,12 +566,12 @@
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1);
int block_size = 2;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> yuv_input(
+ rtc::scoped_ptr<uint8[]> yuv_input(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv422,
y_pointer, u_pointer, v_pointer));
// Allocate space for the output image.
- talk_base::scoped_ptr<uint8[]> yuv_output(
+ rtc::scoped_ptr<uint8[]> yuv_output(
new uint8[I420_SIZE(kHeight, kWidth) + kAlignment]);
uint8 *y_output_pointer = ALIGNP(yuv_output.get(), kAlignment);
uint8 *u_output_pointer = y_output_pointer + y_size;
@@ -579,7 +579,7 @@
// Generate the expected output.
uint8 *y_expected_pointer = NULL, *u_expected_pointer = NULL,
*v_expected_pointer = NULL;
- talk_base::scoped_ptr<uint8[]> yuv_output_expected(
+ rtc::scoped_ptr<uint8[]> yuv_output_expected(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_expected_pointer, u_expected_pointer, v_expected_pointer));
@@ -615,11 +615,11 @@
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1);
int block_size = 2;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> yuv_input(
+ rtc::scoped_ptr<uint8[]> yuv_input(
CreateFakeQ420TestingImage(kHeight, kWidth, block_size,
y_pointer, yuy2_pointer));
// Allocate space for the output image.
- talk_base::scoped_ptr<uint8[]> yuv_output(
+ rtc::scoped_ptr<uint8[]> yuv_output(
new uint8[I420_SIZE(kHeight, kWidth) + kAlignment + unalignment]);
uint8 *y_output_pointer = ALIGNP(yuv_output.get(), kAlignment) +
unalignment;
@@ -628,7 +628,7 @@
// Generate the expected output.
uint8 *y_expected_pointer = NULL, *u_expected_pointer = NULL,
*v_expected_pointer = NULL;
- talk_base::scoped_ptr<uint8[]> yuv_output_expected(
+ rtc::scoped_ptr<uint8[]> yuv_output_expected(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_expected_pointer, u_expected_pointer, v_expected_pointer));
@@ -662,10 +662,10 @@
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1);
int block_size = 2;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> yuv_input(
+ rtc::scoped_ptr<uint8[]> yuv_input(
CreateFakeM420TestingImage(kHeight, kWidth, block_size, m420_pointer));
// Allocate space for the output image.
- talk_base::scoped_ptr<uint8[]> yuv_output(
+ rtc::scoped_ptr<uint8[]> yuv_output(
new uint8[I420_SIZE(kHeight, kWidth) + kAlignment + unalignment]);
uint8 *y_output_pointer = ALIGNP(yuv_output.get(), kAlignment) + unalignment;
uint8 *u_output_pointer = y_output_pointer + y_size;
@@ -673,7 +673,7 @@
// Generate the expected output.
uint8 *y_expected_pointer = NULL, *u_expected_pointer = NULL,
*v_expected_pointer = NULL;
- talk_base::scoped_ptr<uint8[]> yuv_output_expected(
+ rtc::scoped_ptr<uint8[]> yuv_output_expected(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_expected_pointer, u_expected_pointer, v_expected_pointer));
@@ -706,11 +706,11 @@
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1);
int block_size = 2;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> yuv_input(
+ rtc::scoped_ptr<uint8[]> yuv_input(
CreateFakeNV12TestingImage(kHeight, kWidth, block_size,
y_pointer, uv_pointer));
// Allocate space for the output image.
- talk_base::scoped_ptr<uint8[]> yuv_output(
+ rtc::scoped_ptr<uint8[]> yuv_output(
new uint8[I420_SIZE(kHeight, kWidth) + kAlignment + unalignment]);
uint8 *y_output_pointer = ALIGNP(yuv_output.get(), kAlignment) + unalignment;
uint8 *u_output_pointer = y_output_pointer + y_size;
@@ -718,7 +718,7 @@
// Generate the expected output.
uint8 *y_expected_pointer = NULL, *u_expected_pointer = NULL,
*v_expected_pointer = NULL;
- talk_base::scoped_ptr<uint8[]> yuv_output_expected(
+ rtc::scoped_ptr<uint8[]> yuv_output_expected(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_expected_pointer, u_expected_pointer, v_expected_pointer));
@@ -754,11 +754,11 @@
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1); \
int block_size = 2; \
/* Generate a fake input image.*/ \
- talk_base::scoped_ptr<uint8[]> yuv_input( \
+ rtc::scoped_ptr<uint8[]> yuv_input( \
CreateFakeInterleaveYuvTestingImage(kHeight, kWidth, BLOCK_SIZE, \
yuv_pointer, FOURCC_##SRC_NAME)); \
/* Allocate space for the output image.*/ \
- talk_base::scoped_ptr<uint8[]> yuv_output( \
+ rtc::scoped_ptr<uint8[]> yuv_output( \
new uint8[I420_SIZE(kHeight, kWidth) + kAlignment + unalignment]); \
uint8 *y_output_pointer = ALIGNP(yuv_output.get(), kAlignment) + \
unalignment; \
@@ -767,7 +767,7 @@
/* Generate the expected output.*/ \
uint8 *y_expected_pointer = NULL, *u_expected_pointer = NULL, \
*v_expected_pointer = NULL; \
- talk_base::scoped_ptr<uint8[]> yuv_output_expected( \
+ rtc::scoped_ptr<uint8[]> yuv_output_expected( \
CreateFakeYuvTestingImage(kHeight, kWidth, block_size, \
libyuv::kJpegYuv420, \
y_expected_pointer, u_expected_pointer, v_expected_pointer)); \
@@ -800,15 +800,15 @@
int u_pitch = (kWidth + 1) >> 1; \
int v_pitch = (kWidth + 1) >> 1; \
/* Generate a fake input image.*/ \
- talk_base::scoped_ptr<uint8[]> yuv_input( \
+ rtc::scoped_ptr<uint8[]> yuv_input( \
CreateFakeYuvTestingImage(kHeight, kWidth, BLOCK_SIZE, JPG_TYPE, \
y_pointer, u_pointer, v_pointer)); \
/* Generate the expected output.*/ \
- talk_base::scoped_ptr<uint8[]> argb_expected( \
+ rtc::scoped_ptr<uint8[]> argb_expected( \
CreateFakeArgbTestingImage(kHeight, kWidth, BLOCK_SIZE, \
argb_expected_pointer, FOURCC_##DST_NAME)); \
/* Allocate space for the output.*/ \
- talk_base::scoped_ptr<uint8[]> argb_output( \
+ rtc::scoped_ptr<uint8[]> argb_output( \
new uint8[kHeight * kWidth * 4 + kAlignment]); \
uint8 *argb_pointer = ALIGNP(argb_expected.get(), kAlignment); \
for (int i = 0; i < repeat_; ++i) { \
@@ -844,7 +844,7 @@
int v_pitch = (kWidth + 1) >> 1;
int block_size = 3;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> yuv_input(
+ rtc::scoped_ptr<uint8[]> yuv_input(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_pointer, u_pointer, v_pointer));
@@ -852,14 +852,14 @@
// U and V channels to be 128) using an I420 converter.
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1);
- talk_base::scoped_ptr<uint8[]> uv(new uint8[uv_size + kAlignment]);
+ rtc::scoped_ptr<uint8[]> uv(new uint8[uv_size + kAlignment]);
u_pointer = v_pointer = ALIGNP(uv.get(), kAlignment);
memset(u_pointer, 128, uv_size);
// Allocate space for the output image and generate the expected output.
- talk_base::scoped_ptr<uint8[]> argb_expected(
+ rtc::scoped_ptr<uint8[]> argb_expected(
new uint8[kHeight * kWidth * 4 + kAlignment]);
- talk_base::scoped_ptr<uint8[]> argb_output(
+ rtc::scoped_ptr<uint8[]> argb_output(
new uint8[kHeight * kWidth * 4 + kAlignment]);
uint8 *argb_expected_pointer = ALIGNP(argb_expected.get(), kAlignment);
uint8 *argb_pointer = ALIGNP(argb_output.get(), kAlignment);
@@ -890,7 +890,7 @@
int v_pitch = (kWidth + 1) >> 1;
int block_size = 3;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> yuv_input(
+ rtc::scoped_ptr<uint8[]> yuv_input(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_pointer, u_pointer, v_pointer));
@@ -899,17 +899,17 @@
int uv_size = ((kHeight + 1) >> 1) * ((kWidth + 1) >> 1);
// 1 byte extra if in the unaligned mode.
- talk_base::scoped_ptr<uint8[]> uv(new uint8[uv_size * 2 + kAlignment]);
+ rtc::scoped_ptr<uint8[]> uv(new uint8[uv_size * 2 + kAlignment]);
u_pointer = ALIGNP(uv.get(), kAlignment);
v_pointer = u_pointer + uv_size;
memset(u_pointer, 128, uv_size);
memset(v_pointer, 128, uv_size);
// Allocate space for the output image and generate the expected output.
- talk_base::scoped_ptr<uint8[]> argb_expected(
+ rtc::scoped_ptr<uint8[]> argb_expected(
new uint8[kHeight * kWidth * 4 + kAlignment]);
// 1 byte extra if in the misalinged mode.
- talk_base::scoped_ptr<uint8[]> argb_output(
+ rtc::scoped_ptr<uint8[]> argb_output(
new uint8[kHeight * kWidth * 4 + kAlignment + unalignment]);
uint8 *argb_expected_pointer = ALIGNP(argb_expected.get(), kAlignment);
uint8 *argb_pointer = ALIGNP(argb_output.get(), kAlignment) + unalignment;
@@ -940,16 +940,16 @@
uint8 *argb_pointer = NULL;
int block_size = 3;
// Generate a fake input image.
- talk_base::scoped_ptr<uint8[]> argb_input(
+ rtc::scoped_ptr<uint8[]> argb_input(
CreateFakeArgbTestingImage(kHeight, kWidth, block_size,
argb_pointer, FOURCC_ARGB));
// Generate the expected output. Only Y channel is used
- talk_base::scoped_ptr<uint8[]> yuv_expected(
+ rtc::scoped_ptr<uint8[]> yuv_expected(
CreateFakeYuvTestingImage(kHeight, kWidth, block_size,
libyuv::kJpegYuv420,
y_pointer, u_pointer, v_pointer));
// Allocate space for the Y output.
- talk_base::scoped_ptr<uint8[]> y_output(
+ rtc::scoped_ptr<uint8[]> y_output(
new uint8[kHeight * kWidth + kAlignment + unalignment]);
uint8 *y_output_pointer = ALIGNP(y_output.get(), kAlignment) + unalignment;
@@ -972,15 +972,15 @@
int unalignment = GetParam(); /* Get the unalignment offset.*/ \
uint8 *argb_expected_pointer = NULL, *src_pointer = NULL; \
/* Generate a fake input image.*/ \
- talk_base::scoped_ptr<uint8[]> src_input( \
+ rtc::scoped_ptr<uint8[]> src_input( \
CreateFakeArgbTestingImage(kHeight, kWidth, BLOCK_SIZE, \
src_pointer, FOURCC_##FC_ID)); \
/* Generate the expected output.*/ \
- talk_base::scoped_ptr<uint8[]> argb_expected( \
+ rtc::scoped_ptr<uint8[]> argb_expected( \
CreateFakeArgbTestingImage(kHeight, kWidth, BLOCK_SIZE, \
argb_expected_pointer, FOURCC_ARGB)); \
/* Allocate space for the output; 1 byte extra if in the unaligned mode.*/ \
- talk_base::scoped_ptr<uint8[]> argb_output( \
+ rtc::scoped_ptr<uint8[]> argb_output( \
new uint8[kHeight * kWidth * 4 + kAlignment + unalignment]); \
uint8 *argb_pointer = ALIGNP(argb_output.get(), kAlignment) + unalignment; \
for (int i = 0; i < repeat_; ++i) { \
diff --git a/session/media/rtcpmuxfilter.cc b/session/media/rtcpmuxfilter.cc
index 7091952..f951992 100644
--- a/session/media/rtcpmuxfilter.cc
+++ b/session/media/rtcpmuxfilter.cc
@@ -27,7 +27,7 @@
#include "talk/session/media/rtcpmuxfilter.h"
-#include "talk/base/logging.h"
+#include "webrtc/base/logging.h"
namespace cricket {
diff --git a/session/media/rtcpmuxfilter.h b/session/media/rtcpmuxfilter.h
index a5bb85e..40951a2 100644
--- a/session/media/rtcpmuxfilter.h
+++ b/session/media/rtcpmuxfilter.h
@@ -28,8 +28,8 @@
#ifndef TALK_SESSION_MEDIA_RTCPMUXFILTER_H_
#define TALK_SESSION_MEDIA_RTCPMUXFILTER_H_
-#include "talk/base/basictypes.h"
#include "talk/p2p/base/sessiondescription.h"
+#include "webrtc/base/basictypes.h"
namespace cricket {
diff --git a/session/media/rtcpmuxfilter_unittest.cc b/session/media/rtcpmuxfilter_unittest.cc
index ad33498..a947bdf 100644
--- a/session/media/rtcpmuxfilter_unittest.cc
+++ b/session/media/rtcpmuxfilter_unittest.cc
@@ -25,8 +25,8 @@
#include "talk/session/media/rtcpmuxfilter.h"
-#include "talk/base/gunit.h"
#include "talk/media/base/testutils.h"
+#include "webrtc/base/gunit.h"
TEST(RtcpMuxFilterTest, DemuxRtcpSender) {
cricket::RtcpMuxFilter filter;
diff --git a/session/media/soundclip.cc b/session/media/soundclip.cc
index 44f457c..70a3b18 100644
--- a/session/media/soundclip.cc
+++ b/session/media/soundclip.cc
@@ -33,7 +33,7 @@
MSG_PLAYSOUND = 1,
};
-struct PlaySoundMessageData : talk_base::MessageData {
+struct PlaySoundMessageData : rtc::MessageData {
PlaySoundMessageData(const void *c,
int l,
SoundclipMedia::SoundclipFlags f)
@@ -49,7 +49,7 @@
bool result;
};
-Soundclip::Soundclip(talk_base::Thread *thread, SoundclipMedia *soundclip_media)
+Soundclip::Soundclip(rtc::Thread *thread, SoundclipMedia *soundclip_media)
: worker_thread_(thread),
soundclip_media_(soundclip_media) {
}
@@ -70,7 +70,7 @@
flags);
}
-void Soundclip::OnMessage(talk_base::Message *message) {
+void Soundclip::OnMessage(rtc::Message *message) {
ASSERT(message->message_id == MSG_PLAYSOUND);
PlaySoundMessageData *data =
static_cast<PlaySoundMessageData *>(message->pdata);
diff --git a/session/media/soundclip.h b/session/media/soundclip.h
index f057d8d..aaf8579 100644
--- a/session/media/soundclip.h
+++ b/session/media/soundclip.h
@@ -28,10 +28,10 @@
#ifndef TALK_SESSION_MEDIA_SOUNDCLIP_H_
#define TALK_SESSION_MEDIA_SOUNDCLIP_H_
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/mediaengine.h"
+#include "webrtc/base/scoped_ptr.h"
-namespace talk_base {
+namespace rtc {
class Thread;
@@ -41,9 +41,9 @@
// Soundclip wraps SoundclipMedia to support marshalling calls to the proper
// thread.
-class Soundclip : private talk_base::MessageHandler {
+class Soundclip : private rtc::MessageHandler {
public:
- Soundclip(talk_base::Thread* thread, SoundclipMedia* soundclip_media);
+ Soundclip(rtc::Thread* thread, SoundclipMedia* soundclip_media);
// Plays a sound out to the speakers with the given audio stream. The stream
// must be 16-bit little-endian 16 kHz PCM. If a stream is already playing
@@ -59,10 +59,10 @@
SoundclipMedia::SoundclipFlags flags);
// From MessageHandler
- virtual void OnMessage(talk_base::Message* message);
+ virtual void OnMessage(rtc::Message* message);
- talk_base::Thread* worker_thread_;
- talk_base::scoped_ptr<SoundclipMedia> soundclip_media_;
+ rtc::Thread* worker_thread_;
+ rtc::scoped_ptr<SoundclipMedia> soundclip_media_;
};
} // namespace cricket
diff --git a/session/media/srtpfilter.cc b/session/media/srtpfilter.cc
index 10e9514..c79bf13 100644
--- a/session/media/srtpfilter.cc
+++ b/session/media/srtpfilter.cc
@@ -33,11 +33,11 @@
#include <algorithm>
-#include "talk/base/base64.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringencode.h"
-#include "talk/base/timeutils.h"
#include "talk/media/base/rtputils.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringencode.h"
+#include "webrtc/base/timeutils.h"
// Enable this line to turn on SRTP debugging
// #define SRTP_DEBUG
@@ -449,7 +449,7 @@
// Fail if base64 decode fails, or the key is the wrong size.
std::string key_b64(key_params.substr(7)), key_str;
- if (!talk_base::Base64::Decode(key_b64, talk_base::Base64::DO_STRICT,
+ if (!rtc::Base64::Decode(key_b64, rtc::Base64::DO_STRICT,
&key_str, NULL) ||
static_cast<int>(key_str.size()) != len) {
return false;
@@ -869,9 +869,9 @@
if (key.error != SrtpFilter::ERROR_NONE) {
// For errors, signal first time and wait for 1 sec.
FailureStat* stat = &(failures_[key]);
- uint32 current_time = talk_base::Time();
+ uint32 current_time = rtc::Time();
if (stat->last_signal_time == 0 ||
- talk_base::TimeDiff(current_time, stat->last_signal_time) >
+ rtc::TimeDiff(current_time, stat->last_signal_time) >
static_cast<int>(signal_silent_time_)) {
SignalSrtpError(key.ssrc, key.mode, key.error);
stat->last_signal_time = current_time;
diff --git a/session/media/srtpfilter.h b/session/media/srtpfilter.h
index bc1735a..ce3368f 100644
--- a/session/media/srtpfilter.h
+++ b/session/media/srtpfilter.h
@@ -33,11 +33,11 @@
#include <string>
#include <vector>
-#include "talk/base/basictypes.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslotrepeater.h"
#include "talk/media/base/cryptoparams.h"
#include "talk/p2p/base/sessiondescription.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslotrepeater.h"
// Forward declaration to avoid pulling in libsrtp headers here
struct srtp_event_data_t;
@@ -182,10 +182,10 @@
State state_;
uint32 signal_silent_time_in_ms_;
std::vector<CryptoParams> offer_params_;
- talk_base::scoped_ptr<SrtpSession> send_session_;
- talk_base::scoped_ptr<SrtpSession> recv_session_;
- talk_base::scoped_ptr<SrtpSession> send_rtcp_session_;
- talk_base::scoped_ptr<SrtpSession> recv_rtcp_session_;
+ rtc::scoped_ptr<SrtpSession> send_session_;
+ rtc::scoped_ptr<SrtpSession> recv_session_;
+ rtc::scoped_ptr<SrtpSession> send_rtcp_session_;
+ rtc::scoped_ptr<SrtpSession> recv_rtcp_session_;
CryptoParams applied_send_params_;
CryptoParams applied_recv_params_;
};
@@ -241,7 +241,7 @@
srtp_t session_;
int rtp_auth_tag_len_;
int rtcp_auth_tag_len_;
- talk_base::scoped_ptr<SrtpStat> srtp_stat_;
+ rtc::scoped_ptr<SrtpStat> srtp_stat_;
static bool inited_;
int last_send_seq_num_;
DISALLOW_COPY_AND_ASSIGN(SrtpSession);
diff --git a/session/media/srtpfilter_unittest.cc b/session/media/srtpfilter_unittest.cc
index 4f0ebd4..19efa2a 100644
--- a/session/media/srtpfilter_unittest.cc
+++ b/session/media/srtpfilter_unittest.cc
@@ -25,13 +25,13 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/byteorder.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
#include "talk/media/base/cryptoparams.h"
#include "talk/media/base/fakertp.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/session/media/srtpfilter.h"
+#include "webrtc/base/byteorder.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/thread.h"
#ifdef SRTP_RELATIVE_PATH
#include "crypto/include/err.h"
#else
@@ -94,7 +94,7 @@
memcpy(rtp_packet, kPcmuFrame, rtp_len);
// In order to be able to run this test function multiple times we can not
// use the same sequence number twice. Increase the sequence number by one.
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet) + 2,
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet) + 2,
++sequence_number_);
memcpy(original_rtp_packet, rtp_packet, rtp_len);
memcpy(rtcp_packet, kRtcpReport, rtcp_len);
@@ -679,36 +679,36 @@
EXPECT_TRUE(s2_.SetRecv(CS_AES_CM_128_HMAC_SHA1_80, kTestKey1, kTestKeyLen));
// Initial sequence number.
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2, seqnum_big);
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2, seqnum_big);
EXPECT_TRUE(s1_.ProtectRtp(rtp_packet_, rtp_len_, sizeof(rtp_packet_),
&out_len));
// Replay within the 1024 window should succeed.
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
seqnum_big - replay_window + 1);
EXPECT_TRUE(s1_.ProtectRtp(rtp_packet_, rtp_len_, sizeof(rtp_packet_),
&out_len));
// Replay out side of the 1024 window should fail.
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
seqnum_big - replay_window - 1);
EXPECT_FALSE(s1_.ProtectRtp(rtp_packet_, rtp_len_, sizeof(rtp_packet_),
&out_len));
// Increment sequence number to a small number.
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2, seqnum_small);
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2, seqnum_small);
EXPECT_TRUE(s1_.ProtectRtp(rtp_packet_, rtp_len_, sizeof(rtp_packet_),
&out_len));
// Replay around 0 but out side of the 1024 window should fail.
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
kMaxSeqnum + seqnum_small - replay_window - 1);
EXPECT_FALSE(s1_.ProtectRtp(rtp_packet_, rtp_len_, sizeof(rtp_packet_),
&out_len));
// Replay around 0 but within the 1024 window should succeed.
for (uint16 seqnum = 65000; seqnum < 65003; ++seqnum) {
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2, seqnum);
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2, seqnum);
EXPECT_TRUE(s1_.ProtectRtp(rtp_packet_, rtp_len_, sizeof(rtp_packet_),
&out_len));
}
@@ -718,7 +718,7 @@
// without the fix, the loop above would keep incrementing local sequence
// number in libsrtp, eventually the new sequence number would go out side
// of the window.
- talk_base::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
+ rtc::SetBE16(reinterpret_cast<uint8*>(rtp_packet_) + 2,
seqnum_small + 1);
EXPECT_TRUE(s1_.ProtectRtp(rtp_packet_, rtp_len_, sizeof(rtp_packet_),
&out_len));
@@ -782,7 +782,7 @@
EXPECT_EQ(cricket::SrtpFilter::ERROR_NONE, error_);
// Now the error will be triggered again.
Reset();
- talk_base::Thread::Current()->SleepMs(210);
+ rtc::Thread::Current()->SleepMs(210);
srtp_stat_.AddProtectRtpResult(1, err_status_fail);
EXPECT_EQ(1U, ssrc_);
EXPECT_EQ(cricket::SrtpFilter::PROTECT, mode_);
@@ -806,7 +806,7 @@
EXPECT_EQ(cricket::SrtpFilter::UNPROTECT, mode_);
EXPECT_EQ(cricket::SrtpFilter::ERROR_REPLAY, error_);
Reset();
- talk_base::Thread::Current()->SleepMs(210);
+ rtc::Thread::Current()->SleepMs(210);
srtp_stat_.AddUnprotectRtpResult(1, err_status_replay_old);
EXPECT_EQ(1U, ssrc_);
EXPECT_EQ(cricket::SrtpFilter::UNPROTECT, mode_);
@@ -824,7 +824,7 @@
EXPECT_EQ(cricket::SrtpFilter::ERROR_NONE, error_);
// Now the error will be triggered again.
Reset();
- talk_base::Thread::Current()->SleepMs(210);
+ rtc::Thread::Current()->SleepMs(210);
srtp_stat_.AddUnprotectRtpResult(1, err_status_fail);
EXPECT_EQ(1U, ssrc_);
EXPECT_EQ(cricket::SrtpFilter::UNPROTECT, mode_);
@@ -851,7 +851,7 @@
EXPECT_EQ(cricket::SrtpFilter::ERROR_NONE, error_);
// Now the error will be triggered again.
Reset();
- talk_base::Thread::Current()->SleepMs(210);
+ rtc::Thread::Current()->SleepMs(210);
srtp_stat_.AddProtectRtcpResult(err_status_fail);
EXPECT_EQ(cricket::SrtpFilter::PROTECT, mode_);
EXPECT_EQ(cricket::SrtpFilter::ERROR_FAIL, error_);
@@ -871,7 +871,7 @@
EXPECT_EQ(cricket::SrtpFilter::UNPROTECT, mode_);
EXPECT_EQ(cricket::SrtpFilter::ERROR_REPLAY, error_);
Reset();
- talk_base::Thread::Current()->SleepMs(210);
+ rtc::Thread::Current()->SleepMs(210);
srtp_stat_.AddUnprotectRtcpResult(err_status_replay_fail);
EXPECT_EQ(cricket::SrtpFilter::UNPROTECT, mode_);
EXPECT_EQ(cricket::SrtpFilter::ERROR_REPLAY, error_);
@@ -886,7 +886,7 @@
EXPECT_EQ(cricket::SrtpFilter::ERROR_NONE, error_);
// Now the error will be triggered again.
Reset();
- talk_base::Thread::Current()->SleepMs(210);
+ rtc::Thread::Current()->SleepMs(210);
srtp_stat_.AddUnprotectRtcpResult(err_status_fail);
EXPECT_EQ(cricket::SrtpFilter::UNPROTECT, mode_);
EXPECT_EQ(cricket::SrtpFilter::ERROR_FAIL, error_);
diff --git a/session/media/typewrapping.h.pump b/session/media/typewrapping.h.pump
index 3b52927..2cbb20f 100644
--- a/session/media/typewrapping.h.pump
+++ b/session/media/typewrapping.h.pump
@@ -83,7 +83,7 @@
#ifndef TALK_SESSION_PHONE_TYPEWRAPPING_H_
#define TALK_SESSION_PHONE_TYPEWRAPPING_H_
-#include "talk/base/common.h"
+#include "webrtc/base/common.h"
#ifdef OSX
// XCode's GCC doesn't respect typedef-equivalence when casting function pointer
diff --git a/session/media/typingmonitor.cc b/session/media/typingmonitor.cc
index 3c5d387..ee0f92a 100644
--- a/session/media/typingmonitor.cc
+++ b/session/media/typingmonitor.cc
@@ -27,14 +27,14 @@
#include "talk/session/media/typingmonitor.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
#include "talk/session/media/channel.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
namespace cricket {
TypingMonitor::TypingMonitor(VoiceChannel* channel,
- talk_base::Thread* worker_thread,
+ rtc::Thread* worker_thread,
const TypingMonitorOptions& settings)
: channel_(channel),
worker_thread_(worker_thread),
@@ -52,7 +52,7 @@
TypingMonitor::~TypingMonitor() {
// Shortcut any pending unmutes.
if (has_pending_unmute_) {
- talk_base::MessageList messages;
+ rtc::MessageList messages;
worker_thread_->Clear(this, 0, &messages);
ASSERT(messages.size() == 1);
channel_->MuteStream(0, false);
@@ -75,7 +75,7 @@
channel_->MuteStream(0, true);
SignalMuted(channel_, true);
has_pending_unmute_ = true;
- muted_at_ = talk_base::Time();
+ muted_at_ = rtc::Time();
worker_thread_->PostDelayed(mute_period_, this, 0);
LOG(LS_INFO) << "Muting for at least " << mute_period_ << "ms.";
@@ -89,7 +89,7 @@
*/
void TypingMonitor::OnChannelMuted() {
if (has_pending_unmute_) {
- talk_base::MessageList removed;
+ rtc::MessageList removed;
worker_thread_->Clear(this, 0, &removed);
ASSERT(removed.size() == 1);
has_pending_unmute_ = false;
@@ -102,13 +102,13 @@
* elapse since they finished and try to unmute again. Should be called on the
* worker thread.
*/
-void TypingMonitor::OnMessage(talk_base::Message* msg) {
+void TypingMonitor::OnMessage(rtc::Message* msg) {
if (!channel_->IsStreamMuted(0) || !has_pending_unmute_) return;
int silence_period = channel_->media_channel()->GetTimeSinceLastTyping();
int expiry_time = mute_period_ - silence_period;
if (silence_period < 0 || expiry_time < 50) {
LOG(LS_INFO) << "Mute timeout hit, last typing " << silence_period
- << "ms ago, unmuting after " << talk_base::TimeSince(muted_at_)
+ << "ms ago, unmuting after " << rtc::TimeSince(muted_at_)
<< "ms total.";
has_pending_unmute_ = false;
channel_->MuteStream(0, false);
@@ -116,7 +116,7 @@
} else {
LOG(LS_INFO) << "Mute timeout hit, last typing " << silence_period
<< "ms ago, check again in " << expiry_time << "ms.";
- talk_base::Thread::Current()->PostDelayed(expiry_time, this, 0);
+ rtc::Thread::Current()->PostDelayed(expiry_time, this, 0);
}
}
diff --git a/session/media/typingmonitor.h b/session/media/typingmonitor.h
index c9b64e7..4beb8ec 100644
--- a/session/media/typingmonitor.h
+++ b/session/media/typingmonitor.h
@@ -28,10 +28,10 @@
#ifndef TALK_SESSION_MEDIA_TYPINGMONITOR_H_
#define TALK_SESSION_MEDIA_TYPINGMONITOR_H_
-#include "talk/base/messagehandler.h"
#include "talk/media/base/mediachannel.h"
+#include "webrtc/base/messagehandler.h"
-namespace talk_base {
+namespace rtc {
class Thread;
}
@@ -57,9 +57,9 @@
* a conference with loud keystroke audio signals.
*/
class TypingMonitor
- : public talk_base::MessageHandler, public sigslot::has_slots<> {
+ : public rtc::MessageHandler, public sigslot::has_slots<> {
public:
- TypingMonitor(VoiceChannel* channel, talk_base::Thread* worker_thread,
+ TypingMonitor(VoiceChannel* channel, rtc::Thread* worker_thread,
const TypingMonitorOptions& params);
~TypingMonitor();
@@ -69,10 +69,10 @@
private:
void OnVoiceChannelError(uint32 ssrc, VoiceMediaChannel::Error error);
- void OnMessage(talk_base::Message* msg);
+ void OnMessage(rtc::Message* msg);
VoiceChannel* channel_;
- talk_base::Thread* worker_thread_;
+ rtc::Thread* worker_thread_;
int mute_period_;
int muted_at_;
bool has_pending_unmute_;
diff --git a/session/media/typingmonitor_unittest.cc b/session/media/typingmonitor_unittest.cc
index eb8c5bc..95fa7a4 100644
--- a/session/media/typingmonitor_unittest.cc
+++ b/session/media/typingmonitor_unittest.cc
@@ -25,25 +25,25 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/gunit.h"
#include "talk/media/base/fakemediaengine.h"
#include "talk/p2p/base/fakesession.h"
#include "talk/session/media/channel.h"
#include "talk/session/media/currentspeakermonitor.h"
#include "talk/session/media/typingmonitor.h"
+#include "webrtc/base/gunit.h"
namespace cricket {
class TypingMonitorTest : public testing::Test {
protected:
TypingMonitorTest() : session_(true) {
- vc_.reset(new VoiceChannel(talk_base::Thread::Current(), &engine_,
+ vc_.reset(new VoiceChannel(rtc::Thread::Current(), &engine_,
engine_.CreateChannel(), &session_, "", false));
engine_.GetVoiceChannel(0)->set_time_since_last_typing(1000);
TypingMonitorOptions settings = {10, 20, 30, 40, 50};
monitor_.reset(new TypingMonitor(vc_.get(),
- talk_base::Thread::Current(),
+ rtc::Thread::Current(),
settings));
}
@@ -51,8 +51,8 @@
vc_.reset();
}
- talk_base::scoped_ptr<TypingMonitor> monitor_;
- talk_base::scoped_ptr<VoiceChannel> vc_;
+ rtc::scoped_ptr<TypingMonitor> monitor_;
+ rtc::scoped_ptr<VoiceChannel> vc_;
FakeMediaEngine engine_;
FakeSession session_;
};
diff --git a/session/media/yuvscaler_unittest.cc b/session/media/yuvscaler_unittest.cc
index 93ac534..2018246 100644
--- a/session/media/yuvscaler_unittest.cc
+++ b/session/media/yuvscaler_unittest.cc
@@ -29,11 +29,11 @@
#include "libyuv/cpu_id.h"
#include "libyuv/scale.h"
-#include "talk/base/basictypes.h"
-#include "talk/base/flags.h"
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/media/base/testutils.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/flags.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
#if defined(_MSC_VER)
#define ALIGN16(var) __declspec(align(16)) var
@@ -43,7 +43,7 @@
using cricket::LoadPlanarYuvTestImage;
using cricket::DumpPlanarYuvTestImage;
-using talk_base::scoped_ptr;
+using rtc::scoped_ptr;
DEFINE_bool(yuvscaler_dump, false,
"whether to write out scaled images for inspection");
@@ -88,8 +88,8 @@
class YuvScalerTest : public testing::Test {
protected:
virtual void SetUp() {
- dump_ = *FlagList::Lookup("yuvscaler_dump")->bool_variable();
- repeat_ = *FlagList::Lookup("yuvscaler_repeat")->int_variable();
+ dump_ = *rtc::FlagList::Lookup("yuvscaler_dump")->bool_variable();
+ repeat_ = *rtc::FlagList::Lookup("yuvscaler_repeat")->int_variable();
}
// Scale an image and compare against a Lanczos-filtered test image.
diff --git a/session/tunnel/pseudotcpchannel.cc b/session/tunnel/pseudotcpchannel.cc
index d95dc85..f277614 100644
--- a/session/tunnel/pseudotcpchannel.cc
+++ b/session/tunnel/pseudotcpchannel.cc
@@ -26,20 +26,20 @@
*/
#include <string>
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
+#include "pseudotcpchannel.h"
#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/transportchannel.h"
-#include "pseudotcpchannel.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stringutils.h"
-using namespace talk_base;
+using namespace rtc;
namespace cricket {
-extern const talk_base::ConstantLabel SESSION_STATES[];
+extern const rtc::ConstantLabel SESSION_STATES[];
// MSG_WK_* - worker thread messages
// MSG_ST_* - stream thread messages
@@ -341,7 +341,7 @@
void PseudoTcpChannel::OnChannelRead(TransportChannel* channel,
const char* data, size_t size,
- const talk_base::PacketTime& packet_time,
+ const rtc::PacketTime& packet_time,
int flags) {
//LOG_F(LS_VERBOSE) << "(" << size << ")";
ASSERT(worker_thread_->IsCurrent());
@@ -378,7 +378,7 @@
int family = candidate.address().family();
Socket* socket =
worker_thread_->socketserver()->CreateAsyncSocket(family, SOCK_DGRAM);
- talk_base::scoped_ptr<Socket> mtu_socket(socket);
+ rtc::scoped_ptr<Socket> mtu_socket(socket);
if (socket == NULL) {
LOG_F(LS_WARNING) << "Couldn't create socket while estimating MTU.";
} else {
@@ -504,7 +504,7 @@
ASSERT(cs_.CurrentThreadIsOwner());
ASSERT(tcp == tcp_);
ASSERT(NULL != channel_);
- talk_base::PacketOptions packet_options;
+ rtc::PacketOptions packet_options;
int sent = channel_->SendPacket(buffer, len, packet_options);
if (sent > 0) {
//LOG_F(LS_VERBOSE) << "(" << sent << ") Sent";
diff --git a/session/tunnel/pseudotcpchannel.h b/session/tunnel/pseudotcpchannel.h
index 31cd9a1..5ccfa4c 100644
--- a/session/tunnel/pseudotcpchannel.h
+++ b/session/tunnel/pseudotcpchannel.h
@@ -28,13 +28,13 @@
#ifndef TALK_SESSION_TUNNEL_PSEUDOTCPCHANNEL_H_
#define TALK_SESSION_TUNNEL_PSEUDOTCPCHANNEL_H_
-#include "talk/base/criticalsection.h"
-#include "talk/base/messagequeue.h"
-#include "talk/base/stream.h"
#include "talk/p2p/base/pseudotcp.h"
#include "talk/p2p/base/session.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/stream.h"
-namespace talk_base {
+namespace rtc {
class Thread;
}
@@ -64,17 +64,17 @@
class PseudoTcpChannel
: public IPseudoTcpNotify,
- public talk_base::MessageHandler,
+ public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
// Signal thread methods
- PseudoTcpChannel(talk_base::Thread* stream_thread,
+ PseudoTcpChannel(rtc::Thread* stream_thread,
Session* session);
bool Connect(const std::string& content_name,
const std::string& channel_name,
int component);
- talk_base::StreamInterface* GetStream();
+ rtc::StreamInterface* GetStream();
sigslot::signal1<PseudoTcpChannel*> SignalChannelClosed;
@@ -93,15 +93,15 @@
virtual ~PseudoTcpChannel();
// Stream thread methods
- talk_base::StreamState GetState() const;
- talk_base::StreamResult Read(void* buffer, size_t buffer_len,
+ rtc::StreamState GetState() const;
+ rtc::StreamResult Read(void* buffer, size_t buffer_len,
size_t* read, int* error);
- talk_base::StreamResult Write(const void* data, size_t data_len,
+ rtc::StreamResult Write(const void* data, size_t data_len,
size_t* written, int* error);
void Close();
// Multi-thread methods
- void OnMessage(talk_base::Message* pmsg);
+ void OnMessage(rtc::Message* pmsg);
void AdjustClock(bool clear = true);
void CheckDestroy();
@@ -111,7 +111,7 @@
// Worker thread methods
void OnChannelWritableState(TransportChannel* channel);
void OnChannelRead(TransportChannel* channel, const char* data, size_t size,
- const talk_base::PacketTime& packet_time, int flags);
+ const rtc::PacketTime& packet_time, int flags);
void OnChannelConnectionChanged(TransportChannel* channel,
const Candidate& candidate);
@@ -123,7 +123,7 @@
const char* buffer,
size_t len);
- talk_base::Thread* signal_thread_, * worker_thread_, * stream_thread_;
+ rtc::Thread* signal_thread_, * worker_thread_, * stream_thread_;
Session* session_;
TransportChannel* channel_;
std::string content_name_;
@@ -132,7 +132,7 @@
InternalStream* stream_;
bool stream_readable_, pending_read_event_;
bool ready_to_connect_;
- mutable talk_base::CriticalSection cs_;
+ mutable rtc::CriticalSection cs_;
};
} // namespace cricket
diff --git a/session/tunnel/securetunnelsessionclient.cc b/session/tunnel/securetunnelsessionclient.cc
index 55f4083..cb41c3b 100644
--- a/session/tunnel/securetunnelsessionclient.cc
+++ b/session/tunnel/securetunnelsessionclient.cc
@@ -27,18 +27,18 @@
// SecureTunnelSessionClient and SecureTunnelSession implementation.
-#include "talk/session/tunnel/securetunnelsessionclient.h"
-#include "talk/base/basicdefs.h"
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/sslidentity.h"
-#include "talk/base/sslstreamadapter.h"
#include "talk/p2p/base/transportchannel.h"
-#include "talk/xmllite/xmlelement.h"
#include "talk/session/tunnel/pseudotcpchannel.h"
+#include "talk/session/tunnel/securetunnelsessionclient.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
+#include "webrtc/base/basicdefs.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/sslidentity.h"
+#include "webrtc/base/sslstreamadapter.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
@@ -84,14 +84,14 @@
: TunnelSessionClient(jid, manager, NS_SECURE_TUNNEL) {
}
-void SecureTunnelSessionClient::SetIdentity(talk_base::SSLIdentity* identity) {
+void SecureTunnelSessionClient::SetIdentity(rtc::SSLIdentity* identity) {
ASSERT(identity_.get() == NULL);
identity_.reset(identity);
}
bool SecureTunnelSessionClient::GenerateIdentity() {
ASSERT(identity_.get() == NULL);
- identity_.reset(talk_base::SSLIdentity::Generate(
+ identity_.reset(rtc::SSLIdentity::Generate(
// The name on the certificate does not matter: the peer will
// make sure the cert it gets during SSL negotiation matches the
// one it got from XMPP. It would be neat to put something
@@ -112,7 +112,7 @@
return true;
}
-talk_base::SSLIdentity& SecureTunnelSessionClient::GetIdentity() const {
+rtc::SSLIdentity& SecureTunnelSessionClient::GetIdentity() const {
ASSERT(identity_.get() != NULL);
return *identity_;
}
@@ -120,15 +120,15 @@
// Parses a certificate from a PEM encoded string.
// Returns NULL on failure.
// The caller is responsible for freeing the returned object.
-static talk_base::SSLCertificate* ParseCertificate(
+static rtc::SSLCertificate* ParseCertificate(
const std::string& pem_cert) {
if (pem_cert.empty())
return NULL;
- return talk_base::SSLCertificate::FromPEMString(pem_cert);
+ return rtc::SSLCertificate::FromPEMString(pem_cert);
}
TunnelSession* SecureTunnelSessionClient::MakeTunnelSession(
- Session* session, talk_base::Thread* stream_thread,
+ Session* session, rtc::Thread* stream_thread,
TunnelSessionRole role) {
return new SecureTunnelSession(this, session, stream_thread, role);
}
@@ -156,7 +156,7 @@
}
// Validate the certificate
- talk_base::scoped_ptr<talk_base::SSLCertificate> peer_cert(
+ rtc::scoped_ptr<rtc::SSLCertificate> peer_cert(
ParseCertificate(content->client_pem_certificate));
if (peer_cert.get() == NULL) {
LOG(LS_ERROR)
@@ -309,16 +309,16 @@
SecureTunnelSession::SecureTunnelSession(
SecureTunnelSessionClient* client, Session* session,
- talk_base::Thread* stream_thread, TunnelSessionRole role)
+ rtc::Thread* stream_thread, TunnelSessionRole role)
: TunnelSession(client, session, stream_thread),
role_(role) {
}
-talk_base::StreamInterface* SecureTunnelSession::MakeSecureStream(
- talk_base::StreamInterface* stream) {
- talk_base::SSLStreamAdapter* ssl_stream =
- talk_base::SSLStreamAdapter::Create(stream);
- talk_base::SSLIdentity* identity =
+rtc::StreamInterface* SecureTunnelSession::MakeSecureStream(
+ rtc::StreamInterface* stream) {
+ rtc::SSLStreamAdapter* ssl_stream =
+ rtc::SSLStreamAdapter::Create(stream);
+ rtc::SSLIdentity* identity =
static_cast<SecureTunnelSessionClient*>(client_)->
GetIdentity().GetReference();
ssl_stream->SetIdentity(identity);
@@ -334,11 +334,11 @@
// OnAccept()). We won't Connect() the PseudoTcpChannel until we get
// that, so the stream will stay closed until then. Keep a handle
// on the streem so we can configure the peer certificate later.
- ssl_stream_reference_.reset(new talk_base::StreamReference(ssl_stream));
+ ssl_stream_reference_.reset(new rtc::StreamReference(ssl_stream));
return ssl_stream_reference_->NewReference();
}
-talk_base::StreamInterface* SecureTunnelSession::GetStream() {
+rtc::StreamInterface* SecureTunnelSession::GetStream() {
ASSERT(channel_ != NULL);
ASSERT(ssl_stream_reference_.get() == NULL);
return MakeSecureStream(channel_->GetStream());
@@ -360,7 +360,7 @@
const std::string& cert_pem =
role_ == INITIATOR ? remote_tunnel->server_pem_certificate :
remote_tunnel->client_pem_certificate;
- talk_base::scoped_ptr<talk_base::SSLCertificate> peer_cert(
+ rtc::scoped_ptr<rtc::SSLCertificate> peer_cert(
ParseCertificate(cert_pem));
if (peer_cert == NULL) {
ASSERT(role_ == INITIATOR); // when RESPONDER we validated it earlier
@@ -370,8 +370,8 @@
return;
}
ASSERT(ssl_stream_reference_.get() != NULL);
- talk_base::SSLStreamAdapter* ssl_stream =
- static_cast<talk_base::SSLStreamAdapter*>(
+ rtc::SSLStreamAdapter* ssl_stream =
+ static_cast<rtc::SSLStreamAdapter*>(
ssl_stream_reference_->GetStream());
std::string algorithm;
@@ -379,7 +379,7 @@
LOG(LS_ERROR) << "Failed to get the algorithm for the peer cert signature";
return;
}
- unsigned char digest[talk_base::MessageDigest::kMaxSize];
+ unsigned char digest[rtc::MessageDigest::kMaxSize];
size_t digest_len;
peer_cert->ComputeDigest(algorithm, digest, ARRAY_SIZE(digest), &digest_len);
ssl_stream->SetPeerCertificateDigest(algorithm, digest, digest_len);
diff --git a/session/tunnel/securetunnelsessionclient.h b/session/tunnel/securetunnelsessionclient.h
index 5c65b98..15202a1 100644
--- a/session/tunnel/securetunnelsessionclient.h
+++ b/session/tunnel/securetunnelsessionclient.h
@@ -36,9 +36,9 @@
#include <string>
-#include "talk/base/sslidentity.h"
-#include "talk/base/sslstreamadapter.h"
#include "talk/session/tunnel/tunnelsessionclient.h"
+#include "webrtc/base/sslidentity.h"
+#include "webrtc/base/sslstreamadapter.h"
namespace cricket {
@@ -66,7 +66,7 @@
// Configures this client to use a preexisting SSLIdentity.
// The client takes ownership of the identity object.
// Use either SetIdentity or GenerateIdentity, and only once.
- void SetIdentity(talk_base::SSLIdentity* identity);
+ void SetIdentity(rtc::SSLIdentity* identity);
// Generates an identity from nothing.
// Returns true if generation was successful.
@@ -77,7 +77,7 @@
// SetIdentity() or generated by GenerateIdentity(). Call this
// method only after our identity has been successfully established
// by one of those methods.
- talk_base::SSLIdentity& GetIdentity() const;
+ rtc::SSLIdentity& GetIdentity() const;
// Inherited methods
virtual void OnIncomingTunnel(const buzz::Jid& jid, Session *session);
@@ -96,7 +96,7 @@
protected:
virtual TunnelSession* MakeTunnelSession(
- Session* session, talk_base::Thread* stream_thread,
+ Session* session, rtc::Thread* stream_thread,
TunnelSessionRole role);
private:
@@ -104,7 +104,7 @@
// certificate part will be communicated within the session
// description. The identity will be passed to the SSLStreamAdapter
// and used for SSL authentication.
- talk_base::scoped_ptr<talk_base::SSLIdentity> identity_;
+ rtc::scoped_ptr<rtc::SSLIdentity> identity_;
DISALLOW_EVIL_CONSTRUCTORS(SecureTunnelSessionClient);
};
@@ -123,13 +123,13 @@
// role is either INITIATOR or RESPONDER, depending on who is
// initiating the session.
SecureTunnelSession(SecureTunnelSessionClient* client, Session* session,
- talk_base::Thread* stream_thread,
+ rtc::Thread* stream_thread,
TunnelSessionRole role);
// Returns the stream that implements the actual P2P tunnel.
// This may be called only once. Caller is responsible for freeing
// the returned object.
- virtual talk_base::StreamInterface* GetStream();
+ virtual rtc::StreamInterface* GetStream();
protected:
// Inherited method: callback on accepting a session.
@@ -138,8 +138,8 @@
// Helper method for GetStream() that Instantiates the
// SSLStreamAdapter to wrap the PseudoTcpChannel's stream, and
// configures it with our identity and role.
- talk_base::StreamInterface* MakeSecureStream(
- talk_base::StreamInterface* stream);
+ rtc::StreamInterface* MakeSecureStream(
+ rtc::StreamInterface* stream);
// Our role in requesting the tunnel: INITIATOR or
// RESPONDER. Translates to our role in SSL negotiation:
@@ -155,7 +155,7 @@
// stream endpoint is returned early, but we need to keep a handle
// on it so we can setup the peer certificate when we receive it
// later.
- talk_base::scoped_ptr<talk_base::StreamReference> ssl_stream_reference_;
+ rtc::scoped_ptr<rtc::StreamReference> ssl_stream_reference_;
DISALLOW_EVIL_CONSTRUCTORS(SecureTunnelSession);
};
diff --git a/session/tunnel/tunnelsessionclient.cc b/session/tunnel/tunnelsessionclient.cc
index 71d0ce1..7221db4 100644
--- a/session/tunnel/tunnelsessionclient.cc
+++ b/session/tunnel/tunnelsessionclient.cc
@@ -25,17 +25,17 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/basicdefs.h"
-#include "talk/base/basictypes.h"
-#include "talk/base/common.h"
-#include "talk/base/helpers.h"
-#include "talk/base/logging.h"
-#include "talk/base/stringutils.h"
+#include "pseudotcpchannel.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/transportchannel.h"
-#include "talk/xmllite/xmlelement.h"
-#include "pseudotcpchannel.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "tunnelsessionclient.h"
+#include "webrtc/base/basicdefs.h"
+#include "webrtc/base/basictypes.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/helpers.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/stringutils.h"
namespace cricket {
@@ -52,21 +52,21 @@
MSG_CREATE_TUNNEL,
};
-struct EventData : public talk_base::MessageData {
+struct EventData : public rtc::MessageData {
int event, error;
EventData(int ev, int err = 0) : event(ev), error(err) { }
};
-struct CreateTunnelData : public talk_base::MessageData {
+struct CreateTunnelData : public rtc::MessageData {
buzz::Jid jid;
std::string description;
- talk_base::Thread* thread;
- talk_base::StreamInterface* stream;
+ rtc::Thread* thread;
+ rtc::StreamInterface* stream;
};
-extern const talk_base::ConstantLabel SESSION_STATES[];
+extern const rtc::ConstantLabel SESSION_STATES[];
-const talk_base::ConstantLabel SESSION_STATES[] = {
+const rtc::ConstantLabel SESSION_STATES[] = {
KLABEL(Session::STATE_INIT),
KLABEL(Session::STATE_SENTINITIATE),
KLABEL(Session::STATE_RECEIVEDINITIATE),
@@ -124,7 +124,7 @@
ASSERT(session_manager_->signaling_thread()->IsCurrent());
if (received)
sessions_.push_back(
- MakeTunnelSession(session, talk_base::Thread::Current(), RESPONDER));
+ MakeTunnelSession(session, rtc::Thread::Current(), RESPONDER));
}
void TunnelSessionClientBase::OnSessionDestroy(Session* session) {
@@ -143,19 +143,19 @@
}
}
-talk_base::StreamInterface* TunnelSessionClientBase::CreateTunnel(
+rtc::StreamInterface* TunnelSessionClientBase::CreateTunnel(
const buzz::Jid& to, const std::string& description) {
// Valid from any thread
CreateTunnelData data;
data.jid = to;
data.description = description;
- data.thread = talk_base::Thread::Current();
+ data.thread = rtc::Thread::Current();
data.stream = NULL;
session_manager_->signaling_thread()->Send(this, MSG_CREATE_TUNNEL, &data);
return data.stream;
}
-talk_base::StreamInterface* TunnelSessionClientBase::AcceptTunnel(
+rtc::StreamInterface* TunnelSessionClientBase::AcceptTunnel(
Session* session) {
ASSERT(session_manager_->signaling_thread()->IsCurrent());
TunnelSession* tunnel = NULL;
@@ -182,7 +182,7 @@
session->Reject(STR_TERMINATE_DECLINE);
}
-void TunnelSessionClientBase::OnMessage(talk_base::Message* pmsg) {
+void TunnelSessionClientBase::OnMessage(rtc::Message* pmsg) {
if (pmsg->message_id == MSG_CREATE_TUNNEL) {
ASSERT(session_manager_->signaling_thread()->IsCurrent());
CreateTunnelData* data = static_cast<CreateTunnelData*>(pmsg->pdata);
@@ -201,7 +201,7 @@
}
TunnelSession* TunnelSessionClientBase::MakeTunnelSession(
- Session* session, talk_base::Thread* stream_thread,
+ Session* session, rtc::Thread* stream_thread,
TunnelSessionRole /*role*/) {
return new TunnelSession(this, session, stream_thread);
}
@@ -288,7 +288,7 @@
const buzz::Jid &jid, const std::string &description) {
SessionDescription* offer = NewTunnelSessionDescription(
CN_TUNNEL, new TunnelContentDescription(description));
- talk_base::scoped_ptr<TransportDescription> tdesc(
+ rtc::scoped_ptr<TransportDescription> tdesc(
session_manager_->transport_desc_factory()->CreateOffer(
TransportOptions(), NULL));
if (tdesc.get()) {
@@ -313,7 +313,7 @@
if (tinfo) {
const TransportDescription* offer_tdesc = &tinfo->description;
ASSERT(offer_tdesc != NULL);
- talk_base::scoped_ptr<TransportDescription> tdesc(
+ rtc::scoped_ptr<TransportDescription> tdesc(
session_manager_->transport_desc_factory()->CreateAnswer(
offer_tdesc, TransportOptions(), NULL));
if (tdesc.get()) {
@@ -334,7 +334,7 @@
//
TunnelSession::TunnelSession(TunnelSessionClientBase* client, Session* session,
- talk_base::Thread* stream_thread)
+ rtc::Thread* stream_thread)
: client_(client), session_(session), channel_(NULL) {
ASSERT(client_ != NULL);
ASSERT(session_ != NULL);
@@ -349,7 +349,7 @@
ASSERT(channel_ == NULL);
}
-talk_base::StreamInterface* TunnelSession::GetStream() {
+rtc::StreamInterface* TunnelSession::GetStream() {
ASSERT(channel_ != NULL);
return channel_->GetStream();
}
@@ -375,8 +375,8 @@
void TunnelSession::OnSessionState(BaseSession* session,
BaseSession::State state) {
LOG(LS_INFO) << "TunnelSession::OnSessionState("
- << talk_base::nonnull(
- talk_base::FindLabel(state, SESSION_STATES), "Unknown")
+ << rtc::nonnull(
+ rtc::FindLabel(state, SESSION_STATES), "Unknown")
<< ")";
ASSERT(session == session_);
diff --git a/session/tunnel/tunnelsessionclient.h b/session/tunnel/tunnelsessionclient.h
index 55ce14a..d3fa64a 100644
--- a/session/tunnel/tunnelsessionclient.h
+++ b/session/tunnel/tunnelsessionclient.h
@@ -30,16 +30,16 @@
#include <vector>
-#include "talk/base/criticalsection.h"
-#include "talk/base/stream.h"
#include "talk/p2p/base/constants.h"
#include "talk/p2p/base/pseudotcp.h"
#include "talk/p2p/base/session.h"
+#include "talk/p2p/base/sessionclient.h"
#include "talk/p2p/base/sessiondescription.h"
#include "talk/p2p/base/sessionmanager.h"
-#include "talk/p2p/base/sessionclient.h"
-#include "talk/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/qname.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/criticalsection.h"
+#include "webrtc/base/stream.h"
namespace cricket {
@@ -54,7 +54,7 @@
// Base class is still abstract
class TunnelSessionClientBase
- : public SessionClient, public talk_base::MessageHandler {
+ : public SessionClient, public rtc::MessageHandler {
public:
TunnelSessionClientBase(const buzz::Jid& jid, SessionManager* manager,
const std::string &ns);
@@ -69,10 +69,10 @@
// This can be called on any thread. The stream interface is
// thread-safe, but notifications must be registered on the creating
// thread.
- talk_base::StreamInterface* CreateTunnel(const buzz::Jid& to,
+ rtc::StreamInterface* CreateTunnel(const buzz::Jid& to,
const std::string& description);
- talk_base::StreamInterface* AcceptTunnel(Session* session);
+ rtc::StreamInterface* AcceptTunnel(Session* session);
void DeclineTunnel(Session* session);
// Invoked on an incoming tunnel
@@ -88,13 +88,13 @@
protected:
- void OnMessage(talk_base::Message* pmsg);
+ void OnMessage(rtc::Message* pmsg);
// helper method to instantiate TunnelSession. By overriding this,
// subclasses of TunnelSessionClient are able to instantiate
// subclasses of TunnelSession instead.
virtual TunnelSession* MakeTunnelSession(Session* session,
- talk_base::Thread* stream_thread,
+ rtc::Thread* stream_thread,
TunnelSessionRole role);
buzz::Jid jid_;
@@ -155,9 +155,9 @@
public:
// Signalling thread methods
TunnelSession(TunnelSessionClientBase* client, Session* session,
- talk_base::Thread* stream_thread);
+ rtc::Thread* stream_thread);
- virtual talk_base::StreamInterface* GetStream();
+ virtual rtc::StreamInterface* GetStream();
bool HasSession(Session* session);
Session* ReleaseSession(bool channel_exists);
diff --git a/session/tunnel/tunnelsessionclient_unittest.cc b/session/tunnel/tunnelsessionclient_unittest.cc
index 7370351..6d46918 100644
--- a/session/tunnel/tunnelsessionclient_unittest.cc
+++ b/session/tunnel/tunnelsessionclient_unittest.cc
@@ -26,16 +26,16 @@
*/
#include <string>
-#include "talk/base/gunit.h"
-#include "talk/base/messagehandler.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stream.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
#include "talk/p2p/base/sessionmanager.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/client/fakeportallocator.h"
#include "talk/session/tunnel/tunnelsessionclient.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/stream.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timeutils.h"
static const int kTimeoutMs = 10000;
static const int kBlockSize = 4096;
@@ -45,14 +45,14 @@
// This test fixture creates the necessary plumbing to create and run
// two TunnelSessionClients that talk to each other.
class TunnelSessionClientTest : public testing::Test,
- public talk_base::MessageHandler,
+ public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
TunnelSessionClientTest()
- : local_pa_(talk_base::Thread::Current(), NULL),
- remote_pa_(talk_base::Thread::Current(), NULL),
- local_sm_(&local_pa_, talk_base::Thread::Current()),
- remote_sm_(&remote_pa_, talk_base::Thread::Current()),
+ : local_pa_(rtc::Thread::Current(), NULL),
+ remote_pa_(rtc::Thread::Current(), NULL),
+ local_sm_(&local_pa_, rtc::Thread::Current()),
+ remote_sm_(&remote_pa_, rtc::Thread::Current()),
local_client_(kLocalJid, &local_sm_),
remote_client_(kRemoteJid, &remote_sm_),
done_(false) {
@@ -104,19 +104,19 @@
void OnOutgoingMessage(cricket::SessionManager* manager,
const buzz::XmlElement* stanza) {
if (manager == &local_sm_) {
- talk_base::Thread::Current()->Post(this, MSG_LSIGNAL,
- talk_base::WrapMessageData(*stanza));
+ rtc::Thread::Current()->Post(this, MSG_LSIGNAL,
+ rtc::WrapMessageData(*stanza));
} else if (manager == &remote_sm_) {
- talk_base::Thread::Current()->Post(this, MSG_RSIGNAL,
- talk_base::WrapMessageData(*stanza));
+ rtc::Thread::Current()->Post(this, MSG_RSIGNAL,
+ rtc::WrapMessageData(*stanza));
}
}
// Need to add a "from=" attribute (normally added by the server)
// Then route the incoming signaling message to the "other" session manager.
- virtual void OnMessage(talk_base::Message* message) {
- talk_base::TypedMessageData<buzz::XmlElement>* data =
- static_cast<talk_base::TypedMessageData<buzz::XmlElement>*>(
+ virtual void OnMessage(rtc::Message* message) {
+ rtc::TypedMessageData<buzz::XmlElement>* data =
+ static_cast<rtc::TypedMessageData<buzz::XmlElement>*>(
message->pdata);
bool response = data->data().Attr(buzz::QN_TYPE) == buzz::STR_RESULT;
if (message->message_id == MSG_RSIGNAL) {
@@ -150,14 +150,14 @@
// Read bytes out into recv_stream_ as they arrive.
// End the test when we are notified that the local side has closed the
// tunnel. All data has been read out at this point.
- void OnStreamEvent(talk_base::StreamInterface* stream, int events,
+ void OnStreamEvent(rtc::StreamInterface* stream, int events,
int error) {
- if (events & talk_base::SE_READ) {
+ if (events & rtc::SE_READ) {
if (stream == remote_tunnel_.get()) {
ReadData();
}
}
- if (events & talk_base::SE_WRITE) {
+ if (events & rtc::SE_WRITE) {
if (stream == local_tunnel_.get()) {
bool done = false;
WriteData(&done);
@@ -166,7 +166,7 @@
}
}
}
- if (events & talk_base::SE_CLOSE) {
+ if (events & rtc::SE_CLOSE) {
if (stream == remote_tunnel_.get()) {
remote_tunnel_->Close();
done_ = true;
@@ -179,12 +179,12 @@
void ReadData() {
char block[kBlockSize];
size_t read, position;
- talk_base::StreamResult res;
+ rtc::StreamResult res;
while ((res = remote_tunnel_->Read(block, sizeof(block), &read, NULL)) ==
- talk_base::SR_SUCCESS) {
+ rtc::SR_SUCCESS) {
recv_stream_.Write(block, read, NULL, NULL);
}
- ASSERT(res != talk_base::SR_EOS);
+ ASSERT(res != rtc::SR_EOS);
recv_stream_.GetPosition(&position);
LOG(LS_VERBOSE) << "Recv position: " << position;
}
@@ -192,14 +192,14 @@
void WriteData(bool* done) {
char block[kBlockSize];
size_t leftover = 0, position;
- talk_base::StreamResult res = talk_base::Flow(&send_stream_,
+ rtc::StreamResult res = rtc::Flow(&send_stream_,
block, sizeof(block), local_tunnel_.get(), &leftover);
- if (res == talk_base::SR_BLOCK) {
+ if (res == rtc::SR_BLOCK) {
send_stream_.GetPosition(&position);
send_stream_.SetPosition(position - leftover);
LOG(LS_VERBOSE) << "Send position: " << position - leftover;
*done = false;
- } else if (res == talk_base::SR_SUCCESS) {
+ } else if (res == rtc::SR_SUCCESS) {
*done = true;
} else {
ASSERT(false); // shouldn't happen
@@ -213,10 +213,10 @@
cricket::SessionManager remote_sm_;
cricket::TunnelSessionClient local_client_;
cricket::TunnelSessionClient remote_client_;
- talk_base::scoped_ptr<talk_base::StreamInterface> local_tunnel_;
- talk_base::scoped_ptr<talk_base::StreamInterface> remote_tunnel_;
- talk_base::MemoryStream send_stream_;
- talk_base::MemoryStream recv_stream_;
+ rtc::scoped_ptr<rtc::StreamInterface> local_tunnel_;
+ rtc::scoped_ptr<rtc::StreamInterface> remote_tunnel_;
+ rtc::MemoryStream send_stream_;
+ rtc::MemoryStream recv_stream_;
bool done_;
};
diff --git a/sound/alsasoundsystem.cc b/sound/alsasoundsystem.cc
deleted file mode 100644
index 7a8857c..0000000
--- a/sound/alsasoundsystem.cc
+++ /dev/null
@@ -1,761 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/alsasoundsystem.h"
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
-#include "talk/base/timeutils.h"
-#include "talk/base/worker.h"
-#include "talk/sound/sounddevicelocator.h"
-#include "talk/sound/soundinputstreaminterface.h"
-#include "talk/sound/soundoutputstreaminterface.h"
-
-namespace cricket {
-
-// Lookup table from the cricket format enum in soundsysteminterface.h to
-// ALSA's enums.
-static const snd_pcm_format_t kCricketFormatToAlsaFormatTable[] = {
- // The order here must match the order in soundsysteminterface.h
- SND_PCM_FORMAT_S16_LE,
-};
-
-// Lookup table for the size of a single sample of a given format.
-static const size_t kCricketFormatToSampleSizeTable[] = {
- // The order here must match the order in soundsysteminterface.h
- sizeof(int16_t), // 2
-};
-
-// Minimum latency we allow, in microseconds. This is more or less arbitrary,
-// but it has to be at least large enough to be able to buffer data during a
-// missed context switch, and the typical Linux scheduling quantum is 10ms.
-static const int kMinimumLatencyUsecs = 20 * 1000;
-
-// The latency we'll use for kNoLatencyRequirements (chosen arbitrarily).
-static const int kDefaultLatencyUsecs = kMinimumLatencyUsecs * 2;
-
-// We translate newlines in ALSA device descriptions to hyphens.
-static const char kAlsaDescriptionSearch[] = "\n";
-static const char kAlsaDescriptionReplace[] = " - ";
-
-class AlsaDeviceLocator : public SoundDeviceLocator {
- public:
- AlsaDeviceLocator(const std::string &name,
- const std::string &device_name)
- : SoundDeviceLocator(name, device_name) {
- // The ALSA descriptions have newlines in them, which won't show up in
- // a drop-down box. Replace them with hyphens.
- talk_base::replace_substrs(kAlsaDescriptionSearch,
- sizeof(kAlsaDescriptionSearch) - 1,
- kAlsaDescriptionReplace,
- sizeof(kAlsaDescriptionReplace) - 1,
- &name_);
- }
-
- virtual SoundDeviceLocator *Copy() const {
- return new AlsaDeviceLocator(*this);
- }
-};
-
-// Functionality that is common to both AlsaInputStream and AlsaOutputStream.
-class AlsaStream {
- public:
- AlsaStream(AlsaSoundSystem *alsa,
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq)
- : alsa_(alsa),
- handle_(handle),
- frame_size_(frame_size),
- wait_timeout_ms_(wait_timeout_ms),
- flags_(flags),
- freq_(freq) {
- }
-
- ~AlsaStream() {
- Close();
- }
-
- // Waits for the stream to be ready to accept/return more data, and returns
- // how much can be written/read, or 0 if we need to Wait() again.
- snd_pcm_uframes_t Wait() {
- snd_pcm_sframes_t frames;
- // Ideally we would not use snd_pcm_wait() and instead hook snd_pcm_poll_*
- // into PhysicalSocketServer, but PhysicalSocketServer is nasty enough
- // already and the current clients of SoundSystemInterface do not run
- // anything else on their worker threads, so snd_pcm_wait() is good enough.
- frames = symbol_table()->snd_pcm_avail_update()(handle_);
- if (frames < 0) {
- LOG(LS_ERROR) << "snd_pcm_avail_update(): " << GetError(frames);
- Recover(frames);
- return 0;
- } else if (frames > 0) {
- // Already ready, so no need to wait.
- return frames;
- }
- // Else no space/data available, so must wait.
- int ready = symbol_table()->snd_pcm_wait()(handle_, wait_timeout_ms_);
- if (ready < 0) {
- LOG(LS_ERROR) << "snd_pcm_wait(): " << GetError(ready);
- Recover(ready);
- return 0;
- } else if (ready == 0) {
- // Timeout, so nothing can be written/read right now.
- // We set the timeout to twice the requested latency, so continuous
- // timeouts are indicative of a problem, so log as a warning.
- LOG(LS_WARNING) << "Timeout while waiting on stream";
- return 0;
- }
- // Else ready > 0 (i.e., 1), so it's ready. Get count.
- frames = symbol_table()->snd_pcm_avail_update()(handle_);
- if (frames < 0) {
- LOG(LS_ERROR) << "snd_pcm_avail_update(): " << GetError(frames);
- Recover(frames);
- return 0;
- } else if (frames == 0) {
- // wait() said we were ready, so this ought to have been positive. Has
- // been observed to happen in practice though.
- LOG(LS_WARNING) << "Spurious wake-up";
- }
- return frames;
- }
-
- int CurrentDelayUsecs() {
- if (!(flags_ & SoundSystemInterface::FLAG_REPORT_LATENCY)) {
- return 0;
- }
-
- snd_pcm_sframes_t delay;
- int err = symbol_table()->snd_pcm_delay()(handle_, &delay);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_delay(): " << GetError(err);
- Recover(err);
- // We'd rather continue playout/capture with an incorrect delay than stop
- // it altogether, so return a valid value.
- return 0;
- }
- // The delay is in frames. Convert to microseconds.
- return delay * talk_base::kNumMicrosecsPerSec / freq_;
- }
-
- // Used to recover from certain recoverable errors, principally buffer overrun
- // or underrun (identified as EPIPE). Without calling this the stream stays
- // in the error state forever.
- bool Recover(int error) {
- int err;
- err = symbol_table()->snd_pcm_recover()(
- handle_,
- error,
- // Silent; i.e., no logging on stderr.
- 1);
- if (err != 0) {
- // Docs say snd_pcm_recover returns the original error if it is not one
- // of the recoverable ones, so this log message will probably contain the
- // same error twice.
- LOG(LS_ERROR) << "Unable to recover from \"" << GetError(error) << "\": "
- << GetError(err);
- return false;
- }
- if (error == -EPIPE && // Buffer underrun/overrun.
- symbol_table()->snd_pcm_stream()(handle_) == SND_PCM_STREAM_CAPTURE) {
- // For capture streams we also have to repeat the explicit start() to get
- // data flowing again.
- err = symbol_table()->snd_pcm_start()(handle_);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_start(): " << GetError(err);
- return false;
- }
- }
- return true;
- }
-
- bool Close() {
- if (handle_) {
- int err;
- err = symbol_table()->snd_pcm_drop()(handle_);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_drop(): " << GetError(err);
- // Continue anyways.
- }
- err = symbol_table()->snd_pcm_close()(handle_);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_close(): " << GetError(err);
- // Continue anyways.
- }
- handle_ = NULL;
- }
- return true;
- }
-
- AlsaSymbolTable *symbol_table() {
- return &alsa_->symbol_table_;
- }
-
- snd_pcm_t *handle() {
- return handle_;
- }
-
- const char *GetError(int err) {
- return alsa_->GetError(err);
- }
-
- size_t frame_size() {
- return frame_size_;
- }
-
- private:
- AlsaSoundSystem *alsa_;
- snd_pcm_t *handle_;
- size_t frame_size_;
- int wait_timeout_ms_;
- int flags_;
- int freq_;
-
- DISALLOW_COPY_AND_ASSIGN(AlsaStream);
-};
-
-// Implementation of an input stream. See soundinputstreaminterface.h regarding
-// thread-safety.
-class AlsaInputStream :
- public SoundInputStreamInterface,
- private talk_base::Worker {
- public:
- AlsaInputStream(AlsaSoundSystem *alsa,
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq)
- : stream_(alsa, handle, frame_size, wait_timeout_ms, flags, freq),
- buffer_size_(0) {
- }
-
- virtual ~AlsaInputStream() {
- bool success = StopReading();
- // We need that to live.
- VERIFY(success);
- }
-
- virtual bool StartReading() {
- return StartWork();
- }
-
- virtual bool StopReading() {
- return StopWork();
- }
-
- virtual bool GetVolume(int *volume) {
- // TODO: Implement this.
- return false;
- }
-
- virtual bool SetVolume(int volume) {
- // TODO: Implement this.
- return false;
- }
-
- virtual bool Close() {
- return StopReading() && stream_.Close();
- }
-
- virtual int LatencyUsecs() {
- return stream_.CurrentDelayUsecs();
- }
-
- private:
- // Inherited from Worker.
- virtual void OnStart() {
- HaveWork();
- }
-
- // Inherited from Worker.
- virtual void OnHaveWork() {
- // Block waiting for data.
- snd_pcm_uframes_t avail = stream_.Wait();
- if (avail > 0) {
- // Data is available.
- size_t size = avail * stream_.frame_size();
- if (size > buffer_size_) {
- // Must increase buffer size.
- buffer_.reset(new char[size]);
- buffer_size_ = size;
- }
- // Read all the data.
- snd_pcm_sframes_t read = stream_.symbol_table()->snd_pcm_readi()(
- stream_.handle(),
- buffer_.get(),
- avail);
- if (read < 0) {
- LOG(LS_ERROR) << "snd_pcm_readi(): " << GetError(read);
- stream_.Recover(read);
- } else if (read == 0) {
- // Docs say this shouldn't happen.
- ASSERT(false);
- LOG(LS_ERROR) << "No data?";
- } else {
- // Got data. Pass it off to the app.
- SignalSamplesRead(buffer_.get(),
- read * stream_.frame_size(),
- this);
- }
- }
- // Check for more data with no delay, after any pending messages are
- // dispatched.
- HaveWork();
- }
-
- // Inherited from Worker.
- virtual void OnStop() {
- // Nothing to do.
- }
-
- const char *GetError(int err) {
- return stream_.GetError(err);
- }
-
- AlsaStream stream_;
- talk_base::scoped_ptr<char[]> buffer_;
- size_t buffer_size_;
-
- DISALLOW_COPY_AND_ASSIGN(AlsaInputStream);
-};
-
-// Implementation of an output stream. See soundoutputstreaminterface.h
-// regarding thread-safety.
-class AlsaOutputStream :
- public SoundOutputStreamInterface,
- private talk_base::Worker {
- public:
- AlsaOutputStream(AlsaSoundSystem *alsa,
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq)
- : stream_(alsa, handle, frame_size, wait_timeout_ms, flags, freq) {
- }
-
- virtual ~AlsaOutputStream() {
- bool success = DisableBufferMonitoring();
- // We need that to live.
- VERIFY(success);
- }
-
- virtual bool EnableBufferMonitoring() {
- return StartWork();
- }
-
- virtual bool DisableBufferMonitoring() {
- return StopWork();
- }
-
- virtual bool WriteSamples(const void *sample_data,
- size_t size) {
- if (size % stream_.frame_size() != 0) {
- // No client of SoundSystemInterface does this, so let's not support it.
- // (If we wanted to support it, we'd basically just buffer the fractional
- // frame until we get more data.)
- ASSERT(false);
- LOG(LS_ERROR) << "Writes with fractional frames are not supported";
- return false;
- }
- snd_pcm_uframes_t frames = size / stream_.frame_size();
- snd_pcm_sframes_t written = stream_.symbol_table()->snd_pcm_writei()(
- stream_.handle(),
- sample_data,
- frames);
- if (written < 0) {
- LOG(LS_ERROR) << "snd_pcm_writei(): " << GetError(written);
- stream_.Recover(written);
- return false;
- } else if (static_cast<snd_pcm_uframes_t>(written) < frames) {
- // Shouldn't happen. Drop the rest of the data.
- LOG(LS_ERROR) << "Stream wrote only " << written << " of " << frames
- << " frames!";
- return false;
- }
- return true;
- }
-
- virtual bool GetVolume(int *volume) {
- // TODO: Implement this.
- return false;
- }
-
- virtual bool SetVolume(int volume) {
- // TODO: Implement this.
- return false;
- }
-
- virtual bool Close() {
- return DisableBufferMonitoring() && stream_.Close();
- }
-
- virtual int LatencyUsecs() {
- return stream_.CurrentDelayUsecs();
- }
-
- private:
- // Inherited from Worker.
- virtual void OnStart() {
- HaveWork();
- }
-
- // Inherited from Worker.
- virtual void OnHaveWork() {
- snd_pcm_uframes_t avail = stream_.Wait();
- if (avail > 0) {
- size_t space = avail * stream_.frame_size();
- SignalBufferSpace(space, this);
- }
- HaveWork();
- }
-
- // Inherited from Worker.
- virtual void OnStop() {
- // Nothing to do.
- }
-
- const char *GetError(int err) {
- return stream_.GetError(err);
- }
-
- AlsaStream stream_;
-
- DISALLOW_COPY_AND_ASSIGN(AlsaOutputStream);
-};
-
-AlsaSoundSystem::AlsaSoundSystem() : initialized_(false) {}
-
-AlsaSoundSystem::~AlsaSoundSystem() {
- // Not really necessary, because Terminate() doesn't really do anything.
- Terminate();
-}
-
-bool AlsaSoundSystem::Init() {
- if (IsInitialized()) {
- return true;
- }
-
- // Load libasound.
- if (!symbol_table_.Load()) {
- // Very odd for a Linux machine to not have a working libasound ...
- LOG(LS_ERROR) << "Failed to load symbol table";
- return false;
- }
-
- initialized_ = true;
-
- return true;
-}
-
-void AlsaSoundSystem::Terminate() {
- if (!IsInitialized()) {
- return;
- }
-
- initialized_ = false;
-
- // We do not unload the symbol table because we may need it again soon if
- // Init() is called again.
-}
-
-bool AlsaSoundSystem::EnumeratePlaybackDevices(
- SoundDeviceLocatorList *devices) {
- return EnumerateDevices(devices, false);
-}
-
-bool AlsaSoundSystem::EnumerateCaptureDevices(
- SoundDeviceLocatorList *devices) {
- return EnumerateDevices(devices, true);
-}
-
-bool AlsaSoundSystem::GetDefaultPlaybackDevice(SoundDeviceLocator **device) {
- return GetDefaultDevice(device);
-}
-
-bool AlsaSoundSystem::GetDefaultCaptureDevice(SoundDeviceLocator **device) {
- return GetDefaultDevice(device);
-}
-
-SoundOutputStreamInterface *AlsaSoundSystem::OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return OpenDevice<SoundOutputStreamInterface>(
- device,
- params,
- SND_PCM_STREAM_PLAYBACK,
- &AlsaSoundSystem::StartOutputStream);
-}
-
-SoundInputStreamInterface *AlsaSoundSystem::OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return OpenDevice<SoundInputStreamInterface>(
- device,
- params,
- SND_PCM_STREAM_CAPTURE,
- &AlsaSoundSystem::StartInputStream);
-}
-
-const char *AlsaSoundSystem::GetName() const {
- return "ALSA";
-}
-
-bool AlsaSoundSystem::EnumerateDevices(
- SoundDeviceLocatorList *devices,
- bool capture_not_playback) {
- ClearSoundDeviceLocatorList(devices);
-
- if (!IsInitialized()) {
- return false;
- }
-
- const char *type = capture_not_playback ? "Input" : "Output";
- // dmix and dsnoop are only for playback and capture, respectively, but ALSA
- // stupidly includes them in both lists.
- const char *ignore_prefix = capture_not_playback ? "dmix:" : "dsnoop:";
- // (ALSA lists many more "devices" of questionable interest, but we show them
- // just in case the weird devices may actually be desirable for some
- // users/systems.)
- const char *ignore_default = "default";
- const char *ignore_null = "null";
- const char *ignore_pulse = "pulse";
- // The 'pulse' entry has a habit of mysteriously disappearing when you query
- // a second time. Remove it from our list. (GIPS lib did the same thing.)
- int err;
-
- void **hints;
- err = symbol_table_.snd_device_name_hint()(-1, // All cards
- "pcm", // Only PCM devices
- &hints);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_device_name_hint(): " << GetError(err);
- return false;
- }
-
- for (void **list = hints; *list != NULL; ++list) {
- char *actual_type = symbol_table_.snd_device_name_get_hint()(*list, "IOID");
- if (actual_type) { // NULL means it's both.
- bool wrong_type = (strcmp(actual_type, type) != 0);
- free(actual_type);
- if (wrong_type) {
- // Wrong type of device (i.e., input vs. output).
- continue;
- }
- }
-
- char *name = symbol_table_.snd_device_name_get_hint()(*list, "NAME");
- if (!name) {
- LOG(LS_ERROR) << "Device has no name???";
- // Skip it.
- continue;
- }
-
- // Now check if we actually want to show this device.
- if (strcmp(name, ignore_default) != 0 &&
- strcmp(name, ignore_null) != 0 &&
- strcmp(name, ignore_pulse) != 0 &&
- !talk_base::starts_with(name, ignore_prefix)) {
-
- // Yes, we do.
- char *desc = symbol_table_.snd_device_name_get_hint()(*list, "DESC");
- if (!desc) {
- // Virtual devices don't necessarily have descriptions. Use their names
- // instead (not pretty!).
- desc = name;
- }
-
- AlsaDeviceLocator *device = new AlsaDeviceLocator(desc, name);
-
- devices->push_back(device);
-
- if (desc != name) {
- free(desc);
- }
- }
-
- free(name);
- }
-
- err = symbol_table_.snd_device_name_free_hint()(hints);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_device_name_free_hint(): " << GetError(err);
- // Continue and return true anyways, since we did get the whole list.
- }
-
- return true;
-}
-
-bool AlsaSoundSystem::GetDefaultDevice(SoundDeviceLocator **device) {
- if (!IsInitialized()) {
- return false;
- }
- *device = new AlsaDeviceLocator("Default device", "default");
- return true;
-}
-
-inline size_t AlsaSoundSystem::FrameSize(const OpenParams ¶ms) {
- ASSERT(static_cast<int>(params.format) <
- ARRAY_SIZE(kCricketFormatToSampleSizeTable));
- return kCricketFormatToSampleSizeTable[params.format] * params.channels;
-}
-
-template <typename StreamInterface>
-StreamInterface *AlsaSoundSystem::OpenDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms,
- snd_pcm_stream_t type,
- StreamInterface *(AlsaSoundSystem::*start_fn)(
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq)) {
-
- if (!IsInitialized()) {
- return NULL;
- }
-
- StreamInterface *stream;
- int err;
-
- const char *dev = static_cast<const AlsaDeviceLocator *>(device)->
- device_name().c_str();
-
- snd_pcm_t *handle = NULL;
- err = symbol_table_.snd_pcm_open()(
- &handle,
- dev,
- type,
- // No flags.
- 0);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_open(" << dev << "): " << GetError(err);
- return NULL;
- }
- LOG(LS_VERBOSE) << "Opening " << dev;
- ASSERT(handle); // If open succeeded, handle ought to be valid
-
- // Compute requested latency in microseconds.
- int latency;
- if (params.latency == kNoLatencyRequirements) {
- latency = kDefaultLatencyUsecs;
- } else {
- // kLowLatency is 0, so we treat it the same as a request for zero latency.
- // Compute what the user asked for.
- latency = talk_base::kNumMicrosecsPerSec *
- params.latency /
- params.freq /
- FrameSize(params);
- // And this is what we'll actually use.
- latency = talk_base::_max(latency, kMinimumLatencyUsecs);
- }
-
- ASSERT(static_cast<int>(params.format) <
- ARRAY_SIZE(kCricketFormatToAlsaFormatTable));
-
- err = symbol_table_.snd_pcm_set_params()(
- handle,
- kCricketFormatToAlsaFormatTable[params.format],
- // SoundSystemInterface only supports interleaved audio.
- SND_PCM_ACCESS_RW_INTERLEAVED,
- params.channels,
- params.freq,
- 1, // Allow ALSA to resample.
- latency);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_set_params(): " << GetError(err);
- goto fail;
- }
-
- err = symbol_table_.snd_pcm_prepare()(handle);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_prepare(): " << GetError(err);
- goto fail;
- }
-
- stream = (this->*start_fn)(
- handle,
- FrameSize(params),
- // We set the wait time to twice the requested latency, so that wait
- // timeouts should be rare.
- 2 * latency / talk_base::kNumMicrosecsPerMillisec,
- params.flags,
- params.freq);
- if (stream) {
- return stream;
- }
- // Else fall through.
-
- fail:
- err = symbol_table_.snd_pcm_close()(handle);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_close(): " << GetError(err);
- }
- return NULL;
-}
-
-SoundOutputStreamInterface *AlsaSoundSystem::StartOutputStream(
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq) {
- // Nothing to do here but instantiate the stream.
- return new AlsaOutputStream(
- this, handle, frame_size, wait_timeout_ms, flags, freq);
-}
-
-SoundInputStreamInterface *AlsaSoundSystem::StartInputStream(
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq) {
- // Output streams start automatically once enough data has been written, but
- // input streams must be started manually or else snd_pcm_wait() will never
- // return true.
- int err;
- err = symbol_table_.snd_pcm_start()(handle);
- if (err != 0) {
- LOG(LS_ERROR) << "snd_pcm_start(): " << GetError(err);
- return NULL;
- }
- return new AlsaInputStream(
- this, handle, frame_size, wait_timeout_ms, flags, freq);
-}
-
-inline const char *AlsaSoundSystem::GetError(int err) {
- return symbol_table_.snd_strerror()(err);
-}
-
-} // namespace cricket
diff --git a/sound/alsasoundsystem.h b/sound/alsasoundsystem.h
deleted file mode 100644
index 870f25e..0000000
--- a/sound/alsasoundsystem.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_ALSASOUNDSYSTEM_H_
-#define TALK_SOUND_ALSASOUNDSYSTEM_H_
-
-#include "talk/base/constructormagic.h"
-#include "talk/sound/alsasymboltable.h"
-#include "talk/sound/soundsysteminterface.h"
-
-namespace cricket {
-
-class AlsaStream;
-class AlsaInputStream;
-class AlsaOutputStream;
-
-// Sound system implementation for ALSA, the predominant sound device API on
-// Linux (but typically not used directly by applications anymore).
-class AlsaSoundSystem : public SoundSystemInterface {
- friend class AlsaStream;
- friend class AlsaInputStream;
- friend class AlsaOutputStream;
- public:
- static SoundSystemInterface *Create() {
- return new AlsaSoundSystem();
- }
-
- AlsaSoundSystem();
-
- virtual ~AlsaSoundSystem();
-
- virtual bool Init();
- virtual void Terminate();
-
- virtual bool EnumeratePlaybackDevices(SoundDeviceLocatorList *devices);
- virtual bool EnumerateCaptureDevices(SoundDeviceLocatorList *devices);
-
- virtual bool GetDefaultPlaybackDevice(SoundDeviceLocator **device);
- virtual bool GetDefaultCaptureDevice(SoundDeviceLocator **device);
-
- virtual SoundOutputStreamInterface *OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
- virtual SoundInputStreamInterface *OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
-
- virtual const char *GetName() const;
-
- private:
- bool IsInitialized() { return initialized_; }
-
- bool EnumerateDevices(SoundDeviceLocatorList *devices,
- bool capture_not_playback);
-
- bool GetDefaultDevice(SoundDeviceLocator **device);
-
- static size_t FrameSize(const OpenParams ¶ms);
-
- template <typename StreamInterface>
- StreamInterface *OpenDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms,
- snd_pcm_stream_t type,
- StreamInterface *(AlsaSoundSystem::*start_fn)(
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq));
-
- SoundOutputStreamInterface *StartOutputStream(
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq);
-
- SoundInputStreamInterface *StartInputStream(
- snd_pcm_t *handle,
- size_t frame_size,
- int wait_timeout_ms,
- int flags,
- int freq);
-
- const char *GetError(int err);
-
- bool initialized_;
- AlsaSymbolTable symbol_table_;
-
- DISALLOW_COPY_AND_ASSIGN(AlsaSoundSystem);
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_ALSASOUNDSYSTEM_H_
diff --git a/sound/alsasymboltable.cc b/sound/alsasymboltable.cc
deleted file mode 100644
index 290c729..0000000
--- a/sound/alsasymboltable.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/alsasymboltable.h"
-
-namespace cricket {
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME ALSA_SYMBOLS_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST ALSA_SYMBOLS_LIST
-#define LATE_BINDING_SYMBOL_TABLE_DLL_NAME "libasound.so.2"
-#include "talk/base/latebindingsymboltable.cc.def"
-
-} // namespace cricket
diff --git a/sound/alsasymboltable.h b/sound/alsasymboltable.h
deleted file mode 100644
index cf7803f..0000000
--- a/sound/alsasymboltable.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_ALSASYMBOLTABLE_H_
-#define TALK_SOUND_ALSASYMBOLTABLE_H_
-
-#include <alsa/asoundlib.h>
-
-#include "talk/base/latebindingsymboltable.h"
-
-namespace cricket {
-
-#define ALSA_SYMBOLS_CLASS_NAME AlsaSymbolTable
-// The ALSA symbols we need, as an X-Macro list.
-// This list must contain precisely every libasound function that is used in
-// alsasoundsystem.cc.
-#define ALSA_SYMBOLS_LIST \
- X(snd_device_name_free_hint) \
- X(snd_device_name_get_hint) \
- X(snd_device_name_hint) \
- X(snd_pcm_avail_update) \
- X(snd_pcm_close) \
- X(snd_pcm_delay) \
- X(snd_pcm_drop) \
- X(snd_pcm_open) \
- X(snd_pcm_prepare) \
- X(snd_pcm_readi) \
- X(snd_pcm_recover) \
- X(snd_pcm_set_params) \
- X(snd_pcm_start) \
- X(snd_pcm_stream) \
- X(snd_pcm_wait) \
- X(snd_pcm_writei) \
- X(snd_strerror)
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME ALSA_SYMBOLS_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST ALSA_SYMBOLS_LIST
-#include "talk/base/latebindingsymboltable.h.def"
-
-} // namespace cricket
-
-#endif // TALK_SOUND_ALSASYMBOLTABLE_H_
diff --git a/sound/automaticallychosensoundsystem.h b/sound/automaticallychosensoundsystem.h
deleted file mode 100644
index 026c080..0000000
--- a/sound/automaticallychosensoundsystem.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_AUTOMATICALLYCHOSENSOUNDSYSTEM_H_
-#define TALK_SOUND_AUTOMATICALLYCHOSENSOUNDSYSTEM_H_
-
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/sound/soundsysteminterface.h"
-#include "talk/sound/soundsystemproxy.h"
-
-namespace cricket {
-
-// A function type that creates an instance of a sound system implementation.
-typedef SoundSystemInterface *(*SoundSystemCreator)();
-
-// An AutomaticallyChosenSoundSystem is a sound system proxy that defers to
-// an instance of the first sound system implementation in a list that
-// successfully initializes.
-template <const SoundSystemCreator kSoundSystemCreators[], int kNumSoundSystems>
-class AutomaticallyChosenSoundSystem : public SoundSystemProxy {
- public:
- // Chooses and initializes the underlying sound system.
- virtual bool Init();
- // Terminates the underlying sound system implementation, but caches it for
- // future re-use.
- virtual void Terminate();
-
- virtual const char *GetName() const;
-
- private:
- talk_base::scoped_ptr<SoundSystemInterface> sound_systems_[kNumSoundSystems];
-};
-
-template <const SoundSystemCreator kSoundSystemCreators[], int kNumSoundSystems>
-bool AutomaticallyChosenSoundSystem<kSoundSystemCreators,
- kNumSoundSystems>::Init() {
- if (wrapped_) {
- return true;
- }
- for (int i = 0; i < kNumSoundSystems; ++i) {
- if (!sound_systems_[i].get()) {
- sound_systems_[i].reset((*kSoundSystemCreators[i])());
- }
- if (sound_systems_[i]->Init()) {
- // This is the first sound system in the list to successfully
- // initialize, so we're done.
- wrapped_ = sound_systems_[i].get();
- break;
- }
- // Else it failed to initialize, so try the remaining ones.
- }
- if (!wrapped_) {
- LOG(LS_ERROR) << "Failed to find a usable sound system";
- return false;
- }
- LOG(LS_INFO) << "Selected " << wrapped_->GetName() << " sound system";
- return true;
-}
-
-template <const SoundSystemCreator kSoundSystemCreators[], int kNumSoundSystems>
-void AutomaticallyChosenSoundSystem<kSoundSystemCreators,
- kNumSoundSystems>::Terminate() {
- if (!wrapped_) {
- return;
- }
- wrapped_->Terminate();
- wrapped_ = NULL;
- // We do not free the scoped_ptrs because we may be re-init'ed soon.
-}
-
-template <const SoundSystemCreator kSoundSystemCreators[], int kNumSoundSystems>
-const char *AutomaticallyChosenSoundSystem<kSoundSystemCreators,
- kNumSoundSystems>::GetName() const {
- return wrapped_ ? wrapped_->GetName() : "automatic";
-}
-
-} // namespace cricket
-
-#endif // TALK_SOUND_AUTOMATICALLYCHOSENSOUNDSYSTEM_H_
diff --git a/sound/automaticallychosensoundsystem_unittest.cc b/sound/automaticallychosensoundsystem_unittest.cc
deleted file mode 100644
index a8afeec..0000000
--- a/sound/automaticallychosensoundsystem_unittest.cc
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/base/gunit.h"
-#include "talk/sound/automaticallychosensoundsystem.h"
-#include "talk/sound/nullsoundsystem.h"
-
-namespace cricket {
-
-class NeverFailsToFailSoundSystem : public NullSoundSystem {
- public:
- // Overrides superclass.
- virtual bool Init() {
- return false;
- }
-
- static SoundSystemInterface *Create() {
- return new NeverFailsToFailSoundSystem();
- }
-};
-
-class InitCheckingSoundSystem1 : public NullSoundSystem {
- public:
- // Overrides superclass.
- virtual bool Init() {
- created_ = true;
- return true;
- }
-
- static SoundSystemInterface *Create() {
- return new InitCheckingSoundSystem1();
- }
-
- static bool created_;
-};
-
-bool InitCheckingSoundSystem1::created_ = false;
-
-class InitCheckingSoundSystem2 : public NullSoundSystem {
- public:
- // Overrides superclass.
- virtual bool Init() {
- created_ = true;
- return true;
- }
-
- static SoundSystemInterface *Create() {
- return new InitCheckingSoundSystem2();
- }
-
- static bool created_;
-};
-
-bool InitCheckingSoundSystem2::created_ = false;
-
-class DeletionCheckingSoundSystem1 : public NeverFailsToFailSoundSystem {
- public:
- virtual ~DeletionCheckingSoundSystem1() {
- deleted_ = true;
- }
-
- static SoundSystemInterface *Create() {
- return new DeletionCheckingSoundSystem1();
- }
-
- static bool deleted_;
-};
-
-bool DeletionCheckingSoundSystem1::deleted_ = false;
-
-class DeletionCheckingSoundSystem2 : public NeverFailsToFailSoundSystem {
- public:
- virtual ~DeletionCheckingSoundSystem2() {
- deleted_ = true;
- }
-
- static SoundSystemInterface *Create() {
- return new DeletionCheckingSoundSystem2();
- }
-
- static bool deleted_;
-};
-
-bool DeletionCheckingSoundSystem2::deleted_ = false;
-
-class DeletionCheckingSoundSystem3 : public NullSoundSystem {
- public:
- virtual ~DeletionCheckingSoundSystem3() {
- deleted_ = true;
- }
-
- static SoundSystemInterface *Create() {
- return new DeletionCheckingSoundSystem3();
- }
-
- static bool deleted_;
-};
-
-bool DeletionCheckingSoundSystem3::deleted_ = false;
-
-extern const SoundSystemCreator kSingleSystemFailingCreators[] = {
- &NeverFailsToFailSoundSystem::Create,
-};
-
-TEST(AutomaticallyChosenSoundSystem, SingleSystemFailing) {
- AutomaticallyChosenSoundSystem<
- kSingleSystemFailingCreators,
- ARRAY_SIZE(kSingleSystemFailingCreators)> sound_system;
- EXPECT_FALSE(sound_system.Init());
-}
-
-extern const SoundSystemCreator kSingleSystemSucceedingCreators[] = {
- &NullSoundSystem::Create,
-};
-
-TEST(AutomaticallyChosenSoundSystem, SingleSystemSucceeding) {
- AutomaticallyChosenSoundSystem<
- kSingleSystemSucceedingCreators,
- ARRAY_SIZE(kSingleSystemSucceedingCreators)> sound_system;
- EXPECT_TRUE(sound_system.Init());
-}
-
-extern const SoundSystemCreator
- kFailedFirstSystemResultsInUsingSecondCreators[] = {
- &NeverFailsToFailSoundSystem::Create,
- &NullSoundSystem::Create,
-};
-
-TEST(AutomaticallyChosenSoundSystem, FailedFirstSystemResultsInUsingSecond) {
- AutomaticallyChosenSoundSystem<
- kFailedFirstSystemResultsInUsingSecondCreators,
- ARRAY_SIZE(kFailedFirstSystemResultsInUsingSecondCreators)> sound_system;
- EXPECT_TRUE(sound_system.Init());
-}
-
-extern const SoundSystemCreator kEarlierEntriesHavePriorityCreators[] = {
- &InitCheckingSoundSystem1::Create,
- &InitCheckingSoundSystem2::Create,
-};
-
-TEST(AutomaticallyChosenSoundSystem, EarlierEntriesHavePriority) {
- AutomaticallyChosenSoundSystem<
- kEarlierEntriesHavePriorityCreators,
- ARRAY_SIZE(kEarlierEntriesHavePriorityCreators)> sound_system;
- InitCheckingSoundSystem1::created_ = false;
- InitCheckingSoundSystem2::created_ = false;
- EXPECT_TRUE(sound_system.Init());
- EXPECT_TRUE(InitCheckingSoundSystem1::created_);
- EXPECT_FALSE(InitCheckingSoundSystem2::created_);
-}
-
-extern const SoundSystemCreator kManySoundSystemsCreators[] = {
- &NullSoundSystem::Create,
- &NullSoundSystem::Create,
- &NullSoundSystem::Create,
- &NullSoundSystem::Create,
- &NullSoundSystem::Create,
- &NullSoundSystem::Create,
- &NullSoundSystem::Create,
-};
-
-TEST(AutomaticallyChosenSoundSystem, ManySoundSystems) {
- AutomaticallyChosenSoundSystem<
- kManySoundSystemsCreators,
- ARRAY_SIZE(kManySoundSystemsCreators)> sound_system;
- EXPECT_TRUE(sound_system.Init());
-}
-
-extern const SoundSystemCreator kDeletesAllCreatedSoundSystemsCreators[] = {
- &DeletionCheckingSoundSystem1::Create,
- &DeletionCheckingSoundSystem2::Create,
- &DeletionCheckingSoundSystem3::Create,
-};
-
-TEST(AutomaticallyChosenSoundSystem, DeletesAllCreatedSoundSystems) {
- typedef AutomaticallyChosenSoundSystem<
- kDeletesAllCreatedSoundSystemsCreators,
- ARRAY_SIZE(kDeletesAllCreatedSoundSystemsCreators)> TestSoundSystem;
- TestSoundSystem *sound_system = new TestSoundSystem();
- DeletionCheckingSoundSystem1::deleted_ = false;
- DeletionCheckingSoundSystem2::deleted_ = false;
- DeletionCheckingSoundSystem3::deleted_ = false;
- EXPECT_TRUE(sound_system->Init());
- delete sound_system;
- EXPECT_TRUE(DeletionCheckingSoundSystem1::deleted_);
- EXPECT_TRUE(DeletionCheckingSoundSystem2::deleted_);
- EXPECT_TRUE(DeletionCheckingSoundSystem3::deleted_);
-}
-
-} // namespace cricket
diff --git a/sound/linuxsoundsystem.cc b/sound/linuxsoundsystem.cc
deleted file mode 100644
index 7980a15..0000000
--- a/sound/linuxsoundsystem.cc
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/linuxsoundsystem.h"
-
-#include "talk/sound/alsasoundsystem.h"
-#include "talk/sound/pulseaudiosoundsystem.h"
-
-namespace cricket {
-
-const SoundSystemCreator kLinuxSoundSystemCreators[] = {
-#ifdef HAVE_LIBPULSE
- &PulseAudioSoundSystem::Create,
-#endif
- &AlsaSoundSystem::Create,
-};
-
-} // namespace cricket
diff --git a/sound/linuxsoundsystem.h b/sound/linuxsoundsystem.h
deleted file mode 100644
index eb48b88..0000000
--- a/sound/linuxsoundsystem.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_LINUXSOUNDSYSTEM_H_
-#define TALK_SOUND_LINUXSOUNDSYSTEM_H_
-
-#include "talk/sound/automaticallychosensoundsystem.h"
-
-namespace cricket {
-
-extern const SoundSystemCreator kLinuxSoundSystemCreators[
-#ifdef HAVE_LIBPULSE
- 2
-#else
- 1
-#endif
- ];
-
-// The vast majority of Linux systems use ALSA for the device-level sound API,
-// but an increasing number are using PulseAudio for the application API and
-// only using ALSA internally in PulseAudio itself. But like everything on
-// Linux this is user-configurable, so we need to support both and choose the
-// right one at run-time.
-// PulseAudioSoundSystem is designed to only successfully initialize if
-// PulseAudio is installed and running, and if it is running then direct device
-// access using ALSA typically won't work, so if PulseAudioSoundSystem
-// initializes then we choose that. Otherwise we choose ALSA.
-typedef AutomaticallyChosenSoundSystem<
- kLinuxSoundSystemCreators,
- ARRAY_SIZE(kLinuxSoundSystemCreators)> LinuxSoundSystem;
-
-} // namespace cricket
-
-#endif // TALK_SOUND_LINUXSOUNDSYSTEM_H_
diff --git a/sound/nullsoundsystem.cc b/sound/nullsoundsystem.cc
deleted file mode 100644
index 2920008..0000000
--- a/sound/nullsoundsystem.cc
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/nullsoundsystem.h"
-
-#include "talk/base/logging.h"
-#include "talk/sound/sounddevicelocator.h"
-#include "talk/sound/soundinputstreaminterface.h"
-#include "talk/sound/soundoutputstreaminterface.h"
-
-namespace talk_base {
-
-class Thread;
-
-}
-
-namespace cricket {
-
-// Name used for the single device and the sound system itself.
-static const char kNullName[] = "null";
-
-class NullSoundDeviceLocator : public SoundDeviceLocator {
- public:
- NullSoundDeviceLocator() : SoundDeviceLocator(kNullName, kNullName) {}
-
- virtual SoundDeviceLocator *Copy() const {
- return new NullSoundDeviceLocator();
- }
-};
-
-class NullSoundInputStream : public SoundInputStreamInterface {
- public:
- virtual bool StartReading() {
- return true;
- }
-
- virtual bool StopReading() {
- return true;
- }
-
- virtual bool GetVolume(int *volume) {
- *volume = SoundSystemInterface::kMinVolume;
- return true;
- }
-
- virtual bool SetVolume(int volume) {
- return false;
- }
-
- virtual bool Close() {
- return true;
- }
-
- virtual int LatencyUsecs() {
- return 0;
- }
-};
-
-class NullSoundOutputStream : public SoundOutputStreamInterface {
- public:
- virtual bool EnableBufferMonitoring() {
- return true;
- }
-
- virtual bool DisableBufferMonitoring() {
- return true;
- }
-
- virtual bool WriteSamples(const void *sample_data,
- size_t size) {
- LOG(LS_VERBOSE) << "Got " << size << " bytes of playback samples";
- return true;
- }
-
- virtual bool GetVolume(int *volume) {
- *volume = SoundSystemInterface::kMinVolume;
- return true;
- }
-
- virtual bool SetVolume(int volume) {
- return false;
- }
-
- virtual bool Close() {
- return true;
- }
-
- virtual int LatencyUsecs() {
- return 0;
- }
-};
-
-NullSoundSystem::~NullSoundSystem() {
-}
-
-bool NullSoundSystem::Init() {
- return true;
-}
-
-void NullSoundSystem::Terminate() {
- // Nothing to do.
-}
-
-bool NullSoundSystem::EnumeratePlaybackDevices(
- SoundSystemInterface::SoundDeviceLocatorList *devices) {
- ClearSoundDeviceLocatorList(devices);
- SoundDeviceLocator *device;
- GetDefaultPlaybackDevice(&device);
- devices->push_back(device);
- return true;
-}
-
-bool NullSoundSystem::EnumerateCaptureDevices(
- SoundSystemInterface::SoundDeviceLocatorList *devices) {
- ClearSoundDeviceLocatorList(devices);
- SoundDeviceLocator *device;
- GetDefaultCaptureDevice(&device);
- devices->push_back(device);
- return true;
-}
-
-bool NullSoundSystem::GetDefaultPlaybackDevice(
- SoundDeviceLocator **device) {
- *device = new NullSoundDeviceLocator();
- return true;
-}
-
-bool NullSoundSystem::GetDefaultCaptureDevice(
- SoundDeviceLocator **device) {
- *device = new NullSoundDeviceLocator();
- return true;
-}
-
-SoundOutputStreamInterface *NullSoundSystem::OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return new NullSoundOutputStream();
-}
-
-SoundInputStreamInterface *NullSoundSystem::OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return new NullSoundInputStream();
-}
-
-const char *NullSoundSystem::GetName() const {
- return kNullName;
-}
-
-} // namespace cricket
diff --git a/sound/nullsoundsystem.h b/sound/nullsoundsystem.h
deleted file mode 100644
index 3edb4f9..0000000
--- a/sound/nullsoundsystem.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_NULLSOUNDSYSTEM_H_
-#define TALK_SOUND_NULLSOUNDSYSTEM_H_
-
-#include "talk/sound/soundsysteminterface.h"
-
-namespace cricket {
-
-class SoundDeviceLocator;
-class SoundInputStreamInterface;
-class SoundOutputStreamInterface;
-
-// A simple reference sound system that drops output samples and generates
-// no input samples.
-class NullSoundSystem : public SoundSystemInterface {
- public:
- static SoundSystemInterface *Create() {
- return new NullSoundSystem();
- }
-
- virtual ~NullSoundSystem();
-
- virtual bool Init();
- virtual void Terminate();
-
- virtual bool EnumeratePlaybackDevices(SoundDeviceLocatorList *devices);
- virtual bool EnumerateCaptureDevices(SoundDeviceLocatorList *devices);
-
- virtual SoundOutputStreamInterface *OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
- virtual SoundInputStreamInterface *OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
-
- virtual bool GetDefaultPlaybackDevice(SoundDeviceLocator **device);
- virtual bool GetDefaultCaptureDevice(SoundDeviceLocator **device);
-
- virtual const char *GetName() const;
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_NULLSOUNDSYSTEM_H_
diff --git a/sound/nullsoundsystemfactory.cc b/sound/nullsoundsystemfactory.cc
deleted file mode 100644
index 089d51f..0000000
--- a/sound/nullsoundsystemfactory.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/nullsoundsystemfactory.h"
-
-#include "talk/sound/nullsoundsystem.h"
-
-namespace cricket {
-
-NullSoundSystemFactory::NullSoundSystemFactory() {
-}
-
-NullSoundSystemFactory::~NullSoundSystemFactory() {
-}
-
-bool NullSoundSystemFactory::SetupInstance() {
- instance_.reset(new NullSoundSystem());
- return true;
-}
-
-void NullSoundSystemFactory::CleanupInstance() {
- instance_.reset();
-}
-
-} // namespace cricket
diff --git a/sound/nullsoundsystemfactory.h b/sound/nullsoundsystemfactory.h
deleted file mode 100644
index 71ae980..0000000
--- a/sound/nullsoundsystemfactory.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_NULLSOUNDSYSTEMFACTORY_H_
-#define TALK_SOUND_NULLSOUNDSYSTEMFACTORY_H_
-
-#include "talk/sound/soundsystemfactory.h"
-
-namespace cricket {
-
-// A SoundSystemFactory that always returns a NullSoundSystem. Intended for
-// testing.
-class NullSoundSystemFactory : public SoundSystemFactory {
- public:
- NullSoundSystemFactory();
- virtual ~NullSoundSystemFactory();
-
- protected:
- // Inherited from SoundSystemFactory.
- virtual bool SetupInstance();
- virtual void CleanupInstance();
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_NULLSOUNDSYSTEMFACTORY_H_
diff --git a/sound/platformsoundsystem.cc b/sound/platformsoundsystem.cc
deleted file mode 100644
index 9dff9ae..0000000
--- a/sound/platformsoundsystem.cc
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/platformsoundsystem.h"
-
-#include "talk/base/common.h"
-#ifdef LINUX
-#include "talk/sound/linuxsoundsystem.h"
-#else
-#include "talk/sound/nullsoundsystem.h"
-#endif
-
-namespace cricket {
-
-SoundSystemInterface *CreatePlatformSoundSystem() {
-#ifdef LINUX
- return new LinuxSoundSystem();
-#else
- ASSERT(false && "Not implemented");
- return new NullSoundSystem();
-#endif
-}
-
-} // namespace cricket
diff --git a/sound/platformsoundsystem.h b/sound/platformsoundsystem.h
deleted file mode 100644
index 1a8d214..0000000
--- a/sound/platformsoundsystem.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_PLATFORMSOUNDSYSTEM_H_
-#define TALK_SOUND_PLATFORMSOUNDSYSTEM_H_
-
-namespace cricket {
-
-class SoundSystemInterface;
-
-// Creates the sound system implementation for this platform.
-SoundSystemInterface *CreatePlatformSoundSystem();
-
-} // namespace cricket
-
-#endif // TALK_SOUND_PLATFORMSOUNDSYSTEM_H_
diff --git a/sound/platformsoundsystemfactory.cc b/sound/platformsoundsystemfactory.cc
deleted file mode 100644
index 6c69954..0000000
--- a/sound/platformsoundsystemfactory.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/platformsoundsystemfactory.h"
-
-#include "talk/sound/platformsoundsystem.h"
-#include "talk/sound/soundsysteminterface.h"
-
-namespace cricket {
-
-PlatformSoundSystemFactory::PlatformSoundSystemFactory() {
-}
-
-PlatformSoundSystemFactory::~PlatformSoundSystemFactory() {
-}
-
-bool PlatformSoundSystemFactory::SetupInstance() {
- if (!instance_.get()) {
- instance_.reset(CreatePlatformSoundSystem());
- }
- if (!instance_->Init()) {
- LOG(LS_ERROR) << "Can't initialize platform's sound system";
- return false;
- }
- return true;
-}
-
-void PlatformSoundSystemFactory::CleanupInstance() {
- instance_->Terminate();
- // We do not delete the sound system because we might be re-initialized soon.
-}
-
-} // namespace cricket
diff --git a/sound/platformsoundsystemfactory.h b/sound/platformsoundsystemfactory.h
deleted file mode 100644
index 63ca863..0000000
--- a/sound/platformsoundsystemfactory.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_PLATFORMSOUNDSYSTEMFACTORY_H_
-#define TALK_SOUND_PLATFORMSOUNDSYSTEMFACTORY_H_
-
-#include "talk/sound/soundsystemfactory.h"
-
-namespace cricket {
-
-// A SoundSystemFactory that returns the platform's native sound system
-// implementation.
-class PlatformSoundSystemFactory : public SoundSystemFactory {
- public:
- PlatformSoundSystemFactory();
- virtual ~PlatformSoundSystemFactory();
-
- protected:
- // Inherited from SoundSystemFactory.
- virtual bool SetupInstance();
- virtual void CleanupInstance();
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_PLATFORMSOUNDSYSTEMFACTORY_H_
-
-
diff --git a/sound/pulseaudiosoundsystem.cc b/sound/pulseaudiosoundsystem.cc
deleted file mode 100644
index 7eb690a..0000000
--- a/sound/pulseaudiosoundsystem.cc
+++ /dev/null
@@ -1,1559 +0,0 @@
-/*
- * libjingle
- * Copyright 2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/pulseaudiosoundsystem.h"
-
-#ifdef HAVE_LIBPULSE
-
-#include "talk/base/common.h"
-#include "talk/base/fileutils.h" // for GetApplicationName()
-#include "talk/base/logging.h"
-#include "talk/base/worker.h"
-#include "talk/base/timeutils.h"
-#include "talk/sound/sounddevicelocator.h"
-#include "talk/sound/soundinputstreaminterface.h"
-#include "talk/sound/soundoutputstreaminterface.h"
-
-namespace cricket {
-
-// First PulseAudio protocol version that supports PA_STREAM_ADJUST_LATENCY.
-static const uint32_t kAdjustLatencyProtocolVersion = 13;
-
-// Lookup table from the cricket format enum in soundsysteminterface.h to
-// Pulse's enums.
-static const pa_sample_format_t kCricketFormatToPulseFormatTable[] = {
- // The order here must match the order in soundsysteminterface.h
- PA_SAMPLE_S16LE,
-};
-
-// Some timing constants for optimal operation. See
-// https://tango.0pointer.de/pipermail/pulseaudio-discuss/2008-January/001170.html
-// for a good explanation of some of the factors that go into this.
-
-// Playback.
-
-// For playback, there is a round-trip delay to fill the server-side playback
-// buffer, so setting too low of a latency is a buffer underflow risk. We will
-// automatically increase the latency if a buffer underflow does occur, but we
-// also enforce a sane minimum at start-up time. Anything lower would be
-// virtually guaranteed to underflow at least once, so there's no point in
-// allowing lower latencies.
-static const int kPlaybackLatencyMinimumMsecs = 20;
-// Every time a playback stream underflows, we will reconfigure it with target
-// latency that is greater by this amount.
-static const int kPlaybackLatencyIncrementMsecs = 20;
-// We also need to configure a suitable request size. Too small and we'd burn
-// CPU from the overhead of transfering small amounts of data at once. Too large
-// and the amount of data remaining in the buffer right before refilling it
-// would be a buffer underflow risk. We set it to half of the buffer size.
-static const int kPlaybackRequestFactor = 2;
-
-// Capture.
-
-// For capture, low latency is not a buffer overflow risk, but it makes us burn
-// CPU from the overhead of transfering small amounts of data at once, so we set
-// a recommended value that we use for the kLowLatency constant (but if the user
-// explicitly requests something lower then we will honour it).
-// 1ms takes about 6-7% CPU. 5ms takes about 5%. 10ms takes about 4.x%.
-static const int kLowCaptureLatencyMsecs = 10;
-// There is a round-trip delay to ack the data to the server, so the
-// server-side buffer needs extra space to prevent buffer overflow. 20ms is
-// sufficient, but there is no penalty to making it bigger, so we make it huge.
-// (750ms is libpulse's default value for the _total_ buffer size in the
-// kNoLatencyRequirements case.)
-static const int kCaptureBufferExtraMsecs = 750;
-
-static void FillPlaybackBufferAttr(int latency,
- pa_buffer_attr *attr) {
- attr->maxlength = latency;
- attr->tlength = latency;
- attr->minreq = latency / kPlaybackRequestFactor;
- attr->prebuf = attr->tlength - attr->minreq;
- LOG(LS_VERBOSE) << "Configuring latency = " << attr->tlength << ", minreq = "
- << attr->minreq << ", minfill = " << attr->prebuf;
-}
-
-static pa_volume_t CricketVolumeToPulseVolume(int volume) {
- // PA's volume space goes from 0% at PA_VOLUME_MUTED (value 0) to 100% at
- // PA_VOLUME_NORM (value 0x10000). It can also go beyond 100% up to
- // PA_VOLUME_MAX (value UINT32_MAX-1), but using that is probably unwise.
- // We just linearly map the 0-255 scale of SoundSystemInterface onto
- // PA_VOLUME_MUTED-PA_VOLUME_NORM. If the programmer exceeds kMaxVolume then
- // they can access the over-100% features of PA.
- return PA_VOLUME_MUTED + (PA_VOLUME_NORM - PA_VOLUME_MUTED) *
- volume / SoundSystemInterface::kMaxVolume;
-}
-
-static int PulseVolumeToCricketVolume(pa_volume_t pa_volume) {
- return SoundSystemInterface::kMinVolume +
- (SoundSystemInterface::kMaxVolume - SoundSystemInterface::kMinVolume) *
- pa_volume / PA_VOLUME_NORM;
-}
-
-static pa_volume_t MaxChannelVolume(pa_cvolume *channel_volumes) {
- pa_volume_t pa_volume = PA_VOLUME_MUTED; // Minimum possible value.
- for (int i = 0; i < channel_volumes->channels; ++i) {
- if (pa_volume < channel_volumes->values[i]) {
- pa_volume = channel_volumes->values[i];
- }
- }
- return pa_volume;
-}
-
-class PulseAudioDeviceLocator : public SoundDeviceLocator {
- public:
- PulseAudioDeviceLocator(const std::string &name,
- const std::string &device_name)
- : SoundDeviceLocator(name, device_name) {
- }
-
- virtual SoundDeviceLocator *Copy() const {
- return new PulseAudioDeviceLocator(*this);
- }
-};
-
-// Functionality that is common to both PulseAudioInputStream and
-// PulseAudioOutputStream.
-class PulseAudioStream {
- public:
- PulseAudioStream(PulseAudioSoundSystem *pulse, pa_stream *stream, int flags)
- : pulse_(pulse), stream_(stream), flags_(flags) {
- }
-
- ~PulseAudioStream() {
- // Close() should have been called during the containing class's destructor.
- ASSERT(stream_ == NULL);
- }
-
- // Must be called with the lock held.
- bool Close() {
- if (!IsClosed()) {
- // Unset this here so that we don't get a TERMINATED callback.
- symbol_table()->pa_stream_set_state_callback()(stream_, NULL, NULL);
- if (symbol_table()->pa_stream_disconnect()(stream_) != 0) {
- LOG(LS_ERROR) << "Can't disconnect stream";
- // Continue and return true anyways.
- }
- symbol_table()->pa_stream_unref()(stream_);
- stream_ = NULL;
- }
- return true;
- }
-
- // Must be called with the lock held.
- int LatencyUsecs() {
- if (!(flags_ & SoundSystemInterface::FLAG_REPORT_LATENCY)) {
- return 0;
- }
-
- pa_usec_t latency;
- int negative;
- Lock();
- int re = symbol_table()->pa_stream_get_latency()(stream_, &latency,
- &negative);
- Unlock();
- if (re != 0) {
- LOG(LS_ERROR) << "Can't query latency";
- // We'd rather continue playout/capture with an incorrect delay than stop
- // it altogether, so return a valid value.
- return 0;
- }
- if (negative) {
- // The delay can be negative for monitoring streams if the captured
- // samples haven't been played yet. In such a case, "latency" contains the
- // magnitude, so we must negate it to get the real value.
- return -latency;
- } else {
- return latency;
- }
- }
-
- PulseAudioSoundSystem *pulse() {
- return pulse_;
- }
-
- PulseAudioSymbolTable *symbol_table() {
- return &pulse()->symbol_table_;
- }
-
- pa_stream *stream() {
- ASSERT(stream_ != NULL);
- return stream_;
- }
-
- bool IsClosed() {
- return stream_ == NULL;
- }
-
- void Lock() {
- pulse()->Lock();
- }
-
- void Unlock() {
- pulse()->Unlock();
- }
-
- private:
- PulseAudioSoundSystem *pulse_;
- pa_stream *stream_;
- int flags_;
-
- DISALLOW_COPY_AND_ASSIGN(PulseAudioStream);
-};
-
-// Implementation of an input stream. See soundinputstreaminterface.h regarding
-// thread-safety.
-class PulseAudioInputStream :
- public SoundInputStreamInterface,
- private talk_base::Worker {
-
- struct GetVolumeCallbackData {
- PulseAudioInputStream *instance;
- pa_cvolume *channel_volumes;
- };
-
- struct GetSourceChannelCountCallbackData {
- PulseAudioInputStream *instance;
- uint8_t *channels;
- };
-
- public:
- PulseAudioInputStream(PulseAudioSoundSystem *pulse,
- pa_stream *stream,
- int flags)
- : stream_(pulse, stream, flags),
- temp_sample_data_(NULL),
- temp_sample_data_size_(0) {
- // This callback seems to never be issued, but let's set it anyways.
- symbol_table()->pa_stream_set_overflow_callback()(stream, &OverflowCallback,
- NULL);
- }
-
- virtual ~PulseAudioInputStream() {
- bool success = Close();
- // We need that to live.
- VERIFY(success);
- }
-
- virtual bool StartReading() {
- return StartWork();
- }
-
- virtual bool StopReading() {
- return StopWork();
- }
-
- virtual bool GetVolume(int *volume) {
- bool ret = false;
-
- Lock();
-
- // Unlike output streams, input streams have no concept of a stream volume,
- // only a device volume. So we have to retrieve the volume of the device
- // itself.
-
- pa_cvolume channel_volumes;
-
- GetVolumeCallbackData data;
- data.instance = this;
- data.channel_volumes = &channel_volumes;
-
- pa_operation *op = symbol_table()->pa_context_get_source_info_by_index()(
- stream_.pulse()->context_,
- symbol_table()->pa_stream_get_device_index()(stream_.stream()),
- &GetVolumeCallbackThunk,
- &data);
- if (!stream_.pulse()->FinishOperation(op)) {
- goto done;
- }
-
- if (data.channel_volumes) {
- // This pointer was never unset by the callback, so we must have received
- // an empty list of infos. This probably never happens, but we code for it
- // anyway.
- LOG(LS_ERROR) << "Did not receive GetVolumeCallback";
- goto done;
- }
-
- // We now have the volume for each channel. Each channel could have a
- // different volume if, e.g., the user went and changed the volumes in the
- // PA UI. To get a single volume for SoundSystemInterface we just take the
- // maximum. Ideally we'd do so with pa_cvolume_max, but it doesn't exist in
- // Hardy, so we do it manually.
- pa_volume_t pa_volume;
- pa_volume = MaxChannelVolume(&channel_volumes);
- // Now map onto the SoundSystemInterface range.
- *volume = PulseVolumeToCricketVolume(pa_volume);
-
- ret = true;
- done:
- Unlock();
- return ret;
- }
-
- virtual bool SetVolume(int volume) {
- bool ret = false;
- pa_volume_t pa_volume = CricketVolumeToPulseVolume(volume);
-
- Lock();
-
- // Unlike output streams, input streams have no concept of a stream volume,
- // only a device volume. So we have to change the volume of the device
- // itself.
-
- // The device may have a different number of channels than the stream and
- // their mapping may be different, so we don't want to use the channel count
- // from our sample spec. We could use PA_CHANNELS_MAX to cover our bases,
- // and the server allows that even if the device's channel count is lower,
- // but some buggy PA clients don't like that (the pavucontrol on Hardy dies
- // in an assert if the channel count is different). So instead we look up
- // the actual number of channels that the device has.
-
- uint8_t channels;
-
- GetSourceChannelCountCallbackData data;
- data.instance = this;
- data.channels = &channels;
-
- uint32_t device_index = symbol_table()->pa_stream_get_device_index()(
- stream_.stream());
-
- pa_operation *op = symbol_table()->pa_context_get_source_info_by_index()(
- stream_.pulse()->context_,
- device_index,
- &GetSourceChannelCountCallbackThunk,
- &data);
- if (!stream_.pulse()->FinishOperation(op)) {
- goto done;
- }
-
- if (data.channels) {
- // This pointer was never unset by the callback, so we must have received
- // an empty list of infos. This probably never happens, but we code for it
- // anyway.
- LOG(LS_ERROR) << "Did not receive GetSourceChannelCountCallback";
- goto done;
- }
-
- pa_cvolume channel_volumes;
- symbol_table()->pa_cvolume_set()(&channel_volumes, channels, pa_volume);
-
- op = symbol_table()->pa_context_set_source_volume_by_index()(
- stream_.pulse()->context_,
- device_index,
- &channel_volumes,
- // This callback merely logs errors.
- &SetVolumeCallback,
- NULL);
- if (!op) {
- LOG(LS_ERROR) << "pa_context_set_source_volume_by_index()";
- goto done;
- }
- // Don't need to wait for this to complete.
- symbol_table()->pa_operation_unref()(op);
-
- ret = true;
- done:
- Unlock();
- return ret;
- }
-
- virtual bool Close() {
- if (!StopReading()) {
- return false;
- }
- bool ret = true;
- if (!stream_.IsClosed()) {
- Lock();
- ret = stream_.Close();
- Unlock();
- }
- return ret;
- }
-
- virtual int LatencyUsecs() {
- return stream_.LatencyUsecs();
- }
-
- private:
- void Lock() {
- stream_.Lock();
- }
-
- void Unlock() {
- stream_.Unlock();
- }
-
- PulseAudioSymbolTable *symbol_table() {
- return stream_.symbol_table();
- }
-
- void EnableReadCallback() {
- symbol_table()->pa_stream_set_read_callback()(
- stream_.stream(),
- &ReadCallbackThunk,
- this);
- }
-
- void DisableReadCallback() {
- symbol_table()->pa_stream_set_read_callback()(
- stream_.stream(),
- NULL,
- NULL);
- }
-
- static void ReadCallbackThunk(pa_stream *unused1,
- size_t unused2,
- void *userdata) {
- PulseAudioInputStream *instance =
- static_cast<PulseAudioInputStream *>(userdata);
- instance->OnReadCallback();
- }
-
- void OnReadCallback() {
- // We get the data pointer and size now in order to save one Lock/Unlock
- // on OnMessage.
- if (symbol_table()->pa_stream_peek()(stream_.stream(),
- &temp_sample_data_,
- &temp_sample_data_size_) != 0) {
- LOG(LS_ERROR) << "Can't read data!";
- return;
- }
- // Since we consume the data asynchronously on a different thread, we have
- // to temporarily disable the read callback or else Pulse will call it
- // continuously until we consume the data. We re-enable it below.
- DisableReadCallback();
- HaveWork();
- }
-
- // Inherited from Worker.
- virtual void OnStart() {
- Lock();
- EnableReadCallback();
- Unlock();
- }
-
- // Inherited from Worker.
- virtual void OnHaveWork() {
- ASSERT(temp_sample_data_ && temp_sample_data_size_);
- SignalSamplesRead(temp_sample_data_,
- temp_sample_data_size_,
- this);
- temp_sample_data_ = NULL;
- temp_sample_data_size_ = 0;
-
- Lock();
- for (;;) {
- // Ack the last thing we read.
- if (symbol_table()->pa_stream_drop()(stream_.stream()) != 0) {
- LOG(LS_ERROR) << "Can't ack read data";
- }
-
- if (symbol_table()->pa_stream_readable_size()(stream_.stream()) <= 0) {
- // Then that was all the data.
- break;
- }
-
- // Else more data.
- const void *sample_data;
- size_t sample_data_size;
- if (symbol_table()->pa_stream_peek()(stream_.stream(),
- &sample_data,
- &sample_data_size) != 0) {
- LOG(LS_ERROR) << "Can't read data!";
- break;
- }
-
- // Drop lock for sigslot dispatch, which could take a while.
- Unlock();
- SignalSamplesRead(sample_data, sample_data_size, this);
- Lock();
-
- // Return to top of loop for the ack and the check for more data.
- }
- EnableReadCallback();
- Unlock();
- }
-
- // Inherited from Worker.
- virtual void OnStop() {
- Lock();
- DisableReadCallback();
- Unlock();
- }
-
- static void OverflowCallback(pa_stream *stream,
- void *userdata) {
- LOG(LS_WARNING) << "Buffer overflow on capture stream " << stream;
- }
-
- static void GetVolumeCallbackThunk(pa_context *unused,
- const pa_source_info *info,
- int eol,
- void *userdata) {
- GetVolumeCallbackData *data =
- static_cast<GetVolumeCallbackData *>(userdata);
- data->instance->OnGetVolumeCallback(info, eol, &data->channel_volumes);
- }
-
- void OnGetVolumeCallback(const pa_source_info *info,
- int eol,
- pa_cvolume **channel_volumes) {
- if (eol) {
- // List is over. Wake GetVolume().
- stream_.pulse()->Signal();
- return;
- }
-
- if (*channel_volumes) {
- **channel_volumes = info->volume;
- // Unset the pointer so that we know that we have have already copied the
- // volume.
- *channel_volumes = NULL;
- } else {
- // We have received an additional callback after the first one, which
- // doesn't make sense for a single source. This probably never happens,
- // but we code for it anyway.
- LOG(LS_WARNING) << "Ignoring extra GetVolumeCallback";
- }
- }
-
- static void GetSourceChannelCountCallbackThunk(pa_context *unused,
- const pa_source_info *info,
- int eol,
- void *userdata) {
- GetSourceChannelCountCallbackData *data =
- static_cast<GetSourceChannelCountCallbackData *>(userdata);
- data->instance->OnGetSourceChannelCountCallback(info, eol, &data->channels);
- }
-
- void OnGetSourceChannelCountCallback(const pa_source_info *info,
- int eol,
- uint8_t **channels) {
- if (eol) {
- // List is over. Wake SetVolume().
- stream_.pulse()->Signal();
- return;
- }
-
- if (*channels) {
- **channels = info->channel_map.channels;
- // Unset the pointer so that we know that we have have already copied the
- // channel count.
- *channels = NULL;
- } else {
- // We have received an additional callback after the first one, which
- // doesn't make sense for a single source. This probably never happens,
- // but we code for it anyway.
- LOG(LS_WARNING) << "Ignoring extra GetSourceChannelCountCallback";
- }
- }
-
- static void SetVolumeCallback(pa_context *unused1,
- int success,
- void *unused2) {
- if (!success) {
- LOG(LS_ERROR) << "Failed to change capture volume";
- }
- }
-
- PulseAudioStream stream_;
- // Temporary storage for passing data between threads.
- const void *temp_sample_data_;
- size_t temp_sample_data_size_;
-
- DISALLOW_COPY_AND_ASSIGN(PulseAudioInputStream);
-};
-
-// Implementation of an output stream. See soundoutputstreaminterface.h
-// regarding thread-safety.
-class PulseAudioOutputStream :
- public SoundOutputStreamInterface,
- private talk_base::Worker {
-
- struct GetVolumeCallbackData {
- PulseAudioOutputStream *instance;
- pa_cvolume *channel_volumes;
- };
-
- public:
- PulseAudioOutputStream(PulseAudioSoundSystem *pulse,
- pa_stream *stream,
- int flags,
- int latency)
- : stream_(pulse, stream, flags),
- configured_latency_(latency),
- temp_buffer_space_(0) {
- symbol_table()->pa_stream_set_underflow_callback()(stream,
- &UnderflowCallbackThunk,
- this);
- }
-
- virtual ~PulseAudioOutputStream() {
- bool success = Close();
- // We need that to live.
- VERIFY(success);
- }
-
- virtual bool EnableBufferMonitoring() {
- return StartWork();
- }
-
- virtual bool DisableBufferMonitoring() {
- return StopWork();
- }
-
- virtual bool WriteSamples(const void *sample_data,
- size_t size) {
- bool ret = true;
- Lock();
- if (symbol_table()->pa_stream_write()(stream_.stream(),
- sample_data,
- size,
- NULL,
- 0,
- PA_SEEK_RELATIVE) != 0) {
- LOG(LS_ERROR) << "Unable to write";
- ret = false;
- }
- Unlock();
- return ret;
- }
-
- virtual bool GetVolume(int *volume) {
- bool ret = false;
-
- Lock();
-
- pa_cvolume channel_volumes;
-
- GetVolumeCallbackData data;
- data.instance = this;
- data.channel_volumes = &channel_volumes;
-
- pa_operation *op = symbol_table()->pa_context_get_sink_input_info()(
- stream_.pulse()->context_,
- symbol_table()->pa_stream_get_index()(stream_.stream()),
- &GetVolumeCallbackThunk,
- &data);
- if (!stream_.pulse()->FinishOperation(op)) {
- goto done;
- }
-
- if (data.channel_volumes) {
- // This pointer was never unset by the callback, so we must have received
- // an empty list of infos. This probably never happens, but we code for it
- // anyway.
- LOG(LS_ERROR) << "Did not receive GetVolumeCallback";
- goto done;
- }
-
- // We now have the volume for each channel. Each channel could have a
- // different volume if, e.g., the user went and changed the volumes in the
- // PA UI. To get a single volume for SoundSystemInterface we just take the
- // maximum. Ideally we'd do so with pa_cvolume_max, but it doesn't exist in
- // Hardy, so we do it manually.
- pa_volume_t pa_volume;
- pa_volume = MaxChannelVolume(&channel_volumes);
- // Now map onto the SoundSystemInterface range.
- *volume = PulseVolumeToCricketVolume(pa_volume);
-
- ret = true;
- done:
- Unlock();
- return ret;
- }
-
- virtual bool SetVolume(int volume) {
- bool ret = false;
- pa_volume_t pa_volume = CricketVolumeToPulseVolume(volume);
-
- Lock();
-
- const pa_sample_spec *spec = symbol_table()->pa_stream_get_sample_spec()(
- stream_.stream());
- if (!spec) {
- LOG(LS_ERROR) << "pa_stream_get_sample_spec()";
- goto done;
- }
-
- pa_cvolume channel_volumes;
- symbol_table()->pa_cvolume_set()(&channel_volumes, spec->channels,
- pa_volume);
-
- pa_operation *op;
- op = symbol_table()->pa_context_set_sink_input_volume()(
- stream_.pulse()->context_,
- symbol_table()->pa_stream_get_index()(stream_.stream()),
- &channel_volumes,
- // This callback merely logs errors.
- &SetVolumeCallback,
- NULL);
- if (!op) {
- LOG(LS_ERROR) << "pa_context_set_sink_input_volume()";
- goto done;
- }
- // Don't need to wait for this to complete.
- symbol_table()->pa_operation_unref()(op);
-
- ret = true;
- done:
- Unlock();
- return ret;
- }
-
- virtual bool Close() {
- if (!DisableBufferMonitoring()) {
- return false;
- }
- bool ret = true;
- if (!stream_.IsClosed()) {
- Lock();
- symbol_table()->pa_stream_set_underflow_callback()(stream_.stream(),
- NULL,
- NULL);
- ret = stream_.Close();
- Unlock();
- }
- return ret;
- }
-
- virtual int LatencyUsecs() {
- return stream_.LatencyUsecs();
- }
-
-#if 0
- // TODO: Versions 0.9.16 and later of Pulse have a new API for
- // zero-copy writes, but Hardy is not new enough to have that so we can't
- // rely on it. Perhaps auto-detect if it's present or not and use it if we
- // can?
-
- virtual bool GetWriteBuffer(void **buffer, size_t *size) {
- bool ret = true;
- Lock();
- if (symbol_table()->pa_stream_begin_write()(stream_.stream(), buffer, size)
- != 0) {
- LOG(LS_ERROR) << "Can't get write buffer";
- ret = false;
- }
- Unlock();
- return ret;
- }
-
- // Releases the caller's hold on the write buffer. "written" must be the
- // amount of data that was written.
- virtual bool ReleaseWriteBuffer(void *buffer, size_t written) {
- bool ret = true;
- Lock();
- if (written == 0) {
- if (symbol_table()->pa_stream_cancel_write()(stream_.stream()) != 0) {
- LOG(LS_ERROR) << "Can't cancel write";
- ret = false;
- }
- } else {
- if (symbol_table()->pa_stream_write()(stream_.stream(),
- buffer,
- written,
- NULL,
- 0,
- PA_SEEK_RELATIVE) != 0) {
- LOG(LS_ERROR) << "Unable to write";
- ret = false;
- }
- }
- Unlock();
- return ret;
- }
-#endif
-
- private:
- void Lock() {
- stream_.Lock();
- }
-
- void Unlock() {
- stream_.Unlock();
- }
-
- PulseAudioSymbolTable *symbol_table() {
- return stream_.symbol_table();
- }
-
- void EnableWriteCallback() {
- pa_stream_state_t state = symbol_table()->pa_stream_get_state()(
- stream_.stream());
- if (state == PA_STREAM_READY) {
- // May already have available space. Must check.
- temp_buffer_space_ = symbol_table()->pa_stream_writable_size()(
- stream_.stream());
- if (temp_buffer_space_ > 0) {
- // Yup, there is already space available, so if we register a write
- // callback then it will not receive any event. So dispatch one ourself
- // instead.
- HaveWork();
- return;
- }
- }
- symbol_table()->pa_stream_set_write_callback()(
- stream_.stream(),
- &WriteCallbackThunk,
- this);
- }
-
- void DisableWriteCallback() {
- symbol_table()->pa_stream_set_write_callback()(
- stream_.stream(),
- NULL,
- NULL);
- }
-
- static void WriteCallbackThunk(pa_stream *unused,
- size_t buffer_space,
- void *userdata) {
- PulseAudioOutputStream *instance =
- static_cast<PulseAudioOutputStream *>(userdata);
- instance->OnWriteCallback(buffer_space);
- }
-
- void OnWriteCallback(size_t buffer_space) {
- temp_buffer_space_ = buffer_space;
- // Since we write the data asynchronously on a different thread, we have
- // to temporarily disable the write callback or else Pulse will call it
- // continuously until we write the data. We re-enable it below.
- DisableWriteCallback();
- HaveWork();
- }
-
- // Inherited from Worker.
- virtual void OnStart() {
- Lock();
- EnableWriteCallback();
- Unlock();
- }
-
- // Inherited from Worker.
- virtual void OnHaveWork() {
- ASSERT(temp_buffer_space_ > 0);
-
- SignalBufferSpace(temp_buffer_space_, this);
-
- temp_buffer_space_ = 0;
- Lock();
- EnableWriteCallback();
- Unlock();
- }
-
- // Inherited from Worker.
- virtual void OnStop() {
- Lock();
- DisableWriteCallback();
- Unlock();
- }
-
- static void UnderflowCallbackThunk(pa_stream *unused,
- void *userdata) {
- PulseAudioOutputStream *instance =
- static_cast<PulseAudioOutputStream *>(userdata);
- instance->OnUnderflowCallback();
- }
-
- void OnUnderflowCallback() {
- LOG(LS_WARNING) << "Buffer underflow on playback stream "
- << stream_.stream();
-
- if (configured_latency_ == SoundSystemInterface::kNoLatencyRequirements) {
- // We didn't configure a pa_buffer_attr before, so switching to one now
- // would be questionable.
- return;
- }
-
- // Otherwise reconfigure the stream with a higher target latency.
-
- const pa_sample_spec *spec = symbol_table()->pa_stream_get_sample_spec()(
- stream_.stream());
- if (!spec) {
- LOG(LS_ERROR) << "pa_stream_get_sample_spec()";
- return;
- }
-
- size_t bytes_per_sec = symbol_table()->pa_bytes_per_second()(spec);
-
- int new_latency = configured_latency_ +
- bytes_per_sec * kPlaybackLatencyIncrementMsecs /
- talk_base::kNumMicrosecsPerSec;
-
- pa_buffer_attr new_attr = {0};
- FillPlaybackBufferAttr(new_latency, &new_attr);
-
- pa_operation *op = symbol_table()->pa_stream_set_buffer_attr()(
- stream_.stream(),
- &new_attr,
- // No callback.
- NULL,
- NULL);
- if (!op) {
- LOG(LS_ERROR) << "pa_stream_set_buffer_attr()";
- return;
- }
- // Don't need to wait for this to complete.
- symbol_table()->pa_operation_unref()(op);
-
- // Save the new latency in case we underflow again.
- configured_latency_ = new_latency;
- }
-
- static void GetVolumeCallbackThunk(pa_context *unused,
- const pa_sink_input_info *info,
- int eol,
- void *userdata) {
- GetVolumeCallbackData *data =
- static_cast<GetVolumeCallbackData *>(userdata);
- data->instance->OnGetVolumeCallback(info, eol, &data->channel_volumes);
- }
-
- void OnGetVolumeCallback(const pa_sink_input_info *info,
- int eol,
- pa_cvolume **channel_volumes) {
- if (eol) {
- // List is over. Wake GetVolume().
- stream_.pulse()->Signal();
- return;
- }
-
- if (*channel_volumes) {
- **channel_volumes = info->volume;
- // Unset the pointer so that we know that we have have already copied the
- // volume.
- *channel_volumes = NULL;
- } else {
- // We have received an additional callback after the first one, which
- // doesn't make sense for a single sink input. This probably never
- // happens, but we code for it anyway.
- LOG(LS_WARNING) << "Ignoring extra GetVolumeCallback";
- }
- }
-
- static void SetVolumeCallback(pa_context *unused1,
- int success,
- void *unused2) {
- if (!success) {
- LOG(LS_ERROR) << "Failed to change playback volume";
- }
- }
-
- PulseAudioStream stream_;
- int configured_latency_;
- // Temporary storage for passing data between threads.
- size_t temp_buffer_space_;
-
- DISALLOW_COPY_AND_ASSIGN(PulseAudioOutputStream);
-};
-
-PulseAudioSoundSystem::PulseAudioSoundSystem()
- : mainloop_(NULL), context_(NULL) {
-}
-
-PulseAudioSoundSystem::~PulseAudioSoundSystem() {
- Terminate();
-}
-
-bool PulseAudioSoundSystem::Init() {
- if (IsInitialized()) {
- return true;
- }
-
- // Load libpulse.
- if (!symbol_table_.Load()) {
- // Most likely the Pulse library and sound server are not installed on
- // this system.
- LOG(LS_WARNING) << "Failed to load symbol table";
- return false;
- }
-
- // Now create and start the Pulse event thread.
- mainloop_ = symbol_table_.pa_threaded_mainloop_new()();
- if (!mainloop_) {
- LOG(LS_ERROR) << "Can't create mainloop";
- goto fail0;
- }
-
- if (symbol_table_.pa_threaded_mainloop_start()(mainloop_) != 0) {
- LOG(LS_ERROR) << "Can't start mainloop";
- goto fail1;
- }
-
- Lock();
- context_ = CreateNewConnection();
- Unlock();
-
- if (!context_) {
- goto fail2;
- }
-
- // Otherwise we're now ready!
- return true;
-
- fail2:
- symbol_table_.pa_threaded_mainloop_stop()(mainloop_);
- fail1:
- symbol_table_.pa_threaded_mainloop_free()(mainloop_);
- mainloop_ = NULL;
- fail0:
- return false;
-}
-
-void PulseAudioSoundSystem::Terminate() {
- if (!IsInitialized()) {
- return;
- }
-
- Lock();
- symbol_table_.pa_context_disconnect()(context_);
- symbol_table_.pa_context_unref()(context_);
- Unlock();
- context_ = NULL;
- symbol_table_.pa_threaded_mainloop_stop()(mainloop_);
- symbol_table_.pa_threaded_mainloop_free()(mainloop_);
- mainloop_ = NULL;
-
- // We do not unload the symbol table because we may need it again soon if
- // Init() is called again.
-}
-
-bool PulseAudioSoundSystem::EnumeratePlaybackDevices(
- SoundDeviceLocatorList *devices) {
- return EnumerateDevices<pa_sink_info>(
- devices,
- symbol_table_.pa_context_get_sink_info_list(),
- &EnumeratePlaybackDevicesCallbackThunk);
-}
-
-bool PulseAudioSoundSystem::EnumerateCaptureDevices(
- SoundDeviceLocatorList *devices) {
- return EnumerateDevices<pa_source_info>(
- devices,
- symbol_table_.pa_context_get_source_info_list(),
- &EnumerateCaptureDevicesCallbackThunk);
-}
-
-bool PulseAudioSoundSystem::GetDefaultPlaybackDevice(
- SoundDeviceLocator **device) {
- return GetDefaultDevice<&pa_server_info::default_sink_name>(device);
-}
-
-bool PulseAudioSoundSystem::GetDefaultCaptureDevice(
- SoundDeviceLocator **device) {
- return GetDefaultDevice<&pa_server_info::default_source_name>(device);
-}
-
-SoundOutputStreamInterface *PulseAudioSoundSystem::OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return OpenDevice<SoundOutputStreamInterface>(
- device,
- params,
- "Playback",
- &PulseAudioSoundSystem::ConnectOutputStream);
-}
-
-SoundInputStreamInterface *PulseAudioSoundSystem::OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return OpenDevice<SoundInputStreamInterface>(
- device,
- params,
- "Capture",
- &PulseAudioSoundSystem::ConnectInputStream);
-}
-
-const char *PulseAudioSoundSystem::GetName() const {
- return "PulseAudio";
-}
-
-inline bool PulseAudioSoundSystem::IsInitialized() {
- return mainloop_ != NULL;
-}
-
-struct ConnectToPulseCallbackData {
- PulseAudioSoundSystem *instance;
- bool connect_done;
-};
-
-void PulseAudioSoundSystem::ConnectToPulseCallbackThunk(
- pa_context *context, void *userdata) {
- ConnectToPulseCallbackData *data =
- static_cast<ConnectToPulseCallbackData *>(userdata);
- data->instance->OnConnectToPulseCallback(context, &data->connect_done);
-}
-
-void PulseAudioSoundSystem::OnConnectToPulseCallback(
- pa_context *context, bool *connect_done) {
- pa_context_state_t state = symbol_table_.pa_context_get_state()(context);
- if (state == PA_CONTEXT_READY ||
- state == PA_CONTEXT_FAILED ||
- state == PA_CONTEXT_TERMINATED) {
- // Connection process has reached a terminal state. Wake ConnectToPulse().
- *connect_done = true;
- Signal();
- }
-}
-
-// Must be called with the lock held.
-bool PulseAudioSoundSystem::ConnectToPulse(pa_context *context) {
- bool ret = true;
- ConnectToPulseCallbackData data;
- // Have to put this up here to satisfy the compiler.
- pa_context_state_t state;
-
- data.instance = this;
- data.connect_done = false;
-
- symbol_table_.pa_context_set_state_callback()(context,
- &ConnectToPulseCallbackThunk,
- &data);
-
- // Connect to PulseAudio sound server.
- if (symbol_table_.pa_context_connect()(
- context,
- NULL, // Default server
- PA_CONTEXT_NOAUTOSPAWN,
- NULL) != 0) { // No special fork handling needed
- LOG(LS_ERROR) << "Can't start connection to PulseAudio sound server";
- ret = false;
- goto done;
- }
-
- // Wait for the connection state machine to reach a terminal state.
- do {
- Wait();
- } while (!data.connect_done);
-
- // Now check to see what final state we reached.
- state = symbol_table_.pa_context_get_state()(context);
-
- if (state != PA_CONTEXT_READY) {
- if (state == PA_CONTEXT_FAILED) {
- LOG(LS_ERROR) << "Failed to connect to PulseAudio sound server";
- } else if (state == PA_CONTEXT_TERMINATED) {
- LOG(LS_ERROR) << "PulseAudio connection terminated early";
- } else {
- // Shouldn't happen, because we only signal on one of those three states.
- LOG(LS_ERROR) << "Unknown problem connecting to PulseAudio";
- }
- ret = false;
- }
-
- done:
- // We unset our callback for safety just in case the state might somehow
- // change later, because the pointer to "data" will be invalid after return
- // from this function.
- symbol_table_.pa_context_set_state_callback()(context, NULL, NULL);
- return ret;
-}
-
-// Must be called with the lock held.
-pa_context *PulseAudioSoundSystem::CreateNewConnection() {
- // Create connection context.
- std::string app_name;
- // TODO: Pulse etiquette says this name should be localized. Do
- // we care?
- talk_base::Filesystem::GetApplicationName(&app_name);
- pa_context *context = symbol_table_.pa_context_new()(
- symbol_table_.pa_threaded_mainloop_get_api()(mainloop_),
- app_name.c_str());
- if (!context) {
- LOG(LS_ERROR) << "Can't create context";
- goto fail0;
- }
-
- // Now connect.
- if (!ConnectToPulse(context)) {
- goto fail1;
- }
-
- // Otherwise the connection succeeded and is ready.
- return context;
-
- fail1:
- symbol_table_.pa_context_unref()(context);
- fail0:
- return NULL;
-}
-
-struct EnumerateDevicesCallbackData {
- PulseAudioSoundSystem *instance;
- SoundSystemInterface::SoundDeviceLocatorList *devices;
-};
-
-void PulseAudioSoundSystem::EnumeratePlaybackDevicesCallbackThunk(
- pa_context *unused,
- const pa_sink_info *info,
- int eol,
- void *userdata) {
- EnumerateDevicesCallbackData *data =
- static_cast<EnumerateDevicesCallbackData *>(userdata);
- data->instance->OnEnumeratePlaybackDevicesCallback(data->devices, info, eol);
-}
-
-void PulseAudioSoundSystem::EnumerateCaptureDevicesCallbackThunk(
- pa_context *unused,
- const pa_source_info *info,
- int eol,
- void *userdata) {
- EnumerateDevicesCallbackData *data =
- static_cast<EnumerateDevicesCallbackData *>(userdata);
- data->instance->OnEnumerateCaptureDevicesCallback(data->devices, info, eol);
-}
-
-void PulseAudioSoundSystem::OnEnumeratePlaybackDevicesCallback(
- SoundDeviceLocatorList *devices,
- const pa_sink_info *info,
- int eol) {
- if (eol) {
- // List is over. Wake EnumerateDevices().
- Signal();
- return;
- }
-
- // Else this is the next device.
- devices->push_back(
- new PulseAudioDeviceLocator(info->description, info->name));
-}
-
-void PulseAudioSoundSystem::OnEnumerateCaptureDevicesCallback(
- SoundDeviceLocatorList *devices,
- const pa_source_info *info,
- int eol) {
- if (eol) {
- // List is over. Wake EnumerateDevices().
- Signal();
- return;
- }
-
- if (info->monitor_of_sink != PA_INVALID_INDEX) {
- // We don't want to list monitor sources, since they are almost certainly
- // not what the user wants for voice conferencing.
- return;
- }
-
- // Else this is the next device.
- devices->push_back(
- new PulseAudioDeviceLocator(info->description, info->name));
-}
-
-template <typename InfoStruct>
-bool PulseAudioSoundSystem::EnumerateDevices(
- SoundDeviceLocatorList *devices,
- pa_operation *(*enumerate_fn)(
- pa_context *c,
- void (*callback_fn)(
- pa_context *c,
- const InfoStruct *i,
- int eol,
- void *userdata),
- void *userdata),
- void (*callback_fn)(
- pa_context *c,
- const InfoStruct *i,
- int eol,
- void *userdata)) {
- ClearSoundDeviceLocatorList(devices);
- if (!IsInitialized()) {
- return false;
- }
-
- EnumerateDevicesCallbackData data;
- data.instance = this;
- data.devices = devices;
-
- Lock();
- pa_operation *op = (*enumerate_fn)(
- context_,
- callback_fn,
- &data);
- bool ret = FinishOperation(op);
- Unlock();
- return ret;
-}
-
-struct GetDefaultDeviceCallbackData {
- PulseAudioSoundSystem *instance;
- SoundDeviceLocator **device;
-};
-
-template <const char *(pa_server_info::*field)>
-void PulseAudioSoundSystem::GetDefaultDeviceCallbackThunk(
- pa_context *unused,
- const pa_server_info *info,
- void *userdata) {
- GetDefaultDeviceCallbackData *data =
- static_cast<GetDefaultDeviceCallbackData *>(userdata);
- data->instance->OnGetDefaultDeviceCallback<field>(info, data->device);
-}
-
-template <const char *(pa_server_info::*field)>
-void PulseAudioSoundSystem::OnGetDefaultDeviceCallback(
- const pa_server_info *info,
- SoundDeviceLocator **device) {
- if (info) {
- const char *dev = info->*field;
- if (dev) {
- *device = new PulseAudioDeviceLocator("Default device", dev);
- }
- }
- Signal();
-}
-
-template <const char *(pa_server_info::*field)>
-bool PulseAudioSoundSystem::GetDefaultDevice(SoundDeviceLocator **device) {
- if (!IsInitialized()) {
- return false;
- }
- bool ret;
- *device = NULL;
- GetDefaultDeviceCallbackData data;
- data.instance = this;
- data.device = device;
- Lock();
- pa_operation *op = symbol_table_.pa_context_get_server_info()(
- context_,
- &GetDefaultDeviceCallbackThunk<field>,
- &data);
- ret = FinishOperation(op);
- Unlock();
- return ret && (*device != NULL);
-}
-
-void PulseAudioSoundSystem::StreamStateChangedCallbackThunk(
- pa_stream *stream,
- void *userdata) {
- PulseAudioSoundSystem *instance =
- static_cast<PulseAudioSoundSystem *>(userdata);
- instance->OnStreamStateChangedCallback(stream);
-}
-
-void PulseAudioSoundSystem::OnStreamStateChangedCallback(pa_stream *stream) {
- pa_stream_state_t state = symbol_table_.pa_stream_get_state()(stream);
- if (state == PA_STREAM_READY) {
- LOG(LS_INFO) << "Pulse stream " << stream << " ready";
- } else if (state == PA_STREAM_FAILED ||
- state == PA_STREAM_TERMINATED ||
- state == PA_STREAM_UNCONNECTED) {
- LOG(LS_ERROR) << "Pulse stream " << stream << " failed to connect: "
- << LastError();
- }
-}
-
-template <typename StreamInterface>
-StreamInterface *PulseAudioSoundSystem::OpenDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms,
- const char *stream_name,
- StreamInterface *(PulseAudioSoundSystem::*connect_fn)(
- pa_stream *stream,
- const char *dev,
- int flags,
- pa_stream_flags_t pa_flags,
- int latency,
- const pa_sample_spec &spec)) {
- if (!IsInitialized()) {
- return NULL;
- }
-
- const char *dev = static_cast<const PulseAudioDeviceLocator *>(device)->
- device_name().c_str();
-
- StreamInterface *stream_interface = NULL;
-
- ASSERT(params.format < ARRAY_SIZE(kCricketFormatToPulseFormatTable));
-
- pa_sample_spec spec;
- spec.format = kCricketFormatToPulseFormatTable[params.format];
- spec.rate = params.freq;
- spec.channels = params.channels;
-
- int pa_flags = 0;
- if (params.flags & FLAG_REPORT_LATENCY) {
- pa_flags |= PA_STREAM_INTERPOLATE_TIMING |
- PA_STREAM_AUTO_TIMING_UPDATE;
- }
-
- if (params.latency != kNoLatencyRequirements) {
- // If configuring a specific latency then we want to specify
- // PA_STREAM_ADJUST_LATENCY to make the server adjust parameters
- // automatically to reach that target latency. However, that flag doesn't
- // exist in Ubuntu 8.04 and many people still use that, so we have to check
- // the protocol version of libpulse.
- if (symbol_table_.pa_context_get_protocol_version()(context_) >=
- kAdjustLatencyProtocolVersion) {
- pa_flags |= PA_STREAM_ADJUST_LATENCY;
- }
- }
-
- Lock();
-
- pa_stream *stream = symbol_table_.pa_stream_new()(context_, stream_name,
- &spec, NULL);
- if (!stream) {
- LOG(LS_ERROR) << "Can't create pa_stream";
- goto done;
- }
-
- // Set a state callback to log errors.
- symbol_table_.pa_stream_set_state_callback()(stream,
- &StreamStateChangedCallbackThunk,
- this);
-
- stream_interface = (this->*connect_fn)(
- stream,
- dev,
- params.flags,
- static_cast<pa_stream_flags_t>(pa_flags),
- params.latency,
- spec);
- if (!stream_interface) {
- LOG(LS_ERROR) << "Can't connect stream to " << dev;
- symbol_table_.pa_stream_unref()(stream);
- }
-
- done:
- Unlock();
- return stream_interface;
-}
-
-// Must be called with the lock held.
-SoundOutputStreamInterface *PulseAudioSoundSystem::ConnectOutputStream(
- pa_stream *stream,
- const char *dev,
- int flags,
- pa_stream_flags_t pa_flags,
- int latency,
- const pa_sample_spec &spec) {
- pa_buffer_attr attr = {0};
- pa_buffer_attr *pattr = NULL;
- if (latency != kNoLatencyRequirements) {
- // kLowLatency is 0, so we treat it the same as a request for zero latency.
- ssize_t bytes_per_sec = symbol_table_.pa_bytes_per_second()(&spec);
- latency = talk_base::_max(
- latency,
- static_cast<int>(
- bytes_per_sec * kPlaybackLatencyMinimumMsecs /
- talk_base::kNumMicrosecsPerSec));
- FillPlaybackBufferAttr(latency, &attr);
- pattr = &attr;
- }
- if (symbol_table_.pa_stream_connect_playback()(
- stream,
- dev,
- pattr,
- pa_flags,
- // Let server choose volume
- NULL,
- // Not synchronized to any other playout
- NULL) != 0) {
- return NULL;
- }
- return new PulseAudioOutputStream(this, stream, flags, latency);
-}
-
-// Must be called with the lock held.
-SoundInputStreamInterface *PulseAudioSoundSystem::ConnectInputStream(
- pa_stream *stream,
- const char *dev,
- int flags,
- pa_stream_flags_t pa_flags,
- int latency,
- const pa_sample_spec &spec) {
- pa_buffer_attr attr = {0};
- pa_buffer_attr *pattr = NULL;
- if (latency != kNoLatencyRequirements) {
- size_t bytes_per_sec = symbol_table_.pa_bytes_per_second()(&spec);
- if (latency == kLowLatency) {
- latency = bytes_per_sec * kLowCaptureLatencyMsecs /
- talk_base::kNumMicrosecsPerSec;
- }
- // Note: fragsize specifies a maximum transfer size, not a minimum, so it is
- // not possible to force a high latency setting, only a low one.
- attr.fragsize = latency;
- attr.maxlength = latency + bytes_per_sec * kCaptureBufferExtraMsecs /
- talk_base::kNumMicrosecsPerSec;
- LOG(LS_VERBOSE) << "Configuring latency = " << attr.fragsize
- << ", maxlength = " << attr.maxlength;
- pattr = &attr;
- }
- if (symbol_table_.pa_stream_connect_record()(stream,
- dev,
- pattr,
- pa_flags) != 0) {
- return NULL;
- }
- return new PulseAudioInputStream(this, stream, flags);
-}
-
-// Must be called with the lock held.
-bool PulseAudioSoundSystem::FinishOperation(pa_operation *op) {
- if (!op) {
- LOG(LS_ERROR) << "Failed to start operation";
- return false;
- }
-
- do {
- Wait();
- } while (symbol_table_.pa_operation_get_state()(op) == PA_OPERATION_RUNNING);
-
- symbol_table_.pa_operation_unref()(op);
-
- return true;
-}
-
-inline void PulseAudioSoundSystem::Lock() {
- symbol_table_.pa_threaded_mainloop_lock()(mainloop_);
-}
-
-inline void PulseAudioSoundSystem::Unlock() {
- symbol_table_.pa_threaded_mainloop_unlock()(mainloop_);
-}
-
-// Must be called with the lock held.
-inline void PulseAudioSoundSystem::Wait() {
- symbol_table_.pa_threaded_mainloop_wait()(mainloop_);
-}
-
-// Must be called with the lock held.
-inline void PulseAudioSoundSystem::Signal() {
- symbol_table_.pa_threaded_mainloop_signal()(mainloop_, 0);
-}
-
-// Must be called with the lock held.
-const char *PulseAudioSoundSystem::LastError() {
- return symbol_table_.pa_strerror()(symbol_table_.pa_context_errno()(
- context_));
-}
-
-} // namespace cricket
-
-#endif // HAVE_LIBPULSE
diff --git a/sound/pulseaudiosoundsystem.h b/sound/pulseaudiosoundsystem.h
deleted file mode 100644
index 8a9fe49..0000000
--- a/sound/pulseaudiosoundsystem.h
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_PULSEAUDIOSOUNDSYSTEM_H_
-#define TALK_SOUND_PULSEAUDIOSOUNDSYSTEM_H_
-
-#ifdef HAVE_LIBPULSE
-
-#include "talk/base/constructormagic.h"
-#include "talk/sound/pulseaudiosymboltable.h"
-#include "talk/sound/soundsysteminterface.h"
-
-namespace cricket {
-
-class PulseAudioInputStream;
-class PulseAudioOutputStream;
-class PulseAudioStream;
-
-// Sound system implementation for PulseAudio, a cross-platform sound server
-// (but commonly used only on Linux, which is the only platform we support
-// it on).
-// Init(), Terminate(), and the destructor should never be invoked concurrently,
-// but all other methods are thread-safe.
-class PulseAudioSoundSystem : public SoundSystemInterface {
- friend class PulseAudioInputStream;
- friend class PulseAudioOutputStream;
- friend class PulseAudioStream;
- public:
- static SoundSystemInterface *Create() {
- return new PulseAudioSoundSystem();
- }
-
- PulseAudioSoundSystem();
-
- virtual ~PulseAudioSoundSystem();
-
- virtual bool Init();
- virtual void Terminate();
-
- virtual bool EnumeratePlaybackDevices(SoundDeviceLocatorList *devices);
- virtual bool EnumerateCaptureDevices(SoundDeviceLocatorList *devices);
-
- virtual bool GetDefaultPlaybackDevice(SoundDeviceLocator **device);
- virtual bool GetDefaultCaptureDevice(SoundDeviceLocator **device);
-
- virtual SoundOutputStreamInterface *OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
- virtual SoundInputStreamInterface *OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
-
- virtual const char *GetName() const;
-
- private:
- bool IsInitialized();
-
- static void ConnectToPulseCallbackThunk(pa_context *context, void *userdata);
-
- void OnConnectToPulseCallback(pa_context *context, bool *connect_done);
-
- bool ConnectToPulse(pa_context *context);
-
- pa_context *CreateNewConnection();
-
- template <typename InfoStruct>
- bool EnumerateDevices(SoundDeviceLocatorList *devices,
- pa_operation *(*enumerate_fn)(
- pa_context *c,
- void (*callback_fn)(
- pa_context *c,
- const InfoStruct *i,
- int eol,
- void *userdata),
- void *userdata),
- void (*callback_fn)(
- pa_context *c,
- const InfoStruct *i,
- int eol,
- void *userdata));
-
- static void EnumeratePlaybackDevicesCallbackThunk(pa_context *unused,
- const pa_sink_info *info,
- int eol,
- void *userdata);
-
- static void EnumerateCaptureDevicesCallbackThunk(pa_context *unused,
- const pa_source_info *info,
- int eol,
- void *userdata);
-
- void OnEnumeratePlaybackDevicesCallback(
- SoundDeviceLocatorList *devices,
- const pa_sink_info *info,
- int eol);
-
- void OnEnumerateCaptureDevicesCallback(
- SoundDeviceLocatorList *devices,
- const pa_source_info *info,
- int eol);
-
- template <const char *(pa_server_info::*field)>
- static void GetDefaultDeviceCallbackThunk(
- pa_context *unused,
- const pa_server_info *info,
- void *userdata);
-
- template <const char *(pa_server_info::*field)>
- void OnGetDefaultDeviceCallback(
- const pa_server_info *info,
- SoundDeviceLocator **device);
-
- template <const char *(pa_server_info::*field)>
- bool GetDefaultDevice(SoundDeviceLocator **device);
-
- static void StreamStateChangedCallbackThunk(pa_stream *stream,
- void *userdata);
-
- void OnStreamStateChangedCallback(pa_stream *stream);
-
- template <typename StreamInterface>
- StreamInterface *OpenDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms,
- const char *stream_name,
- StreamInterface *(PulseAudioSoundSystem::*connect_fn)(
- pa_stream *stream,
- const char *dev,
- int flags,
- pa_stream_flags_t pa_flags,
- int latency,
- const pa_sample_spec &spec));
-
- SoundOutputStreamInterface *ConnectOutputStream(
- pa_stream *stream,
- const char *dev,
- int flags,
- pa_stream_flags_t pa_flags,
- int latency,
- const pa_sample_spec &spec);
-
- SoundInputStreamInterface *ConnectInputStream(
- pa_stream *stream,
- const char *dev,
- int flags,
- pa_stream_flags_t pa_flags,
- int latency,
- const pa_sample_spec &spec);
-
- bool FinishOperation(pa_operation *op);
-
- void Lock();
- void Unlock();
- void Wait();
- void Signal();
-
- const char *LastError();
-
- pa_threaded_mainloop *mainloop_;
- pa_context *context_;
- PulseAudioSymbolTable symbol_table_;
-
- DISALLOW_COPY_AND_ASSIGN(PulseAudioSoundSystem);
-};
-
-} // namespace cricket
-
-#endif // HAVE_LIBPULSE
-
-#endif // TALK_SOUND_PULSEAUDIOSOUNDSYSTEM_H_
diff --git a/sound/pulseaudiosymboltable.cc b/sound/pulseaudiosymboltable.cc
deleted file mode 100644
index 05213ec..0000000
--- a/sound/pulseaudiosymboltable.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_LIBPULSE
-
-#include "talk/sound/pulseaudiosymboltable.h"
-
-namespace cricket {
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME PULSE_AUDIO_SYMBOLS_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST PULSE_AUDIO_SYMBOLS_LIST
-#define LATE_BINDING_SYMBOL_TABLE_DLL_NAME "libpulse.so.0"
-#include "talk/base/latebindingsymboltable.cc.def"
-
-} // namespace cricket
-
-#endif // HAVE_LIBPULSE
diff --git a/sound/pulseaudiosymboltable.h b/sound/pulseaudiosymboltable.h
deleted file mode 100644
index ef65157..0000000
--- a/sound/pulseaudiosymboltable.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_PULSEAUDIOSYMBOLTABLE_H_
-#define TALK_SOUND_PULSEAUDIOSYMBOLTABLE_H_
-
-#include <pulse/context.h>
-#include <pulse/def.h>
-#include <pulse/error.h>
-#include <pulse/introspect.h>
-#include <pulse/stream.h>
-#include <pulse/thread-mainloop.h>
-
-#include "talk/base/latebindingsymboltable.h"
-
-namespace cricket {
-
-#define PULSE_AUDIO_SYMBOLS_CLASS_NAME PulseAudioSymbolTable
-// The PulseAudio symbols we need, as an X-Macro list.
-// This list must contain precisely every libpulse function that is used in
-// pulseaudiosoundsystem.cc.
-#define PULSE_AUDIO_SYMBOLS_LIST \
- X(pa_bytes_per_second) \
- X(pa_context_connect) \
- X(pa_context_disconnect) \
- X(pa_context_errno) \
- X(pa_context_get_protocol_version) \
- X(pa_context_get_server_info) \
- X(pa_context_get_sink_info_list) \
- X(pa_context_get_sink_input_info) \
- X(pa_context_get_source_info_by_index) \
- X(pa_context_get_source_info_list) \
- X(pa_context_get_state) \
- X(pa_context_new) \
- X(pa_context_set_sink_input_volume) \
- X(pa_context_set_source_volume_by_index) \
- X(pa_context_set_state_callback) \
- X(pa_context_unref) \
- X(pa_cvolume_set) \
- X(pa_operation_get_state) \
- X(pa_operation_unref) \
- X(pa_stream_connect_playback) \
- X(pa_stream_connect_record) \
- X(pa_stream_disconnect) \
- X(pa_stream_drop) \
- X(pa_stream_get_device_index) \
- X(pa_stream_get_index) \
- X(pa_stream_get_latency) \
- X(pa_stream_get_sample_spec) \
- X(pa_stream_get_state) \
- X(pa_stream_new) \
- X(pa_stream_peek) \
- X(pa_stream_readable_size) \
- X(pa_stream_set_buffer_attr) \
- X(pa_stream_set_overflow_callback) \
- X(pa_stream_set_read_callback) \
- X(pa_stream_set_state_callback) \
- X(pa_stream_set_underflow_callback) \
- X(pa_stream_set_write_callback) \
- X(pa_stream_unref) \
- X(pa_stream_writable_size) \
- X(pa_stream_write) \
- X(pa_strerror) \
- X(pa_threaded_mainloop_free) \
- X(pa_threaded_mainloop_get_api) \
- X(pa_threaded_mainloop_lock) \
- X(pa_threaded_mainloop_new) \
- X(pa_threaded_mainloop_signal) \
- X(pa_threaded_mainloop_start) \
- X(pa_threaded_mainloop_stop) \
- X(pa_threaded_mainloop_unlock) \
- X(pa_threaded_mainloop_wait)
-
-#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME PULSE_AUDIO_SYMBOLS_CLASS_NAME
-#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST PULSE_AUDIO_SYMBOLS_LIST
-#include "talk/base/latebindingsymboltable.h.def"
-
-} // namespace cricket
-
-#endif // TALK_SOUND_PULSEAUDIOSYMBOLTABLE_H_
diff --git a/sound/sounddevicelocator.h b/sound/sounddevicelocator.h
deleted file mode 100644
index e0a8970..0000000
--- a/sound/sounddevicelocator.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_SOUNDDEVICELOCATOR_H_
-#define TALK_SOUND_SOUNDDEVICELOCATOR_H_
-
-#include <string>
-
-#include "talk/base/constructormagic.h"
-
-namespace cricket {
-
-// A simple container for holding the name of a device and any additional id
-// information needed to locate and open it. Implementations of
-// SoundSystemInterface must subclass this to add any id information that they
-// need.
-class SoundDeviceLocator {
- public:
- virtual ~SoundDeviceLocator() {}
-
- // Human-readable name for the device.
- const std::string &name() const { return name_; }
-
- // Name sound system uses to locate this device.
- const std::string &device_name() const { return device_name_; }
-
- // Makes a duplicate of this locator.
- virtual SoundDeviceLocator *Copy() const = 0;
-
- protected:
- SoundDeviceLocator(const std::string &name,
- const std::string &device_name)
- : name_(name), device_name_(device_name) {}
-
- explicit SoundDeviceLocator(const SoundDeviceLocator &that)
- : name_(that.name_), device_name_(that.device_name_) {}
-
- std::string name_;
- std::string device_name_;
-
- private:
- DISALLOW_ASSIGN(SoundDeviceLocator);
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_SOUNDDEVICELOCATOR_H_
diff --git a/sound/soundinputstreaminterface.h b/sound/soundinputstreaminterface.h
deleted file mode 100644
index de831a6..0000000
--- a/sound/soundinputstreaminterface.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_SOUNDINPUTSTREAMINTERFACE_H_
-#define TALK_SOUND_SOUNDINPUTSTREAMINTERFACE_H_
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/sigslot.h"
-
-namespace cricket {
-
-// Interface for consuming an input stream from a recording device.
-// Semantics and thread-safety of StartReading()/StopReading() are the same as
-// for talk_base::Worker.
-class SoundInputStreamInterface {
- public:
- virtual ~SoundInputStreamInterface() {}
-
- // Starts the reading of samples on the current thread.
- virtual bool StartReading() = 0;
- // Stops the reading of samples.
- virtual bool StopReading() = 0;
-
- // Retrieves the current input volume for this stream. Nominal range is
- // defined by SoundSystemInterface::k(Max|Min)Volume, but values exceeding the
- // max may be possible in some implementations. This call retrieves the actual
- // volume currently in use by the OS, not a cached value from a previous
- // (Get|Set)Volume() call.
- virtual bool GetVolume(int *volume) = 0;
-
- // Changes the input volume for this stream. Nominal range is defined by
- // SoundSystemInterface::k(Max|Min)Volume. The effect of exceeding kMaxVolume
- // is implementation-defined.
- virtual bool SetVolume(int volume) = 0;
-
- // Closes this stream object. If currently reading then this may only be
- // called from the reading thread.
- virtual bool Close() = 0;
-
- // Get the latency of the stream.
- virtual int LatencyUsecs() = 0;
-
- // Notifies the consumer of new data read from the device.
- // The first parameter is a pointer to the data read, and is only valid for
- // the duration of the call.
- // The second parameter is the amount of data read in bytes (i.e., the valid
- // length of the memory pointed to).
- // The 3rd parameter is the stream that is issuing the callback.
- sigslot::signal3<const void *, size_t,
- SoundInputStreamInterface *> SignalSamplesRead;
-
- protected:
- SoundInputStreamInterface() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SoundInputStreamInterface);
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_SOUNDOUTPUTSTREAMINTERFACE_H_
diff --git a/sound/soundoutputstreaminterface.h b/sound/soundoutputstreaminterface.h
deleted file mode 100644
index d096ba3..0000000
--- a/sound/soundoutputstreaminterface.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_SOUNDOUTPUTSTREAMINTERFACE_H_
-#define TALK_SOUND_SOUNDOUTPUTSTREAMINTERFACE_H_
-
-#include "talk/base/constructormagic.h"
-#include "talk/base/sigslot.h"
-
-namespace cricket {
-
-// Interface for outputting a stream to a playback device.
-// Semantics and thread-safety of EnableBufferMonitoring()/
-// DisableBufferMonitoring() are the same as for talk_base::Worker.
-class SoundOutputStreamInterface {
- public:
- virtual ~SoundOutputStreamInterface() {}
-
- // Enables monitoring the available buffer space on the current thread.
- virtual bool EnableBufferMonitoring() = 0;
- // Disables the monitoring.
- virtual bool DisableBufferMonitoring() = 0;
-
- // Write the given samples to the devices. If currently monitoring then this
- // may only be called from the monitoring thread.
- virtual bool WriteSamples(const void *sample_data,
- size_t size) = 0;
-
- // Retrieves the current output volume for this stream. Nominal range is
- // defined by SoundSystemInterface::k(Max|Min)Volume, but values exceeding the
- // max may be possible in some implementations. This call retrieves the actual
- // volume currently in use by the OS, not a cached value from a previous
- // (Get|Set)Volume() call.
- virtual bool GetVolume(int *volume) = 0;
-
- // Changes the output volume for this stream. Nominal range is defined by
- // SoundSystemInterface::k(Max|Min)Volume. The effect of exceeding kMaxVolume
- // is implementation-defined.
- virtual bool SetVolume(int volume) = 0;
-
- // Closes this stream object. If currently monitoring then this may only be
- // called from the monitoring thread.
- virtual bool Close() = 0;
-
- // Get the latency of the stream.
- virtual int LatencyUsecs() = 0;
-
- // Notifies the producer of the available buffer space for writes.
- // It fires continuously as long as the space is greater than zero.
- // The first parameter is the amount of buffer space available for data to
- // be written (i.e., the maximum amount of data that can be written right now
- // with WriteSamples() without blocking).
- // The 2nd parameter is the stream that is issuing the callback.
- sigslot::signal2<size_t, SoundOutputStreamInterface *> SignalBufferSpace;
-
- protected:
- SoundOutputStreamInterface() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SoundOutputStreamInterface);
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_SOUNDOUTPUTSTREAMINTERFACE_H_
diff --git a/sound/soundsystemfactory.h b/sound/soundsystemfactory.h
deleted file mode 100644
index 517220b..0000000
--- a/sound/soundsystemfactory.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_SOUNDSYSTEMFACTORY_H_
-#define TALK_SOUND_SOUNDSYSTEMFACTORY_H_
-
-#include "talk/base/referencecountedsingletonfactory.h"
-
-namespace cricket {
-
-class SoundSystemInterface;
-
-typedef talk_base::ReferenceCountedSingletonFactory<SoundSystemInterface>
- SoundSystemFactory;
-
-typedef talk_base::rcsf_ptr<SoundSystemInterface> SoundSystemHandle;
-
-} // namespace cricket
-
-#endif // TALK_SOUND_SOUNDSYSTEMFACTORY_H_
diff --git a/sound/soundsysteminterface.cc b/sound/soundsysteminterface.cc
deleted file mode 100644
index b432262..0000000
--- a/sound/soundsysteminterface.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/soundsysteminterface.h"
-
-#include "talk/sound/sounddevicelocator.h"
-
-namespace cricket {
-
-void SoundSystemInterface::ClearSoundDeviceLocatorList(
- SoundSystemInterface::SoundDeviceLocatorList *devices) {
- for (SoundDeviceLocatorList::iterator i = devices->begin();
- i != devices->end();
- ++i) {
- if (*i) {
- delete *i;
- }
- }
- devices->clear();
-}
-
-} // namespace cricket
diff --git a/sound/soundsysteminterface.h b/sound/soundsysteminterface.h
deleted file mode 100644
index 7a059b0..0000000
--- a/sound/soundsysteminterface.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_SOUNDSYSTEMINTERFACE_H_
-#define TALK_SOUND_SOUNDSYSTEMINTERFACE_H_
-
-#include <vector>
-
-#include "talk/base/constructormagic.h"
-
-namespace cricket {
-
-class SoundDeviceLocator;
-class SoundInputStreamInterface;
-class SoundOutputStreamInterface;
-
-// Interface for a platform's sound system.
-// Implementations must guarantee thread-safety for at least the following use
-// cases:
-// 1) Concurrent enumeration and opening of devices from different threads.
-// 2) Concurrent use of different Sound(Input|Output)StreamInterface
-// instances from different threads (but concurrent use of the _same_ one from
-// different threads need not be supported).
-class SoundSystemInterface {
- public:
- typedef std::vector<SoundDeviceLocator *> SoundDeviceLocatorList;
-
- enum SampleFormat {
- // Only one supported sample format at this time.
- // The values here may be used in lookup tables, so they shouldn't change.
- FORMAT_S16LE = 0,
- };
-
- enum Flags {
- // Enable reporting the current stream latency in
- // Sound(Input|Output)StreamInterface. See those classes for more details.
- FLAG_REPORT_LATENCY = (1 << 0),
- };
-
- struct OpenParams {
- // Format for the sound stream.
- SampleFormat format;
- // Sampling frequency in hertz.
- unsigned int freq;
- // Number of channels in the PCM stream.
- unsigned int channels;
- // Misc flags. Should be taken from the Flags enum above.
- int flags;
- // Desired latency, measured as number of bytes of sample data
- int latency;
- };
-
- // Special values for the "latency" field of OpenParams.
- // Use this one to say you don't care what the latency is. The sound system
- // will optimize for other things instead.
- static const int kNoLatencyRequirements = -1;
- // Use this one to say that you want the sound system to pick an appropriate
- // small latency value. The sound system may pick the minimum allowed one, or
- // a slightly higher one in the event that the true minimum requires an
- // undesirable trade-off.
- static const int kLowLatency = 0;
-
- // Max value for the volume parameters for Sound(Input|Output)StreamInterface.
- static const int kMaxVolume = 255;
- // Min value for the volume parameters for Sound(Input|Output)StreamInterface.
- static const int kMinVolume = 0;
-
- // Helper for clearing a locator list and deleting the entries.
- static void ClearSoundDeviceLocatorList(SoundDeviceLocatorList *devices);
-
- virtual ~SoundSystemInterface() {}
-
- virtual bool Init() = 0;
- virtual void Terminate() = 0;
-
- // Enumerates the available devices. (Any pre-existing locators in the lists
- // are deleted.)
- virtual bool EnumeratePlaybackDevices(SoundDeviceLocatorList *devices) = 0;
- virtual bool EnumerateCaptureDevices(SoundDeviceLocatorList *devices) = 0;
-
- // Gets a special locator for the default device.
- virtual bool GetDefaultPlaybackDevice(SoundDeviceLocator **device) = 0;
- virtual bool GetDefaultCaptureDevice(SoundDeviceLocator **device) = 0;
-
- // Opens the given device, or returns NULL on error.
- virtual SoundOutputStreamInterface *OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) = 0;
- virtual SoundInputStreamInterface *OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) = 0;
-
- // A human-readable name for this sound system.
- virtual const char *GetName() const = 0;
-
- protected:
- SoundSystemInterface() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SoundSystemInterface);
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_SOUNDSYSTEMINTERFACE_H_
diff --git a/sound/soundsystemproxy.cc b/sound/soundsystemproxy.cc
deleted file mode 100644
index 737a6bb..0000000
--- a/sound/soundsystemproxy.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "talk/sound/soundsystemproxy.h"
-
-namespace cricket {
-
-bool SoundSystemProxy::EnumeratePlaybackDevices(
- SoundDeviceLocatorList *devices) {
- return wrapped_ ? wrapped_->EnumeratePlaybackDevices(devices) : false;
-}
-
-bool SoundSystemProxy::EnumerateCaptureDevices(
- SoundDeviceLocatorList *devices) {
- return wrapped_ ? wrapped_->EnumerateCaptureDevices(devices) : false;
-}
-
-bool SoundSystemProxy::GetDefaultPlaybackDevice(
- SoundDeviceLocator **device) {
- return wrapped_ ? wrapped_->GetDefaultPlaybackDevice(device) : false;
-}
-
-bool SoundSystemProxy::GetDefaultCaptureDevice(
- SoundDeviceLocator **device) {
- return wrapped_ ? wrapped_->GetDefaultCaptureDevice(device) : false;
-}
-
-SoundOutputStreamInterface *SoundSystemProxy::OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return wrapped_ ? wrapped_->OpenPlaybackDevice(device, params) : NULL;
-}
-
-SoundInputStreamInterface *SoundSystemProxy::OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms) {
- return wrapped_ ? wrapped_->OpenCaptureDevice(device, params) : NULL;
-}
-
-} // namespace cricket
diff --git a/sound/soundsystemproxy.h b/sound/soundsystemproxy.h
deleted file mode 100644
index 9ccace8..0000000
--- a/sound/soundsystemproxy.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * libjingle
- * Copyright 2004--2010, Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TALK_SOUND_SOUNDSYSTEMPROXY_H_
-#define TALK_SOUND_SOUNDSYSTEMPROXY_H_
-
-#include "talk/base/basictypes.h" // for NULL
-#include "talk/sound/soundsysteminterface.h"
-
-namespace cricket {
-
-// A SoundSystemProxy is a sound system that defers to another one.
-// Init(), Terminate(), and GetName() are left as pure virtual, so a sub-class
-// must define them.
-class SoundSystemProxy : public SoundSystemInterface {
- public:
- SoundSystemProxy() : wrapped_(NULL) {}
-
- // Each of these methods simply defers to wrapped_ if non-NULL, else fails.
-
- virtual bool EnumeratePlaybackDevices(SoundDeviceLocatorList *devices);
- virtual bool EnumerateCaptureDevices(SoundDeviceLocatorList *devices);
-
- virtual bool GetDefaultPlaybackDevice(SoundDeviceLocator **device);
- virtual bool GetDefaultCaptureDevice(SoundDeviceLocator **device);
-
- virtual SoundOutputStreamInterface *OpenPlaybackDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
- virtual SoundInputStreamInterface *OpenCaptureDevice(
- const SoundDeviceLocator *device,
- const OpenParams ¶ms);
-
- protected:
- SoundSystemInterface *wrapped_;
-};
-
-} // namespace cricket
-
-#endif // TALK_SOUND_SOUNDSYSTEMPROXY_H_
diff --git a/third_party/libudev/libudev.h b/third_party/libudev/libudev.h
deleted file mode 100644
index 5bc42df..0000000
--- a/third_party/libudev/libudev.h
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * libudev - interface to udev device information
- *
- * Copyright (C) 2008-2010 Kay Sievers <kay.sievers@vrfy.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- */
-
-#ifndef _LIBUDEV_H_
-#define _LIBUDEV_H_
-
-#include <stdarg.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * udev - library context
- *
- * reads the udev config and system environment
- * allows custom logging
- */
-struct udev;
-struct udev *udev_ref(struct udev *udev);
-void udev_unref(struct udev *udev);
-struct udev *udev_new(void);
-void udev_set_log_fn(struct udev *udev,
- void (*log_fn)(struct udev *udev,
- int priority, const char *file, int line, const char *fn,
- const char *format, va_list args));
-int udev_get_log_priority(struct udev *udev);
-void udev_set_log_priority(struct udev *udev, int priority);
-const char *udev_get_sys_path(struct udev *udev);
-const char *udev_get_dev_path(struct udev *udev);
-void *udev_get_userdata(struct udev *udev);
-void udev_set_userdata(struct udev *udev, void *userdata);
-
-/*
- * udev_list
- *
- * access to libudev generated lists
- */
-struct udev_list_entry;
-struct udev_list_entry *udev_list_entry_get_next(struct udev_list_entry *list_entry);
-struct udev_list_entry *udev_list_entry_get_by_name(struct udev_list_entry *list_entry, const char *name);
-const char *udev_list_entry_get_name(struct udev_list_entry *list_entry);
-const char *udev_list_entry_get_value(struct udev_list_entry *list_entry);
-/**
- * udev_list_entry_foreach:
- * @list_entry: entry to store the current position
- * @first_entry: first entry to start with
- *
- * Helper to iterate over all entries of a list.
- */
-#define udev_list_entry_foreach(list_entry, first_entry) \
- for (list_entry = first_entry; \
- list_entry != NULL; \
- list_entry = udev_list_entry_get_next(list_entry))
-
-/*
- * udev_device
- *
- * access to sysfs/kernel devices
- */
-struct udev_device;
-struct udev_device *udev_device_ref(struct udev_device *udev_device);
-void udev_device_unref(struct udev_device *udev_device);
-struct udev *udev_device_get_udev(struct udev_device *udev_device);
-struct udev_device *udev_device_new_from_syspath(struct udev *udev, const char *syspath);
-struct udev_device *udev_device_new_from_devnum(struct udev *udev, char type, dev_t devnum);
-struct udev_device *udev_device_new_from_subsystem_sysname(struct udev *udev, const char *subsystem, const char *sysname);
-struct udev_device *udev_device_new_from_environment(struct udev *udev);
-/* udev_device_get_parent_*() does not take a reference on the returned device, it is automatically unref'd with the parent */
-struct udev_device *udev_device_get_parent(struct udev_device *udev_device);
-struct udev_device *udev_device_get_parent_with_subsystem_devtype(struct udev_device *udev_device,
- const char *subsystem, const char *devtype);
-/* retrieve device properties */
-const char *udev_device_get_devpath(struct udev_device *udev_device);
-const char *udev_device_get_subsystem(struct udev_device *udev_device);
-const char *udev_device_get_devtype(struct udev_device *udev_device);
-const char *udev_device_get_syspath(struct udev_device *udev_device);
-const char *udev_device_get_sysname(struct udev_device *udev_device);
-const char *udev_device_get_sysnum(struct udev_device *udev_device);
-const char *udev_device_get_devnode(struct udev_device *udev_device);
-struct udev_list_entry *udev_device_get_devlinks_list_entry(struct udev_device *udev_device);
-struct udev_list_entry *udev_device_get_properties_list_entry(struct udev_device *udev_device);
-struct udev_list_entry *udev_device_get_tags_list_entry(struct udev_device *udev_device);
-const char *udev_device_get_property_value(struct udev_device *udev_device, const char *key);
-const char *udev_device_get_driver(struct udev_device *udev_device);
-dev_t udev_device_get_devnum(struct udev_device *udev_device);
-const char *udev_device_get_action(struct udev_device *udev_device);
-unsigned long long int udev_device_get_seqnum(struct udev_device *udev_device);
-const char *udev_device_get_sysattr_value(struct udev_device *udev_device, const char *sysattr);
-
-/*
- * udev_monitor
- *
- * access to kernel uevents and udev events
- */
-struct udev_monitor;
-struct udev_monitor *udev_monitor_ref(struct udev_monitor *udev_monitor);
-void udev_monitor_unref(struct udev_monitor *udev_monitor);
-struct udev *udev_monitor_get_udev(struct udev_monitor *udev_monitor);
-/* kernel and udev generated events over netlink */
-struct udev_monitor *udev_monitor_new_from_netlink(struct udev *udev, const char *name);
-/* custom socket (use netlink and filters instead) */
-struct udev_monitor *udev_monitor_new_from_socket(struct udev *udev, const char *socket_path);
-/* bind socket */
-int udev_monitor_enable_receiving(struct udev_monitor *udev_monitor);
-int udev_monitor_set_receive_buffer_size(struct udev_monitor *udev_monitor, int size);
-int udev_monitor_get_fd(struct udev_monitor *udev_monitor);
-struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor);
-/* in-kernel socket filters to select messages that get delivered to a listener */
-int udev_monitor_filter_add_match_subsystem_devtype(struct udev_monitor *udev_monitor,
- const char *subsystem, const char *devtype);
-int udev_monitor_filter_add_match_tag(struct udev_monitor *udev_monitor, const char *tag);
-int udev_monitor_filter_update(struct udev_monitor *udev_monitor);
-int udev_monitor_filter_remove(struct udev_monitor *udev_monitor);
-
-/*
- * udev_enumerate
- *
- * search sysfs for specific devices and provide a sorted list
- */
-struct udev_enumerate;
-struct udev_enumerate *udev_enumerate_ref(struct udev_enumerate *udev_enumerate);
-void udev_enumerate_unref(struct udev_enumerate *udev_enumerate);
-struct udev *udev_enumerate_get_udev(struct udev_enumerate *udev_enumerate);
-struct udev_enumerate *udev_enumerate_new(struct udev *udev);
-/* device properties filter */
-int udev_enumerate_add_match_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem);
-int udev_enumerate_add_nomatch_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem);
-int udev_enumerate_add_match_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value);
-int udev_enumerate_add_nomatch_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value);
-int udev_enumerate_add_match_property(struct udev_enumerate *udev_enumerate, const char *property, const char *value);
-int udev_enumerate_add_match_sysname(struct udev_enumerate *udev_enumerate, const char *sysname);
-int udev_enumerate_add_match_tag(struct udev_enumerate *udev_enumerate, const char *tag);
-int udev_enumerate_add_syspath(struct udev_enumerate *udev_enumerate, const char *syspath);
-/* run enumeration with active filters */
-int udev_enumerate_scan_devices(struct udev_enumerate *udev_enumerate);
-int udev_enumerate_scan_subsystems(struct udev_enumerate *udev_enumerate);
-/* return device list */
-struct udev_list_entry *udev_enumerate_get_list_entry(struct udev_enumerate *udev_enumerate);
-
-/*
- * udev_queue
- *
- * access to the currently running udev events
- */
-struct udev_queue;
-struct udev_queue *udev_queue_ref(struct udev_queue *udev_queue);
-void udev_queue_unref(struct udev_queue *udev_queue);
-struct udev *udev_queue_get_udev(struct udev_queue *udev_queue);
-struct udev_queue *udev_queue_new(struct udev *udev);
-unsigned long long int udev_queue_get_kernel_seqnum(struct udev_queue *udev_queue);
-unsigned long long int udev_queue_get_udev_seqnum(struct udev_queue *udev_queue);
-int udev_queue_get_udev_is_active(struct udev_queue *udev_queue);
-int udev_queue_get_queue_is_empty(struct udev_queue *udev_queue);
-int udev_queue_get_seqnum_is_finished(struct udev_queue *udev_queue, unsigned long long int seqnum);
-int udev_queue_get_seqnum_sequence_is_finished(struct udev_queue *udev_queue,
- unsigned long long int start, unsigned long long int end);
-struct udev_list_entry *udev_queue_get_queued_list_entry(struct udev_queue *udev_queue);
-struct udev_list_entry *udev_queue_get_failed_list_entry(struct udev_queue *udev_queue);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif
diff --git a/xmllite/qname_unittest.cc b/xmllite/qname_unittest.cc
index 976d822..72c1713 100644
--- a/xmllite/qname_unittest.cc
+++ b/xmllite/qname_unittest.cc
@@ -26,8 +26,8 @@
*/
#include <string>
-#include "talk/base/gunit.h"
#include "talk/xmllite/qname.h"
+#include "webrtc/base/gunit.h"
using buzz::StaticQName;
using buzz::QName;
diff --git a/xmllite/xmlbuilder.cc b/xmllite/xmlbuilder.cc
index f71e542..a091ed9 100644
--- a/xmllite/xmlbuilder.cc
+++ b/xmllite/xmlbuilder.cc
@@ -27,11 +27,11 @@
#include "talk/xmllite/xmlbuilder.h"
-#include <vector>
#include <set>
-#include "talk/base/common.h"
+#include <vector>
#include "talk/xmllite/xmlconstants.h"
#include "talk/xmllite/xmlelement.h"
+#include "webrtc/base/common.h"
namespace buzz {
@@ -107,8 +107,8 @@
void
XmlBuilder::EndElement(XmlParseContext * pctx, const char * name) {
- UNUSED(pctx);
- UNUSED(name);
+ RTC_UNUSED(pctx);
+ RTC_UNUSED(name);
pelCurrent_ = pvParents_->back();
pvParents_->pop_back();
}
@@ -116,7 +116,7 @@
void
XmlBuilder::CharacterData(XmlParseContext * pctx,
const char * text, int len) {
- UNUSED(pctx);
+ RTC_UNUSED(pctx);
if (pelCurrent_) {
pelCurrent_->AddParsedText(text, len);
}
@@ -124,8 +124,8 @@
void
XmlBuilder::Error(XmlParseContext * pctx, XML_Error err) {
- UNUSED(pctx);
- UNUSED(err);
+ RTC_UNUSED(pctx);
+ RTC_UNUSED(err);
pelRoot_.reset(NULL);
pelCurrent_ = NULL;
pvParents_->clear();
diff --git a/xmllite/xmlbuilder.h b/xmllite/xmlbuilder.h
index 984eee2..38fc009 100644
--- a/xmllite/xmlbuilder.h
+++ b/xmllite/xmlbuilder.h
@@ -30,8 +30,8 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
#include "talk/xmllite/xmlparser.h"
+#include "webrtc/base/scoped_ptr.h"
#ifdef EXPAT_RELATIVE_PATH
#include "expat.h"
@@ -69,8 +69,8 @@
private:
XmlElement * pelCurrent_;
- talk_base::scoped_ptr<XmlElement> pelRoot_;
- talk_base::scoped_ptr<std::vector<XmlElement*> > pvParents_;
+ rtc::scoped_ptr<XmlElement> pelRoot_;
+ rtc::scoped_ptr<std::vector<XmlElement*> > pvParents_;
};
}
diff --git a/xmllite/xmlbuilder_unittest.cc b/xmllite/xmlbuilder_unittest.cc
index 9302276..56304cf 100644
--- a/xmllite/xmlbuilder_unittest.cc
+++ b/xmllite/xmlbuilder_unittest.cc
@@ -25,14 +25,14 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
+#include <sstream>
+#include <string>
#include "talk/xmllite/xmlbuilder.h"
#include "talk/xmllite/xmlelement.h"
#include "talk/xmllite/xmlparser.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
using buzz::XmlBuilder;
using buzz::XmlElement;
diff --git a/xmllite/xmlelement.cc b/xmllite/xmlelement.cc
index 176ce5c..d76d0f5 100644
--- a/xmllite/xmlelement.cc
+++ b/xmllite/xmlelement.cc
@@ -32,12 +32,12 @@
#include <string>
#include <vector>
-#include "talk/base/common.h"
#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlparser.h"
#include "talk/xmllite/xmlbuilder.h"
-#include "talk/xmllite/xmlprinter.h"
#include "talk/xmllite/xmlconstants.h"
+#include "talk/xmllite/xmlparser.h"
+#include "talk/xmllite/xmlprinter.h"
+#include "webrtc/base/common.h"
namespace buzz {
diff --git a/xmllite/xmlelement.h b/xmllite/xmlelement.h
index ffdc333..044d2c4 100644
--- a/xmllite/xmlelement.h
+++ b/xmllite/xmlelement.h
@@ -31,8 +31,8 @@
#include <iosfwd>
#include <string>
-#include "talk/base/scoped_ptr.h"
#include "talk/xmllite/qname.h"
+#include "webrtc/base/scoped_ptr.h"
namespace buzz {
diff --git a/xmllite/xmlelement_unittest.cc b/xmllite/xmlelement_unittest.cc
index 3c31ce4..5b2e106 100644
--- a/xmllite/xmlelement_unittest.cc
+++ b/xmllite/xmlelement_unittest.cc
@@ -25,13 +25,13 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/base/thread.h"
+#include <sstream>
+#include <string>
#include "talk/xmllite/xmlelement.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/thread.h"
using buzz::QName;
using buzz::XmlAttr;
@@ -230,7 +230,7 @@
delete element;
}
-class XmlElementCreatorThread : public talk_base::Thread {
+class XmlElementCreatorThread : public rtc::Thread {
public:
XmlElementCreatorThread(int count, buzz::QName qname) :
count_(count), qname_(qname) {}
@@ -261,7 +261,7 @@
int elem_count = 100; // Was 100000, but that's too slow.
buzz::QName qname("foo", "bar");
- std::vector<talk_base::Thread*> threads;
+ std::vector<rtc::Thread*> threads;
for (int i = 0; i < thread_count; i++) {
threads.push_back(
new XmlElementCreatorThread(elem_count, qname));
diff --git a/xmllite/xmlnsstack.cc b/xmllite/xmlnsstack.cc
index 26e27f8..bc66b4f 100644
--- a/xmllite/xmlnsstack.cc
+++ b/xmllite/xmlnsstack.cc
@@ -31,8 +31,8 @@
#include <string>
#include <vector>
-#include "talk/xmllite/xmlelement.h"
#include "talk/xmllite/xmlconstants.h"
+#include "talk/xmllite/xmlelement.h"
namespace buzz {
diff --git a/xmllite/xmlnsstack.h b/xmllite/xmlnsstack.h
index f6b4b81..a3c4368 100644
--- a/xmllite/xmlnsstack.h
+++ b/xmllite/xmlnsstack.h
@@ -30,8 +30,8 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
#include "talk/xmllite/qname.h"
+#include "webrtc/base/scoped_ptr.h"
namespace buzz {
@@ -54,8 +54,8 @@
private:
- talk_base::scoped_ptr<std::vector<std::string> > pxmlnsStack_;
- talk_base::scoped_ptr<std::vector<size_t> > pxmlnsDepthStack_;
+ rtc::scoped_ptr<std::vector<std::string> > pxmlnsStack_;
+ rtc::scoped_ptr<std::vector<size_t> > pxmlnsDepthStack_;
};
}
diff --git a/xmllite/xmlnsstack_unittest.cc b/xmllite/xmlnsstack_unittest.cc
index 20b5972..82a39dd 100644
--- a/xmllite/xmlnsstack_unittest.cc
+++ b/xmllite/xmlnsstack_unittest.cc
@@ -27,13 +27,13 @@
#include "talk/xmllite/xmlnsstack.h"
-#include <string>
-#include <sstream>
#include <iostream>
+#include <sstream>
+#include <string>
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
#include "talk/xmllite/xmlconstants.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
using buzz::NS_XML;
using buzz::NS_XMLNS;
diff --git a/xmllite/xmlparser.cc b/xmllite/xmlparser.cc
index 8802231..c985b1f 100644
--- a/xmllite/xmlparser.cc
+++ b/xmllite/xmlparser.cc
@@ -30,11 +30,11 @@
#include <string>
#include <vector>
-#include "talk/base/common.h"
#include "talk/xmllite/xmlconstants.h"
#include "talk/xmllite/xmlelement.h"
#include "talk/xmllite/xmlnsstack.h"
#include "talk/xmllite/xmlnsstack.h"
+#include "webrtc/base/common.h"
namespace buzz {
diff --git a/xmllite/xmlparser_unittest.cc b/xmllite/xmlparser_unittest.cc
index 24947fb..322f8be 100644
--- a/xmllite/xmlparser_unittest.cc
+++ b/xmllite/xmlparser_unittest.cc
@@ -25,13 +25,13 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
+#include <sstream>
+#include <string>
#include "talk/xmllite/qname.h"
#include "talk/xmllite/xmlparser.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
using buzz::QName;
using buzz::XmlParser;
@@ -51,17 +51,17 @@
ss_ << ") ";
}
virtual void EndElement(XmlParseContext * pctx, const char * name) {
- UNUSED(pctx);
- UNUSED(name);
+ RTC_UNUSED(pctx);
+ RTC_UNUSED(name);
ss_ << "END ";
}
virtual void CharacterData(XmlParseContext * pctx,
const char * text, int len) {
- UNUSED(pctx);
+ RTC_UNUSED(pctx);
ss_ << "TEXT (" << std::string(text, len) << ") ";
}
virtual void Error(XmlParseContext * pctx, XML_Error code) {
- UNUSED(pctx);
+ RTC_UNUSED(pctx);
ss_ << "ERROR (" << static_cast<int>(code) << ") ";
}
virtual ~XmlParserTestHandler() {
diff --git a/xmllite/xmlprinter_unittest.cc b/xmllite/xmlprinter_unittest.cc
index 60b0e42..7100025 100644
--- a/xmllite/xmlprinter_unittest.cc
+++ b/xmllite/xmlprinter_unittest.cc
@@ -30,11 +30,11 @@
#include <sstream>
#include <string>
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
#include "talk/xmllite/qname.h"
#include "talk/xmllite/xmlelement.h"
#include "talk/xmllite/xmlnsstack.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
using buzz::QName;
using buzz::XmlElement;
diff --git a/xmpp/asyncsocket.h b/xmpp/asyncsocket.h
index fb4ef02..2514742 100644
--- a/xmpp/asyncsocket.h
+++ b/xmpp/asyncsocket.h
@@ -25,12 +25,14 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _ASYNCSOCKET_H_
-#define _ASYNCSOCKET_H_
+#ifndef TALK_XMPP_ASYNCSOCKET_H_
+#define TALK_XMPP_ASYNCSOCKET_H_
-#include "talk/base/sigslot.h"
+#include <string>
-namespace talk_base {
+#include "webrtc/base/sigslot.h"
+
+namespace rtc {
class SocketAddress;
}
@@ -64,7 +66,7 @@
virtual Error error() = 0;
virtual int GetError() = 0; // winsock error code
- virtual bool Connect(const talk_base::SocketAddress& addr) = 0;
+ virtual bool Connect(const rtc::SocketAddress& addr) = 0;
virtual bool Read(char * data, size_t len, size_t* len_read) = 0;
virtual bool Write(const char * data, size_t len) = 0;
virtual bool Close() = 0;
@@ -84,4 +86,4 @@
}
-#endif
+#endif // TALK_XMPP_ASYNCSOCKET_H_
diff --git a/xmpp/chatroommodule.h b/xmpp/chatroommodule.h
index 47a7106..8358fc1 100644
--- a/xmpp/chatroommodule.h
+++ b/xmpp/chatroommodule.h
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _multiuserchatmodule_h_
-#define _multiuserchatmodule_h_
+#ifndef TALK_XMPP_CHATROOMMODULE_H_
+#define TALK_XMPP_CHATROOMMODULE_H_
#include "talk/xmpp/module.h"
#include "talk/xmpp/rostermodule.h"
@@ -267,4 +267,4 @@
}
-#endif
+#endif // TALK_XMPP_CHATROOMMODULE_H_
diff --git a/xmpp/chatroommodule_unittest.cc b/xmpp/chatroommodule_unittest.cc
index a152f60..400a2dd 100644
--- a/xmpp/chatroommodule_unittest.cc
+++ b/xmpp/chatroommodule_unittest.cc
@@ -25,17 +25,17 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string>
-#include <sstream>
#include <iostream>
-#include "common/common.h"
-#include "buzz/xmppengine.h"
-#include "buzz/xmlelement.h"
+#include <sstream>
+#include <string>
#include "buzz/chatroommodule.h"
#include "buzz/constants.h"
+#include "buzz/xmlelement.h"
+#include "buzz/xmppengine.h"
+#include "common/common.h"
#include "engine/util_unittest.h"
-#include "test/unittest.h"
#include "test/unittest-inl.h"
+#include "test/unittest.h"
#define TEST_OK(x) TEST_EQ((x),XMPP_RETURN_OK)
#define TEST_BADARGUMENT(x) TEST_EQ((x),XMPP_RETURN_BADARGUMENT)
@@ -116,7 +116,7 @@
void ChatroomEnteredStatus(XmppChatroomModule* room,
XmppChatroomEnteredStatus status) {
- UNUSED(room);
+ RTC_UNUSED(room);
ss_ <<"[ChatroomEnteredStatus status: ";
WriteEnteredStatus(ss_, status);
ss_ <<"]";
@@ -125,7 +125,7 @@
void ChatroomExitedStatus(XmppChatroomModule* room,
XmppChatroomExitedStatus status) {
- UNUSED(room);
+ RTC_UNUSED(room);
ss_ <<"[ChatroomExitedStatus status: ";
WriteExitedStatus(ss_, status);
ss_ <<"]";
@@ -133,24 +133,24 @@
void MemberEntered(XmppChatroomModule* room,
const XmppChatroomMember* entered_member) {
- UNUSED(room);
+ RTC_UNUSED(room);
ss_ << "[MemberEntered " << entered_member->member_jid().Str() << "]";
}
void MemberExited(XmppChatroomModule* room,
const XmppChatroomMember* exited_member) {
- UNUSED(room);
+ RTC_UNUSED(room);
ss_ << "[MemberExited " << exited_member->member_jid().Str() << "]";
}
void MemberChanged(XmppChatroomModule* room,
const XmppChatroomMember* changed_member) {
- UNUSED(room);
+ RTC_UNUSED(room);
ss_ << "[MemberChanged " << changed_member->member_jid().Str() << "]";
}
virtual void MessageReceived(XmppChatroomModule* room, const XmlElement& message) {
- UNUSED2(room, message);
+ RTC_UNUSED2(room, message);
}
diff --git a/xmpp/chatroommoduleimpl.cc b/xmpp/chatroommoduleimpl.cc
index a12ff5e..45db014 100644
--- a/xmpp/chatroommoduleimpl.cc
+++ b/xmpp/chatroommoduleimpl.cc
@@ -25,16 +25,16 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <vector>
-#include <string>
-#include <map>
#include <algorithm>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
+#include <map>
+#include <sstream>
+#include <string>
+#include <vector>
+#include "talk/xmpp/chatroommodule.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/moduleimpl.h"
-#include "talk/xmpp/chatroommodule.h"
+#include "webrtc/base/common.h"
namespace buzz {
@@ -74,7 +74,7 @@
virtual XmppReturnStatus SendMessage(const XmlElement& message);
// XmppModule
- virtual void IqResponse(XmppIqCookie cookie, const XmlElement * pelStanza) {UNUSED2(cookie, pelStanza);}
+ virtual void IqResponse(XmppIqCookie cookie, const XmlElement * pelStanza) {RTC_UNUSED2(cookie, pelStanza);}
virtual bool HandleStanza(const XmlElement *);
private:
@@ -121,7 +121,7 @@
const XmppPresence* presence() const;
private:
- talk_base::scoped_ptr<XmppPresence> presence_;
+ rtc::scoped_ptr<XmppPresence> presence_;
};
class XmppChatroomMemberEnumeratorImpl :
@@ -276,7 +276,7 @@
const std::string& password,
const std::string& client_version,
const std::string& locale) {
- UNUSED(password);
+ RTC_UNUSED(password);
if (!engine())
return XMPP_RETURN_BADSTATE;
@@ -446,7 +446,7 @@
XmppChatroomModuleImpl::FireEnteredStatus(const XmlElement* presence,
XmppChatroomEnteredStatus status) {
if (chatroom_handler_) {
- talk_base::scoped_ptr<XmppPresence> xmpp_presence(XmppPresence::Create());
+ rtc::scoped_ptr<XmppPresence> xmpp_presence(XmppPresence::Create());
xmpp_presence->set_raw_xml(presence);
chatroom_handler_->ChatroomEnteredStatus(this, xmpp_presence.get(), status);
}
@@ -488,7 +488,7 @@
XmppChatroomModuleImpl::ServerChangedOtherPresence(const XmlElement&
presence_element) {
XmppReturnStatus xmpp_status = XMPP_RETURN_OK;
- talk_base::scoped_ptr<XmppPresence> presence(XmppPresence::Create());
+ rtc::scoped_ptr<XmppPresence> presence(XmppPresence::Create());
IFR(presence->set_raw_xml(&presence_element));
JidMemberMap::iterator pos = chatroom_jid_members_.find(presence->jid());
@@ -542,7 +542,7 @@
XmppChatroomModuleImpl::ChangePresence(XmppChatroomState new_state,
const XmlElement* presence,
bool isServer) {
- UNUSED(presence);
+ RTC_UNUSED(presence);
XmppChatroomState old_state = chatroom_state_;
diff --git a/xmpp/constants.cc b/xmpp/constants.cc
index f69f84e..297eafd 100644
--- a/xmpp/constants.cc
+++ b/xmpp/constants.cc
@@ -29,11 +29,11 @@
#include <string>
-#include "talk/base/basicdefs.h"
-#include "talk/xmllite/xmlconstants.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlconstants.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/jid.h"
+#include "webrtc/base/basicdefs.h"
namespace buzz {
diff --git a/xmpp/constants.h b/xmpp/constants.h
index 6d94095..6aa1a54 100644
--- a/xmpp/constants.h
+++ b/xmpp/constants.h
@@ -29,7 +29,7 @@
#define TALK_XMPP_CONSTANTS_H_
#include <string>
-#include "talk/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/qname.h"
#include "talk/xmpp/jid.h"
namespace buzz {
diff --git a/xmpp/discoitemsquerytask.cc b/xmpp/discoitemsquerytask.cc
index 7cdee2c..d900b85 100644
--- a/xmpp/discoitemsquerytask.cc
+++ b/xmpp/discoitemsquerytask.cc
@@ -25,10 +25,10 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/scoped_ptr.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/discoitemsquerytask.h"
#include "talk/xmpp/xmpptask.h"
+#include "webrtc/base/scoped_ptr.h"
namespace buzz {
diff --git a/xmpp/fakexmppclient.h b/xmpp/fakexmppclient.h
index 83b8e82..3522ba9 100644
--- a/xmpp/fakexmppclient.h
+++ b/xmpp/fakexmppclient.h
@@ -42,7 +42,7 @@
class FakeXmppClient : public XmppTaskParentInterface,
public XmppClientInterface {
public:
- explicit FakeXmppClient(talk_base::TaskParent* parent)
+ explicit FakeXmppClient(rtc::TaskParent* parent)
: XmppTaskParentInterface(parent) {
}
diff --git a/xmpp/hangoutpubsubclient.cc b/xmpp/hangoutpubsubclient.cc
index aede563..63f5bcf 100644
--- a/xmpp/hangoutpubsubclient.cc
+++ b/xmpp/hangoutpubsubclient.cc
@@ -27,11 +27,11 @@
#include "talk/xmpp/hangoutpubsubclient.h"
-#include "talk/base/logging.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/jid.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/base/logging.h"
// Gives a high-level API for MUC call PubSub needs such as
diff --git a/xmpp/hangoutpubsubclient.h b/xmpp/hangoutpubsubclient.h
index 2fcd691..5692fc6 100644
--- a/xmpp/hangoutpubsubclient.h
+++ b/xmpp/hangoutpubsubclient.h
@@ -32,12 +32,12 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/sigslotrepeater.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/pubsubclient.h"
#include "talk/xmpp/pubsubstateclient.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/sigslotrepeater.h"
// Gives a high-level API for MUC call PubSub needs such as
// presenter state, recording state, mute state, and remote mute.
@@ -180,14 +180,14 @@
const XmlElement* stanza);
Jid mucjid_;
std::string nick_;
- talk_base::scoped_ptr<PubSubClient> media_client_;
- talk_base::scoped_ptr<PubSubClient> presenter_client_;
- talk_base::scoped_ptr<PubSubStateClient<bool> > presenter_state_client_;
- talk_base::scoped_ptr<PubSubStateClient<bool> > audio_mute_state_client_;
- talk_base::scoped_ptr<PubSubStateClient<bool> > video_mute_state_client_;
- talk_base::scoped_ptr<PubSubStateClient<bool> > video_pause_state_client_;
- talk_base::scoped_ptr<PubSubStateClient<bool> > recording_state_client_;
- talk_base::scoped_ptr<PubSubStateClient<bool> > media_block_state_client_;
+ rtc::scoped_ptr<PubSubClient> media_client_;
+ rtc::scoped_ptr<PubSubClient> presenter_client_;
+ rtc::scoped_ptr<PubSubStateClient<bool> > presenter_state_client_;
+ rtc::scoped_ptr<PubSubStateClient<bool> > audio_mute_state_client_;
+ rtc::scoped_ptr<PubSubStateClient<bool> > video_mute_state_client_;
+ rtc::scoped_ptr<PubSubStateClient<bool> > video_pause_state_client_;
+ rtc::scoped_ptr<PubSubStateClient<bool> > recording_state_client_;
+ rtc::scoped_ptr<PubSubStateClient<bool> > media_block_state_client_;
};
} // namespace buzz
diff --git a/xmpp/hangoutpubsubclient_unittest.cc b/xmpp/hangoutpubsubclient_unittest.cc
index 1d1c14b..555ee5c 100644
--- a/xmpp/hangoutpubsubclient_unittest.cc
+++ b/xmpp/hangoutpubsubclient_unittest.cc
@@ -3,15 +3,15 @@
#include <string>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
-#include "talk/xmpp/jid.h"
#include "talk/xmpp/fakexmppclient.h"
#include "talk/xmpp/hangoutpubsubclient.h"
+#include "talk/xmpp/jid.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
class TestHangoutPubSubListener : public sigslot::has_slots<> {
public:
@@ -181,7 +181,7 @@
pubsubjid("room@domain.com"),
nick("me") {
- runner.reset(new talk_base::FakeTaskRunner());
+ runner.reset(new rtc::FakeTaskRunner());
xmpp_client = new buzz::FakeXmppClient(runner.get());
client.reset(new buzz::HangoutPubSubClient(xmpp_client, pubsubjid, nick));
listener.reset(new TestHangoutPubSubListener());
@@ -221,11 +221,11 @@
listener.get(), &TestHangoutPubSubListener::OnMediaBlockError);
}
- talk_base::scoped_ptr<talk_base::FakeTaskRunner> runner;
+ rtc::scoped_ptr<rtc::FakeTaskRunner> runner;
// xmpp_client deleted by deleting runner.
buzz::FakeXmppClient* xmpp_client;
- talk_base::scoped_ptr<buzz::HangoutPubSubClient> client;
- talk_base::scoped_ptr<TestHangoutPubSubListener> listener;
+ rtc::scoped_ptr<buzz::HangoutPubSubClient> client;
+ rtc::scoped_ptr<TestHangoutPubSubListener> listener;
buzz::Jid pubsubjid;
std::string nick;
};
diff --git a/xmpp/iqtask.cc b/xmpp/iqtask.cc
index f54f630..f6a21d4 100644
--- a/xmpp/iqtask.cc
+++ b/xmpp/iqtask.cc
@@ -27,8 +27,8 @@
#include "talk/xmpp/iqtask.h"
-#include "talk/xmpp/xmppclient.h"
#include "talk/xmpp/constants.h"
+#include "talk/xmpp/xmppclient.h"
namespace buzz {
diff --git a/xmpp/iqtask.h b/xmpp/iqtask.h
index 2228e6f..312c4af 100644
--- a/xmpp/iqtask.h
+++ b/xmpp/iqtask.h
@@ -30,8 +30,8 @@
#include <string>
-#include "talk/xmpp/xmpptask.h"
#include "talk/xmpp/xmppengine.h"
+#include "talk/xmpp/xmpptask.h"
namespace buzz {
@@ -57,7 +57,7 @@
virtual int OnTimeout();
Jid to_;
- talk_base::scoped_ptr<XmlElement> stanza_;
+ rtc::scoped_ptr<XmlElement> stanza_;
};
} // namespace buzz
diff --git a/xmpp/jid.cc b/xmpp/jid.cc
index 4583871..702e477 100644
--- a/xmpp/jid.cc
+++ b/xmpp/jid.cc
@@ -32,9 +32,9 @@
#include <algorithm>
#include <string>
-#include "talk/base/common.h"
-#include "talk/base/logging.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/logging.h"
namespace buzz {
diff --git a/xmpp/jid.h b/xmpp/jid.h
index dcfc123..2bfe0d9 100644
--- a/xmpp/jid.h
+++ b/xmpp/jid.h
@@ -29,8 +29,8 @@
#define TALK_XMPP_JID_H_
#include <string>
-#include "talk/base/basictypes.h"
-#include "talk/xmllite/xmlconstants.h"
+#include "webrtc/libjingle/xmllite/xmlconstants.h"
+#include "webrtc/base/basictypes.h"
namespace buzz {
diff --git a/xmpp/jid_unittest.cc b/xmpp/jid_unittest.cc
index b9597da..05835cf 100644
--- a/xmpp/jid_unittest.cc
+++ b/xmpp/jid_unittest.cc
@@ -1,8 +1,8 @@
// Copyright 2004 Google Inc. All Rights Reserved
-#include "talk/base/gunit.h"
#include "talk/xmpp/jid.h"
+#include "webrtc/base/gunit.h"
using buzz::Jid;
diff --git a/xmpp/jingleinfotask.cc b/xmpp/jingleinfotask.cc
index cf3eac2..3ceae07 100644
--- a/xmpp/jingleinfotask.cc
+++ b/xmpp/jingleinfotask.cc
@@ -27,10 +27,10 @@
#include "talk/xmpp/jingleinfotask.h"
-#include "talk/base/socketaddress.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/xmppclient.h"
#include "talk/xmpp/xmpptask.h"
+#include "webrtc/base/socketaddress.h"
namespace buzz {
@@ -41,7 +41,7 @@
done_(false) {}
virtual int ProcessStart() {
- talk_base::scoped_ptr<XmlElement> get(
+ rtc::scoped_ptr<XmlElement> get(
MakeIq(STR_GET, Jid(), task_id()));
get->AddElement(new XmlElement(QN_JINGLE_INFO_QUERY, true));
if (SendStanza(get.get()) != XMPP_RETURN_OK) {
@@ -101,7 +101,7 @@
int
JingleInfoTask::ProcessStart() {
std::vector<std::string> relay_hosts;
- std::vector<talk_base::SocketAddress> stun_hosts;
+ std::vector<rtc::SocketAddress> stun_hosts;
std::string relay_token;
const XmlElement * stanza = NextStanza();
if (stanza == NULL)
@@ -116,7 +116,7 @@
std::string host = server->Attr(QN_JINGLE_INFO_HOST);
std::string port = server->Attr(QN_JINGLE_INFO_UDP);
if (host != STR_EMPTY && host != STR_EMPTY) {
- stun_hosts.push_back(talk_base::SocketAddress(host, atoi(port.c_str())));
+ stun_hosts.push_back(rtc::SocketAddress(host, atoi(port.c_str())));
}
}
}
diff --git a/xmpp/jingleinfotask.h b/xmpp/jingleinfotask.h
index dbc3fb0..18cb5a9 100644
--- a/xmpp/jingleinfotask.h
+++ b/xmpp/jingleinfotask.h
@@ -25,15 +25,15 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef TALK_EXAMPLES_LOGIN_JINGLEINFOTASK_H_
-#define TALK_EXAMPLES_LOGIN_JINGLEINFOTASK_H_
+#ifndef TALK_XMPP_JINGLEINFOTASK_H_
+#define TALK_XMPP_JINGLEINFOTASK_H_
#include <vector>
#include "talk/p2p/client/httpportallocator.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
-#include "talk/base/sigslot.h"
+#include "webrtc/base/sigslot.h"
namespace buzz {
@@ -47,7 +47,7 @@
sigslot::signal3<const std::string &,
const std::vector<std::string> &,
- const std::vector<talk_base::SocketAddress> &>
+ const std::vector<rtc::SocketAddress> &>
SignalJingleInfo;
protected:
@@ -58,4 +58,4 @@
};
}
-#endif // TALK_EXAMPLES_LOGIN_JINGLEINFOTASK_H_
+#endif // TALK_XMPP_JINGLEINFOTASK_H_
diff --git a/xmpp/module.h b/xmpp/module.h
index 75a190d..a5d0687 100644
--- a/xmpp/module.h
+++ b/xmpp/module.h
@@ -25,13 +25,14 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _module_h_
-#define _module_h_
+#ifndef TALK_XMPP_MODULE_H_
+#define TALK_XMPP_MODULE_H_
+
+#include "talk/xmpp/xmppengine.h"
namespace buzz {
class XmppEngine;
-enum XmppReturnStatus;
//! This is the base class for extension modules.
//! An engine is registered with the module and the module then hooks the
@@ -48,4 +49,4 @@
};
}
-#endif
+#endif // TALK_XMPP_MODULE_H_
diff --git a/xmpp/moduleimpl.cc b/xmpp/moduleimpl.cc
index b23ca29..4635bee 100644
--- a/xmpp/moduleimpl.cc
+++ b/xmpp/moduleimpl.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/common.h"
#include "talk/xmpp/moduleimpl.h"
+#include "webrtc/base/common.h"
namespace buzz {
diff --git a/xmpp/moduleimpl.h b/xmpp/moduleimpl.h
index 085c83a..897bfce 100644
--- a/xmpp/moduleimpl.h
+++ b/xmpp/moduleimpl.h
@@ -25,11 +25,11 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _moduleimpl_h_
-#define _moduleimpl_h_
+#ifndef TALK_XMPP_MODULEIMPL_H_
+#define TALK_XMPP_MODULEIMPL_H_
-#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/module.h"
+#include "talk/xmpp/xmppengine.h"
namespace buzz {
@@ -90,4 +90,4 @@
}
-#endif
+#endif // TALK_XMPP_MODULEIMPL_H_
diff --git a/xmpp/mucroomconfigtask.cc b/xmpp/mucroomconfigtask.cc
index 272bd44..536eb9b 100644
--- a/xmpp/mucroomconfigtask.cc
+++ b/xmpp/mucroomconfigtask.cc
@@ -30,8 +30,8 @@
#include "talk/xmpp/mucroomconfigtask.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/scoped_ptr.h"
namespace buzz {
diff --git a/xmpp/mucroomconfigtask_unittest.cc b/xmpp/mucroomconfigtask_unittest.cc
index e0a8aca..bf5e7b4 100644
--- a/xmpp/mucroomconfigtask_unittest.cc
+++ b/xmpp/mucroomconfigtask_unittest.cc
@@ -28,13 +28,13 @@
#include <string>
#include <vector>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/fakexmppclient.h"
#include "talk/xmpp/mucroomconfigtask.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
class MucRoomConfigListener : public sigslot::has_slots<> {
public:
@@ -61,7 +61,7 @@
}
virtual void SetUp() {
- runner = new talk_base::FakeTaskRunner();
+ runner = new rtc::FakeTaskRunner();
xmpp_client = new buzz::FakeXmppClient(runner);
listener = new MucRoomConfigListener();
}
@@ -72,7 +72,7 @@
delete runner;
}
- talk_base::FakeTaskRunner* runner;
+ rtc::FakeTaskRunner* runner;
buzz::FakeXmppClient* xmpp_client;
MucRoomConfigListener* listener;
buzz::Jid room_jid;
diff --git a/xmpp/mucroomdiscoverytask_unittest.cc b/xmpp/mucroomdiscoverytask_unittest.cc
index 354503f..e1a633e 100644
--- a/xmpp/mucroomdiscoverytask_unittest.cc
+++ b/xmpp/mucroomdiscoverytask_unittest.cc
@@ -28,13 +28,13 @@
#include <string>
#include <vector>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/fakexmppclient.h"
#include "talk/xmpp/mucroomdiscoverytask.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
class MucRoomDiscoveryListener : public sigslot::has_slots<> {
public:
@@ -75,7 +75,7 @@
}
virtual void SetUp() {
- runner = new talk_base::FakeTaskRunner();
+ runner = new rtc::FakeTaskRunner();
xmpp_client = new buzz::FakeXmppClient(runner);
listener = new MucRoomDiscoveryListener();
}
@@ -86,7 +86,7 @@
delete runner;
}
- talk_base::FakeTaskRunner* runner;
+ rtc::FakeTaskRunner* runner;
buzz::FakeXmppClient* xmpp_client;
MucRoomDiscoveryListener* listener;
buzz::Jid room_jid;
diff --git a/xmpp/mucroomlookuptask.cc b/xmpp/mucroomlookuptask.cc
index b78e5dd..8e1895c 100644
--- a/xmpp/mucroomlookuptask.cc
+++ b/xmpp/mucroomlookuptask.cc
@@ -27,9 +27,9 @@
#include "talk/xmpp/mucroomlookuptask.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
namespace buzz {
diff --git a/xmpp/mucroomlookuptask_unittest.cc b/xmpp/mucroomlookuptask_unittest.cc
index a662d53..03be292 100644
--- a/xmpp/mucroomlookuptask_unittest.cc
+++ b/xmpp/mucroomlookuptask_unittest.cc
@@ -28,13 +28,13 @@
#include <string>
#include <vector>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/fakexmppclient.h"
#include "talk/xmpp/mucroomlookuptask.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
class MucRoomLookupListener : public sigslot::has_slots<> {
public:
@@ -66,7 +66,7 @@
}
virtual void SetUp() {
- runner = new talk_base::FakeTaskRunner();
+ runner = new rtc::FakeTaskRunner();
xmpp_client = new buzz::FakeXmppClient(runner);
listener = new MucRoomLookupListener();
}
@@ -77,7 +77,7 @@
delete runner;
}
- talk_base::FakeTaskRunner* runner;
+ rtc::FakeTaskRunner* runner;
buzz::FakeXmppClient* xmpp_client;
MucRoomLookupListener* listener;
buzz::Jid lookup_server_jid;
diff --git a/xmpp/mucroomuniquehangoutidtask_unittest.cc b/xmpp/mucroomuniquehangoutidtask_unittest.cc
index 128bab3..42bed13 100644
--- a/xmpp/mucroomuniquehangoutidtask_unittest.cc
+++ b/xmpp/mucroomuniquehangoutidtask_unittest.cc
@@ -28,13 +28,13 @@
#include <string>
#include <vector>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/fakexmppclient.h"
#include "talk/xmpp/mucroomuniquehangoutidtask.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
class MucRoomUniqueHangoutIdListener : public sigslot::has_slots<> {
public:
@@ -62,7 +62,7 @@
}
virtual void SetUp() {
- runner = new talk_base::FakeTaskRunner();
+ runner = new rtc::FakeTaskRunner();
xmpp_client = new buzz::FakeXmppClient(runner);
listener = new MucRoomUniqueHangoutIdListener();
}
@@ -73,7 +73,7 @@
delete runner;
}
- talk_base::FakeTaskRunner* runner;
+ rtc::FakeTaskRunner* runner;
buzz::FakeXmppClient* xmpp_client;
MucRoomUniqueHangoutIdListener* listener;
buzz::Jid lookup_server_jid;
diff --git a/xmpp/pingtask.cc b/xmpp/pingtask.cc
index 233062f..7922ea0 100644
--- a/xmpp/pingtask.cc
+++ b/xmpp/pingtask.cc
@@ -3,14 +3,14 @@
#include "talk/xmpp/pingtask.h"
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
namespace buzz {
PingTask::PingTask(buzz::XmppTaskParentInterface* parent,
- talk_base::MessageQueue* message_queue,
+ rtc::MessageQueue* message_queue,
uint32 ping_period_millis,
uint32 ping_timeout_millis)
: buzz::XmppTask(parent, buzz::XmppEngine::HL_SINGLE),
@@ -49,7 +49,7 @@
ping_response_deadline_ = 0;
}
- uint32 now = talk_base::Time();
+ uint32 now = rtc::Time();
// If the ping timed out, signal.
if (ping_response_deadline_ != 0 && now >= ping_response_deadline_) {
@@ -59,7 +59,7 @@
// Send a ping if it's time.
if (now >= next_ping_time_) {
- talk_base::scoped_ptr<buzz::XmlElement> stanza(
+ rtc::scoped_ptr<buzz::XmlElement> stanza(
MakeIq(buzz::STR_GET, Jid(STR_EMPTY), task_id()));
stanza->AddElement(new buzz::XmlElement(QN_PING));
SendStanza(stanza.get());
@@ -76,7 +76,7 @@
return STATE_BLOCKED;
}
-void PingTask::OnMessage(talk_base::Message* msg) {
+void PingTask::OnMessage(rtc::Message* msg) {
// Get the task manager to run this task so we can send a ping or signal or
// process a ping response.
Wake();
diff --git a/xmpp/pingtask.h b/xmpp/pingtask.h
index 8375241..2a869a3 100644
--- a/xmpp/pingtask.h
+++ b/xmpp/pingtask.h
@@ -28,9 +28,9 @@
#ifndef TALK_XMPP_PINGTASK_H_
#define TALK_XMPP_PINGTASK_H_
-#include "talk/base/messagehandler.h"
-#include "talk/base/messagequeue.h"
#include "talk/xmpp/xmpptask.h"
+#include "webrtc/base/messagehandler.h"
+#include "webrtc/base/messagequeue.h"
namespace buzz {
@@ -42,10 +42,10 @@
// proxies.
// 2. It detects when the server has crashed or any other case in which the
// connection has broken without a fin or reset packet being sent to us.
-class PingTask : public buzz::XmppTask, private talk_base::MessageHandler {
+class PingTask : public buzz::XmppTask, private rtc::MessageHandler {
public:
PingTask(buzz::XmppTaskParentInterface* parent,
- talk_base::MessageQueue* message_queue, uint32 ping_period_millis,
+ rtc::MessageQueue* message_queue, uint32 ping_period_millis,
uint32 ping_timeout_millis);
virtual bool HandleStanza(const buzz::XmlElement* stanza);
@@ -57,9 +57,9 @@
private:
// Implementation of MessageHandler.
- virtual void OnMessage(talk_base::Message* msg);
+ virtual void OnMessage(rtc::Message* msg);
- talk_base::MessageQueue* message_queue_;
+ rtc::MessageQueue* message_queue_;
uint32 ping_period_millis_;
uint32 ping_timeout_millis_;
uint32 next_ping_time_;
diff --git a/xmpp/pingtask_unittest.cc b/xmpp/pingtask_unittest.cc
index 477847d..fe88a5c 100644
--- a/xmpp/pingtask_unittest.cc
+++ b/xmpp/pingtask_unittest.cc
@@ -28,19 +28,19 @@
#include <string>
#include <vector>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/fakexmppclient.h"
#include "talk/xmpp/pingtask.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
class PingTaskTest;
class PingXmppClient : public buzz::FakeXmppClient {
public:
- PingXmppClient(talk_base::TaskParent* parent, PingTaskTest* tst) :
+ PingXmppClient(rtc::TaskParent* parent, PingTaskTest* tst) :
FakeXmppClient(parent), test(tst) {
}
@@ -56,7 +56,7 @@
}
virtual void SetUp() {
- runner = new talk_base::FakeTaskRunner();
+ runner = new rtc::FakeTaskRunner();
xmpp_client = new PingXmppClient(runner, this);
}
@@ -73,7 +73,7 @@
timed_out = true;
}
- talk_base::FakeTaskRunner* runner;
+ rtc::FakeTaskRunner* runner;
PingXmppClient* xmpp_client;
bool respond_to_pings;
bool timed_out;
@@ -93,7 +93,7 @@
TEST_F(PingTaskTest, TestSuccess) {
uint32 ping_period_millis = 100;
buzz::PingTask* task = new buzz::PingTask(xmpp_client,
- talk_base::Thread::Current(),
+ rtc::Thread::Current(),
ping_period_millis, ping_period_millis / 10);
ConnectTimeoutSignal(task);
task->Start();
@@ -108,7 +108,7 @@
respond_to_pings = false;
uint32 ping_timeout_millis = 200;
buzz::PingTask* task = new buzz::PingTask(xmpp_client,
- talk_base::Thread::Current(),
+ rtc::Thread::Current(),
ping_timeout_millis * 10, ping_timeout_millis);
ConnectTimeoutSignal(task);
task->Start();
diff --git a/xmpp/plainsaslhandler.h b/xmpp/plainsaslhandler.h
index e7d44b9..31032e4 100644
--- a/xmpp/plainsaslhandler.h
+++ b/xmpp/plainsaslhandler.h
@@ -25,17 +25,19 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _PLAINSASLHANDLER_H_
-#define _PLAINSASLHANDLER_H_
+#ifndef TALK_XMPP_PLAINSASLHANDLER_H_
+#define TALK_XMPP_PLAINSASLHANDLER_H_
-#include "talk/xmpp/saslhandler.h"
#include <algorithm>
+#include "talk/xmpp/saslhandler.h"
+#include "talk/xmpp/saslplainmechanism.h"
+#include "webrtc/base/cryptstring.h"
namespace buzz {
class PlainSaslHandler : public SaslHandler {
public:
- PlainSaslHandler(const Jid & jid, const talk_base::CryptString & password,
+ PlainSaslHandler(const Jid & jid, const rtc::CryptString & password,
bool allow_plain) : jid_(jid), password_(password),
allow_plain_(allow_plain) {}
@@ -69,12 +71,11 @@
private:
Jid jid_;
- talk_base::CryptString password_;
+ rtc::CryptString password_;
bool allow_plain_;
};
}
-#endif
-
+#endif // TALK_XMPP_PLAINSASLHANDLER_H_
diff --git a/xmpp/presenceouttask.cc b/xmpp/presenceouttask.cc
index cebd740..a77d9d6 100644
--- a/xmpp/presenceouttask.cc
+++ b/xmpp/presenceouttask.cc
@@ -27,10 +27,10 @@
#include <time.h>
#include <sstream>
-#include "talk/base/stringencode.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/presenceouttask.h"
#include "talk/xmpp/xmppclient.h"
+#include "webrtc/base/stringencode.h"
namespace buzz {
@@ -117,7 +117,7 @@
}
std::string pri;
- talk_base::ToString(s.priority(), &pri);
+ rtc::ToString(s.priority(), &pri);
result->AddElement(new XmlElement(QN_PRIORITY));
result->AddText(pri, 1);
diff --git a/xmpp/presenceouttask.h b/xmpp/presenceouttask.h
index cea2b56..53bbae5 100644
--- a/xmpp/presenceouttask.h
+++ b/xmpp/presenceouttask.h
@@ -25,12 +25,12 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _PRESENCEOUTTASK_H_
-#define _PRESENCEOUTTASK_H_
+#ifndef TALK_XMPP_PRESENCEOUTTASK_H_
+#define TALK_XMPP_PRESENCEOUTTASK_H_
+#include "talk/xmpp/presencestatus.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
-#include "talk/xmpp/presencestatus.h"
namespace buzz {
@@ -51,4 +51,4 @@
}
-#endif
+#endif // TALK_XMPP_PRESENCEOUTTASK_H_
diff --git a/xmpp/presencereceivetask.cc b/xmpp/presencereceivetask.cc
index 80121dd..940c53b 100644
--- a/xmpp/presencereceivetask.cc
+++ b/xmpp/presencereceivetask.cc
@@ -27,8 +27,8 @@
#include "talk/xmpp/presencereceivetask.h"
-#include "talk/base/stringencode.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/stringencode.h"
namespace buzz {
@@ -108,7 +108,7 @@
const XmlElement * priority = stanza->FirstNamed(QN_PRIORITY);
if (priority != NULL) {
int pri;
- if (talk_base::FromString(priority->BodyText(), &pri)) {
+ if (rtc::FromString(priority->BodyText(), &pri)) {
presence_status->set_priority(pri);
}
}
diff --git a/xmpp/presencereceivetask.h b/xmpp/presencereceivetask.h
index 2bd6494..6a090f3 100644
--- a/xmpp/presencereceivetask.h
+++ b/xmpp/presencereceivetask.h
@@ -28,7 +28,7 @@
#ifndef THIRD_PARTY_LIBJINGLE_FILES_TALK_XMPP_PRESENCERECEIVETASK_H_
#define THIRD_PARTY_LIBJINGLE_FILES_TALK_XMPP_PRESENCERECEIVETASK_H_
-#include "talk/base/sigslot.h"
+#include "webrtc/base/sigslot.h"
#include "talk/xmpp/presencestatus.h"
#include "talk/xmpp/xmpptask.h"
diff --git a/xmpp/presencestatus.h b/xmpp/presencestatus.h
index 5cf6b61..45c5471 100644
--- a/xmpp/presencestatus.h
+++ b/xmpp/presencestatus.h
@@ -28,8 +28,8 @@
#ifndef THIRD_PARTY_LIBJINGLE_FILES_TALK_XMPP_PRESENCESTATUS_H_
#define THIRD_PARTY_LIBJINGLE_FILES_TALK_XMPP_PRESENCESTATUS_H_
-#include "talk/xmpp/jid.h"
#include "talk/xmpp/constants.h"
+#include "talk/xmpp/jid.h"
namespace buzz {
diff --git a/xmpp/prexmppauth.h b/xmpp/prexmppauth.h
index 3bc5ca6..71fcae4 100644
--- a/xmpp/prexmppauth.h
+++ b/xmpp/prexmppauth.h
@@ -28,11 +28,11 @@
#ifndef TALK_XMPP_PREXMPPAUTH_H_
#define TALK_XMPP_PREXMPPAUTH_H_
-#include "talk/base/cryptstring.h"
-#include "talk/base/sigslot.h"
#include "talk/xmpp/saslhandler.h"
+#include "webrtc/base/cryptstring.h"
+#include "webrtc/base/sigslot.h"
-namespace talk_base {
+namespace rtc {
class SocketAddress;
}
@@ -67,8 +67,8 @@
virtual void StartPreXmppAuth(
const Jid& jid,
- const talk_base::SocketAddress& server,
- const talk_base::CryptString& pass,
+ const rtc::SocketAddress& server,
+ const rtc::CryptString& pass,
const std::string& auth_mechanism,
const std::string& auth_token) = 0;
diff --git a/xmpp/pubsub_task.cc b/xmpp/pubsub_task.cc
index 91e2c72..3552764 100644
--- a/xmpp/pubsub_task.cc
+++ b/xmpp/pubsub_task.cc
@@ -30,9 +30,9 @@
#include <map>
#include <string>
-#include "talk/base/common.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/common.h"
namespace buzz {
@@ -99,7 +99,7 @@
bool PubsubTask::SubscribeToNode(const std::string& pubsub_node,
NodeHandler handler) {
subscribed_nodes_[pubsub_node] = handler;
- talk_base::scoped_ptr<buzz::XmlElement> get_iq_request(
+ rtc::scoped_ptr<buzz::XmlElement> get_iq_request(
MakeIq(buzz::STR_GET, pubsub_node_jid_, task_id()));
if (!get_iq_request) {
return false;
diff --git a/xmpp/pubsub_task.h b/xmpp/pubsub_task.h
index 45a7462..2787cbc 100644
--- a/xmpp/pubsub_task.h
+++ b/xmpp/pubsub_task.h
@@ -30,7 +30,7 @@
#include <map>
#include <string>
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/xmpptask.h"
diff --git a/xmpp/pubsubclient.h b/xmpp/pubsubclient.h
index f0cd7a9..d7b5066 100644
--- a/xmpp/pubsubclient.h
+++ b/xmpp/pubsubclient.h
@@ -31,11 +31,11 @@
#include <string>
#include <vector>
-#include "talk/base/sigslot.h"
-#include "talk/base/sigslotrepeater.h"
-#include "talk/base/task.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/pubsubtasks.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/sigslotrepeater.h"
+#include "webrtc/base/task.h"
// Easy to use clients built on top of the tasks for XEP-0060
// (http://xmpp.org/extensions/xep-0060.html).
diff --git a/xmpp/pubsubclient_unittest.cc b/xmpp/pubsubclient_unittest.cc
index 2e4c511..f191a18 100644
--- a/xmpp/pubsubclient_unittest.cc
+++ b/xmpp/pubsubclient_unittest.cc
@@ -3,15 +3,15 @@
#include <string>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/fakexmppclient.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/pubsubclient.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
struct HandledPubSubItem {
std::string itemid;
@@ -78,7 +78,7 @@
pubsubjid("room@domain.com"),
node("topic"),
itemid("key") {
- runner.reset(new talk_base::FakeTaskRunner());
+ runner.reset(new rtc::FakeTaskRunner());
xmpp_client = new buzz::FakeXmppClient(runner.get());
client.reset(new buzz::PubSubClient(xmpp_client, pubsubjid, node));
listener.reset(new TestPubSubItemsListener());
@@ -96,11 +96,11 @@
listener.get(), &TestPubSubItemsListener::OnRetractError);
}
- talk_base::scoped_ptr<talk_base::FakeTaskRunner> runner;
+ rtc::scoped_ptr<rtc::FakeTaskRunner> runner;
// xmpp_client deleted by deleting runner.
buzz::FakeXmppClient* xmpp_client;
- talk_base::scoped_ptr<buzz::PubSubClient> client;
- talk_base::scoped_ptr<TestPubSubItemsListener> listener;
+ rtc::scoped_ptr<buzz::PubSubClient> client;
+ rtc::scoped_ptr<TestPubSubItemsListener> listener;
buzz::Jid pubsubjid;
std::string node;
std::string itemid;
diff --git a/xmpp/pubsubstateclient.h b/xmpp/pubsubstateclient.h
index f38658d..09ef0f4 100644
--- a/xmpp/pubsubstateclient.h
+++ b/xmpp/pubsubstateclient.h
@@ -32,14 +32,14 @@
#include <string>
#include <vector>
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/sigslotrepeater.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/pubsubclient.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/sigslotrepeater.h"
namespace buzz {
@@ -273,8 +273,8 @@
PubSubClient* client_;
const QName state_name_;
C default_state_;
- talk_base::scoped_ptr<PubSubStateKeySerializer> key_serializer_;
- talk_base::scoped_ptr<PubSubStateSerializer<C> > state_serializer_;
+ rtc::scoped_ptr<PubSubStateKeySerializer> key_serializer_;
+ rtc::scoped_ptr<PubSubStateSerializer<C> > state_serializer_;
// key => state
std::map<std::string, C> state_by_key_;
// itemid => StateItemInfo
diff --git a/xmpp/pubsubtasks.h b/xmpp/pubsubtasks.h
index 2ba618b..94be276 100644
--- a/xmpp/pubsubtasks.h
+++ b/xmpp/pubsubtasks.h
@@ -30,9 +30,9 @@
#include <vector>
-#include "talk/base/sigslot.h"
#include "talk/xmpp/iqtask.h"
#include "talk/xmpp/receivetask.h"
+#include "webrtc/base/sigslot.h"
namespace buzz {
diff --git a/xmpp/pubsubtasks_unittest.cc b/xmpp/pubsubtasks_unittest.cc
index 67fc306..48cd04a 100644
--- a/xmpp/pubsubtasks_unittest.cc
+++ b/xmpp/pubsubtasks_unittest.cc
@@ -3,16 +3,16 @@
#include <string>
-#include "talk/base/faketaskrunner.h"
-#include "talk/base/gunit.h"
-#include "talk/base/sigslot.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
-#include "talk/xmpp/iqtask.h"
#include "talk/xmpp/fakexmppclient.h"
+#include "talk/xmpp/iqtask.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/pubsubtasks.h"
+#include "webrtc/base/faketaskrunner.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/sigslot.h"
struct HandledPubSubItem {
std::string itemid;
@@ -68,15 +68,15 @@
pubsubjid("room@domain.com"),
node("topic"),
itemid("key") {
- runner.reset(new talk_base::FakeTaskRunner());
+ runner.reset(new rtc::FakeTaskRunner());
client = new buzz::FakeXmppClient(runner.get());
listener.reset(new TestPubSubTasksListener());
}
- talk_base::scoped_ptr<talk_base::FakeTaskRunner> runner;
+ rtc::scoped_ptr<rtc::FakeTaskRunner> runner;
// Client deleted by deleting runner.
buzz::FakeXmppClient* client;
- talk_base::scoped_ptr<TestPubSubTasksListener> listener;
+ rtc::scoped_ptr<TestPubSubTasksListener> listener;
buzz::Jid pubsubjid;
std::string node;
std::string itemid;
diff --git a/xmpp/receivetask.cc b/xmpp/receivetask.cc
index 53fac7e..c2fb244 100644
--- a/xmpp/receivetask.cc
+++ b/xmpp/receivetask.cc
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/xmpp/receivetask.h"
#include "talk/xmpp/constants.h"
+#include "talk/xmpp/receivetask.h"
namespace buzz {
diff --git a/xmpp/rostermodule.h b/xmpp/rostermodule.h
index 7e14dc1..dfb647d 100644
--- a/xmpp/rostermodule.h
+++ b/xmpp/rostermodule.h
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _rostermodule_h_
-#define _rostermodule_h_
+#ifndef TALK_XMPP_ROSTERMODULE_H_
+#define TALK_XMPP_ROSTERMODULE_H_
#include "talk/xmpp/module.h"
@@ -345,4 +345,4 @@
}
-#endif
+#endif // TALK_XMPP_ROSTERMODULE_H_
diff --git a/xmpp/rostermodule_unittest.cc b/xmpp/rostermodule_unittest.cc
index 9273eb5..cb7f773 100644
--- a/xmpp/rostermodule_unittest.cc
+++ b/xmpp/rostermodule_unittest.cc
@@ -25,17 +25,17 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string>
-#include <sstream>
#include <iostream>
+#include <sstream>
+#include <string>
-#include "talk/base/gunit.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/xmpp/xmppengine.h"
-#include "talk/xmpp/rostermodule.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "talk/xmpp/rostermodule.h"
#include "talk/xmpp/util_unittest.h"
+#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/gunit.h"
+#include "webrtc/base/scoped_ptr.h"
#define TEST_OK(x) EXPECT_EQ((x),XMPP_RETURN_OK)
#define TEST_BADARGUMENT(x) EXPECT_EQ((x),XMPP_RETURN_BADARGUMENT)
@@ -267,7 +267,7 @@
status->AddAttr(QN_STATUS, STR_PSTN_CONFERENCE_STATUS_CONNECTING);
XmlElement presence_xml(QN_PRESENCE);
presence_xml.AddElement(status);
- talk_base::scoped_ptr<XmppPresence> presence(XmppPresence::Create());
+ rtc::scoped_ptr<XmppPresence> presence(XmppPresence::Create());
presence->set_raw_xml(&presence_xml);
EXPECT_EQ(presence->connection_status(), XMPP_CONNECTION_STATUS_CONNECTING);
}
@@ -275,11 +275,11 @@
TEST_F(RosterModuleTest, TestOutgoingPresence) {
std::stringstream dump;
- talk_base::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
+ rtc::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
XmppTestHandler handler(engine.get());
XmppTestRosterHandler roster_handler;
- talk_base::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
+ rtc::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
roster->set_roster_handler(&roster_handler);
// Configure the roster module
@@ -381,7 +381,7 @@
EXPECT_EQ(handler.SessionActivity(), "");
// Construct a directed presence
- talk_base::scoped_ptr<XmppPresence> directed_presence(XmppPresence::Create());
+ rtc::scoped_ptr<XmppPresence> directed_presence(XmppPresence::Create());
TEST_OK(directed_presence->set_available(XMPP_PRESENCE_AVAILABLE));
TEST_OK(directed_presence->set_priority(120));
TEST_OK(directed_presence->set_status("*very* available"));
@@ -398,11 +398,11 @@
}
TEST_F(RosterModuleTest, TestIncomingPresence) {
- talk_base::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
+ rtc::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
XmppTestHandler handler(engine.get());
XmppTestRosterHandler roster_handler;
- talk_base::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
+ rtc::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
roster->set_roster_handler(&roster_handler);
// Configure the roster module
@@ -530,11 +530,11 @@
}
TEST_F(RosterModuleTest, TestPresenceSubscription) {
- talk_base::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
+ rtc::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
XmppTestHandler handler(engine.get());
XmppTestRosterHandler roster_handler;
- talk_base::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
+ rtc::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
roster->set_roster_handler(&roster_handler);
// Configure the roster module
@@ -593,11 +593,11 @@
}
TEST_F(RosterModuleTest, TestRosterReceive) {
- talk_base::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
+ rtc::scoped_ptr<XmppEngine> engine(XmppEngine::Create());
XmppTestHandler handler(engine.get());
XmppTestRosterHandler roster_handler;
- talk_base::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
+ rtc::scoped_ptr<XmppRosterModule> roster(XmppRosterModule::Create());
roster->set_roster_handler(&roster_handler);
// Configure the roster module
@@ -713,7 +713,7 @@
EXPECT_EQ(handler.SessionActivity(), "");
// Request that someone be added
- talk_base::scoped_ptr<XmppRosterContact> contact(XmppRosterContact::Create());
+ rtc::scoped_ptr<XmppRosterContact> contact(XmppRosterContact::Create());
TEST_OK(contact->set_jid(Jid("brandt@example.net")));
TEST_OK(contact->set_name("Brandt"));
TEST_OK(contact->AddGroup("Business Partners"));
diff --git a/xmpp/rostermoduleimpl.cc b/xmpp/rostermoduleimpl.cc
index 993cfa9..e52e78e 100644
--- a/xmpp/rostermoduleimpl.cc
+++ b/xmpp/rostermoduleimpl.cc
@@ -25,16 +25,16 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <vector>
-#include <string>
-#include <map>
#include <algorithm>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
-#include "talk/base/stringencode.h"
+#include <map>
+#include <sstream>
+#include <string>
+#include <vector>
#include "talk/xmpp/constants.h"
#include "talk/xmpp/rostermoduleimpl.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/stringencode.h"
namespace buzz {
@@ -217,7 +217,7 @@
return 0;
int raw_priority = 0;
- if (!talk_base::FromString(raw_xml_->TextNamed(QN_PRIORITY), &raw_priority))
+ if (!rtc::FromString(raw_xml_->TextNamed(QN_PRIORITY), &raw_priority))
raw_priority = 0;
if (raw_priority < -128)
raw_priority = -128;
@@ -238,7 +238,7 @@
raw_xml_->ClearNamedChildren(QN_PRIORITY);
if (0 != priority) {
std::string priority_string;
- if (talk_base::ToString(priority, &priority_string)) {
+ if (rtc::ToString(priority, &priority_string)) {
raw_xml_->AddElement(new XmlElement(QN_PRIORITY));
raw_xml_->AddText(priority_string, 1);
}
diff --git a/xmpp/rostermoduleimpl.h b/xmpp/rostermoduleimpl.h
index df6b70f..37d1117 100644
--- a/xmpp/rostermoduleimpl.h
+++ b/xmpp/rostermoduleimpl.h
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _rostermoduleimpl_h_
-#define _rostermoduleimpl_h_
+#ifndef TALK_XMPP_XMPPTHREAD_H_
+#define TALK_XMPP_XMPPTHREAD_H_
#include "talk/xmpp/moduleimpl.h"
#include "talk/xmpp/rostermodule.h"
@@ -103,7 +103,7 @@
// Store everything in the XML element. If this becomes a perf issue we can
// cache the data.
- talk_base::scoped_ptr<XmlElement> raw_xml_;
+ rtc::scoped_ptr<XmlElement> raw_xml_;
};
//! A contact as given by the server
@@ -168,7 +168,7 @@
int group_count_;
int group_index_returned_;
XmlElement * group_returned_;
- talk_base::scoped_ptr<XmlElement> raw_xml_;
+ rtc::scoped_ptr<XmlElement> raw_xml_;
};
//! An XmppModule for handle roster and presence functionality
@@ -290,13 +290,13 @@
typedef std::vector<XmppPresenceImpl*> PresenceVector;
typedef std::map<Jid, PresenceVector*> JidPresenceVectorMap;
- talk_base::scoped_ptr<JidPresenceVectorMap> incoming_presence_map_;
- talk_base::scoped_ptr<PresenceVector> incoming_presence_vector_;
+ rtc::scoped_ptr<JidPresenceVectorMap> incoming_presence_map_;
+ rtc::scoped_ptr<PresenceVector> incoming_presence_vector_;
typedef std::vector<XmppRosterContactImpl*> ContactVector;
- talk_base::scoped_ptr<ContactVector> contacts_;
+ rtc::scoped_ptr<ContactVector> contacts_;
};
}
-#endif
+#endif // TALK_XMPP_XMPPTHREAD_H_
diff --git a/xmpp/saslcookiemechanism.h b/xmpp/saslcookiemechanism.h
index ded9e97..eda142c 100644
--- a/xmpp/saslcookiemechanism.h
+++ b/xmpp/saslcookiemechanism.h
@@ -28,10 +28,10 @@
#ifndef TALK_XMPP_SASLCOOKIEMECHANISM_H_
#define TALK_XMPP_SASLCOOKIEMECHANISM_H_
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/xmpp/saslmechanism.h"
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "talk/xmpp/saslmechanism.h"
namespace buzz {
diff --git a/xmpp/saslhandler.h b/xmpp/saslhandler.h
index bead8aa..a4a73e4 100644
--- a/xmpp/saslhandler.h
+++ b/xmpp/saslhandler.h
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _SASLHANDLER_H_
-#define _SASLHANDLER_H_
+#ifndef TALK_XMPP_SASLHANDLER_H_
+#define TALK_XMPP_SASLHANDLER_H_
#include <string>
#include <vector>
@@ -56,4 +56,4 @@
}
-#endif
+#endif // TALK_XMPP_SASLHANDLER_H_
diff --git a/xmpp/saslmechanism.cc b/xmpp/saslmechanism.cc
index 2645ac0..8877084 100644
--- a/xmpp/saslmechanism.cc
+++ b/xmpp/saslmechanism.cc
@@ -25,12 +25,12 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/base/base64.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/saslmechanism.h"
+#include "webrtc/base/base64.h"
-using talk_base::Base64;
+using rtc::Base64;
namespace buzz {
diff --git a/xmpp/saslmechanism.h b/xmpp/saslmechanism.h
index f2e5adc..ee419d1 100644
--- a/xmpp/saslmechanism.h
+++ b/xmpp/saslmechanism.h
@@ -25,8 +25,8 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _SASLMECHANISM_H_
-#define _SASLMECHANISM_H_
+#ifndef TALK_XMPP_SASLMECHANISM_H_
+#define TALK_XMPP_SASLMECHANISM_H_
#include <string>
@@ -71,4 +71,4 @@
}
-#endif
+#endif // TALK_XMPP_SASLMECHANISM_H_
diff --git a/xmpp/saslplainmechanism.h b/xmpp/saslplainmechanism.h
index f0793b4..36b9bb9 100644
--- a/xmpp/saslplainmechanism.h
+++ b/xmpp/saslplainmechanism.h
@@ -28,15 +28,15 @@
#ifndef TALK_XMPP_SASLPLAINMECHANISM_H_
#define TALK_XMPP_SASLPLAINMECHANISM_H_
-#include "talk/base/cryptstring.h"
#include "talk/xmpp/saslmechanism.h"
+#include "webrtc/base/cryptstring.h"
namespace buzz {
class SaslPlainMechanism : public SaslMechanism {
public:
- SaslPlainMechanism(const buzz::Jid user_jid, const talk_base::CryptString & password) :
+ SaslPlainMechanism(const buzz::Jid user_jid, const rtc::CryptString & password) :
user_jid_(user_jid), password_(password) {}
virtual std::string GetMechanismName() { return "PLAIN"; }
@@ -46,7 +46,7 @@
XmlElement * el = new XmlElement(QN_SASL_AUTH, true);
el->AddAttr(QN_MECHANISM, "PLAIN");
- talk_base::FormatCryptString credential;
+ rtc::FormatCryptString credential;
credential.Append("\0", 1);
credential.Append(user_jid_.node());
credential.Append("\0", 1);
@@ -57,7 +57,7 @@
private:
Jid user_jid_;
- talk_base::CryptString password_;
+ rtc::CryptString password_;
};
}
diff --git a/xmpp/util_unittest.cc b/xmpp/util_unittest.cc
index 3d13007..3e47d3f 100644
--- a/xmpp/util_unittest.cc
+++ b/xmpp/util_unittest.cc
@@ -1,13 +1,13 @@
// Copyright 2004 Google, Inc. All Rights Reserved.
// Author: Joe Beda
-#include <string>
-#include <sstream>
#include <iostream>
-#include "talk/base/gunit.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/xmpp/xmppengine.h"
+#include <sstream>
+#include <string>
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/util_unittest.h"
+#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/gunit.h"
namespace buzz {
diff --git a/xmpp/util_unittest.h b/xmpp/util_unittest.h
index bb0656c..c9377ff 100644
--- a/xmpp/util_unittest.h
+++ b/xmpp/util_unittest.h
@@ -28,8 +28,8 @@
#ifndef TALK_XMPP_UTIL_UNITTEST_H_
#define TALK_XMPP_UTIL_UNITTEST_H_
-#include <string>
#include <sstream>
+#include <string>
#include "talk/xmpp/xmppengine.h"
namespace buzz {
diff --git a/xmpp/xmppauth.cc b/xmpp/xmppauth.cc
index efda967..d828475 100644
--- a/xmpp/xmppauth.cc
+++ b/xmpp/xmppauth.cc
@@ -40,8 +40,8 @@
}
void XmppAuth::StartPreXmppAuth(const buzz::Jid& jid,
- const talk_base::SocketAddress& server,
- const talk_base::CryptString& pass,
+ const rtc::SocketAddress& server,
+ const rtc::CryptString& pass,
const std::string& auth_mechanism,
const std::string& auth_token) {
jid_ = jid;
diff --git a/xmpp/xmppauth.h b/xmpp/xmppauth.h
index 5dd6963..fec73e6 100644
--- a/xmpp/xmppauth.h
+++ b/xmpp/xmppauth.h
@@ -30,11 +30,11 @@
#include <vector>
-#include "talk/base/cryptstring.h"
-#include "talk/base/sigslot.h"
#include "talk/xmpp/jid.h"
-#include "talk/xmpp/saslhandler.h"
#include "talk/xmpp/prexmppauth.h"
+#include "talk/xmpp/saslhandler.h"
+#include "webrtc/base/cryptstring.h"
+#include "webrtc/base/sigslot.h"
class XmppAuth: public buzz::PreXmppAuth {
public:
@@ -44,8 +44,8 @@
// TODO: Just have one "secret" that is either pass or
// token?
virtual void StartPreXmppAuth(const buzz::Jid& jid,
- const talk_base::SocketAddress& server,
- const talk_base::CryptString& pass,
+ const rtc::SocketAddress& server,
+ const rtc::CryptString& pass,
const std::string& auth_mechanism,
const std::string& auth_token);
@@ -68,7 +68,7 @@
private:
buzz::Jid jid_;
- talk_base::CryptString passwd_;
+ rtc::CryptString passwd_;
std::string auth_mechanism_;
std::string auth_token_;
bool done_;
diff --git a/xmpp/xmppclient.cc b/xmpp/xmppclient.cc
index 8927dad..27aa5e4 100644
--- a/xmpp/xmppclient.cc
+++ b/xmpp/xmppclient.cc
@@ -25,16 +25,17 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "xmppclient.h"
-#include "xmpptask.h"
-#include "talk/base/logging.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/scoped_ptr.h"
-#include "talk/base/stringutils.h"
+#include "talk/xmpp/xmppclient.h"
+
#include "talk/xmpp/constants.h"
-#include "talk/xmpp/saslplainmechanism.h"
-#include "talk/xmpp/prexmppauth.h"
#include "talk/xmpp/plainsaslhandler.h"
+#include "talk/xmpp/prexmppauth.h"
+#include "talk/xmpp/saslplainmechanism.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/stringutils.h"
+#include "xmpptask.h"
namespace buzz {
@@ -64,13 +65,13 @@
XmppClient* const client_;
// the two main objects
- talk_base::scoped_ptr<AsyncSocket> socket_;
- talk_base::scoped_ptr<XmppEngine> engine_;
- talk_base::scoped_ptr<PreXmppAuth> pre_auth_;
- talk_base::CryptString pass_;
+ rtc::scoped_ptr<AsyncSocket> socket_;
+ rtc::scoped_ptr<XmppEngine> engine_;
+ rtc::scoped_ptr<PreXmppAuth> pre_auth_;
+ rtc::CryptString pass_;
std::string auth_mechanism_;
std::string auth_token_;
- talk_base::SocketAddress server_;
+ rtc::SocketAddress server_;
std::string proxy_host_;
int proxy_port_;
XmppEngine::Error pre_engine_error_;
@@ -103,7 +104,7 @@
bool IsTestServer(const std::string& server_name,
const std::string& test_server_domain) {
return (!test_server_domain.empty() &&
- talk_base::ends_with(server_name.c_str(),
+ rtc::ends_with(server_name.c_str(),
test_server_domain.c_str()));
}
diff --git a/xmpp/xmppclient.h b/xmpp/xmppclient.h
index c8dd91e..53b2d24 100644
--- a/xmpp/xmppclient.h
+++ b/xmpp/xmppclient.h
@@ -29,13 +29,13 @@
#define TALK_XMPP_XMPPCLIENT_H_
#include <string>
-#include "talk/base/basicdefs.h"
-#include "talk/base/sigslot.h"
-#include "talk/base/task.h"
#include "talk/xmpp/asyncsocket.h"
#include "talk/xmpp/xmppclientsettings.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
+#include "webrtc/base/basicdefs.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/task.h"
namespace buzz {
@@ -73,7 +73,7 @@
public sigslot::has_slots<>
{
public:
- explicit XmppClient(talk_base::TaskParent * parent);
+ explicit XmppClient(rtc::TaskParent * parent);
virtual ~XmppClient();
XmppReturnStatus Connect(const XmppClientSettings & settings,
@@ -154,7 +154,7 @@
class Private;
friend class Private;
- talk_base::scoped_ptr<Private> d_;
+ rtc::scoped_ptr<Private> d_;
bool delivering_signal_;
bool valid_;
diff --git a/xmpp/xmppclientsettings.h b/xmpp/xmppclientsettings.h
index 8851f18..50028b7 100644
--- a/xmpp/xmppclientsettings.h
+++ b/xmpp/xmppclientsettings.h
@@ -29,8 +29,8 @@
#define TALK_XMPP_XMPPCLIENTSETTINGS_H_
#include "talk/p2p/base/port.h"
-#include "talk/base/cryptstring.h"
#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/cryptstring.h"
namespace buzz {
@@ -43,7 +43,7 @@
void set_user(const std::string& user) { user_ = user; }
void set_host(const std::string& host) { host_ = host; }
- void set_pass(const talk_base::CryptString& pass) { pass_ = pass; }
+ void set_pass(const rtc::CryptString& pass) { pass_ = pass; }
void set_auth_token(const std::string& mechanism,
const std::string& token) {
auth_mechanism_ = mechanism;
@@ -61,7 +61,7 @@
const std::string& user() const { return user_; }
const std::string& host() const { return host_; }
- const talk_base::CryptString& pass() const { return pass_; }
+ const rtc::CryptString& pass() const { return pass_; }
const std::string& auth_mechanism() const { return auth_mechanism_; }
const std::string& auth_token() const { return auth_token_; }
const std::string& resource() const { return resource_; }
@@ -73,7 +73,7 @@
private:
std::string user_;
std::string host_;
- talk_base::CryptString pass_;
+ rtc::CryptString pass_;
std::string auth_mechanism_;
std::string auth_token_;
std::string resource_;
@@ -87,40 +87,40 @@
public:
XmppClientSettings()
: protocol_(cricket::PROTO_TCP),
- proxy_(talk_base::PROXY_NONE),
+ proxy_(rtc::PROXY_NONE),
proxy_port_(80),
use_proxy_auth_(false) {
}
- void set_server(const talk_base::SocketAddress& server) {
+ void set_server(const rtc::SocketAddress& server) {
server_ = server;
}
void set_protocol(cricket::ProtocolType protocol) { protocol_ = protocol; }
- void set_proxy(talk_base::ProxyType f) { proxy_ = f; }
+ void set_proxy(rtc::ProxyType f) { proxy_ = f; }
void set_proxy_host(const std::string& host) { proxy_host_ = host; }
void set_proxy_port(int port) { proxy_port_ = port; };
void set_use_proxy_auth(bool f) { use_proxy_auth_ = f; }
void set_proxy_user(const std::string& user) { proxy_user_ = user; }
- void set_proxy_pass(const talk_base::CryptString& pass) { proxy_pass_ = pass; }
+ void set_proxy_pass(const rtc::CryptString& pass) { proxy_pass_ = pass; }
- const talk_base::SocketAddress& server() const { return server_; }
+ const rtc::SocketAddress& server() const { return server_; }
cricket::ProtocolType protocol() const { return protocol_; }
- talk_base::ProxyType proxy() const { return proxy_; }
+ rtc::ProxyType proxy() const { return proxy_; }
const std::string& proxy_host() const { return proxy_host_; }
int proxy_port() const { return proxy_port_; }
bool use_proxy_auth() const { return use_proxy_auth_; }
const std::string& proxy_user() const { return proxy_user_; }
- const talk_base::CryptString& proxy_pass() const { return proxy_pass_; }
+ const rtc::CryptString& proxy_pass() const { return proxy_pass_; }
private:
- talk_base::SocketAddress server_;
+ rtc::SocketAddress server_;
cricket::ProtocolType protocol_;
- talk_base::ProxyType proxy_;
+ rtc::ProxyType proxy_;
std::string proxy_host_;
int proxy_port_;
bool use_proxy_auth_;
std::string proxy_user_;
- talk_base::CryptString proxy_pass_;
+ rtc::CryptString proxy_pass_;
};
}
diff --git a/xmpp/xmppengine.h b/xmpp/xmppengine.h
index e1b35a3..461e90f 100644
--- a/xmpp/xmppengine.h
+++ b/xmpp/xmppengine.h
@@ -25,13 +25,13 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _xmppengine_h_
-#define _xmppengine_h_
+#ifndef TALK_XMPP_XMPPENGINE_H_
+#define TALK_XMPP_XMPPENGINE_H_
// also part of the API
+#include "webrtc/libjingle/xmllite/qname.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/jid.h"
-#include "talk/xmllite/qname.h"
-#include "talk/xmllite/xmlelement.h"
namespace buzz {
@@ -346,4 +346,4 @@
} while (false) \
-#endif
+#endif // TALK_XMPP_XMPPENGINE_H_
diff --git a/xmpp/xmppengine_unittest.cc b/xmpp/xmppengine_unittest.cc
index 46b79c6..b519a65 100644
--- a/xmpp/xmppengine_unittest.cc
+++ b/xmpp/xmppengine_unittest.cc
@@ -1,17 +1,17 @@
// Copyright 2004 Google Inc. All Rights Reserved
// Author: David Bau
-#include <string>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/xmllite/xmlelement.h"
+#include <sstream>
+#include <string>
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
-#include "talk/xmpp/util_unittest.h"
-#include "talk/xmpp/saslplainmechanism.h"
#include "talk/xmpp/plainsaslhandler.h"
+#include "talk/xmpp/saslplainmechanism.h"
+#include "talk/xmpp/util_unittest.h"
#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
using buzz::Jid;
using buzz::QName;
@@ -54,14 +54,14 @@
handler_.reset(new XmppTestHandler(engine_.get()));
Jid jid("david@my-server");
- talk_base::InsecureCryptStringImpl pass;
+ rtc::InsecureCryptStringImpl pass;
pass.password() = "david";
engine_->SetSessionHandler(handler_.get());
engine_->SetOutputHandler(handler_.get());
engine_->AddStanzaHandler(handler_.get());
engine_->SetUser(jid);
engine_->SetSaslHandler(
- new buzz::PlainSaslHandler(jid, talk_base::CryptString(pass), true));
+ new buzz::PlainSaslHandler(jid, rtc::CryptString(pass), true));
}
virtual void TearDown() {
handler_.reset();
@@ -70,8 +70,8 @@
void RunLogin();
private:
- talk_base::scoped_ptr<XmppEngine> engine_;
- talk_base::scoped_ptr<XmppTestHandler> handler_;
+ rtc::scoped_ptr<XmppEngine> engine_;
+ rtc::scoped_ptr<XmppTestHandler> handler_;
};
void XmppEngineTest::RunLogin() {
diff --git a/xmpp/xmppengineimpl.cc b/xmpp/xmppengineimpl.cc
index cf07ab7..5de9de7 100644
--- a/xmpp/xmppengineimpl.cc
+++ b/xmpp/xmppengineimpl.cc
@@ -31,12 +31,12 @@
#include <sstream>
#include <vector>
-#include "talk/base/common.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/xmllite/xmlprinter.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlprinter.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/saslhandler.h"
#include "talk/xmpp/xmpplogintask.h"
+#include "webrtc/base/common.h"
namespace buzz {
diff --git a/xmpp/xmppengineimpl.h b/xmpp/xmppengineimpl.h
index 8278681..4eacf2f 100644
--- a/xmpp/xmppengineimpl.h
+++ b/xmpp/xmppengineimpl.h
@@ -250,7 +250,7 @@
TlsOptions tls_option_;
std::string tls_server_hostname_;
std::string tls_server_domain_;
- talk_base::scoped_ptr<XmppLoginTask> login_task_;
+ rtc::scoped_ptr<XmppLoginTask> login_task_;
std::string lang_;
int next_id_;
@@ -259,7 +259,7 @@
bool encrypted_;
Error error_code_;
int subcode_;
- talk_base::scoped_ptr<XmlElement> stream_error_;
+ rtc::scoped_ptr<XmlElement> stream_error_;
bool raised_reset_;
XmppOutputHandler* output_handler_;
XmppSessionHandler* session_handler_;
@@ -267,14 +267,14 @@
XmlnsStack xmlns_stack_;
typedef std::vector<XmppStanzaHandler*> StanzaHandlerVector;
- talk_base::scoped_ptr<StanzaHandlerVector> stanza_handlers_[HL_COUNT];
+ rtc::scoped_ptr<StanzaHandlerVector> stanza_handlers_[HL_COUNT];
typedef std::vector<XmppIqEntry*> IqEntryVector;
- talk_base::scoped_ptr<IqEntryVector> iq_entries_;
+ rtc::scoped_ptr<IqEntryVector> iq_entries_;
- talk_base::scoped_ptr<SaslHandler> sasl_handler_;
+ rtc::scoped_ptr<SaslHandler> sasl_handler_;
- talk_base::scoped_ptr<std::stringstream> output_;
+ rtc::scoped_ptr<std::stringstream> output_;
};
} // namespace buzz
diff --git a/xmpp/xmppengineimpl_iq.cc b/xmpp/xmppengineimpl_iq.cc
index 5834b90..208e164 100644
--- a/xmpp/xmppengineimpl_iq.cc
+++ b/xmpp/xmppengineimpl_iq.cc
@@ -25,11 +25,11 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include <vector>
#include <algorithm>
-#include "talk/base/common.h"
-#include "talk/xmpp/xmppengineimpl.h"
+#include <vector>
#include "talk/xmpp/constants.h"
+#include "talk/xmpp/xmppengineimpl.h"
+#include "webrtc/base/common.h"
namespace buzz {
diff --git a/xmpp/xmpplogintask.cc b/xmpp/xmpplogintask.cc
index b3a2047..a48a94c 100644
--- a/xmpp/xmpplogintask.cc
+++ b/xmpp/xmpplogintask.cc
@@ -30,15 +30,15 @@
#include <string>
#include <vector>
-#include "talk/base/base64.h"
-#include "talk/base/common.h"
-#include "talk/xmllite/xmlelement.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/saslmechanism.h"
#include "talk/xmpp/xmppengineimpl.h"
+#include "webrtc/base/base64.h"
+#include "webrtc/base/common.h"
-using talk_base::ConstantLabel;
+using rtc::ConstantLabel;
namespace buzz {
@@ -103,7 +103,7 @@
#if _DEBUG
LOG(LS_VERBOSE) << "XmppLoginTask::Advance - "
- << talk_base::ErrorName(state_, LOGINTASK_STATES);
+ << rtc::ErrorName(state_, LOGINTASK_STATES);
#endif // _DEBUG
switch (state_) {
diff --git a/xmpp/xmpplogintask.h b/xmpp/xmpplogintask.h
index 9b3f5ae..8685658 100644
--- a/xmpp/xmpplogintask.h
+++ b/xmpp/xmpplogintask.h
@@ -31,10 +31,10 @@
#include <string>
#include <vector>
-#include "talk/base/logging.h"
-#include "talk/base/scoped_ptr.h"
#include "talk/xmpp/jid.h"
#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/scoped_ptr.h"
namespace buzz {
@@ -87,15 +87,15 @@
const XmlElement * pelStanza_;
bool isStart_;
std::string iqId_;
- talk_base::scoped_ptr<XmlElement> pelFeatures_;
+ rtc::scoped_ptr<XmlElement> pelFeatures_;
Jid fullJid_;
std::string streamId_;
- talk_base::scoped_ptr<std::vector<XmlElement *> > pvecQueuedStanzas_;
+ rtc::scoped_ptr<std::vector<XmlElement *> > pvecQueuedStanzas_;
- talk_base::scoped_ptr<SaslMechanism> sasl_mech_;
+ rtc::scoped_ptr<SaslMechanism> sasl_mech_;
#ifdef _DEBUG
- static const talk_base::ConstantLabel LOGINTASK_STATES[];
+ static const rtc::ConstantLabel LOGINTASK_STATES[];
#endif // _DEBUG
};
diff --git a/xmpp/xmpplogintask_unittest.cc b/xmpp/xmpplogintask_unittest.cc
index 51af81a..ae9a554 100644
--- a/xmpp/xmpplogintask_unittest.cc
+++ b/xmpp/xmpplogintask_unittest.cc
@@ -1,18 +1,18 @@
// Copyright 2004 Google Inc. All Rights Reserved
-#include <string>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
-#include "talk/base/cryptstring.h"
-#include "talk/base/gunit.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/xmpp/util_unittest.h"
+#include <sstream>
+#include <string>
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
-#include "talk/xmpp/saslplainmechanism.h"
#include "talk/xmpp/plainsaslhandler.h"
+#include "talk/xmpp/saslplainmechanism.h"
+#include "talk/xmpp/util_unittest.h"
#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/cryptstring.h"
+#include "webrtc/base/gunit.h"
using buzz::Jid;
using buzz::QName;
@@ -43,14 +43,14 @@
handler_.reset(new XmppTestHandler(engine_.get()));
Jid jid("david@my-server");
- talk_base::InsecureCryptStringImpl pass;
+ rtc::InsecureCryptStringImpl pass;
pass.password() = "david";
engine_->SetSessionHandler(handler_.get());
engine_->SetOutputHandler(handler_.get());
engine_->AddStanzaHandler(handler_.get());
engine_->SetUser(jid);
engine_->SetSaslHandler(
- new buzz::PlainSaslHandler(jid, talk_base::CryptString(pass), true));
+ new buzz::PlainSaslHandler(jid, rtc::CryptString(pass), true));
}
virtual void TearDown() {
handler_.reset();
@@ -60,8 +60,8 @@
void SetTlsOptions(buzz::TlsOptions option);
private:
- talk_base::scoped_ptr<XmppEngine> engine_;
- talk_base::scoped_ptr<XmppTestHandler> handler_;
+ rtc::scoped_ptr<XmppEngine> engine_;
+ rtc::scoped_ptr<XmppTestHandler> handler_;
};
void XmppLoginTaskTest::SetTlsOptions(buzz::TlsOptions option) {
diff --git a/xmpp/xmpppump.cc b/xmpp/xmpppump.cc
index 5732986..cf7aa7b 100644
--- a/xmpp/xmpppump.cc
+++ b/xmpp/xmpppump.cc
@@ -63,14 +63,14 @@
}
void XmppPump::WakeTasks() {
- talk_base::Thread::Current()->Post(this);
+ rtc::Thread::Current()->Post(this);
}
int64 XmppPump::CurrentTime() {
- return (int64)talk_base::Time();
+ return (int64)rtc::Time();
}
-void XmppPump::OnMessage(talk_base::Message *pmsg) {
+void XmppPump::OnMessage(rtc::Message *pmsg) {
RunTasks();
}
diff --git a/xmpp/xmpppump.h b/xmpp/xmpppump.h
index 7a374cc..ff72f54 100644
--- a/xmpp/xmpppump.h
+++ b/xmpp/xmpppump.h
@@ -28,13 +28,13 @@
#ifndef TALK_XMPP_XMPPPUMP_H_
#define TALK_XMPP_XMPPPUMP_H_
-#include "talk/base/messagequeue.h"
-#include "talk/base/taskrunner.h"
-#include "talk/base/thread.h"
-#include "talk/base/timeutils.h"
#include "talk/xmpp/xmppclient.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
+#include "webrtc/base/messagequeue.h"
+#include "webrtc/base/taskrunner.h"
+#include "webrtc/base/thread.h"
+#include "webrtc/base/timeutils.h"
namespace buzz {
@@ -46,7 +46,7 @@
virtual void OnStateChange(buzz::XmppEngine::State state) = 0;
};
-class XmppPump : public talk_base::MessageHandler, public talk_base::TaskRunner {
+class XmppPump : public rtc::MessageHandler, public rtc::TaskRunner {
public:
XmppPump(buzz::XmppPumpNotify * notify = NULL);
@@ -63,7 +63,7 @@
int64 CurrentTime();
- void OnMessage(talk_base::Message *pmsg);
+ void OnMessage(rtc::Message *pmsg);
buzz::XmppReturnStatus SendStanza(const buzz::XmlElement *stanza);
diff --git a/xmpp/xmppsocket.cc b/xmpp/xmppsocket.cc
index 31d1b69..67240ba 100644
--- a/xmpp/xmppsocket.cc
+++ b/xmpp/xmppsocket.cc
@@ -32,17 +32,17 @@
#endif
#include <errno.h>
-#include "talk/base/basicdefs.h"
-#include "talk/base/logging.h"
-#include "talk/base/thread.h"
+#include "webrtc/base/basicdefs.h"
+#include "webrtc/base/logging.h"
+#include "webrtc/base/thread.h"
#ifdef FEATURE_ENABLE_SSL
-#include "talk/base/ssladapter.h"
+#include "webrtc/base/ssladapter.h"
#endif
#ifdef USE_SSLSTREAM
-#include "talk/base/socketstream.h"
+#include "webrtc/base/socketstream.h"
#ifdef FEATURE_ENABLE_SSL
-#include "talk/base/sslstreamadapter.h"
+#include "webrtc/base/sslstreamadapter.h"
#endif // FEATURE_ENABLE_SSL
#endif // USE_SSLSTREAM
@@ -54,16 +54,16 @@
}
void XmppSocket::CreateCricketSocket(int family) {
- talk_base::Thread* pth = talk_base::Thread::Current();
+ rtc::Thread* pth = rtc::Thread::Current();
if (family == AF_UNSPEC) {
family = AF_INET;
}
- talk_base::AsyncSocket* socket =
+ rtc::AsyncSocket* socket =
pth->socketserver()->CreateAsyncSocket(family, SOCK_STREAM);
#ifndef USE_SSLSTREAM
#ifdef FEATURE_ENABLE_SSL
if (tls_ != buzz::TLS_DISABLED) {
- socket = talk_base::SSLAdapter::Create(socket);
+ socket = rtc::SSLAdapter::Create(socket);
}
#endif // FEATURE_ENABLE_SSL
cricket_socket_ = socket;
@@ -74,10 +74,10 @@
cricket_socket_->SignalCloseEvent.connect(this, &XmppSocket::OnCloseEvent);
#else // USE_SSLSTREAM
cricket_socket_ = socket;
- stream_ = new talk_base::SocketStream(cricket_socket_);
+ stream_ = new rtc::SocketStream(cricket_socket_);
#ifdef FEATURE_ENABLE_SSL
if (tls_ != buzz::TLS_DISABLED)
- stream_ = talk_base::SSLStreamAdapter::Create(stream_);
+ stream_ = rtc::SSLStreamAdapter::Create(stream_);
#endif // FEATURE_ENABLE_SSL
stream_->SignalEvent.connect(this, &XmppSocket::OnEvent);
#endif // USE_SSLSTREAM
@@ -93,11 +93,11 @@
}
#ifndef USE_SSLSTREAM
-void XmppSocket::OnReadEvent(talk_base::AsyncSocket * socket) {
+void XmppSocket::OnReadEvent(rtc::AsyncSocket * socket) {
SignalRead();
}
-void XmppSocket::OnWriteEvent(talk_base::AsyncSocket * socket) {
+void XmppSocket::OnWriteEvent(rtc::AsyncSocket * socket) {
// Write bytes if there are any
while (buffer_.Length() != 0) {
int written = cricket_socket_->Send(buffer_.Data(), buffer_.Length());
@@ -111,7 +111,7 @@
}
}
-void XmppSocket::OnConnectEvent(talk_base::AsyncSocket * socket) {
+void XmppSocket::OnConnectEvent(rtc::AsyncSocket * socket) {
#if defined(FEATURE_ENABLE_SSL)
if (state_ == buzz::AsyncSocket::STATE_TLS_CONNECTING) {
state_ = buzz::AsyncSocket::STATE_TLS_OPEN;
@@ -124,20 +124,20 @@
SignalConnected();
}
-void XmppSocket::OnCloseEvent(talk_base::AsyncSocket * socket, int error) {
+void XmppSocket::OnCloseEvent(rtc::AsyncSocket * socket, int error) {
SignalCloseEvent(error);
}
#else // USE_SSLSTREAM
-void XmppSocket::OnEvent(talk_base::StreamInterface* stream,
+void XmppSocket::OnEvent(rtc::StreamInterface* stream,
int events, int err) {
- if ((events & talk_base::SE_OPEN)) {
+ if ((events & rtc::SE_OPEN)) {
#if defined(FEATURE_ENABLE_SSL)
if (state_ == buzz::AsyncSocket::STATE_TLS_CONNECTING) {
state_ = buzz::AsyncSocket::STATE_TLS_OPEN;
SignalSSLConnected();
- events |= talk_base::SE_WRITE;
+ events |= rtc::SE_WRITE;
} else
#endif
{
@@ -145,28 +145,28 @@
SignalConnected();
}
}
- if ((events & talk_base::SE_READ))
+ if ((events & rtc::SE_READ))
SignalRead();
- if ((events & talk_base::SE_WRITE)) {
+ if ((events & rtc::SE_WRITE)) {
// Write bytes if there are any
while (buffer_.Length() != 0) {
- talk_base::StreamResult result;
+ rtc::StreamResult result;
size_t written;
int error;
result = stream_->Write(buffer_.Data(), buffer_.Length(),
&written, &error);
- if (result == talk_base::SR_ERROR) {
+ if (result == rtc::SR_ERROR) {
LOG(LS_ERROR) << "Send error: " << error;
return;
}
- if (result == talk_base::SR_BLOCK)
+ if (result == rtc::SR_BLOCK)
return;
- ASSERT(result == talk_base::SR_SUCCESS);
+ ASSERT(result == rtc::SR_SUCCESS);
ASSERT(written > 0);
buffer_.Shift(written);
}
}
- if ((events & talk_base::SE_CLOSE))
+ if ((events & rtc::SE_CLOSE))
SignalCloseEvent(err);
}
#endif // USE_SSLSTREAM
@@ -183,7 +183,7 @@
return 0;
}
-bool XmppSocket::Connect(const talk_base::SocketAddress& addr) {
+bool XmppSocket::Connect(const rtc::SocketAddress& addr) {
if (cricket_socket_ == NULL) {
CreateCricketSocket(addr.family());
}
@@ -201,8 +201,8 @@
return true;
}
#else // USE_SSLSTREAM
- talk_base::StreamResult result = stream_->Read(data, len, len_read, NULL);
- if (result == talk_base::SR_SUCCESS)
+ rtc::StreamResult result = stream_->Read(data, len, len_read, NULL);
+ if (result == rtc::SR_SUCCESS)
return true;
#endif // USE_SSLSTREAM
return false;
@@ -213,7 +213,7 @@
#ifndef USE_SSLSTREAM
OnWriteEvent(cricket_socket_);
#else // USE_SSLSTREAM
- OnEvent(stream_, talk_base::SE_WRITE, 0);
+ OnEvent(stream_, rtc::SE_WRITE, 0);
#endif // USE_SSLSTREAM
return true;
}
@@ -241,13 +241,13 @@
if (tls_ == buzz::TLS_DISABLED)
return false;
#ifndef USE_SSLSTREAM
- talk_base::SSLAdapter* ssl_adapter =
- static_cast<talk_base::SSLAdapter *>(cricket_socket_);
+ rtc::SSLAdapter* ssl_adapter =
+ static_cast<rtc::SSLAdapter *>(cricket_socket_);
if (ssl_adapter->StartSSL(domainname.c_str(), false) != 0)
return false;
#else // USE_SSLSTREAM
- talk_base::SSLStreamAdapter* ssl_stream =
- static_cast<talk_base::SSLStreamAdapter *>(stream_);
+ rtc::SSLStreamAdapter* ssl_stream =
+ static_cast<rtc::SSLStreamAdapter *>(stream_);
if (ssl_stream->StartSSLWithServer(domainname.c_str()) != 0)
return false;
#endif // USE_SSLSTREAM
diff --git a/xmpp/xmppsocket.h b/xmpp/xmppsocket.h
index f89333f..3d6df52 100644
--- a/xmpp/xmppsocket.h
+++ b/xmpp/xmppsocket.h
@@ -28,21 +28,21 @@
#ifndef TALK_XMPP_XMPPSOCKET_H_
#define TALK_XMPP_XMPPSOCKET_H_
-#include "talk/base/asyncsocket.h"
-#include "talk/base/bytebuffer.h"
-#include "talk/base/sigslot.h"
#include "talk/xmpp/asyncsocket.h"
#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/asyncsocket.h"
+#include "webrtc/base/bytebuffer.h"
+#include "webrtc/base/sigslot.h"
// The below define selects the SSLStreamAdapter implementation for
// SSL, as opposed to the SSLAdapter socket adapter.
// #define USE_SSLSTREAM
-namespace talk_base {
+namespace rtc {
class StreamInterface;
class SocketAddress;
};
-extern talk_base::AsyncSocket* cricket_socket_;
+extern rtc::AsyncSocket* cricket_socket_;
namespace buzz {
@@ -55,7 +55,7 @@
virtual buzz::AsyncSocket::Error error();
virtual int GetError();
- virtual bool Connect(const talk_base::SocketAddress& addr);
+ virtual bool Connect(const rtc::SocketAddress& addr);
virtual bool Read(char * data, size_t len, size_t* len_read);
virtual bool Write(const char * data, size_t len);
virtual bool Close();
@@ -66,20 +66,20 @@
private:
void CreateCricketSocket(int family);
#ifndef USE_SSLSTREAM
- void OnReadEvent(talk_base::AsyncSocket * socket);
- void OnWriteEvent(talk_base::AsyncSocket * socket);
- void OnConnectEvent(talk_base::AsyncSocket * socket);
- void OnCloseEvent(talk_base::AsyncSocket * socket, int error);
+ void OnReadEvent(rtc::AsyncSocket * socket);
+ void OnWriteEvent(rtc::AsyncSocket * socket);
+ void OnConnectEvent(rtc::AsyncSocket * socket);
+ void OnCloseEvent(rtc::AsyncSocket * socket, int error);
#else // USE_SSLSTREAM
- void OnEvent(talk_base::StreamInterface* stream, int events, int err);
+ void OnEvent(rtc::StreamInterface* stream, int events, int err);
#endif // USE_SSLSTREAM
- talk_base::AsyncSocket * cricket_socket_;
+ rtc::AsyncSocket * cricket_socket_;
#ifdef USE_SSLSTREAM
- talk_base::StreamInterface *stream_;
+ rtc::StreamInterface *stream_;
#endif // USE_SSLSTREAM
buzz::AsyncSocket::State state_;
- talk_base::ByteBuffer buffer_;
+ rtc::ByteBuffer buffer_;
buzz::TlsOptions tls_;
};
diff --git a/xmpp/xmppstanzaparser.cc b/xmpp/xmppstanzaparser.cc
index 6c3ef5f..4795839 100644
--- a/xmpp/xmppstanzaparser.cc
+++ b/xmpp/xmppstanzaparser.cc
@@ -27,9 +27,9 @@
#include "talk/xmpp/xmppstanzaparser.h"
-#include "talk/xmllite/xmlelement.h"
-#include "talk/base/common.h"
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/constants.h"
+#include "webrtc/base/common.h"
#ifdef EXPAT_RELATIVE_PATH
#include "expat.h"
#else
@@ -98,8 +98,8 @@
void
XmppStanzaParser::IncomingError(
XmlParseContext * pctx, XML_Error errCode) {
- UNUSED(pctx);
- UNUSED(errCode);
+ RTC_UNUSED(pctx);
+ RTC_UNUSED(errCode);
psph_->XmlError();
}
diff --git a/xmpp/xmppstanzaparser.h b/xmpp/xmppstanzaparser.h
index c6f8b08..ffb3275 100644
--- a/xmpp/xmppstanzaparser.h
+++ b/xmpp/xmppstanzaparser.h
@@ -25,11 +25,11 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef _xmppstanzaparser_h_
-#define _xmppstanzaparser_h_
+#ifndef TALK_XMPP_XMPPSTANZAPARSER_H_
+#define TALK_XMPP_XMPPSTANZAPARSER_H_
-#include "talk/xmllite/xmlparser.h"
-#include "talk/xmllite/xmlbuilder.h"
+#include "webrtc/libjingle/xmllite/xmlbuilder.h"
+#include "webrtc/libjingle/xmllite/xmlparser.h"
namespace buzz {
@@ -94,4 +94,4 @@
}
-#endif
+#endif // TALK_XMPP_XMPPSTANZAPARSER_H_
diff --git a/xmpp/xmppstanzaparser_unittest.cc b/xmpp/xmppstanzaparser_unittest.cc
index 06faf87..0b114c0 100644
--- a/xmpp/xmppstanzaparser_unittest.cc
+++ b/xmpp/xmppstanzaparser_unittest.cc
@@ -1,13 +1,13 @@
// Copyright 2004 Google Inc. All Rights Reserved
-#include <string>
-#include <sstream>
#include <iostream>
-#include "talk/base/common.h"
-#include "talk/base/gunit.h"
-#include "talk/xmllite/xmlelement.h"
+#include <sstream>
+#include <string>
+#include "webrtc/libjingle/xmllite/xmlelement.h"
#include "talk/xmpp/xmppstanzaparser.h"
+#include "webrtc/base/common.h"
+#include "webrtc/base/gunit.h"
using buzz::QName;
using buzz::XmlElement;
diff --git a/xmpp/xmpptask.cc b/xmpp/xmpptask.cc
index 046f7a1..c5e86fa 100644
--- a/xmpp/xmpptask.cc
+++ b/xmpp/xmpptask.cc
@@ -25,10 +25,10 @@
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "talk/xmpp/xmpptask.h"
+#include "talk/xmpp/constants.h"
#include "talk/xmpp/xmppclient.h"
#include "talk/xmpp/xmppengine.h"
-#include "talk/xmpp/constants.h"
+#include "talk/xmpp/xmpptask.h"
namespace buzz {
diff --git a/xmpp/xmpptask.h b/xmpp/xmpptask.h
index 6a88f98..f6dd156 100644
--- a/xmpp/xmpptask.h
+++ b/xmpp/xmpptask.h
@@ -28,12 +28,12 @@
#ifndef TALK_XMPP_XMPPTASK_H_
#define TALK_XMPP_XMPPTASK_H_
-#include <string>
#include <deque>
-#include "talk/base/sigslot.h"
-#include "talk/base/task.h"
-#include "talk/base/taskparent.h"
+#include <string>
#include "talk/xmpp/xmppengine.h"
+#include "webrtc/base/sigslot.h"
+#include "webrtc/base/task.h"
+#include "webrtc/base/taskparent.h"
namespace buzz {
@@ -94,9 +94,9 @@
// We really ought to inherit from a TaskParentInterface, but we tried
// that and it's way too complicated to change
// Task/TaskParent/TaskRunner. For now, this works.
-class XmppTaskParentInterface : public talk_base::Task {
+class XmppTaskParentInterface : public rtc::Task {
public:
- explicit XmppTaskParentInterface(talk_base::TaskParent* parent)
+ explicit XmppTaskParentInterface(rtc::TaskParent* parent)
: Task(parent) {
}
virtual ~XmppTaskParentInterface() {}
@@ -176,7 +176,7 @@
bool stopped_;
std::deque<XmlElement*> stanza_queue_;
- talk_base::scoped_ptr<XmlElement> next_stanza_;
+ rtc::scoped_ptr<XmlElement> next_stanza_;
std::string id_;
#ifdef _DEBUG
diff --git a/xmpp/xmppthread.cc b/xmpp/xmppthread.cc
index 716aaf8..e67bffe 100644
--- a/xmpp/xmppthread.cc
+++ b/xmpp/xmppthread.cc
@@ -36,7 +36,7 @@
const uint32 MSG_LOGIN = 1;
const uint32 MSG_DISCONNECT = 2;
-struct LoginData: public talk_base::MessageData {
+struct LoginData: public rtc::MessageData {
LoginData(const buzz::XmppClientSettings& s) : xcs(s) {}
virtual ~LoginData() {}
@@ -55,7 +55,7 @@
}
void XmppThread::ProcessMessages(int cms) {
- talk_base::Thread::ProcessMessages(cms);
+ rtc::Thread::ProcessMessages(cms);
}
void XmppThread::Login(const buzz::XmppClientSettings& xcs) {
@@ -69,7 +69,7 @@
void XmppThread::OnStateChange(buzz::XmppEngine::State state) {
}
-void XmppThread::OnMessage(talk_base::Message* pmsg) {
+void XmppThread::OnMessage(rtc::Message* pmsg) {
if (pmsg->message_id == MSG_LOGIN) {
ASSERT(pmsg->pdata != NULL);
LoginData* data = reinterpret_cast<LoginData*>(pmsg->pdata);
diff --git a/xmpp/xmppthread.h b/xmpp/xmppthread.h
index 62a5ce6..bfb74d6 100644
--- a/xmpp/xmppthread.h
+++ b/xmpp/xmppthread.h
@@ -28,16 +28,16 @@
#ifndef TALK_XMPP_XMPPTHREAD_H_
#define TALK_XMPP_XMPPTHREAD_H_
-#include "talk/base/thread.h"
#include "talk/xmpp/xmppclientsettings.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpppump.h"
#include "talk/xmpp/xmppsocket.h"
+#include "webrtc/base/thread.h"
namespace buzz {
class XmppThread:
- public talk_base::Thread, buzz::XmppPumpNotify, talk_base::MessageHandler {
+ public rtc::Thread, buzz::XmppPumpNotify, rtc::MessageHandler {
public:
XmppThread();
~XmppThread();
@@ -53,7 +53,7 @@
buzz::XmppPump* pump_;
void OnStateChange(buzz::XmppEngine::State state);
- void OnMessage(talk_base::Message* pmsg);
+ void OnMessage(rtc::Message* pmsg);
};
} // namespace buzz