summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc
blob: 95412d07480eb7987b4db29d19ac1bc8c6a9e17e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright 2015 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.

#include "third_party/blink/renderer/modules/mediarecorder/media_recorder.h"

#include <algorithm>
#include <limits>
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_media_stream.h"
#include "third_party/blink/renderer/bindings/core/v8/dictionary.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/mediarecorder/blob_event.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
#include "third_party/blink/renderer/platform/wtf/time.h"

namespace blink {

namespace {

const char kDefaultMimeType[] = "video/webm";

// Boundaries of Opus bitrate from https://www.opus-codec.org/.
const int kSmallestPossibleOpusBitRate = 6000;
const int kLargestAutoAllocatedOpusBitRate = 128000;

// Smallest Vpx bitrate that can be requested.
const int kSmallestPossibleVpxBitRate = 100000;

String StateToString(MediaRecorder::State state) {
  switch (state) {
    case MediaRecorder::State::kInactive:
      return "inactive";
    case MediaRecorder::State::kRecording:
      return "recording";
    case MediaRecorder::State::kPaused:
      return "paused";
  }

  NOTREACHED();
  return String();
}

// Allocates the requested bit rates from |bitrateOptions| into the respective
// |{audio,video}BitsPerSecond| (where a value of zero indicates Platform to use
// whatever it sees fit). If |options.bitsPerSecond()| is specified, it
// overrides any specific bitrate, and the UA is free to allocate as desired:
// here a 90%/10% video/audio is used. In all cases where a value is explicited
// or calculated, values are clamped in sane ranges.
// This method throws NotSupportedError.
void AllocateVideoAndAudioBitrates(ExceptionState& exception_state,
                                   ExecutionContext* context,
                                   const MediaRecorderOptions& options,
                                   MediaStream* stream,
                                   int* audio_bits_per_second,
                                   int* video_bits_per_second) {
  const bool use_video = !stream->getVideoTracks().IsEmpty();
  const bool use_audio = !stream->getAudioTracks().IsEmpty();

  // Clamp incoming values into a signed integer's range.
  // TODO(mcasas): This section would no be needed if the bit rates are signed
  // or double, see https://github.com/w3c/mediacapture-record/issues/48.
  const unsigned kMaxIntAsUnsigned = std::numeric_limits<int>::max();

  int overall_bps = 0;
  if (options.hasBitsPerSecond())
    overall_bps = std::min(options.bitsPerSecond(), kMaxIntAsUnsigned);
  int video_bps = 0;
  if (options.hasVideoBitsPerSecond() && use_video)
    video_bps = std::min(options.videoBitsPerSecond(), kMaxIntAsUnsigned);
  int audio_bps = 0;
  if (options.hasAudioBitsPerSecond() && use_audio)
    audio_bps = std::min(options.audioBitsPerSecond(), kMaxIntAsUnsigned);

  if (use_audio) {
    // |overallBps| overrides the specific audio and video bit rates.
    if (options.hasBitsPerSecond()) {
      if (use_video)
        audio_bps = overall_bps / 10;
      else
        audio_bps = overall_bps;
    }
    // Limit audio bitrate values if set explicitly or calculated.
    if (options.hasAudioBitsPerSecond() || options.hasBitsPerSecond()) {
      if (audio_bps > kLargestAutoAllocatedOpusBitRate) {
        context->AddConsoleMessage(ConsoleMessage::Create(
            kJSMessageSource, kWarningMessageLevel,
            "Clamping calculated audio bitrate (" + String::Number(audio_bps) +
                "bps) to the maximum (" +
                String::Number(kLargestAutoAllocatedOpusBitRate) + "bps)"));
        audio_bps = kLargestAutoAllocatedOpusBitRate;
      }

      if (audio_bps < kSmallestPossibleOpusBitRate) {
        context->AddConsoleMessage(ConsoleMessage::Create(
            kJSMessageSource, kWarningMessageLevel,
            "Clamping calculated audio bitrate (" + String::Number(audio_bps) +
                "bps) to the minimum (" +
                String::Number(kSmallestPossibleOpusBitRate) + "bps)"));
        audio_bps = kSmallestPossibleOpusBitRate;
      }
    } else {
      DCHECK(!audio_bps);
    }
  }

  if (use_video) {
    // Allocate the remaining |overallBps|, if any, to video.
    if (options.hasBitsPerSecond())
      video_bps = overall_bps - audio_bps;
    // Clamp the video bit rate. Avoid clamping if the user has not set it
    // explicitly.
    if (options.hasVideoBitsPerSecond() || options.hasBitsPerSecond()) {
      if (video_bps < kSmallestPossibleVpxBitRate) {
        context->AddConsoleMessage(ConsoleMessage::Create(
            kJSMessageSource, kWarningMessageLevel,
            "Clamping calculated video bitrate (" + String::Number(video_bps) +
                "bps) to the minimum (" +
                String::Number(kSmallestPossibleVpxBitRate) + "bps)"));
        video_bps = kSmallestPossibleVpxBitRate;
      }
    } else {
      DCHECK(!video_bps);
    }
  }

  *video_bits_per_second = video_bps;
  *audio_bits_per_second = audio_bps;
  return;
}

}  // namespace

MediaRecorder* MediaRecorder::Create(ExecutionContext* context,
                                     MediaStream* stream,
                                     ExceptionState& exception_state) {
  MediaRecorder* recorder = new MediaRecorder(
      context, stream, MediaRecorderOptions(), exception_state);
  recorder->PauseIfNeeded();

  return recorder;
}

MediaRecorder* MediaRecorder::Create(ExecutionContext* context,
                                     MediaStream* stream,
                                     const MediaRecorderOptions& options,
                                     ExceptionState& exception_state) {
  MediaRecorder* recorder =
      new MediaRecorder(context, stream, options, exception_state);
  recorder->PauseIfNeeded();

  return recorder;
}

MediaRecorder::MediaRecorder(ExecutionContext* context,
                             MediaStream* stream,
                             const MediaRecorderOptions& options,
                             ExceptionState& exception_state)
    : PausableObject(context),
      stream_(stream),
      mime_type_(options.hasMimeType() ? options.mimeType() : kDefaultMimeType),
      stopped_(true),
      audio_bits_per_second_(0),
      video_bits_per_second_(0),
      state_(State::kInactive),
      // MediaStream recording should use DOM manipulation task source.
      // https://www.w3.org/TR/mediastream-recording/
      dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
          this,
          &MediaRecorder::DispatchScheduledEvent,
          context->GetTaskRunner(TaskType::kDOMManipulation))) {
  DCHECK(stream_->getTracks().size());

  recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
      context->GetTaskRunner(TaskType::kInternalMediaRealTime));
  DCHECK(recorder_handler_);

  if (!recorder_handler_) {
    exception_state.ThrowDOMException(
        kNotSupportedError, "No MediaRecorder handler can be created.");
    return;
  }

  AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
                                &audio_bits_per_second_,
                                &video_bits_per_second_);

  const ContentType content_type(mime_type_);
  if (!recorder_handler_->Initialize(
          this, stream->Descriptor(), content_type.GetType(),
          content_type.Parameter("codecs"), audio_bits_per_second_,
          video_bits_per_second_)) {
    exception_state.ThrowDOMException(
        kNotSupportedError,
        "Failed to initialize native MediaRecorder the type provided (" +
            mime_type_ + ") is not supported.");
    return;
  }
  stopped_ = false;
}

String MediaRecorder::state() const {
  return StateToString(state_);
}

void MediaRecorder::start(ExceptionState& exception_state) {
  start(std::numeric_limits<int>::max() /* timeSlice */, exception_state);
}

void MediaRecorder::start(int time_slice, ExceptionState& exception_state) {
  if (state_ != State::kInactive) {
    exception_state.ThrowDOMException(
        kInvalidStateError,
        "The MediaRecorder's state is '" + StateToString(state_) + "'.");
    return;
  }
  state_ = State::kRecording;

  if (!recorder_handler_->Start(time_slice)) {
    exception_state.ThrowDOMException(kUnknownError,
                                      "The MediaRecorder failed to start "
                                      "because there are no audio or video "
                                      "tracks available.");
    return;
  }
  ScheduleDispatchEvent(Event::Create(EventTypeNames::start));
}

void MediaRecorder::stop(ExceptionState& exception_state) {
  if (state_ == State::kInactive) {
    exception_state.ThrowDOMException(
        kInvalidStateError,
        "The MediaRecorder's state is '" + StateToString(state_) + "'.");
    return;
  }

  StopRecording();
}

void MediaRecorder::pause(ExceptionState& exception_state) {
  if (state_ == State::kInactive) {
    exception_state.ThrowDOMException(
        kInvalidStateError,
        "The MediaRecorder's state is '" + StateToString(state_) + "'.");
    return;
  }
  if (state_ == State::kPaused)
    return;

  state_ = State::kPaused;

  recorder_handler_->Pause();

  ScheduleDispatchEvent(Event::Create(EventTypeNames::pause));
}

void MediaRecorder::resume(ExceptionState& exception_state) {
  if (state_ == State::kInactive) {
    exception_state.ThrowDOMException(
        kInvalidStateError,
        "The MediaRecorder's state is '" + StateToString(state_) + "'.");
    return;
  }
  if (state_ == State::kRecording)
    return;

  state_ = State::kRecording;

  recorder_handler_->Resume();
  ScheduleDispatchEvent(Event::Create(EventTypeNames::resume));
}

void MediaRecorder::requestData(ExceptionState& exception_state) {
  if (state_ == State::kInactive) {
    exception_state.ThrowDOMException(
        kInvalidStateError,
        "The MediaRecorder's state is '" + StateToString(state_) + "'.");
    return;
  }
  WriteData(nullptr /* data */, 0 /* length */, true /* lastInSlice */,
            WTF::CurrentTimeMS());
}

bool MediaRecorder::isTypeSupported(ExecutionContext* context,
                                    const String& type) {
  std::unique_ptr<WebMediaRecorderHandler> handler =
      Platform::Current()->CreateMediaRecorderHandler(
          context->GetTaskRunner(TaskType::kInternalMediaRealTime));
  if (!handler)
    return false;

  // If true is returned from this method, it only indicates that the
  // MediaRecorder implementation is capable of recording Blob objects for the
  // specified MIME type. Recording may still fail if sufficient resources are
  // not available to support the concrete media encoding.
  // https://w3c.github.io/mediacapture-record/#dom-mediarecorder-istypesupported
  ContentType content_type(type);
  return handler->CanSupportMimeType(content_type.GetType(),
                                     content_type.Parameter("codecs"));
}

const AtomicString& MediaRecorder::InterfaceName() const {
  return EventTargetNames::MediaRecorder;
}

ExecutionContext* MediaRecorder::GetExecutionContext() const {
  return PausableObject::GetExecutionContext();
}

void MediaRecorder::Pause() {
  dispatch_scheduled_event_runner_->Pause();
}

void MediaRecorder::Unpause() {
  dispatch_scheduled_event_runner_->Unpause();
}

void MediaRecorder::ContextDestroyed(ExecutionContext*) {
  if (stopped_)
    return;

  stopped_ = true;
  stream_.Clear();
  recorder_handler_.reset();
}

void MediaRecorder::WriteData(const char* data,
                              size_t length,
                              bool last_in_slice,
                              double timecode) {
  if (stopped_ && !last_in_slice) {
    stopped_ = false;
    ScheduleDispatchEvent(Event::Create(EventTypeNames::start));
  }

  if (!blob_data_) {
    blob_data_ = BlobData::Create();
    blob_data_->SetContentType(mime_type_);
  }
  if (data)
    blob_data_->AppendBytes(data, length);

  if (!last_in_slice)
    return;

  // Cache |m_blobData->length()| before release()ng it.
  const long long blob_data_length = blob_data_->length();
  CreateBlobEvent(Blob::Create(BlobDataHandle::Create(std::move(blob_data_),
                                                      blob_data_length)),
                  timecode);
}

void MediaRecorder::OnError(const WebString& message) {
  DLOG(ERROR) << message.Ascii();
  StopRecording();
  ScheduleDispatchEvent(Event::Create(EventTypeNames::error));
}

void MediaRecorder::CreateBlobEvent(Blob* blob, double timecode) {
  ScheduleDispatchEvent(
      BlobEvent::Create(EventTypeNames::dataavailable, blob, timecode));
}

void MediaRecorder::StopRecording() {
  DCHECK(state_ != State::kInactive);
  state_ = State::kInactive;

  recorder_handler_->Stop();

  WriteData(nullptr /* data */, 0 /* length */, true /* lastInSlice */,
            WTF::CurrentTimeMS());
  ScheduleDispatchEvent(Event::Create(EventTypeNames::stop));
}

void MediaRecorder::ScheduleDispatchEvent(Event* event) {
  scheduled_events_.push_back(event);

  dispatch_scheduled_event_runner_->RunAsync();
}

void MediaRecorder::DispatchScheduledEvent() {
  HeapVector<Member<Event>> events;
  events.swap(scheduled_events_);

  for (const auto& event : events)
    DispatchEvent(event);
}

void MediaRecorder::Trace(blink::Visitor* visitor) {
  visitor->Trace(stream_);
  visitor->Trace(dispatch_scheduled_event_runner_);
  visitor->Trace(scheduled_events_);
  EventTargetWithInlineData::Trace(visitor);
  PausableObject::Trace(visitor);
}

}  // namespace blink