blob: 8561230821138e1f865b996942d2dc5756b8db0a [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/session/media/mediasession.h"
29
30#include <functional>
31#include <map>
32#include <set>
33#include <utility>
34
35#include "talk/base/helpers.h"
36#include "talk/base/logging.h"
37#include "talk/base/scoped_ptr.h"
38#include "talk/base/stringutils.h"
39#include "talk/media/base/constants.h"
40#include "talk/media/base/cryptoparams.h"
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000041#include "talk/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042#include "talk/p2p/base/constants.h"
43#include "talk/session/media/channelmanager.h"
44#include "talk/session/media/srtpfilter.h"
45#include "talk/xmpp/constants.h"
46
47namespace {
48const char kInline[] = "inline:";
49}
50
51namespace cricket {
52
53using talk_base::scoped_ptr;
54
55// RTP Profile names
56// http://www.iana.org/assignments/rtp-parameters/rtp-parameters.xml
57// RFC4585
58const char kMediaProtocolAvpf[] = "RTP/AVPF";
59// RFC5124
60const char kMediaProtocolSavpf[] = "RTP/SAVPF";
61
62const char kMediaProtocolRtpPrefix[] = "RTP/";
63
64const char kMediaProtocolSctp[] = "SCTP";
65const char kMediaProtocolDtlsSctp[] = "DTLS/SCTP";
66
67static bool IsMediaContentOfType(const ContentInfo* content,
68 MediaType media_type) {
69 if (!IsMediaContent(content)) {
70 return false;
71 }
72
73 const MediaContentDescription* mdesc =
74 static_cast<const MediaContentDescription*>(content->description);
75 return mdesc && mdesc->type() == media_type;
76}
77
78static bool CreateCryptoParams(int tag, const std::string& cipher,
79 CryptoParams *out) {
80 std::string key;
81 key.reserve(SRTP_MASTER_KEY_BASE64_LEN);
82
83 if (!talk_base::CreateRandomString(SRTP_MASTER_KEY_BASE64_LEN, &key)) {
84 return false;
85 }
86 out->tag = tag;
87 out->cipher_suite = cipher;
88 out->key_params = kInline;
89 out->key_params += key;
90 return true;
91}
92
93#ifdef HAVE_SRTP
94static bool AddCryptoParams(const std::string& cipher_suite,
95 CryptoParamsVec *out) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +000096 int size = static_cast<int>(out->size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
98 out->resize(size + 1);
99 return CreateCryptoParams(size, cipher_suite, &out->at(size));
100}
101
102void AddMediaCryptos(const CryptoParamsVec& cryptos,
103 MediaContentDescription* media) {
104 for (CryptoParamsVec::const_iterator crypto = cryptos.begin();
105 crypto != cryptos.end(); ++crypto) {
106 media->AddCrypto(*crypto);
107 }
108}
109
110bool CreateMediaCryptos(const std::vector<std::string>& crypto_suites,
111 MediaContentDescription* media) {
112 CryptoParamsVec cryptos;
113 for (std::vector<std::string>::const_iterator it = crypto_suites.begin();
114 it != crypto_suites.end(); ++it) {
115 if (!AddCryptoParams(*it, &cryptos)) {
116 return false;
117 }
118 }
119 AddMediaCryptos(cryptos, media);
120 return true;
121}
122#endif
123
124const CryptoParamsVec* GetCryptos(const MediaContentDescription* media) {
125 if (!media) {
126 return NULL;
127 }
128 return &media->cryptos();
129}
130
131bool FindMatchingCrypto(const CryptoParamsVec& cryptos,
132 const CryptoParams& crypto,
133 CryptoParams* out) {
134 for (CryptoParamsVec::const_iterator it = cryptos.begin();
135 it != cryptos.end(); ++it) {
136 if (crypto.Matches(*it)) {
137 *out = *it;
138 return true;
139 }
140 }
141 return false;
142}
143
144// For audio, HMAC 32 is prefered because of the low overhead.
145void GetSupportedAudioCryptoSuites(
146 std::vector<std::string>* crypto_suites) {
147#ifdef HAVE_SRTP
148 crypto_suites->push_back(CS_AES_CM_128_HMAC_SHA1_32);
149 crypto_suites->push_back(CS_AES_CM_128_HMAC_SHA1_80);
150#endif
151}
152
153void GetSupportedVideoCryptoSuites(
154 std::vector<std::string>* crypto_suites) {
155 GetSupportedDefaultCryptoSuites(crypto_suites);
156}
157
158void GetSupportedDataCryptoSuites(
159 std::vector<std::string>* crypto_suites) {
160 GetSupportedDefaultCryptoSuites(crypto_suites);
161}
162
163void GetSupportedDefaultCryptoSuites(
164 std::vector<std::string>* crypto_suites) {
165#ifdef HAVE_SRTP
166 crypto_suites->push_back(CS_AES_CM_128_HMAC_SHA1_80);
167#endif
168}
169
170// For video support only 80-bit SHA1 HMAC. For audio 32-bit HMAC is
171// tolerated unless bundle is enabled because it is low overhead. Pick the
172// crypto in the list that is supported.
173static bool SelectCrypto(const MediaContentDescription* offer,
174 bool bundle,
175 CryptoParams *crypto) {
176 bool audio = offer->type() == MEDIA_TYPE_AUDIO;
177 const CryptoParamsVec& cryptos = offer->cryptos();
178
179 for (CryptoParamsVec::const_iterator i = cryptos.begin();
180 i != cryptos.end(); ++i) {
181 if (CS_AES_CM_128_HMAC_SHA1_80 == i->cipher_suite ||
182 (CS_AES_CM_128_HMAC_SHA1_32 == i->cipher_suite && audio && !bundle)) {
183 return CreateCryptoParams(i->tag, i->cipher_suite, crypto);
184 }
185 }
186 return false;
187}
188
189static const StreamParams* FindFirstStreamParamsByCname(
190 const StreamParamsVec& params_vec,
191 const std::string& cname) {
192 for (StreamParamsVec::const_iterator it = params_vec.begin();
193 it != params_vec.end(); ++it) {
194 if (cname == it->cname)
195 return &*it;
196 }
197 return NULL;
198}
199
200// Generates a new CNAME or the CNAME of an already existing StreamParams
201// if a StreamParams exist for another Stream in streams with sync_label
202// sync_label.
203static bool GenerateCname(const StreamParamsVec& params_vec,
204 const MediaSessionOptions::Streams& streams,
205 const std::string& synch_label,
206 std::string* cname) {
207 ASSERT(cname != NULL);
208 if (!cname)
209 return false;
210
211 // Check if a CNAME exist for any of the other synched streams.
212 for (MediaSessionOptions::Streams::const_iterator stream_it = streams.begin();
213 stream_it != streams.end() ; ++stream_it) {
214 if (synch_label != stream_it->sync_label)
215 continue;
216
217 StreamParams param;
218 // groupid is empty for StreamParams generated using
219 // MediaSessionDescriptionFactory.
220 if (GetStreamByIds(params_vec, "", stream_it->id,
221 &param)) {
222 *cname = param.cname;
223 return true;
224 }
225 }
226 // No other stream seems to exist that we should sync with.
227 // Generate a random string for the RTCP CNAME, as stated in RFC 6222.
228 // This string is only used for synchronization, and therefore is opaque.
229 do {
230 if (!talk_base::CreateRandomString(16, cname)) {
231 ASSERT(false);
232 return false;
233 }
234 } while (FindFirstStreamParamsByCname(params_vec, *cname));
235
236 return true;
237}
238
239// Generate random SSRC values that are not already present in |params_vec|.
240// Either 2 or 1 ssrcs will be generated based on |include_rtx_stream| being
241// true or false. The generated values are added to |ssrcs|.
242static void GenerateSsrcs(const StreamParamsVec& params_vec,
243 bool include_rtx_stream,
244 std::vector<uint32>* ssrcs) {
245 unsigned int num_ssrcs = include_rtx_stream ? 2 : 1;
246 for (unsigned int i = 0; i < num_ssrcs; i++) {
247 uint32 candidate;
248 do {
249 candidate = talk_base::CreateRandomNonZeroId();
250 } while (GetStreamBySsrc(params_vec, candidate, NULL) ||
251 std::count(ssrcs->begin(), ssrcs->end(), candidate) > 0);
252 ssrcs->push_back(candidate);
253 }
254}
255
256// Returns false if we exhaust the range of SIDs.
257static bool GenerateSctpSid(const StreamParamsVec& params_vec,
258 uint32* sid) {
259 if (params_vec.size() > kMaxSctpSid) {
260 LOG(LS_WARNING) <<
261 "Could not generate an SCTP SID: too many SCTP streams.";
262 return false;
263 }
264 while (true) {
265 uint32 candidate = talk_base::CreateRandomNonZeroId() % kMaxSctpSid;
266 if (!GetStreamBySsrc(params_vec, candidate, NULL)) {
267 *sid = candidate;
268 return true;
269 }
270 }
271}
272
273static bool GenerateSctpSids(const StreamParamsVec& params_vec,
274 std::vector<uint32>* sids) {
275 uint32 sid;
276 if (!GenerateSctpSid(params_vec, &sid)) {
277 LOG(LS_WARNING) << "Could not generated an SCTP SID.";
278 return false;
279 }
280 sids->push_back(sid);
281 return true;
282}
283
284// Finds all StreamParams of all media types and attach them to stream_params.
285static void GetCurrentStreamParams(const SessionDescription* sdesc,
286 StreamParamsVec* stream_params) {
287 if (!sdesc)
288 return;
289
290 const ContentInfos& contents = sdesc->contents();
291 for (ContentInfos::const_iterator content = contents.begin();
292 content != contents.end(); ++content) {
293 if (!IsMediaContent(&*content)) {
294 continue;
295 }
296 const MediaContentDescription* media =
297 static_cast<const MediaContentDescription*>(
298 content->description);
299 const StreamParamsVec& streams = media->streams();
300 for (StreamParamsVec::const_iterator it = streams.begin();
301 it != streams.end(); ++it) {
302 stream_params->push_back(*it);
303 }
304 }
305}
306
307template <typename IdStruct>
308class UsedIds {
309 public:
310 UsedIds(int min_allowed_id, int max_allowed_id)
311 : min_allowed_id_(min_allowed_id),
312 max_allowed_id_(max_allowed_id),
313 next_id_(max_allowed_id) {
314 }
315
316 // Loops through all Id in |ids| and changes its id if it is
317 // already in use by another IdStruct. Call this methods with all Id
318 // in a session description to make sure no duplicate ids exists.
319 // Note that typename Id must be a type of IdStruct.
320 template <typename Id>
321 void FindAndSetIdUsed(std::vector<Id>* ids) {
322 for (typename std::vector<Id>::iterator it = ids->begin();
323 it != ids->end(); ++it) {
324 FindAndSetIdUsed(&*it);
325 }
326 }
327
328 // Finds and sets an unused id if the |idstruct| id is already in use.
329 void FindAndSetIdUsed(IdStruct* idstruct) {
330 const int original_id = idstruct->id;
331 int new_id = idstruct->id;
332
333 if (original_id > max_allowed_id_ || original_id < min_allowed_id_) {
334 // If the original id is not in range - this is an id that can't be
335 // dynamically changed.
336 return;
337 }
338
339 if (IsIdUsed(original_id)) {
340 new_id = FindUnusedId();
341 LOG(LS_WARNING) << "Duplicate id found. Reassigning from " << original_id
342 << " to " << new_id;
343 idstruct->id = new_id;
344 }
345 SetIdUsed(new_id);
346 }
347
348 private:
349 // Returns the first unused id in reverse order.
350 // This hopefully reduce the risk of more collisions. We want to change the
351 // default ids as little as possible.
352 int FindUnusedId() {
353 while (IsIdUsed(next_id_) && next_id_ >= min_allowed_id_) {
354 --next_id_;
355 }
356 ASSERT(next_id_ >= min_allowed_id_);
357 return next_id_;
358 }
359
360 bool IsIdUsed(int new_id) {
361 return id_set_.find(new_id) != id_set_.end();
362 }
363
364 void SetIdUsed(int new_id) {
365 id_set_.insert(new_id);
366 }
367
368 const int min_allowed_id_;
369 const int max_allowed_id_;
370 int next_id_;
371 std::set<int> id_set_;
372};
373
374// Helper class used for finding duplicate RTP payload types among audio, video
375// and data codecs. When bundle is used the payload types may not collide.
376class UsedPayloadTypes : public UsedIds<Codec> {
377 public:
378 UsedPayloadTypes()
379 : UsedIds<Codec>(kDynamicPayloadTypeMin, kDynamicPayloadTypeMax) {
380 }
381
382
383 private:
384 static const int kDynamicPayloadTypeMin = 96;
385 static const int kDynamicPayloadTypeMax = 127;
386};
387
388// Helper class used for finding duplicate RTP Header extension ids among
389// audio and video extensions.
390class UsedRtpHeaderExtensionIds : public UsedIds<RtpHeaderExtension> {
391 public:
392 UsedRtpHeaderExtensionIds()
393 : UsedIds<RtpHeaderExtension>(kLocalIdMin, kLocalIdMax) {
394 }
395
396 private:
397 // Min and Max local identifier as specified by RFC5285.
398 static const int kLocalIdMin = 1;
399 static const int kLocalIdMax = 255;
400};
401
402static bool IsSctp(const MediaContentDescription* desc) {
403 return ((desc->protocol() == kMediaProtocolSctp) ||
404 (desc->protocol() == kMediaProtocolDtlsSctp));
405}
406
407// Adds a StreamParams for each Stream in Streams with media type
408// media_type to content_description.
409// |current_params| - All currently known StreamParams of any media type.
410template <class C>
411static bool AddStreamParams(
412 MediaType media_type,
413 const MediaSessionOptions::Streams& streams,
414 StreamParamsVec* current_streams,
415 MediaContentDescriptionImpl<C>* content_description,
416 const bool add_legacy_stream) {
417 const bool include_rtx_stream =
418 ContainsRtxCodec(content_description->codecs());
419
420 if (streams.empty() && add_legacy_stream) {
421 // TODO(perkj): Remove this legacy stream when all apps use StreamParams.
422 std::vector<uint32> ssrcs;
423 if (IsSctp(content_description)) {
424 GenerateSctpSids(*current_streams, &ssrcs);
425 } else {
426 GenerateSsrcs(*current_streams, include_rtx_stream, &ssrcs);
427 }
428 if (include_rtx_stream) {
429 content_description->AddLegacyStream(ssrcs[0], ssrcs[1]);
430 content_description->set_multistream(true);
431 } else {
432 content_description->AddLegacyStream(ssrcs[0]);
433 }
434 return true;
435 }
436
437 MediaSessionOptions::Streams::const_iterator stream_it;
438 for (stream_it = streams.begin();
439 stream_it != streams.end(); ++stream_it) {
440 if (stream_it->type != media_type)
441 continue; // Wrong media type.
442
443 StreamParams param;
444 // groupid is empty for StreamParams generated using
445 // MediaSessionDescriptionFactory.
446 if (!GetStreamByIds(*current_streams, "", stream_it->id,
447 &param)) {
448 // This is a new stream.
449 // Get a CNAME. Either new or same as one of the other synched streams.
450 std::string cname;
451 if (!GenerateCname(*current_streams, streams, stream_it->sync_label,
452 &cname)) {
453 return false;
454 }
455
456 std::vector<uint32> ssrcs;
457 if (IsSctp(content_description)) {
458 GenerateSctpSids(*current_streams, &ssrcs);
459 } else {
460 GenerateSsrcs(*current_streams, include_rtx_stream, &ssrcs);
461 }
462 StreamParams stream_param;
463 stream_param.id = stream_it->id;
464 stream_param.ssrcs.push_back(ssrcs[0]);
465 if (include_rtx_stream) {
466 stream_param.AddFidSsrc(ssrcs[0], ssrcs[1]);
467 content_description->set_multistream(true);
468 }
469 stream_param.cname = cname;
470 stream_param.sync_label = stream_it->sync_label;
471 content_description->AddStream(stream_param);
472
473 // Store the new StreamParams in current_streams.
474 // This is necessary so that we can use the CNAME for other media types.
475 current_streams->push_back(stream_param);
476 } else {
477 content_description->AddStream(param);
478 }
479 }
480 return true;
481}
482
483// Updates the transport infos of the |sdesc| according to the given
484// |bundle_group|. The transport infos of the content names within the
485// |bundle_group| should be updated to use the ufrag and pwd of the first
486// content within the |bundle_group|.
487static bool UpdateTransportInfoForBundle(const ContentGroup& bundle_group,
488 SessionDescription* sdesc) {
489 // The bundle should not be empty.
490 if (!sdesc || !bundle_group.FirstContentName()) {
491 return false;
492 }
493
494 // We should definitely have a transport for the first content.
495 std::string selected_content_name = *bundle_group.FirstContentName();
496 const TransportInfo* selected_transport_info =
497 sdesc->GetTransportInfoByName(selected_content_name);
498 if (!selected_transport_info) {
499 return false;
500 }
501
502 // Set the other contents to use the same ICE credentials.
503 const std::string selected_ufrag =
504 selected_transport_info->description.ice_ufrag;
505 const std::string selected_pwd =
506 selected_transport_info->description.ice_pwd;
507 for (TransportInfos::iterator it =
508 sdesc->transport_infos().begin();
509 it != sdesc->transport_infos().end(); ++it) {
510 if (bundle_group.HasContentName(it->content_name) &&
511 it->content_name != selected_content_name) {
512 it->description.ice_ufrag = selected_ufrag;
513 it->description.ice_pwd = selected_pwd;
514 }
515 }
516 return true;
517}
518
519// Gets the CryptoParamsVec of the given |content_name| from |sdesc|, and
520// sets it to |cryptos|.
521static bool GetCryptosByName(const SessionDescription* sdesc,
522 const std::string& content_name,
523 CryptoParamsVec* cryptos) {
524 if (!sdesc || !cryptos) {
525 return false;
526 }
527
528 const ContentInfo* content = sdesc->GetContentByName(content_name);
529 if (!IsMediaContent(content) || !content->description) {
530 return false;
531 }
532
533 const MediaContentDescription* media_desc =
534 static_cast<const MediaContentDescription*>(content->description);
535 *cryptos = media_desc->cryptos();
536 return true;
537}
538
539// Predicate function used by the remove_if.
540// Returns true if the |crypto|'s cipher_suite is not found in |filter|.
541static bool CryptoNotFound(const CryptoParams crypto,
542 const CryptoParamsVec* filter) {
543 if (filter == NULL) {
544 return true;
545 }
546 for (CryptoParamsVec::const_iterator it = filter->begin();
547 it != filter->end(); ++it) {
548 if (it->cipher_suite == crypto.cipher_suite) {
549 return false;
550 }
551 }
552 return true;
553}
554
555// Prunes the |target_cryptos| by removing the crypto params (cipher_suite)
556// which are not available in |filter|.
557static void PruneCryptos(const CryptoParamsVec& filter,
558 CryptoParamsVec* target_cryptos) {
559 if (!target_cryptos) {
560 return;
561 }
562 target_cryptos->erase(std::remove_if(target_cryptos->begin(),
563 target_cryptos->end(),
564 bind2nd(ptr_fun(CryptoNotFound),
565 &filter)),
566 target_cryptos->end());
567}
568
569static bool IsRtpContent(SessionDescription* sdesc,
570 const std::string& content_name) {
571 bool is_rtp = false;
572 ContentInfo* content = sdesc->GetContentByName(content_name);
573 if (IsMediaContent(content)) {
574 MediaContentDescription* media_desc =
575 static_cast<MediaContentDescription*>(content->description);
576 if (!media_desc) {
577 return false;
578 }
579 is_rtp = media_desc->protocol().empty() ||
580 talk_base::starts_with(media_desc->protocol().data(),
581 kMediaProtocolRtpPrefix);
582 }
583 return is_rtp;
584}
585
586// Updates the crypto parameters of the |sdesc| according to the given
587// |bundle_group|. The crypto parameters of all the contents within the
588// |bundle_group| should be updated to use the common subset of the
589// available cryptos.
590static bool UpdateCryptoParamsForBundle(const ContentGroup& bundle_group,
591 SessionDescription* sdesc) {
592 // The bundle should not be empty.
593 if (!sdesc || !bundle_group.FirstContentName()) {
594 return false;
595 }
596
597 // Get the common cryptos.
598 const ContentNames& content_names = bundle_group.content_names();
599 CryptoParamsVec common_cryptos;
600 for (ContentNames::const_iterator it = content_names.begin();
601 it != content_names.end(); ++it) {
602 if (!IsRtpContent(sdesc, *it)) {
603 continue;
604 }
605 if (it == content_names.begin()) {
606 // Initial the common_cryptos with the first content in the bundle group.
607 if (!GetCryptosByName(sdesc, *it, &common_cryptos)) {
608 return false;
609 }
610 if (common_cryptos.empty()) {
611 // If there's no crypto params, we should just return.
612 return true;
613 }
614 } else {
615 CryptoParamsVec cryptos;
616 if (!GetCryptosByName(sdesc, *it, &cryptos)) {
617 return false;
618 }
619 PruneCryptos(cryptos, &common_cryptos);
620 }
621 }
622
623 if (common_cryptos.empty()) {
624 return false;
625 }
626
627 // Update to use the common cryptos.
628 for (ContentNames::const_iterator it = content_names.begin();
629 it != content_names.end(); ++it) {
630 if (!IsRtpContent(sdesc, *it)) {
631 continue;
632 }
633 ContentInfo* content = sdesc->GetContentByName(*it);
634 if (IsMediaContent(content)) {
635 MediaContentDescription* media_desc =
636 static_cast<MediaContentDescription*>(content->description);
637 if (!media_desc) {
638 return false;
639 }
640 media_desc->set_cryptos(common_cryptos);
641 }
642 }
643 return true;
644}
645
646template <class C>
647static bool ContainsRtxCodec(const std::vector<C>& codecs) {
648 typename std::vector<C>::const_iterator it;
649 for (it = codecs.begin(); it != codecs.end(); ++it) {
650 if (IsRtxCodec(*it)) {
651 return true;
652 }
653 }
654 return false;
655}
656
657template <class C>
658static bool IsRtxCodec(const C& codec) {
659 return stricmp(codec.name.c_str(), kRtxCodecName) == 0;
660}
661
662// Create a media content to be offered in a session-initiate,
663// according to the given options.rtcp_mux, options.is_muc,
664// options.streams, codecs, secure_transport, crypto, and streams. If we don't
665// currently have crypto (in current_cryptos) and it is enabled (in
666// secure_policy), crypto is created (according to crypto_suites). If
667// add_legacy_stream is true, and current_streams is empty, a legacy
668// stream is created. The created content is added to the offer.
669template <class C>
670static bool CreateMediaContentOffer(
671 const MediaSessionOptions& options,
672 const std::vector<C>& codecs,
673 const SecureMediaPolicy& secure_policy,
674 const CryptoParamsVec* current_cryptos,
675 const std::vector<std::string>& crypto_suites,
676 const RtpHeaderExtensions& rtp_extensions,
677 bool add_legacy_stream,
678 StreamParamsVec* current_streams,
679 MediaContentDescriptionImpl<C>* offer) {
680 offer->AddCodecs(codecs);
681 offer->SortCodecs();
682
683 offer->set_crypto_required(secure_policy == SEC_REQUIRED);
684 offer->set_rtcp_mux(options.rtcp_mux_enabled);
685 offer->set_multistream(options.is_muc);
686 offer->set_rtp_header_extensions(rtp_extensions);
687
688 if (!AddStreamParams(
689 offer->type(), options.streams, current_streams,
690 offer, add_legacy_stream)) {
691 return false;
692 }
693
694#ifdef HAVE_SRTP
695 if (secure_policy != SEC_DISABLED) {
696 if (current_cryptos) {
697 AddMediaCryptos(*current_cryptos, offer);
698 }
699 if (offer->cryptos().empty()) {
700 if (!CreateMediaCryptos(crypto_suites, offer)) {
701 return false;
702 }
703 }
704 }
705#endif
706
707 if (offer->crypto_required() && offer->cryptos().empty()) {
708 return false;
709 }
710 return true;
711}
712
713template <class C>
714static void NegotiateCodecs(const std::vector<C>& local_codecs,
715 const std::vector<C>& offered_codecs,
716 std::vector<C>* negotiated_codecs) {
717 typename std::vector<C>::const_iterator ours;
718 for (ours = local_codecs.begin();
719 ours != local_codecs.end(); ++ours) {
720 typename std::vector<C>::const_iterator theirs;
721 for (theirs = offered_codecs.begin();
722 theirs != offered_codecs.end(); ++theirs) {
723 if (ours->Matches(*theirs)) {
724 C negotiated = *ours;
725 negotiated.IntersectFeedbackParams(*theirs);
726 if (IsRtxCodec(negotiated)) {
727 // Only negotiate RTX if kCodecParamAssociatedPayloadType has been
728 // set.
729 std::string apt_value;
730 if (!theirs->GetParam(kCodecParamAssociatedPayloadType, &apt_value)) {
731 LOG(LS_WARNING) << "RTX missing associated payload type.";
732 continue;
733 }
734 negotiated.SetParam(kCodecParamAssociatedPayloadType, apt_value);
735 }
736 negotiated.id = theirs->id;
737 negotiated_codecs->push_back(negotiated);
738 }
739 }
740 }
741}
742
743template <class C>
744static bool FindMatchingCodec(const std::vector<C>& codecs,
745 const C& codec_to_match,
746 C* found_codec) {
747 for (typename std::vector<C>::const_iterator it = codecs.begin();
748 it != codecs.end(); ++it) {
749 if (it->Matches(codec_to_match)) {
750 if (found_codec != NULL) {
751 *found_codec= *it;
752 }
753 return true;
754 }
755 }
756 return false;
757}
758
759// Adds all codecs from |reference_codecs| to |offered_codecs| that dont'
760// already exist in |offered_codecs| and ensure the payload types don't
761// collide.
762template <class C>
763static void FindCodecsToOffer(
764 const std::vector<C>& reference_codecs,
765 std::vector<C>* offered_codecs,
766 UsedPayloadTypes* used_pltypes) {
767
768 typedef std::map<int, C> RtxCodecReferences;
769 RtxCodecReferences new_rtx_codecs;
770
771 // Find all new RTX codecs.
772 for (typename std::vector<C>::const_iterator it = reference_codecs.begin();
773 it != reference_codecs.end(); ++it) {
774 if (!FindMatchingCodec<C>(*offered_codecs, *it, NULL) && IsRtxCodec(*it)) {
775 C rtx_codec = *it;
776 int referenced_pl_type =
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000777 talk_base::FromString<int>(0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778 rtx_codec.params[kCodecParamAssociatedPayloadType]);
779 new_rtx_codecs.insert(std::pair<int, C>(referenced_pl_type,
780 rtx_codec));
781 }
782 }
783
784 // Add all new codecs that are not RTX codecs.
785 for (typename std::vector<C>::const_iterator it = reference_codecs.begin();
786 it != reference_codecs.end(); ++it) {
787 if (!FindMatchingCodec<C>(*offered_codecs, *it, NULL) && !IsRtxCodec(*it)) {
788 C codec = *it;
789 int original_payload_id = codec.id;
790 used_pltypes->FindAndSetIdUsed(&codec);
791 offered_codecs->push_back(codec);
792
793 // If this codec is referenced by a new RTX codec, update the reference
794 // in the RTX codec with the new payload type.
795 typename RtxCodecReferences::iterator rtx_it =
796 new_rtx_codecs.find(original_payload_id);
797 if (rtx_it != new_rtx_codecs.end()) {
798 C& rtx_codec = rtx_it->second;
799 rtx_codec.params[kCodecParamAssociatedPayloadType] =
800 talk_base::ToString(codec.id);
801 }
802 }
803 }
804
805 // Add all new RTX codecs.
806 for (typename RtxCodecReferences::iterator it = new_rtx_codecs.begin();
807 it != new_rtx_codecs.end(); ++it) {
808 C& rtx_codec = it->second;
809 used_pltypes->FindAndSetIdUsed(&rtx_codec);
810 offered_codecs->push_back(rtx_codec);
811 }
812}
813
814
815static bool FindByUri(const RtpHeaderExtensions& extensions,
816 const RtpHeaderExtension& ext_to_match,
817 RtpHeaderExtension* found_extension) {
818 for (RtpHeaderExtensions::const_iterator it = extensions.begin();
819 it != extensions.end(); ++it) {
820 // We assume that all URIs are given in a canonical format.
821 if (it->uri == ext_to_match.uri) {
822 if (found_extension != NULL) {
823 *found_extension= *it;
824 }
825 return true;
826 }
827 }
828 return false;
829}
830
831static void FindAndSetRtpHdrExtUsed(
832 const RtpHeaderExtensions& reference_extensions,
833 RtpHeaderExtensions* offered_extensions,
834 UsedRtpHeaderExtensionIds* used_extensions) {
835 for (RtpHeaderExtensions::const_iterator it = reference_extensions.begin();
836 it != reference_extensions.end(); ++it) {
837 if (!FindByUri(*offered_extensions, *it, NULL)) {
838 RtpHeaderExtension ext = *it;
839 used_extensions->FindAndSetIdUsed(&ext);
840 offered_extensions->push_back(ext);
841 }
842 }
843}
844
845static void NegotiateRtpHeaderExtensions(
846 const RtpHeaderExtensions& local_extensions,
847 const RtpHeaderExtensions& offered_extensions,
848 RtpHeaderExtensions* negotiated_extenstions) {
849 RtpHeaderExtensions::const_iterator ours;
850 for (ours = local_extensions.begin();
851 ours != local_extensions.end(); ++ours) {
852 RtpHeaderExtension theirs;
853 if (FindByUri(offered_extensions, *ours, &theirs)) {
854 // We respond with their RTP header extension id.
855 negotiated_extenstions->push_back(theirs);
856 }
857 }
858}
859
860static void StripCNCodecs(AudioCodecs* audio_codecs) {
861 AudioCodecs::iterator iter = audio_codecs->begin();
862 while (iter != audio_codecs->end()) {
863 if (stricmp(iter->name.c_str(), kComfortNoiseCodecName) == 0) {
864 iter = audio_codecs->erase(iter);
865 } else {
866 ++iter;
867 }
868 }
869}
870
871// Create a media content to be answered in a session-accept,
872// according to the given options.rtcp_mux, options.streams, codecs,
873// crypto, and streams. If we don't currently have crypto (in
874// current_cryptos) and it is enabled (in secure_policy), crypto is
875// created (according to crypto_suites). If add_legacy_stream is
876// true, and current_streams is empty, a legacy stream is created.
877// The codecs, rtcp_mux, and crypto are all negotiated with the offer
878// from the incoming session-initiate. If the negotiation fails, this
879// method returns false. The created content is added to the offer.
880template <class C>
881static bool CreateMediaContentAnswer(
882 const MediaContentDescriptionImpl<C>* offer,
883 const MediaSessionOptions& options,
884 const std::vector<C>& local_codecs,
885 const SecureMediaPolicy& sdes_policy,
886 const CryptoParamsVec* current_cryptos,
887 const RtpHeaderExtensions& local_rtp_extenstions,
888 StreamParamsVec* current_streams,
889 bool add_legacy_stream,
890 bool bundle_enabled,
891 MediaContentDescriptionImpl<C>* answer) {
892 std::vector<C> negotiated_codecs;
893 NegotiateCodecs(local_codecs, offer->codecs(), &negotiated_codecs);
894 answer->AddCodecs(negotiated_codecs);
895 answer->SortCodecs();
896 answer->set_protocol(offer->protocol());
897 RtpHeaderExtensions negotiated_rtp_extensions;
898 NegotiateRtpHeaderExtensions(local_rtp_extenstions,
899 offer->rtp_header_extensions(),
900 &negotiated_rtp_extensions);
901 answer->set_rtp_header_extensions(negotiated_rtp_extensions);
902
903 answer->set_rtcp_mux(options.rtcp_mux_enabled && offer->rtcp_mux());
904
905 if (sdes_policy != SEC_DISABLED) {
906 CryptoParams crypto;
907 if (SelectCrypto(offer, bundle_enabled, &crypto)) {
908 if (current_cryptos) {
909 FindMatchingCrypto(*current_cryptos, crypto, &crypto);
910 }
911 answer->AddCrypto(crypto);
912 }
913 }
914
915 if (answer->cryptos().empty() &&
916 (offer->crypto_required() || sdes_policy == SEC_REQUIRED)) {
917 return false;
918 }
919
920 if (!AddStreamParams(
921 answer->type(), options.streams, current_streams,
922 answer, add_legacy_stream)) {
923 return false; // Something went seriously wrong.
924 }
925
926 // Make sure the answer media content direction is per default set as
927 // described in RFC3264 section 6.1.
928 switch (offer->direction()) {
929 case MD_INACTIVE:
930 answer->set_direction(MD_INACTIVE);
931 break;
932 case MD_SENDONLY:
933 answer->set_direction(MD_RECVONLY);
934 break;
935 case MD_RECVONLY:
936 answer->set_direction(MD_SENDONLY);
937 break;
938 case MD_SENDRECV:
939 answer->set_direction(MD_SENDRECV);
940 break;
941 default:
942 break;
943 }
944
945 return true;
946}
947
948static bool IsMediaProtocolSupported(MediaType type,
949 const std::string& protocol) {
950 // Data channels can have a protocol of SCTP or SCTP/DTLS.
951 if (type == MEDIA_TYPE_DATA &&
952 (protocol == kMediaProtocolSctp ||
953 protocol == kMediaProtocolDtlsSctp)) {
954 return true;
955 }
956 // Since not all applications serialize and deserialize the media protocol,
957 // we will have to accept |protocol| to be empty.
958 return protocol == kMediaProtocolAvpf || protocol == kMediaProtocolSavpf ||
959 protocol.empty();
960}
961
962static void SetMediaProtocol(bool secure_transport,
963 MediaContentDescription* desc) {
964 if (!desc->cryptos().empty() || secure_transport)
965 desc->set_protocol(kMediaProtocolSavpf);
966 else
967 desc->set_protocol(kMediaProtocolAvpf);
968}
969
970void MediaSessionOptions::AddStream(MediaType type,
971 const std::string& id,
972 const std::string& sync_label) {
973 streams.push_back(Stream(type, id, sync_label));
974
975 if (type == MEDIA_TYPE_VIDEO)
976 has_video = true;
977 else if (type == MEDIA_TYPE_AUDIO)
978 has_audio = true;
979 // If we haven't already set the data_channel_type, and we add a
980 // stream, we assume it's an RTP data stream.
981 else if (type == MEDIA_TYPE_DATA && data_channel_type == DCT_NONE)
982 data_channel_type = DCT_RTP;
983}
984
985void MediaSessionOptions::RemoveStream(MediaType type,
986 const std::string& id) {
987 Streams::iterator stream_it = streams.begin();
988 for (; stream_it != streams.end(); ++stream_it) {
989 if (stream_it->type == type && stream_it->id == id) {
990 streams.erase(stream_it);
991 return;
992 }
993 }
994 ASSERT(false);
995}
996
997MediaSessionDescriptionFactory::MediaSessionDescriptionFactory(
998 const TransportDescriptionFactory* transport_desc_factory)
999 : secure_(SEC_DISABLED),
1000 add_legacy_(true),
1001 transport_desc_factory_(transport_desc_factory) {
1002}
1003
1004MediaSessionDescriptionFactory::MediaSessionDescriptionFactory(
1005 ChannelManager* channel_manager,
1006 const TransportDescriptionFactory* transport_desc_factory)
1007 : secure_(SEC_DISABLED),
1008 add_legacy_(true),
1009 transport_desc_factory_(transport_desc_factory) {
1010 channel_manager->GetSupportedAudioCodecs(&audio_codecs_);
1011 channel_manager->GetSupportedAudioRtpHeaderExtensions(&audio_rtp_extensions_);
1012 channel_manager->GetSupportedVideoCodecs(&video_codecs_);
1013 channel_manager->GetSupportedVideoRtpHeaderExtensions(&video_rtp_extensions_);
1014 channel_manager->GetSupportedDataCodecs(&data_codecs_);
1015}
1016
1017SessionDescription* MediaSessionDescriptionFactory::CreateOffer(
1018 const MediaSessionOptions& options,
1019 const SessionDescription* current_description) const {
1020 bool secure_transport = (transport_desc_factory_->secure() != SEC_DISABLED);
1021
1022 scoped_ptr<SessionDescription> offer(new SessionDescription());
1023
1024 StreamParamsVec current_streams;
1025 GetCurrentStreamParams(current_description, &current_streams);
1026
1027 AudioCodecs audio_codecs;
1028 VideoCodecs video_codecs;
1029 DataCodecs data_codecs;
1030 GetCodecsToOffer(current_description, &audio_codecs, &video_codecs,
1031 &data_codecs);
1032
1033 if (!options.vad_enabled) {
1034 // If application doesn't want CN codecs in offer.
1035 StripCNCodecs(&audio_codecs);
1036 }
1037
1038 RtpHeaderExtensions audio_rtp_extensions;
1039 RtpHeaderExtensions video_rtp_extensions;
1040 GetRtpHdrExtsToOffer(current_description, &audio_rtp_extensions,
1041 &video_rtp_extensions);
1042
1043 // Handle m=audio.
1044 if (options.has_audio) {
1045 scoped_ptr<AudioContentDescription> audio(new AudioContentDescription());
1046 std::vector<std::string> crypto_suites;
1047 GetSupportedAudioCryptoSuites(&crypto_suites);
1048 if (!CreateMediaContentOffer(
1049 options,
1050 audio_codecs,
1051 secure(),
1052 GetCryptos(GetFirstAudioContentDescription(current_description)),
1053 crypto_suites,
1054 audio_rtp_extensions,
1055 add_legacy_,
1056 &current_streams,
1057 audio.get())) {
1058 return NULL;
1059 }
1060
1061 audio->set_lang(lang_);
1062 SetMediaProtocol(secure_transport, audio.get());
1063 offer->AddContent(CN_AUDIO, NS_JINGLE_RTP, audio.release());
1064 if (!AddTransportOffer(CN_AUDIO, options.transport_options,
1065 current_description, offer.get())) {
1066 return NULL;
1067 }
1068 }
1069
1070 // Handle m=video.
1071 if (options.has_video) {
1072 scoped_ptr<VideoContentDescription> video(new VideoContentDescription());
1073 std::vector<std::string> crypto_suites;
1074 GetSupportedVideoCryptoSuites(&crypto_suites);
1075 if (!CreateMediaContentOffer(
1076 options,
1077 video_codecs,
1078 secure(),
1079 GetCryptos(GetFirstVideoContentDescription(current_description)),
1080 crypto_suites,
1081 video_rtp_extensions,
1082 add_legacy_,
1083 &current_streams,
1084 video.get())) {
1085 return NULL;
1086 }
1087
1088 video->set_bandwidth(options.video_bandwidth);
1089 SetMediaProtocol(secure_transport, video.get());
1090 offer->AddContent(CN_VIDEO, NS_JINGLE_RTP, video.release());
1091 if (!AddTransportOffer(CN_VIDEO, options.transport_options,
1092 current_description, offer.get())) {
1093 return NULL;
1094 }
1095 }
1096
1097 // Handle m=data.
1098 if (options.has_data()) {
1099 scoped_ptr<DataContentDescription> data(new DataContentDescription());
1100 bool is_sctp = (options.data_channel_type == DCT_SCTP);
1101
1102 std::vector<std::string> crypto_suites;
1103 cricket::SecurePolicy sdes_policy = secure();
1104 if (is_sctp) {
1105 // SDES doesn't make sense for SCTP, so we disable it, and we only
1106 // get SDES crypto suites for RTP-based data channels.
1107 sdes_policy = cricket::SEC_DISABLED;
1108 // Unlike SetMediaProtocol below, we need to set the protocol
1109 // before we call CreateMediaContentOffer. Otherwise,
1110 // CreateMediaContentOffer won't know this is SCTP and will
1111 // generate SSRCs rather than SIDs.
1112 data->set_protocol(
1113 secure_transport ? kMediaProtocolDtlsSctp : kMediaProtocolSctp);
1114 } else {
1115 GetSupportedDataCryptoSuites(&crypto_suites);
1116 }
1117
1118 if (!CreateMediaContentOffer(
1119 options,
1120 data_codecs,
1121 sdes_policy,
1122 GetCryptos(GetFirstDataContentDescription(current_description)),
1123 crypto_suites,
1124 RtpHeaderExtensions(),
1125 add_legacy_,
1126 &current_streams,
1127 data.get())) {
1128 return NULL;
1129 }
1130
1131 if (is_sctp) {
1132 offer->AddContent(CN_DATA, NS_JINGLE_DRAFT_SCTP, data.release());
1133 } else {
1134 data->set_bandwidth(options.data_bandwidth);
1135 SetMediaProtocol(secure_transport, data.get());
1136 offer->AddContent(CN_DATA, NS_JINGLE_RTP, data.release());
1137 }
1138 if (!AddTransportOffer(CN_DATA, options.transport_options,
1139 current_description, offer.get())) {
1140 return NULL;
1141 }
1142 }
1143
1144 // Bundle the contents together, if we've been asked to do so, and update any
1145 // parameters that need to be tweaked for BUNDLE.
1146 if (options.bundle_enabled) {
1147 ContentGroup offer_bundle(GROUP_TYPE_BUNDLE);
1148 for (ContentInfos::const_iterator content = offer->contents().begin();
1149 content != offer->contents().end(); ++content) {
1150 offer_bundle.AddContentName(content->name);
1151 }
1152 offer->AddGroup(offer_bundle);
1153 if (!UpdateTransportInfoForBundle(offer_bundle, offer.get())) {
1154 LOG(LS_ERROR) << "CreateOffer failed to UpdateTransportInfoForBundle.";
1155 return NULL;
1156 }
1157 if (!UpdateCryptoParamsForBundle(offer_bundle, offer.get())) {
1158 LOG(LS_ERROR) << "CreateOffer failed to UpdateCryptoParamsForBundle.";
1159 return NULL;
1160 }
1161 }
1162
1163 return offer.release();
1164}
1165
1166SessionDescription* MediaSessionDescriptionFactory::CreateAnswer(
1167 const SessionDescription* offer, const MediaSessionOptions& options,
1168 const SessionDescription* current_description) const {
1169 // The answer contains the intersection of the codecs in the offer with the
1170 // codecs we support, ordered by our local preference. As indicated by
1171 // XEP-0167, we retain the same payload ids from the offer in the answer.
1172 scoped_ptr<SessionDescription> answer(new SessionDescription());
1173
1174 StreamParamsVec current_streams;
1175 GetCurrentStreamParams(current_description, &current_streams);
1176
1177 bool bundle_enabled =
1178 offer->HasGroup(GROUP_TYPE_BUNDLE) && options.bundle_enabled;
1179
1180 // Handle m=audio.
1181 const ContentInfo* audio_content = GetFirstAudioContent(offer);
1182 if (audio_content) {
1183 scoped_ptr<TransportDescription> audio_transport(
1184 CreateTransportAnswer(audio_content->name, offer,
1185 options.transport_options,
1186 current_description));
1187 if (!audio_transport) {
1188 return NULL;
1189 }
1190
1191 AudioCodecs audio_codecs = audio_codecs_;
1192 if (!options.vad_enabled) {
1193 StripCNCodecs(&audio_codecs);
1194 }
1195
1196 scoped_ptr<AudioContentDescription> audio_answer(
1197 new AudioContentDescription());
1198 // Do not require or create SDES cryptos if DTLS is used.
1199 cricket::SecurePolicy sdes_policy =
1200 audio_transport->secure() ? cricket::SEC_DISABLED : secure();
1201 if (!CreateMediaContentAnswer(
1202 static_cast<const AudioContentDescription*>(
1203 audio_content->description),
1204 options,
1205 audio_codecs,
1206 sdes_policy,
1207 GetCryptos(GetFirstAudioContentDescription(current_description)),
1208 audio_rtp_extensions_,
1209 &current_streams,
1210 add_legacy_,
1211 bundle_enabled,
1212 audio_answer.get())) {
1213 return NULL; // Fails the session setup.
1214 }
1215
1216 bool rejected = !options.has_audio || audio_content->rejected ||
1217 !IsMediaProtocolSupported(MEDIA_TYPE_AUDIO,
1218 audio_answer->protocol());
1219 if (!rejected) {
1220 AddTransportAnswer(audio_content->name, *(audio_transport.get()),
1221 answer.get());
1222 } else {
1223 // RFC 3264
1224 // The answer MUST contain the same number of m-lines as the offer.
1225 LOG(LS_INFO) << "Audio is not supported in the answer.";
1226 }
1227
1228 answer->AddContent(audio_content->name, audio_content->type, rejected,
1229 audio_answer.release());
1230 } else {
1231 LOG(LS_INFO) << "Audio is not available in the offer.";
1232 }
1233
1234 // Handle m=video.
1235 const ContentInfo* video_content = GetFirstVideoContent(offer);
1236 if (video_content) {
1237 scoped_ptr<TransportDescription> video_transport(
1238 CreateTransportAnswer(video_content->name, offer,
1239 options.transport_options,
1240 current_description));
1241 if (!video_transport) {
1242 return NULL;
1243 }
1244
1245 scoped_ptr<VideoContentDescription> video_answer(
1246 new VideoContentDescription());
1247 // Do not require or create SDES cryptos if DTLS is used.
1248 cricket::SecurePolicy sdes_policy =
1249 video_transport->secure() ? cricket::SEC_DISABLED : secure();
1250 if (!CreateMediaContentAnswer(
1251 static_cast<const VideoContentDescription*>(
1252 video_content->description),
1253 options,
1254 video_codecs_,
1255 sdes_policy,
1256 GetCryptos(GetFirstVideoContentDescription(current_description)),
1257 video_rtp_extensions_,
1258 &current_streams,
1259 add_legacy_,
1260 bundle_enabled,
1261 video_answer.get())) {
1262 return NULL;
1263 }
1264 bool rejected = !options.has_video || video_content->rejected ||
1265 !IsMediaProtocolSupported(MEDIA_TYPE_VIDEO, video_answer->protocol());
1266 if (!rejected) {
1267 if (!AddTransportAnswer(video_content->name, *(video_transport.get()),
1268 answer.get())) {
1269 return NULL;
1270 }
1271 video_answer->set_bandwidth(options.video_bandwidth);
1272 } else {
1273 // RFC 3264
1274 // The answer MUST contain the same number of m-lines as the offer.
1275 LOG(LS_INFO) << "Video is not supported in the answer.";
1276 }
1277 answer->AddContent(video_content->name, video_content->type, rejected,
1278 video_answer.release());
1279 } else {
1280 LOG(LS_INFO) << "Video is not available in the offer.";
1281 }
1282
1283 // Handle m=data.
1284 const ContentInfo* data_content = GetFirstDataContent(offer);
1285 if (data_content) {
1286 scoped_ptr<TransportDescription> data_transport(
1287 CreateTransportAnswer(data_content->name, offer,
1288 options.transport_options,
1289 current_description));
1290 if (!data_transport) {
1291 return NULL;
1292 }
1293 scoped_ptr<DataContentDescription> data_answer(
1294 new DataContentDescription());
1295 // Do not require or create SDES cryptos if DTLS is used.
1296 cricket::SecurePolicy sdes_policy =
1297 data_transport->secure() ? cricket::SEC_DISABLED : secure();
1298 if (!CreateMediaContentAnswer(
1299 static_cast<const DataContentDescription*>(
1300 data_content->description),
1301 options,
1302 data_codecs_,
1303 sdes_policy,
1304 GetCryptos(GetFirstDataContentDescription(current_description)),
1305 RtpHeaderExtensions(),
1306 &current_streams,
1307 add_legacy_,
1308 bundle_enabled,
1309 data_answer.get())) {
1310 return NULL; // Fails the session setup.
1311 }
1312
1313 bool rejected = !options.has_data() || data_content->rejected ||
1314 !IsMediaProtocolSupported(MEDIA_TYPE_DATA, data_answer->protocol());
1315 if (!rejected) {
1316 data_answer->set_bandwidth(options.data_bandwidth);
1317 if (!AddTransportAnswer(data_content->name, *(data_transport.get()),
1318 answer.get())) {
1319 return NULL;
1320 }
1321 } else {
1322 // RFC 3264
1323 // The answer MUST contain the same number of m-lines as the offer.
1324 LOG(LS_INFO) << "Data is not supported in the answer.";
1325 }
1326 answer->AddContent(data_content->name, data_content->type, rejected,
1327 data_answer.release());
1328 } else {
1329 LOG(LS_INFO) << "Data is not available in the offer.";
1330 }
1331
1332 // If the offer supports BUNDLE, and we want to use it too, create a BUNDLE
1333 // group in the answer with the appropriate content names.
1334 if (offer->HasGroup(GROUP_TYPE_BUNDLE) && options.bundle_enabled) {
1335 const ContentGroup* offer_bundle = offer->GetGroupByName(GROUP_TYPE_BUNDLE);
1336 ContentGroup answer_bundle(GROUP_TYPE_BUNDLE);
1337 for (ContentInfos::const_iterator content = answer->contents().begin();
1338 content != answer->contents().end(); ++content) {
1339 if (!content->rejected && offer_bundle->HasContentName(content->name)) {
1340 answer_bundle.AddContentName(content->name);
1341 }
1342 }
1343 if (answer_bundle.FirstContentName()) {
1344 answer->AddGroup(answer_bundle);
1345
1346 // Share the same ICE credentials and crypto params across all contents,
1347 // as BUNDLE requires.
1348 if (!UpdateTransportInfoForBundle(answer_bundle, answer.get())) {
1349 LOG(LS_ERROR) << "CreateAnswer failed to UpdateTransportInfoForBundle.";
1350 return NULL;
1351 }
1352
1353 if (!UpdateCryptoParamsForBundle(answer_bundle, answer.get())) {
1354 LOG(LS_ERROR) << "CreateAnswer failed to UpdateCryptoParamsForBundle.";
1355 return NULL;
1356 }
1357 }
1358 }
1359
1360 return answer.release();
1361}
1362
1363// Gets the TransportInfo of the given |content_name| from the
1364// |current_description|. If doesn't exist, returns a new one.
1365static const TransportDescription* GetTransportDescription(
1366 const std::string& content_name,
1367 const SessionDescription* current_description) {
1368 const TransportDescription* desc = NULL;
1369 if (current_description) {
1370 const TransportInfo* info =
1371 current_description->GetTransportInfoByName(content_name);
1372 if (info) {
1373 desc = &info->description;
1374 }
1375 }
1376 return desc;
1377}
1378
1379void MediaSessionDescriptionFactory::GetCodecsToOffer(
1380 const SessionDescription* current_description,
1381 AudioCodecs* audio_codecs,
1382 VideoCodecs* video_codecs,
1383 DataCodecs* data_codecs) const {
1384 UsedPayloadTypes used_pltypes;
1385 audio_codecs->clear();
1386 video_codecs->clear();
1387 data_codecs->clear();
1388
1389
1390 // First - get all codecs from the current description if the media type
1391 // is used.
1392 // Add them to |used_pltypes| so the payloadtype is not reused if a new media
1393 // type is added.
1394 if (current_description) {
1395 const AudioContentDescription* audio =
1396 GetFirstAudioContentDescription(current_description);
1397 if (audio) {
1398 *audio_codecs = audio->codecs();
1399 used_pltypes.FindAndSetIdUsed<AudioCodec>(audio_codecs);
1400 }
1401 const VideoContentDescription* video =
1402 GetFirstVideoContentDescription(current_description);
1403 if (video) {
1404 *video_codecs = video->codecs();
1405 used_pltypes.FindAndSetIdUsed<VideoCodec>(video_codecs);
1406 }
1407 const DataContentDescription* data =
1408 GetFirstDataContentDescription(current_description);
1409 if (data) {
1410 *data_codecs = data->codecs();
1411 used_pltypes.FindAndSetIdUsed<DataCodec>(data_codecs);
1412 }
1413 }
1414
1415 // Add our codecs that are not in |current_description|.
1416 FindCodecsToOffer<AudioCodec>(audio_codecs_, audio_codecs, &used_pltypes);
1417 FindCodecsToOffer<VideoCodec>(video_codecs_, video_codecs, &used_pltypes);
1418 FindCodecsToOffer<DataCodec>(data_codecs_, data_codecs, &used_pltypes);
1419}
1420
1421void MediaSessionDescriptionFactory::GetRtpHdrExtsToOffer(
1422 const SessionDescription* current_description,
1423 RtpHeaderExtensions* audio_extensions,
1424 RtpHeaderExtensions* video_extensions) const {
1425 UsedRtpHeaderExtensionIds used_ids;
1426 audio_extensions->clear();
1427 video_extensions->clear();
1428
1429 // First - get all extensions from the current description if the media type
1430 // is used.
1431 // Add them to |used_ids| so the local ids are not reused if a new media
1432 // type is added.
1433 if (current_description) {
1434 const AudioContentDescription* audio =
1435 GetFirstAudioContentDescription(current_description);
1436 if (audio) {
1437 *audio_extensions = audio->rtp_header_extensions();
1438 used_ids.FindAndSetIdUsed(audio_extensions);
1439 }
1440 const VideoContentDescription* video =
1441 GetFirstVideoContentDescription(current_description);
1442 if (video) {
1443 *video_extensions = video->rtp_header_extensions();
1444 used_ids.FindAndSetIdUsed(video_extensions);
1445 }
1446 }
1447
1448 // Add our default RTP header extensions that are not in
1449 // |current_description|.
1450 FindAndSetRtpHdrExtUsed(audio_rtp_header_extensions(), audio_extensions,
1451 &used_ids);
1452 FindAndSetRtpHdrExtUsed(video_rtp_header_extensions(), video_extensions,
1453 &used_ids);
1454}
1455
1456bool MediaSessionDescriptionFactory::AddTransportOffer(
1457 const std::string& content_name,
1458 const TransportOptions& transport_options,
1459 const SessionDescription* current_desc,
1460 SessionDescription* offer_desc) const {
1461 if (!transport_desc_factory_)
1462 return false;
1463 const TransportDescription* current_tdesc =
1464 GetTransportDescription(content_name, current_desc);
1465 talk_base::scoped_ptr<TransportDescription> new_tdesc(
1466 transport_desc_factory_->CreateOffer(transport_options, current_tdesc));
1467 bool ret = (new_tdesc.get() != NULL &&
1468 offer_desc->AddTransportInfo(TransportInfo(content_name, *new_tdesc)));
1469 if (!ret) {
1470 LOG(LS_ERROR)
1471 << "Failed to AddTransportOffer, content name=" << content_name;
1472 }
1473 return ret;
1474}
1475
1476TransportDescription* MediaSessionDescriptionFactory::CreateTransportAnswer(
1477 const std::string& content_name,
1478 const SessionDescription* offer_desc,
1479 const TransportOptions& transport_options,
1480 const SessionDescription* current_desc) const {
1481 if (!transport_desc_factory_)
1482 return NULL;
1483 const TransportDescription* offer_tdesc =
1484 GetTransportDescription(content_name, offer_desc);
1485 const TransportDescription* current_tdesc =
1486 GetTransportDescription(content_name, current_desc);
1487 return
1488 transport_desc_factory_->CreateAnswer(offer_tdesc, transport_options,
1489 current_tdesc);
1490}
1491
1492bool MediaSessionDescriptionFactory::AddTransportAnswer(
1493 const std::string& content_name,
1494 const TransportDescription& transport_desc,
1495 SessionDescription* answer_desc) const {
1496 if (!answer_desc->AddTransportInfo(TransportInfo(content_name,
1497 transport_desc))) {
1498 LOG(LS_ERROR)
1499 << "Failed to AddTransportAnswer, content name=" << content_name;
1500 return false;
1501 }
1502 return true;
1503}
1504
1505bool IsMediaContent(const ContentInfo* content) {
1506 return (content &&
1507 (content->type == NS_JINGLE_RTP ||
1508 content->type == NS_JINGLE_DRAFT_SCTP));
1509}
1510
1511bool IsAudioContent(const ContentInfo* content) {
1512 return IsMediaContentOfType(content, MEDIA_TYPE_AUDIO);
1513}
1514
1515bool IsVideoContent(const ContentInfo* content) {
1516 return IsMediaContentOfType(content, MEDIA_TYPE_VIDEO);
1517}
1518
1519bool IsDataContent(const ContentInfo* content) {
1520 return IsMediaContentOfType(content, MEDIA_TYPE_DATA);
1521}
1522
1523static const ContentInfo* GetFirstMediaContent(const ContentInfos& contents,
1524 MediaType media_type) {
1525 for (ContentInfos::const_iterator content = contents.begin();
1526 content != contents.end(); content++) {
1527 if (IsMediaContentOfType(&*content, media_type)) {
1528 return &*content;
1529 }
1530 }
1531 return NULL;
1532}
1533
1534const ContentInfo* GetFirstAudioContent(const ContentInfos& contents) {
1535 return GetFirstMediaContent(contents, MEDIA_TYPE_AUDIO);
1536}
1537
1538const ContentInfo* GetFirstVideoContent(const ContentInfos& contents) {
1539 return GetFirstMediaContent(contents, MEDIA_TYPE_VIDEO);
1540}
1541
1542const ContentInfo* GetFirstDataContent(const ContentInfos& contents) {
1543 return GetFirstMediaContent(contents, MEDIA_TYPE_DATA);
1544}
1545
1546static const ContentInfo* GetFirstMediaContent(const SessionDescription* sdesc,
1547 MediaType media_type) {
1548 if (sdesc == NULL)
1549 return NULL;
1550
1551 return GetFirstMediaContent(sdesc->contents(), media_type);
1552}
1553
1554const ContentInfo* GetFirstAudioContent(const SessionDescription* sdesc) {
1555 return GetFirstMediaContent(sdesc, MEDIA_TYPE_AUDIO);
1556}
1557
1558const ContentInfo* GetFirstVideoContent(const SessionDescription* sdesc) {
1559 return GetFirstMediaContent(sdesc, MEDIA_TYPE_VIDEO);
1560}
1561
1562const ContentInfo* GetFirstDataContent(const SessionDescription* sdesc) {
1563 return GetFirstMediaContent(sdesc, MEDIA_TYPE_DATA);
1564}
1565
1566const MediaContentDescription* GetFirstMediaContentDescription(
1567 const SessionDescription* sdesc, MediaType media_type) {
1568 const ContentInfo* content = GetFirstMediaContent(sdesc, media_type);
1569 const ContentDescription* description = content ? content->description : NULL;
1570 return static_cast<const MediaContentDescription*>(description);
1571}
1572
1573const AudioContentDescription* GetFirstAudioContentDescription(
1574 const SessionDescription* sdesc) {
1575 return static_cast<const AudioContentDescription*>(
1576 GetFirstMediaContentDescription(sdesc, MEDIA_TYPE_AUDIO));
1577}
1578
1579const VideoContentDescription* GetFirstVideoContentDescription(
1580 const SessionDescription* sdesc) {
1581 return static_cast<const VideoContentDescription*>(
1582 GetFirstMediaContentDescription(sdesc, MEDIA_TYPE_VIDEO));
1583}
1584
1585const DataContentDescription* GetFirstDataContentDescription(
1586 const SessionDescription* sdesc) {
1587 return static_cast<const DataContentDescription*>(
1588 GetFirstMediaContentDescription(sdesc, MEDIA_TYPE_DATA));
1589}
1590
1591bool GetMediaChannelNameFromComponent(
1592 int component, MediaType media_type, std::string* channel_name) {
1593 if (media_type == MEDIA_TYPE_AUDIO) {
1594 if (component == ICE_CANDIDATE_COMPONENT_RTP) {
1595 *channel_name = GICE_CHANNEL_NAME_RTP;
1596 return true;
1597 } else if (component == ICE_CANDIDATE_COMPONENT_RTCP) {
1598 *channel_name = GICE_CHANNEL_NAME_RTCP;
1599 return true;
1600 }
1601 } else if (media_type == MEDIA_TYPE_VIDEO) {
1602 if (component == ICE_CANDIDATE_COMPONENT_RTP) {
1603 *channel_name = GICE_CHANNEL_NAME_VIDEO_RTP;
1604 return true;
1605 } else if (component == ICE_CANDIDATE_COMPONENT_RTCP) {
1606 *channel_name = GICE_CHANNEL_NAME_VIDEO_RTCP;
1607 return true;
1608 }
1609 } else if (media_type == MEDIA_TYPE_DATA) {
1610 if (component == ICE_CANDIDATE_COMPONENT_RTP) {
1611 *channel_name = GICE_CHANNEL_NAME_DATA_RTP;
1612 return true;
1613 } else if (component == ICE_CANDIDATE_COMPONENT_RTCP) {
1614 *channel_name = GICE_CHANNEL_NAME_DATA_RTCP;
1615 return true;
1616 }
1617 }
1618
1619 return false;
1620}
1621
1622bool GetMediaComponentFromChannelName(
1623 const std::string& channel_name, int* component) {
1624 if (channel_name == GICE_CHANNEL_NAME_RTP ||
1625 channel_name == GICE_CHANNEL_NAME_VIDEO_RTP ||
1626 channel_name == GICE_CHANNEL_NAME_DATA_RTP) {
1627 *component = ICE_CANDIDATE_COMPONENT_RTP;
1628 return true;
1629 } else if (channel_name == GICE_CHANNEL_NAME_RTCP ||
1630 channel_name == GICE_CHANNEL_NAME_VIDEO_RTCP ||
1631 channel_name == GICE_CHANNEL_NAME_DATA_RTP) {
1632 *component = ICE_CANDIDATE_COMPONENT_RTCP;
1633 return true;
1634 }
1635
1636 return false;
1637}
1638
1639bool GetMediaTypeFromChannelName(
1640 const std::string& channel_name, MediaType* media_type) {
1641 if (channel_name == GICE_CHANNEL_NAME_RTP ||
1642 channel_name == GICE_CHANNEL_NAME_RTCP) {
1643 *media_type = MEDIA_TYPE_AUDIO;
1644 return true;
1645 } else if (channel_name == GICE_CHANNEL_NAME_VIDEO_RTP ||
1646 channel_name == GICE_CHANNEL_NAME_VIDEO_RTCP) {
1647 *media_type = MEDIA_TYPE_VIDEO;
1648 return true;
1649 } else if (channel_name == GICE_CHANNEL_NAME_DATA_RTP ||
1650 channel_name == GICE_CHANNEL_NAME_DATA_RTCP) {
1651 *media_type = MEDIA_TYPE_DATA;
1652 return true;
1653 }
1654
1655 return false;
1656}
1657
1658} // namespace cricket