desktop_streams_registry.cc revision 3551c9c881056c480085172ff9840cab31610854
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
13namespace {
14
15const int kStreamIdLengthBytes = 16;
16
17const int kApprovedStreamTimeToLiveSeconds = 10;
18
19std::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
32DesktopStreamsRegistry::DesktopStreamsRegistry() {}
33DesktopStreamsRegistry::~DesktopStreamsRegistry() {}
34
35std::string DesktopStreamsRegistry::RegisterStream(
36    const GURL& origin,
37    const content::DesktopMediaID& source) {
38  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
39
40  std::string id = GenerateRandomStreamId();
41  ApprovedDesktopMediaStream& stream = approved_streams_[id];
42  stream.origin = origin;
43  stream.source = source;
44
45  content::BrowserThread::PostDelayedTask(
46      content::BrowserThread::UI, FROM_HERE,
47      base::Bind(&DesktopStreamsRegistry::CleanupStream,
48                 base::Unretained(this), id),
49      base::TimeDelta::FromSeconds(kApprovedStreamTimeToLiveSeconds));
50
51  return id;
52}
53
54content::DesktopMediaID DesktopStreamsRegistry::RequestMediaForStreamId(
55    const std::string& id,
56    const GURL& origin) {
57  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
58
59  StreamsMap::iterator it = approved_streams_.find(id);
60  if (it == approved_streams_.end() || origin != it->second.origin)
61    return content::DesktopMediaID();
62  content::DesktopMediaID result = it->second.source;
63  approved_streams_.erase(it);
64  return result;
65}
66
67void DesktopStreamsRegistry::CleanupStream(const std::string& id) {
68  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
69  approved_streams_.erase(id);
70}
71