- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / media / desktop_streams_registry.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/media/desktop_streams_registry.h"
6
7 #include "base/base64.h"
8 #include "base/location.h"
9 #include "base/time/time.h"
10 #include "content/public/browser/browser_thread.h"
11 #include "crypto/random.h"
12
13 namespace {
14
15 const int kStreamIdLengthBytes = 16;
16
17 const int kApprovedStreamTimeToLiveSeconds = 10;
18
19 std::string GenerateRandomStreamId() {
20   char buffer[kStreamIdLengthBytes];
21   crypto::RandBytes(buffer, arraysize(buffer));
22   std::string result;
23   if (!base::Base64Encode(base::StringPiece(buffer, arraysize(buffer)),
24                           &result)) {
25     LOG(FATAL) << "Base64Encode failed.";
26   }
27   return result;
28 }
29
30 }  // namespace
31
32 DesktopStreamsRegistry::DesktopStreamsRegistry() {}
33 DesktopStreamsRegistry::~DesktopStreamsRegistry() {}
34
35 std::string DesktopStreamsRegistry::RegisterStream(
36     int render_process_id,
37     int render_view_id,
38     const GURL& origin,
39     const content::DesktopMediaID& source) {
40   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
41
42   std::string id = GenerateRandomStreamId();
43   ApprovedDesktopMediaStream& stream = approved_streams_[id];
44   stream.render_process_id = render_process_id;
45   stream.render_view_id = render_view_id;
46   stream.origin = origin;
47   stream.source = source;
48
49   content::BrowserThread::PostDelayedTask(
50       content::BrowserThread::UI, FROM_HERE,
51       base::Bind(&DesktopStreamsRegistry::CleanupStream,
52                  base::Unretained(this), id),
53       base::TimeDelta::FromSeconds(kApprovedStreamTimeToLiveSeconds));
54
55   return id;
56 }
57
58 content::DesktopMediaID DesktopStreamsRegistry::RequestMediaForStreamId(
59     const std::string& id,
60     int render_process_id,
61     int render_view_id,
62     const GURL& origin) {
63   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
64
65   StreamsMap::iterator it = approved_streams_.find(id);
66
67   // Verify that if there is a request with the specified ID it was created for
68   // the same origin and the same renderer.
69   if (it == approved_streams_.end() ||
70       render_process_id != it->second.render_process_id ||
71       render_view_id != it->second.render_view_id ||
72       origin != it->second.origin) {
73     return content::DesktopMediaID();
74   }
75
76   content::DesktopMediaID result = it->second.source;
77   approved_streams_.erase(it);
78   return result;
79 }
80
81 void DesktopStreamsRegistry::CleanupStream(const std::string& id) {
82   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
83   approved_streams_.erase(id);
84 }