Revert 268405 "Make sure that ScratchBuffer::Allocate() always r..."
[chromium-blink-merge.git] / content / browser / renderer_host / media / midi_host.cc
blob39520b03e5cc4087e83626be4a63d1222f9a61be
1 // Copyright (c) 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.
5 #include "content/browser/renderer_host/media/midi_host.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/debug/trace_event.h"
10 #include "base/process/process.h"
11 #include "content/browser/browser_main_loop.h"
12 #include "content/browser/child_process_security_policy_impl.h"
13 #include "content/browser/media/media_internals.h"
14 #include "content/common/media/midi_messages.h"
15 #include "content/public/browser/content_browser_client.h"
16 #include "content/public/browser/media_observer.h"
17 #include "content/public/browser/user_metrics.h"
18 #include "media/midi/midi_manager.h"
19 #include "media/midi/midi_message_queue.h"
20 #include "media/midi/midi_message_util.h"
22 using media::MidiManager;
23 using media::MidiPortInfoList;
25 namespace content {
26 namespace {
28 // The total number of bytes which we're allowed to send to the OS
29 // before knowing that they have been successfully sent.
30 const size_t kMaxInFlightBytes = 10 * 1024 * 1024; // 10 MB.
32 // We keep track of the number of bytes successfully sent to
33 // the hardware. Every once in a while we report back to the renderer
34 // the number of bytes sent since the last report. This threshold determines
35 // how many bytes will be sent before reporting back to the renderer.
36 const size_t kAcknowledgementThresholdBytes = 1024 * 1024; // 1 MB.
38 bool IsDataByte(uint8 data) {
39 return (data & 0x80) == 0;
42 bool IsSystemRealTimeMessage(uint8 data) {
43 return 0xf8 <= data && data <= 0xff;
46 } // namespace
48 using media::kSysExByte;
49 using media::kEndOfSysExByte;
51 MidiHost::MidiHost(int renderer_process_id, media::MidiManager* midi_manager)
52 : BrowserMessageFilter(MidiMsgStart),
53 renderer_process_id_(renderer_process_id),
54 has_sys_ex_permission_(false),
55 midi_manager_(midi_manager),
56 sent_bytes_in_flight_(0),
57 bytes_sent_since_last_acknowledgement_(0) {
60 MidiHost::~MidiHost() {
61 if (midi_manager_)
62 midi_manager_->EndSession(this);
65 void MidiHost::OnDestruct() const {
66 BrowserThread::DeleteOnIOThread::Destruct(this);
69 // IPC Messages handler
70 bool MidiHost::OnMessageReceived(const IPC::Message& message,
71 bool* message_was_ok) {
72 bool handled = true;
73 IPC_BEGIN_MESSAGE_MAP_EX(MidiHost, message, *message_was_ok)
74 IPC_MESSAGE_HANDLER(MidiHostMsg_StartSession, OnStartSession)
75 IPC_MESSAGE_HANDLER(MidiHostMsg_SendData, OnSendData)
76 IPC_MESSAGE_UNHANDLED(handled = false)
77 IPC_END_MESSAGE_MAP_EX()
79 return handled;
82 void MidiHost::OnStartSession(int client_id) {
83 if (midi_manager_)
84 midi_manager_->StartSession(this, client_id);
87 void MidiHost::OnSendData(uint32 port,
88 const std::vector<uint8>& data,
89 double timestamp) {
90 if (!midi_manager_)
91 return;
93 if (data.empty())
94 return;
96 // Blink running in a renderer checks permission to raise a SecurityError
97 // in JavaScript. The actual permission check for security purposes
98 // happens here in the browser process.
99 if (!has_sys_ex_permission_ &&
100 std::find(data.begin(), data.end(), kSysExByte) != data.end()) {
101 RecordAction(base::UserMetricsAction("BadMessageTerminate_MIDI"));
102 BadMessageReceived();
103 return;
106 if (!IsValidWebMIDIData(data))
107 return;
110 base::AutoLock auto_lock(in_flight_lock_);
111 // Sanity check that we won't send too much data.
112 // TODO(yukawa): Consider to send an error event back to the renderer
113 // after some future discussion in W3C.
114 if (data.size() + sent_bytes_in_flight_ > kMaxInFlightBytes)
115 return;
116 sent_bytes_in_flight_ += data.size();
118 midi_manager_->DispatchSendMidiData(this, port, data, timestamp);
121 void MidiHost::CompleteStartSession(int client_id, media::MidiResult result) {
122 MidiPortInfoList input_ports;
123 MidiPortInfoList output_ports;
125 // TODO(toyoshim): Report what error happens back to blink.
126 bool success = result == media::MIDI_OK;
127 if (success) {
128 input_ports = midi_manager_->input_ports();
129 output_ports = midi_manager_->output_ports();
130 received_messages_queues_.clear();
131 received_messages_queues_.resize(input_ports.size());
132 // ChildSecurityPolicy is set just before OnStartSession by
133 // MidiDispatcherHost. So we can safely cache the policy.
134 has_sys_ex_permission_ = ChildProcessSecurityPolicyImpl::GetInstance()->
135 CanSendMidiSysExMessage(renderer_process_id_);
138 Send(new MidiMsg_SessionStarted(client_id,
139 success,
140 input_ports,
141 output_ports));
144 void MidiHost::ReceiveMidiData(
145 uint32 port,
146 const uint8* data,
147 size_t length,
148 double timestamp) {
149 TRACE_EVENT0("midi", "MidiHost::ReceiveMidiData");
151 if (received_messages_queues_.size() <= port)
152 return;
154 // Lazy initialization
155 if (received_messages_queues_[port] == NULL)
156 received_messages_queues_[port] = new media::MidiMessageQueue(true);
158 received_messages_queues_[port]->Add(data, length);
159 std::vector<uint8> message;
160 while (true) {
161 received_messages_queues_[port]->Get(&message);
162 if (message.empty())
163 break;
165 // MIDI devices may send a system exclusive messages even if the renderer
166 // doesn't have a permission to receive it. Don't kill the renderer as
167 // OnSendData() does.
168 if (message[0] == kSysExByte && !has_sys_ex_permission_)
169 continue;
171 // Send to the renderer.
172 Send(new MidiMsg_DataReceived(port, message, timestamp));
176 void MidiHost::AccumulateMidiBytesSent(size_t n) {
178 base::AutoLock auto_lock(in_flight_lock_);
179 if (n <= sent_bytes_in_flight_)
180 sent_bytes_in_flight_ -= n;
183 if (bytes_sent_since_last_acknowledgement_ + n >=
184 bytes_sent_since_last_acknowledgement_)
185 bytes_sent_since_last_acknowledgement_ += n;
187 if (bytes_sent_since_last_acknowledgement_ >=
188 kAcknowledgementThresholdBytes) {
189 Send(new MidiMsg_AcknowledgeSentData(
190 bytes_sent_since_last_acknowledgement_));
191 bytes_sent_since_last_acknowledgement_ = 0;
195 // static
196 bool MidiHost::IsValidWebMIDIData(const std::vector<uint8>& data) {
197 bool in_sysex = false;
198 size_t waiting_data_length = 0;
199 for (size_t i = 0; i < data.size(); ++i) {
200 const uint8 current = data[i];
201 if (IsSystemRealTimeMessage(current))
202 continue; // Real time message can be placed at any point.
203 if (waiting_data_length > 0) {
204 if (!IsDataByte(current))
205 return false; // Error: |current| should have been data byte.
206 --waiting_data_length;
207 continue; // Found data byte as expected.
209 if (in_sysex) {
210 if (data[i] == kEndOfSysExByte)
211 in_sysex = false;
212 else if (!IsDataByte(current))
213 return false; // Error: |current| should have been data byte.
214 continue; // Found data byte as expected.
216 if (current == kSysExByte) {
217 in_sysex = true;
218 continue; // Found SysEX
220 waiting_data_length = media::GetMidiMessageLength(current);
221 if (waiting_data_length == 0)
222 return false; // Error: |current| should have been a valid status byte.
223 --waiting_data_length; // Found status byte
225 return waiting_data_length == 0 && !in_sysex;
228 } // namespace content