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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/mediasource/MediaSource.h"
#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/ExceptionCode.h"
#include "core/events/Event.h"
#include "core/events/GenericEventQueue.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/TimeRanges.h"
#include "modules/mediasource/MediaSourceRegistry.h"
#include "platform/ContentType.h"
#include "platform/Logging.h"
#include "platform/MIMETypeRegistry.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "public/platform/WebMediaSource.h"
#include "public/platform/WebSourceBuffer.h"
#include "wtf/Uint8Array.h"
#include "wtf/text/CString.h"
using blink::WebMediaSource;
using blink::WebSourceBuffer;
namespace WebCore {
static bool throwExceptionIfClosedOrUpdating(bool isOpen, bool isUpdating, ExceptionState& exceptionState)
{
if (!isOpen) {
exceptionState.throwDOMException(InvalidStateError, "The MediaSource's readyState is not 'open'.");
return true;
}
if (isUpdating) {
exceptionState.throwDOMException(InvalidStateError, "The 'updating' attribute is true on one or more of this MediaSource's SourceBuffers.");
return true;
}
return false;
}
const AtomicString& MediaSource::openKeyword()
{
DEFINE_STATIC_LOCAL(const AtomicString, open, ("open", AtomicString::ConstructFromLiteral));
return open;
}
const AtomicString& MediaSource::closedKeyword()
{
DEFINE_STATIC_LOCAL(const AtomicString, closed, ("closed", AtomicString::ConstructFromLiteral));
return closed;
}
const AtomicString& MediaSource::endedKeyword()
{
DEFINE_STATIC_LOCAL(const AtomicString, ended, ("ended", AtomicString::ConstructFromLiteral));
return ended;
}
PassRefPtrWillBeRawPtr<MediaSource> MediaSource::create(ExecutionContext* context)
{
RefPtrWillBeRawPtr<MediaSource> mediaSource(adoptRefWillBeRefCountedGarbageCollected(new MediaSource(context)));
mediaSource->suspendIfNeeded();
return mediaSource.release();
}
MediaSource::MediaSource(ExecutionContext* context)
: ActiveDOMObject(context)
, m_readyState(closedKeyword())
, m_asyncEventQueue(GenericEventQueue::create(this))
, m_attachedElement(0)
, m_sourceBuffers(SourceBufferList::create(executionContext(), m_asyncEventQueue.get()))
, m_activeSourceBuffers(SourceBufferList::create(executionContext(), m_asyncEventQueue.get()))
{
WTF_LOG(Media, "MediaSource::MediaSource %p", this);
ScriptWrappable::init(this);
}
MediaSource::~MediaSource()
{
WTF_LOG(Media, "MediaSource::~MediaSource %p", this);
ASSERT(isClosed());
}
SourceBuffer* MediaSource::addSourceBuffer(const String& type, ExceptionState& exceptionState)
{
WTF_LOG(Media, "MediaSource::addSourceBuffer(%s) %p", type.ascii().data(), this);
// 2.2 https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-MediaSource-addSourceBuffer-SourceBuffer-DOMString-type
// 1. If type is an empty string then throw an InvalidAccessError exception
// and abort these steps.
if (type.isEmpty()) {
exceptionState.throwDOMException(InvalidAccessError, "The type provided is empty.");
return 0;
}
// 2. If type contains a MIME type that is not supported ..., then throw a
// NotSupportedError exception and abort these steps.
if (!isTypeSupported(type)) {
exceptionState.throwDOMException(NotSupportedError, "The type provided ('" + type + "') is unsupported.");
return 0;
}
// 4. If the readyState attribute is not in the "open" state then throw an
// InvalidStateError exception and abort these steps.
if (!isOpen()) {
exceptionState.throwDOMException(InvalidStateError, "The MediaSource's readyState is not 'open'.");
return 0;
}
// 5. Create a new SourceBuffer object and associated resources.
ContentType contentType(type);
Vector<String> codecs = contentType.codecs();
OwnPtr<WebSourceBuffer> webSourceBuffer = createWebSourceBuffer(contentType.type(), codecs, exceptionState);
if (!webSourceBuffer) {
ASSERT(exceptionState.code() == NotSupportedError || exceptionState.code() == QuotaExceededError);
// 2. If type contains a MIME type that is not supported ..., then throw a NotSupportedError exception and abort these steps.
// 3. If the user agent can't handle any more SourceBuffer objects then throw a QuotaExceededError exception and abort these steps
return 0;
}
RefPtrWillBeRawPtr<SourceBuffer> buffer = SourceBuffer::create(webSourceBuffer.release(), this, m_asyncEventQueue.get());
// 6. Add the new object to sourceBuffers and fire a addsourcebuffer on that object.
m_sourceBuffers->add(buffer);
m_activeSourceBuffers->add(buffer);
// 7. Return the new object to the caller.
return buffer.get();
}
void MediaSource::removeSourceBuffer(SourceBuffer* buffer, ExceptionState& exceptionState)
{
WTF_LOG(Media, "MediaSource::removeSourceBuffer() %p", this);
RefPtr<SourceBuffer> protect(buffer);
// 2.2 https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-MediaSource-removeSourceBuffer-void-SourceBuffer-sourceBuffer
// 1. If sourceBuffer specifies an object that is not in sourceBuffers then
// throw a NotFoundError exception and abort these steps.
if (!m_sourceBuffers->length() || !m_sourceBuffers->contains(buffer)) {
exceptionState.throwDOMException(NotFoundError, "The SourceBuffer provided is not contained in this MediaSource.");
return;
}
// 2. If the sourceBuffer.updating attribute equals true, then run the following steps: ...
buffer->abortIfUpdating();
// Steps 3-8 are related to updating audioTracks, videoTracks, and textTracks which aren't implmented yet.
// FIXME(91649): support track selection
// 9. If sourceBuffer is in activeSourceBuffers, then remove sourceBuffer from activeSourceBuffers ...
m_activeSourceBuffers->remove(buffer);
// 10. Remove sourceBuffer from sourceBuffers and fire a removesourcebuffer event
// on that object.
m_sourceBuffers->remove(buffer);
// 11. Destroy all resources for sourceBuffer.
buffer->removedFromMediaSource();
}
void MediaSource::onReadyStateChange(const AtomicString& oldState, const AtomicString& newState)
{
if (isOpen()) {
scheduleEvent(EventTypeNames::sourceopen);
return;
}
if (oldState == openKeyword() && newState == endedKeyword()) {
scheduleEvent(EventTypeNames::sourceended);
return;
}
ASSERT(isClosed());
m_activeSourceBuffers->clear();
// Clear SourceBuffer references to this object.
for (unsigned long i = 0; i < m_sourceBuffers->length(); ++i)
m_sourceBuffers->item(i)->removedFromMediaSource();
m_sourceBuffers->clear();
scheduleEvent(EventTypeNames::sourceclose);
}
bool MediaSource::isUpdating() const
{
// Return true if any member of |m_sourceBuffers| is updating.
for (unsigned long i = 0; i < m_sourceBuffers->length(); ++i) {
if (m_sourceBuffers->item(i)->updating())
return true;
}
return false;
}
bool MediaSource::isTypeSupported(const String& type)
{
WTF_LOG(Media, "MediaSource::isTypeSupported(%s)", type.ascii().data());
// Section 2.2 isTypeSupported() method steps.
// https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-MediaSource-isTypeSupported-boolean-DOMString-type
// 1. If type is an empty string, then return false.
if (type.isNull() || type.isEmpty())
return false;
ContentType contentType(type);
String codecs = contentType.parameter("codecs");
// 2. If type does not contain a valid MIME type string, then return false.
if (contentType.type().isEmpty())
return false;
// 3. If type contains a media type or media subtype that the MediaSource does not support, then return false.
// 4. If type contains at a codec that the MediaSource does not support, then return false.
// 5. If the MediaSource does not support the specified combination of media type, media subtype, and codecs then return false.
// 6. Return true.
return MIMETypeRegistry::isSupportedMediaSourceMIMEType(contentType.type(), codecs);
}
const AtomicString& MediaSource::interfaceName() const
{
return EventTargetNames::MediaSource;
}
ExecutionContext* MediaSource::executionContext() const
{
return ActiveDOMObject::executionContext();
}
void MediaSource::trace(Visitor* visitor)
{
visitor->trace(m_asyncEventQueue);
visitor->trace(m_sourceBuffers);
visitor->trace(m_activeSourceBuffers);
EventTargetWithInlineData::trace(visitor);
}
void MediaSource::setWebMediaSourceAndOpen(PassOwnPtr<WebMediaSource> webMediaSource)
{
TRACE_EVENT_ASYNC_END0("media", "MediaSource::attachToElement", this);
ASSERT(webMediaSource);
ASSERT(!m_webMediaSource);
ASSERT(m_attachedElement);
m_webMediaSource = webMediaSource;
setReadyState(openKeyword());
}
void MediaSource::addedToRegistry()
{
setPendingActivity(this);
}
void MediaSource::removedFromRegistry()
{
unsetPendingActivity(this);
}
double MediaSource::duration() const
{
return isClosed() ? std::numeric_limits<float>::quiet_NaN() : m_webMediaSource->duration();
}
PassRefPtr<TimeRanges> MediaSource::buffered() const
{
// Implements MediaSource algorithm for HTMLMediaElement.buffered.
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#htmlmediaelement-extensions
Vector<RefPtr<TimeRanges> > ranges(m_activeSourceBuffers->length());
for (size_t i = 0; i < m_activeSourceBuffers->length(); ++i)
ranges[i] = m_activeSourceBuffers->item(i)->buffered(ASSERT_NO_EXCEPTION);
// 1. If activeSourceBuffers.length equals 0 then return an empty TimeRanges object and abort these steps.
if (ranges.isEmpty())
return TimeRanges::create();
// 2. Let active ranges be the ranges returned by buffered for each SourceBuffer object in activeSourceBuffers.
// 3. Let highest end time be the largest range end time in the active ranges.
double highestEndTime = -1;
for (size_t i = 0; i < ranges.size(); ++i) {
unsigned length = ranges[i]->length();
if (length)
highestEndTime = std::max(highestEndTime, ranges[i]->end(length - 1, ASSERT_NO_EXCEPTION));
}
// Return an empty range if all ranges are empty.
if (highestEndTime < 0)
return TimeRanges::create();
// 4. Let intersection ranges equal a TimeRange object containing a single range from 0 to highest end time.
RefPtr<TimeRanges> intersectionRanges = TimeRanges::create(0, highestEndTime);
// 5. For each SourceBuffer object in activeSourceBuffers run the following steps:
bool ended = readyState() == endedKeyword();
for (size_t i = 0; i < ranges.size(); ++i) {
// 5.1 Let source ranges equal the ranges returned by the buffered attribute on the current SourceBuffer.
TimeRanges* sourceRanges = ranges[i].get();
// 5.2 If readyState is "ended", then set the end time on the last range in source ranges to highest end time.
if (ended && sourceRanges->length())
sourceRanges->add(sourceRanges->start(sourceRanges->length() - 1, ASSERT_NO_EXCEPTION), highestEndTime);
// 5.3 Let new intersection ranges equal the the intersection between the intersection ranges and the source ranges.
// 5.4 Replace the ranges in intersection ranges with the new intersection ranges.
intersectionRanges->intersectWith(sourceRanges);
}
return intersectionRanges.release();
}
void MediaSource::setDuration(double duration, ExceptionState& exceptionState)
{
// 2.1 http://www.w3.org/TR/media-source/#widl-MediaSource-duration
// 1. If the value being set is negative or NaN then throw an InvalidAccessError
// exception and abort these steps.
if (std::isnan(duration)) {
exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::notAFiniteNumber(duration, "duration"));
return;
}
if (duration < 0.0) {
exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::indexExceedsMinimumBound("duration", duration, 0.0));
return;
}
// 2. If the readyState attribute is not "open" then throw an InvalidStateError
// exception and abort these steps.
// 3. If the updating attribute equals true on any SourceBuffer in sourceBuffers,
// then throw an InvalidStateError exception and abort these steps.
if (throwExceptionIfClosedOrUpdating(isOpen(), isUpdating(), exceptionState))
return;
// 4. Run the duration change algorithm with new duration set to the value being
// assigned to this attribute.
durationChangeAlgorithm(duration);
}
void MediaSource::durationChangeAlgorithm(double newDuration)
{
// Section 2.6.4 Duration change
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#duration-change-algorithm
// 1. If the current value of duration is equal to new duration, then return.
if (newDuration == duration())
return;
// 2. Set old duration to the current value of duration.
double oldDuration = duration();
bool requestSeek = m_attachedElement->currentTime() > newDuration;
// 3. Update duration to new duration.
m_webMediaSource->setDuration(newDuration);
// 4. If the new duration is less than old duration, then call remove(new duration, old duration) on all all objects in sourceBuffers.
if (newDuration < oldDuration) {
for (size_t i = 0; i < m_sourceBuffers->length(); ++i)
m_sourceBuffers->item(i)->remove(newDuration, oldDuration, ASSERT_NO_EXCEPTION);
}
// 5. If a user agent is unable to partially render audio frames or text cues that start before and end after the duration, then run the following steps:
// NOTE: Currently we assume that the media engine is able to render partial frames/cues. If a media
// engine gets added that doesn't support this, then we'll need to add logic to handle the substeps.
// 6. Update the media controller duration to new duration and run the HTMLMediaElement duration change algorithm.
m_attachedElement->durationChanged(newDuration, requestSeek);
}
void MediaSource::setReadyState(const AtomicString& state)
{
ASSERT(state == openKeyword() || state == closedKeyword() || state == endedKeyword());
AtomicString oldState = readyState();
WTF_LOG(Media, "MediaSource::setReadyState() %p : %s -> %s", this, oldState.ascii().data(), state.ascii().data());
if (state == closedKeyword()) {
m_webMediaSource.clear();
m_attachedElement = 0;
}
if (oldState == state)
return;
m_readyState = state;
onReadyStateChange(oldState, state);
}
void MediaSource::endOfStream(const AtomicString& error, ExceptionState& exceptionState)
{
DEFINE_STATIC_LOCAL(const AtomicString, network, ("network", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(const AtomicString, decode, ("decode", AtomicString::ConstructFromLiteral));
if (error == network) {
endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusNetworkError, exceptionState);
} else if (error == decode) {
endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusDecodeError, exceptionState);
} else {
ASSERT_NOT_REACHED(); // IDL enforcement should prevent this case.
}
}
void MediaSource::endOfStream(ExceptionState& exceptionState)
{
endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusNoError, exceptionState);
}
void MediaSource::endOfStreamInternal(const blink::WebMediaSource::EndOfStreamStatus eosStatus, ExceptionState& exceptionState)
{
// 2.2 http://www.w3.org/TR/media-source/#widl-MediaSource-endOfStream-void-EndOfStreamError-error
// 1. If the readyState attribute is not in the "open" state then throw an
// InvalidStateError exception and abort these steps.
// 2. If the updating attribute equals true on any SourceBuffer in sourceBuffers, then throw an
// InvalidStateError exception and abort these steps.
if (throwExceptionIfClosedOrUpdating(isOpen(), isUpdating(), exceptionState))
return;
// 3. Run the end of stream algorithm with the error parameter set to error.
// 1. Change the readyState attribute value to "ended".
// 2. Queue a task to fire a simple event named sourceended at the MediaSource.
setReadyState(endedKeyword());
// 3. Do various steps based on |eosStatus|.
m_webMediaSource->markEndOfStream(eosStatus);
}
bool MediaSource::isOpen() const
{
return readyState() == openKeyword();
}
bool MediaSource::isClosed() const
{
return readyState() == closedKeyword();
}
void MediaSource::close()
{
setReadyState(closedKeyword());
}
bool MediaSource::attachToElement(HTMLMediaElement* element)
{
if (m_attachedElement)
return false;
ASSERT(isClosed());
TRACE_EVENT_ASYNC_BEGIN0("media", "MediaSource::attachToElement", this);
m_attachedElement = element;
return true;
}
void MediaSource::openIfInEndedState()
{
if (m_readyState != endedKeyword())
return;
setReadyState(openKeyword());
m_webMediaSource->unmarkEndOfStream();
}
bool MediaSource::hasPendingActivity() const
{
return m_attachedElement || m_webMediaSource
|| m_asyncEventQueue->hasPendingEvents()
|| ActiveDOMObject::hasPendingActivity();
}
void MediaSource::stop()
{
m_asyncEventQueue->close();
if (!isClosed())
setReadyState(closedKeyword());
m_webMediaSource.clear();
}
PassOwnPtr<WebSourceBuffer> MediaSource::createWebSourceBuffer(const String& type, const Vector<String>& codecs, ExceptionState& exceptionState)
{
WebSourceBuffer* webSourceBuffer = 0;
switch (m_webMediaSource->addSourceBuffer(type, codecs, &webSourceBuffer)) {
case WebMediaSource::AddStatusOk:
return adoptPtr(webSourceBuffer);
case WebMediaSource::AddStatusNotSupported:
ASSERT(!webSourceBuffer);
// 2.2 https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-MediaSource-addSourceBuffer-SourceBuffer-DOMString-type
// Step 2: If type contains a MIME type ... that is not supported with the types
// specified for the other SourceBuffer objects in sourceBuffers, then throw
// a NotSupportedError exception and abort these steps.
exceptionState.throwDOMException(NotSupportedError, "The type provided ('" + type + "') is not supported.");
return nullptr;
case WebMediaSource::AddStatusReachedIdLimit:
ASSERT(!webSourceBuffer);
// 2.2 https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-MediaSource-addSourceBuffer-SourceBuffer-DOMString-type
// Step 3: If the user agent can't handle any more SourceBuffer objects then throw
// a QuotaExceededError exception and abort these steps.
exceptionState.throwDOMException(QuotaExceededError, "This MediaSource has reached the limit of SourceBuffer objects it can handle. No additional SourceBuffer objects may be added.");
return nullptr;
}
ASSERT_NOT_REACHED();
return nullptr;
}
void MediaSource::scheduleEvent(const AtomicString& eventName)
{
ASSERT(m_asyncEventQueue);
RefPtrWillBeRawPtr<Event> event = Event::create(eventName);
event->setTarget(this);
m_asyncEventQueue->enqueueEvent(event.release());
}
URLRegistry& MediaSource::registry() const
{
return MediaSourceRegistry::registry();
}
} // namespace WebCore
|