[e2d867]: content / media / MediaRecorder.cpp  Maximize  Restore  History

Download this file

409 lines (347 with data), 11.1 kB

  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
403
404
405
406
407
408
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "MediaRecorder.h"
#include "GeneratedEvents.h"
#include "MediaEncoder.h"
#include "mozilla/Util.h"
#include "nsDOMEventTargetHelper.h"
#include "nsDOMFile.h"
#include "nsError.h"
#include "nsIDocument.h"
#include "nsIDOMBlobEvent.h"
#include "nsIDOMRecordErrorEvent.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsIScriptSecurityManager.h"
#include "nsAString.h"
#include "nsTArray.h"
namespace mozilla {
namespace dom {
NS_IMPL_CYCLE_COLLECTION_INHERITED_1(MediaRecorder, nsDOMEventTargetHelper,
mStream)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(MediaRecorder)
NS_INTERFACE_MAP_END_INHERITING(nsDOMEventTargetHelper)
NS_IMPL_ADDREF_INHERITED(MediaRecorder, nsDOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(MediaRecorder, nsDOMEventTargetHelper)
// This task is used for triggering the creating blob object and it runs at main thread.
class MediaRecorder::PushBlobTask : public nsRunnable
{
public:
PushBlobTask(MediaRecorder* recorder)
: mRecorder(recorder) {}
NS_IMETHODIMP Run()
{
MOZ_ASSERT(NS_IsMainThread());
nsresult rv = mRecorder->CreateAndDispatchBlobEvent();
if (NS_FAILED(rv)) {
mRecorder->NotifyError(rv);
}
return NS_OK;
}
MediaRecorder* mRecorder;
};
// This task is for firing the error message from encoder and it runs in main thread
class MediaRecorder::PushErrorMessageTask : public nsRunnable
{
public:
PushErrorMessageTask(MediaRecorder* recorder, nsresult aError)
: mRecorder(recorder),
mError(aError) { }
NS_IMETHODIMP Run()
{
MOZ_ASSERT(NS_IsMainThread());
mRecorder->NotifyError(mError);
return NS_OK;
}
private:
MediaRecorder* mRecorder;
nsresult mError;
};
// This class is used for avoiding abort by directly use the NS_NewRunnableMethod and invoke ExtractEncodedData function
// The abort is checking if the destructor runs at main thread during the cycle-collect step in nsDOMEventTargetHelper
class MediaRecorder::ExtractEncodedDataTask : public nsRunnable
{
public:
ExtractEncodedDataTask(MediaRecorder* aRecorder, MediaEncoder* aEncoder)
: mRecorder(aRecorder),
mEncoder(aEncoder) {}
class ReleaseEncoderThreadTask : public nsRunnable
{
public:
ReleaseEncoderThreadTask(already_AddRefed<MediaRecorder> recorder)
: mRecorder(recorder) {}
NS_IMETHODIMP Run()
{
MOZ_ASSERT(NS_IsMainThread());
mRecorder->mState = RecordingState::Inactive;
mRecorder->DispatchSimpleEvent(NS_LITERAL_STRING("stop"));
mRecorder->mReadThread->Shutdown();
mRecorder->mReadThread = nullptr;
return NS_OK;
}
private:
nsRefPtr<MediaRecorder> mRecorder;
};
NS_IMETHODIMP Run()
{
MOZ_ASSERT(!NS_IsMainThread());
mRecorder->ExtractEncodedData();
NS_DispatchToMainThread(new ReleaseEncoderThreadTask(mRecorder.forget()));
return NS_OK;
}
private:
nsRefPtr<MediaRecorder> mRecorder;
nsRefPtr<MediaEncoder> mEncoder;
};
MediaRecorder::~MediaRecorder()
{
if (mStreamPort) {
mStreamPort->Destroy();
}
if (mTrackUnionStream) {
mTrackUnionStream->Destroy();
}
}
void
MediaRecorder::Init(JSContext* aCx, nsPIDOMWindow* aOwnerWindow)
{
MOZ_ASSERT(aOwnerWindow);
MOZ_ASSERT(aOwnerWindow->IsInnerWindow());
BindToOwner(aOwnerWindow);
}
MediaRecorder::MediaRecorder(DOMMediaStream& aStream)
: mTimeSlice(0),
mState(RecordingState::Inactive)
{
mStream = &aStream;
SetIsDOMBinding();
}
void
MediaRecorder::ExtractEncodedData()
{
TimeStamp lastBlobTimeStamp = TimeStamp::Now();
do {
nsTArray<nsTArray<uint8_t> > outputBufs;
mEncoder->GetEncodedData(&outputBufs, mMimeType);
for (uint i = 0; i < outputBufs.Length(); i++) {
mEncodedBufferCache->AppendBuffer(outputBufs[i]);
}
if (mTimeSlice > 0 && (TimeStamp::Now() - lastBlobTimeStamp).ToMilliseconds() > mTimeSlice) {
NS_DispatchToMainThread(new PushBlobTask(this));
lastBlobTimeStamp = TimeStamp::Now();
}
} while (mState == RecordingState::Recording && !mEncoder->IsShutdown());
NS_DispatchToMainThread(new PushBlobTask(this));
}
void
MediaRecorder::Start(const Optional<int32_t>& aTimeSlice, ErrorResult& aResult)
{
if (mState != RecordingState::Inactive) {
aResult.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (mStream->GetStream()->IsFinished() || mStream->GetStream()->IsDestroyed()) {
aResult.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (aTimeSlice.WasPassed()) {
if (aTimeSlice.Value() < 0) {
aResult.Throw(NS_ERROR_INVALID_ARG);
return;
}
mTimeSlice = aTimeSlice.Value();
} else {
mTimeSlice = 0;
}
// Create a TrackUnionStream to support Pause/Resume by using ChangeExplicitBlockerCount
MediaStreamGraph* gm = mStream->GetStream()->Graph();
mTrackUnionStream = gm->CreateTrackUnionStream(nullptr);
MOZ_ASSERT(mTrackUnionStream, "CreateTrackUnionStream failed");
if (!CheckPrincipal()) {
aResult.Throw(NS_ERROR_DOM_SECURITY_ERR);
return;
}
if (mEncodedBufferCache == nullptr) {
mEncodedBufferCache = new EncodedBufferCache(MAX_ALLOW_MEMORY_BUFFER);
}
mEncoder = MediaEncoder::CreateEncoder(NS_LITERAL_STRING(""));
MOZ_ASSERT(mEncoder, "CreateEncoder failed");
mTrackUnionStream->SetAutofinish(true);
mStreamPort = mTrackUnionStream->AllocateInputPort(mStream->GetStream(), MediaInputPort::FLAG_BLOCK_OUTPUT);
if (mEncoder) {
mTrackUnionStream->AddListener(mEncoder);
} else {
aResult.Throw(NS_ERROR_DOM_ABORT_ERR);
}
if (!mReadThread) {
nsresult rv = NS_NewNamedThread("Media Encoder",
getter_AddRefs(mReadThread));
if (NS_FAILED(rv)) {
aResult.Throw(rv);
return;
}
nsRefPtr<ExtractEncodedDataTask> event = new ExtractEncodedDataTask(this, mEncoder);
mReadThread->Dispatch(event, NS_DISPATCH_NORMAL);
mState = RecordingState::Recording;
}
}
void
MediaRecorder::Stop(ErrorResult& aResult)
{
if (mState == RecordingState::Inactive) {
aResult.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
mState = RecordingState::Inactive;
mTrackUnionStream->RemoveListener(mEncoder);
}
void
MediaRecorder::Pause(ErrorResult& aResult)
{
if (mState != RecordingState::Recording) {
aResult.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
mTrackUnionStream->ChangeExplicitBlockerCount(-1);
mState = RecordingState::Paused;
}
void
MediaRecorder::Resume(ErrorResult& aResult)
{
if (mState != RecordingState::Paused) {
aResult.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
mTrackUnionStream->ChangeExplicitBlockerCount(1);
mState = RecordingState::Recording;
}
void
MediaRecorder::RequestData(ErrorResult& aResult)
{
if (mState != RecordingState::Recording) {
aResult.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
NS_DispatchToMainThread(NS_NewRunnableMethod(this, &MediaRecorder::CreateAndDispatchBlobEvent),
NS_DISPATCH_NORMAL);
}
JSObject*
MediaRecorder::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
{
return MediaRecorderBinding::Wrap(aCx, aScope, this);
}
/* static */ already_AddRefed<MediaRecorder>
MediaRecorder::Constructor(const GlobalObject& aGlobal, JSContext* aCx,
DOMMediaStream& aStream, ErrorResult& aRv)
{
nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(aGlobal.Get());
if (!sgo) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
nsCOMPtr<nsPIDOMWindow> ownerWindow = do_QueryInterface(aGlobal.Get());
if (!ownerWindow) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
nsRefPtr<MediaRecorder> object = new MediaRecorder(aStream);
object->Init(aCx, ownerWindow);
return object.forget();
}
nsresult
MediaRecorder::CreateAndDispatchBlobEvent()
{
NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
if (!CheckPrincipal()) {
// Media is not same-origin, don't allow the data out.
return NS_ERROR_DOM_SECURITY_ERR;
}
nsCOMPtr<nsIDOMBlob> blob;
blob = mEncodedBufferCache->ExtractBlob(mMimeType);
// create an event that uses the MessageEvent interface,
// which does not bubble, is not cancelable, and has no default action
nsCOMPtr<nsIDOMEvent> event;
nsresult rv = NS_NewDOMBlobEvent(getter_AddRefs(event), this, nullptr, nullptr);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDOMBlobEvent> blobEvent = do_QueryInterface(event);
rv = blobEvent->InitBlobEvent(NS_LITERAL_STRING("dataavailable"),
false, false, blob);
NS_ENSURE_SUCCESS(rv, rv);
event->SetTrusted(true);
return DispatchDOMEvent(nullptr, event, nullptr, nullptr);
}
void
MediaRecorder::DispatchSimpleEvent(const nsAString & aStr)
{
NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
nsresult rv = CheckInnerWindowCorrectness();
if (NS_FAILED(rv)) {
return;
}
nsCOMPtr<nsIDOMEvent> event;
rv = NS_NewDOMEvent(getter_AddRefs(event), this, nullptr, nullptr);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to create the error event!!!");
return;
}
rv = event->InitEvent(aStr, false, false);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to init the error event!!!");
return;
}
event->SetTrusted(true);
rv = DispatchDOMEvent(nullptr, event, nullptr, nullptr);
if (NS_FAILED(rv)) {
NS_ERROR("Failed to dispatch the event!!!");
return;
}
}
void
MediaRecorder::NotifyError(nsresult aRv)
{
NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
nsresult rv = CheckInnerWindowCorrectness();
if (NS_FAILED(rv)) {
return;
}
nsString errorMsg;
switch (aRv) {
case NS_ERROR_DOM_SECURITY_ERR:
errorMsg = NS_LITERAL_STRING("SecurityError");
break;
case NS_ERROR_OUT_OF_MEMORY:
errorMsg = NS_LITERAL_STRING("OutOfMemoryError");
break;
default:
errorMsg = NS_LITERAL_STRING("GenericError");
}
nsCOMPtr<nsIDOMEvent> event;
rv = NS_NewDOMRecordErrorEvent(getter_AddRefs(event), this, nullptr, nullptr);
nsCOMPtr<nsIDOMRecordErrorEvent> errorEvent = do_QueryInterface(event);
rv = errorEvent->InitRecordErrorEvent(NS_LITERAL_STRING("error"),
false, false, errorMsg);
event->SetTrusted(true);
rv = DispatchDOMEvent(nullptr, event, nullptr, nullptr);
if (NS_FAILED(rv)) {
NS_ERROR("Failed to dispatch the error event!!!");
return;
}
return;
}
bool MediaRecorder::CheckPrincipal()
{
nsCOMPtr<nsIPrincipal> principal = mStream->GetPrincipal();
if (!GetOwner())
return false;
nsCOMPtr<nsIDocument> doc = GetOwner()->GetExtantDoc();
if (!doc || !principal)
return false;
bool subsumes;
if (NS_FAILED(doc->NodePrincipal()->Subsumes(principal, &subsumes)))
return false;
return subsumes;
}
}
}

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks