2 * Copyright (C) 2011, 2013 Google Inc. All rights reserved.
3 * Copyright (C) 2011-2014 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #if ENABLE(VIDEO_TRACK)
36 #include "TextTrack.h"
39 #include "HTMLMediaElement.h"
40 #include "SourceBuffer.h"
41 #include "TextTrackCueList.h"
42 #include "TextTrackList.h"
43 #include "VTTRegion.h"
44 #include "VTTRegionList.h"
48 static const int invalidTrackIndex = -1;
50 const AtomicString& TextTrack::subtitlesKeyword()
52 static NeverDestroyed<const AtomicString> subtitles("subtitles", AtomicString::ConstructFromLiteral);
56 static const AtomicString& captionsKeyword()
58 static NeverDestroyed<const AtomicString> captions("captions", AtomicString::ConstructFromLiteral);
62 static const AtomicString& descriptionsKeyword()
64 static NeverDestroyed<const AtomicString> descriptions("descriptions", AtomicString::ConstructFromLiteral);
68 static const AtomicString& chaptersKeyword()
70 static NeverDestroyed<const AtomicString> chapters("chapters", AtomicString::ConstructFromLiteral);
74 static const AtomicString& metadataKeyword()
76 static NeverDestroyed<const AtomicString> metadata("metadata", AtomicString::ConstructFromLiteral);
80 static const AtomicString& forcedKeyword()
82 static NeverDestroyed<const AtomicString> forced("forced", AtomicString::ConstructFromLiteral);
86 TextTrack* TextTrack::captionMenuOffItem()
88 static TextTrack& off = TextTrack::create(0, 0, "off menu item", emptyAtom, emptyAtom, emptyAtom).leakRef();
92 TextTrack* TextTrack::captionMenuAutomaticItem()
94 static TextTrack& automatic = TextTrack::create(0, 0, "automatic menu item", emptyAtom, emptyAtom, emptyAtom).leakRef();
98 TextTrack::TextTrack(ScriptExecutionContext* context, TextTrackClient* client, const AtomicString& kind, const AtomicString& id, const AtomicString& label, const AtomicString& language, TextTrackType type)
99 : TrackBase(TrackBase::TextTrack, id, label, language)
100 , m_scriptExecutionContext(context)
103 , m_trackIndex(invalidTrackIndex)
104 , m_renderedTrackIndex(invalidTrackIndex)
106 if (kind == captionsKeyword())
107 m_kind = Kind::Captions;
108 else if (kind == chaptersKeyword())
109 m_kind = Kind::Chapters;
110 else if (kind == descriptionsKeyword())
111 m_kind = Kind::Descriptions;
112 else if (kind == forcedKeyword())
113 m_kind = Kind::Forced;
114 else if (kind == metadataKeyword())
115 m_kind = Kind::Metadata;
118 TextTrack::~TextTrack()
122 m_client->textTrackRemoveCues(this, m_cues.get());
124 for (size_t i = 0; i < m_cues->length(); ++i)
125 m_cues->item(i)->setTrack(nullptr);
128 for (size_t i = 0; i < m_regions->length(); ++i)
129 m_regions->item(i)->setTrack(nullptr);
133 bool TextTrack::enabled() const
135 return m_mode != Mode::Disabled;
138 bool TextTrack::isValidKindKeyword(const AtomicString& value)
140 if (value == subtitlesKeyword())
142 if (value == captionsKeyword())
144 if (value == descriptionsKeyword())
146 if (value == chaptersKeyword())
148 if (value == metadataKeyword())
150 if (value == forcedKeyword())
156 const AtomicString& TextTrack::kindKeyword() const
160 return captionsKeyword();
162 return chaptersKeyword();
163 case Kind::Descriptions:
164 return descriptionsKeyword();
166 return forcedKeyword();
168 return metadataKeyword();
169 case Kind::Subtitles:
170 return subtitlesKeyword();
172 ASSERT_NOT_REACHED();
173 return subtitlesKeyword();
176 void TextTrack::setKind(Kind newKind)
178 auto oldKind = m_kind;
180 // 10.1 kind, on setting:
181 // 1. If the value being assigned to this attribute does not match one of the text track kinds,
182 // then abort these steps.
184 // 2. Update this attribute to the new value.
187 #if ENABLE(MEDIA_SOURCE)
188 // 3. If the sourceBuffer attribute on this track is not null, then queue a task to fire a simple
189 // event named change at sourceBuffer.textTracks.
191 m_sourceBuffer->textTracks()->scheduleChangeEvent();
193 // 4. Queue a task to fire a simple event named change at the TextTrackList object referenced by
194 // the textTracks attribute on the HTMLMediaElement.
196 mediaElement()->textTracks().scheduleChangeEvent();
199 if (m_client && oldKind != m_kind)
200 m_client->textTrackKindChanged(this);
203 void TextTrack::setKindKeywordIgnoringASCIICase(StringView keyword)
205 if (equalLettersIgnoringASCIICase(keyword, "captions"))
206 setKind(Kind::Captions);
207 else if (equalLettersIgnoringASCIICase(keyword, "chapters"))
208 setKind(Kind::Chapters);
209 else if (equalLettersIgnoringASCIICase(keyword, "descriptions"))
210 setKind(Kind::Descriptions);
211 else if (equalLettersIgnoringASCIICase(keyword, "forced"))
212 setKind(Kind::Forced);
213 else if (equalLettersIgnoringASCIICase(keyword, "metadata"))
214 setKind(Kind::Metadata);
215 else if (equalLettersIgnoringASCIICase(keyword, "subtitles"))
216 setKind(Kind::Subtitles);
217 #if !ENABLE(MEDIA_SOURCE)
218 // FIXME: This preserves the behavior of an older version of this code before refactoring.
219 // !ENABLE(MEDIA_SOURCE): unknown keywords all get turned into Subtitles.
220 // ENABLE(MEDIA_SOURCE): unknown keywords leave the old value for kind untouched.
221 // I am not sure that either of those is the correct behavior; should test and fix.
223 setKind(Kind::Subtitles);
227 void TextTrack::setMode(Mode mode)
229 // On setting, if the new value isn't equal to what the attribute would currently
230 // return, the new value must be processed as follows ...
234 // If mode changes to disabled, remove this track's cues from the client
235 // because they will no longer be accessible from the cues() function.
236 if (mode == Mode::Disabled && m_client && m_cues)
237 m_client->textTrackRemoveCues(this, m_cues.get());
239 if (mode != Mode::Showing && m_cues) {
240 for (size_t i = 0; i < m_cues->length(); ++i) {
241 TextTrackCue* cue = m_cues->item(i);
242 if (cue->isRenderable())
243 toVTTCue(cue)->removeDisplayTree();
250 m_client->textTrackModeChanged(this);
253 TextTrackCueList* TextTrack::cues()
255 // 4.8.10.12.5 If the text track mode ... is not the text track disabled mode,
256 // then the cues attribute must return a live TextTrackCueList object ...
257 // Otherwise, it must return null. When an object is returned, the
258 // same object must be returned each time.
259 // http://www.whatwg.org/specs/web-apps/current-work/#dom-texttrack-cues
260 if (m_mode == Mode::Disabled)
262 return &ensureTextTrackCueList();
265 void TextTrack::removeAllCues()
271 m_client->textTrackRemoveCues(this, m_cues.get());
273 for (size_t i = 0; i < m_cues->length(); ++i)
274 m_cues->item(i)->setTrack(nullptr);
279 TextTrackCueList* TextTrack::activeCues() const
281 // 4.8.10.12.5 If the text track mode ... is not the text track disabled mode,
282 // then the activeCues attribute must return a live TextTrackCueList object ...
283 // ... whose active flag was set when the script started, in text track cue
284 // order. Otherwise, it must return null. When an object is returned, the
285 // same object must be returned each time.
286 // http://www.whatwg.org/specs/web-apps/current-work/#dom-texttrack-activecues
287 if (!m_cues || m_mode == Mode::Disabled)
289 return m_cues->activeCues();
292 void TextTrack::addCue(PassRefPtr<TextTrackCue> prpCue, ExceptionCode& ec)
297 RefPtr<TextTrackCue> cue = prpCue;
299 // 4.7.10.12.6 Text tracks exposing in-band metadata
300 // The UA will use DataCue to expose only text track cue objects that belong to a text track that has a text
301 // track kind of metadata.
302 // If a DataCue is added to a TextTrack via the addCue() method but the text track does not have its text
303 // track kind set to metadata, throw a InvalidNodeTypeError exception and don't add the cue to the TextTrackList
305 if (cue->cueType() == TextTrackCue::Data && m_kind != Kind::Metadata) {
306 ec = INVALID_NODE_TYPE_ERR;
310 // TODO(93143): Add spec-compliant behavior for negative time values.
311 if (!cue->startMediaTime().isValid() || !cue->endMediaTime().isValid() || cue->startMediaTime() < MediaTime::zeroTime() || cue->endMediaTime() < MediaTime::zeroTime())
314 // 4.8.10.12.5 Text track API
316 // The addCue(cue) method of TextTrack objects, when invoked, must run the following steps:
318 // 1. If the given cue is in a text track list of cues, then remove cue from that text track
320 TextTrack* cueTrack = cue->track();
321 if (cueTrack && cueTrack != this)
322 cueTrack->removeCue(cue.get(), ASSERT_NO_EXCEPTION);
324 // 2. Add cue to the method's TextTrack object's text track's text track list of cues.
326 ensureTextTrackCueList().add(cue);
329 m_client->textTrackAddCue(this, cue.get());
332 void TextTrack::removeCue(TextTrackCue* cue, ExceptionCode& ec)
337 // 4.8.10.12.5 Text track API
339 // The removeCue(cue) method of TextTrack objects, when invoked, must run the following steps:
341 // 1. If the given cue is not currently listed in the method's TextTrack
342 // object's text track's text track list of cues, then throw a NotFoundError exception.
343 if (cue->track() != this) {
348 // 2. Remove cue from the method's TextTrack object's text track's text track list of cues.
349 if (!m_cues || !m_cues->remove(cue)) {
350 ec = INVALID_STATE_ERR;
356 m_client->textTrackRemoveCue(this, cue);
359 VTTRegionList& TextTrack::ensureVTTRegionList()
362 m_regions = VTTRegionList::create();
367 VTTRegionList* TextTrack::regions()
369 // If the text track mode of the text track that the TextTrack object
370 // represents is not the text track disabled mode, then the regions
371 // attribute must return a live VTTRegionList object that represents
372 // the text track list of regions of the text track. Otherwise, it must
373 // return null. When an object is returned, the same object must be returned
375 if (m_mode == Mode::Disabled)
377 return &ensureVTTRegionList();
380 void TextTrack::addRegion(PassRefPtr<VTTRegion> prpRegion)
385 RefPtr<VTTRegion> region = prpRegion;
386 VTTRegionList& regionList = ensureVTTRegionList();
388 // 1. If the given region is in a text track list of regions, then remove
389 // region from that text track list of regions.
390 TextTrack* regionTrack = region->track();
391 if (regionTrack && regionTrack != this)
392 regionTrack->removeRegion(region.get(), ASSERT_NO_EXCEPTION);
394 // 2. If the method's TextTrack object's text track list of regions contains
395 // a region with the same identifier as region replace the values of that
396 // region's width, height, anchor point, viewport anchor point and scroll
397 // attributes with those of region.
398 VTTRegion* existingRegion = regionList.getRegionById(region->id());
399 if (existingRegion) {
400 existingRegion->updateParametersFromRegion(region.get());
404 // Otherwise: add region to the method's TextTrack object's text track
406 region->setTrack(this);
407 regionList.add(region);
410 void TextTrack::removeRegion(VTTRegion* region, ExceptionCode &ec)
415 // 1. If the given region is not currently listed in the method's TextTrack
416 // object's text track list of regions, then throw a NotFoundError exception.
417 if (region->track() != this) {
422 if (!m_regions || !m_regions->remove(region)) {
423 ec = INVALID_STATE_ERR;
430 void TextTrack::cueWillChange(TextTrackCue* cue)
435 // The cue may need to be repositioned in the media element's interval tree, may need to
436 // be re-rendered, etc, so remove it before the modification...
437 m_client->textTrackRemoveCue(this, cue);
440 void TextTrack::cueDidChange(TextTrackCue* cue)
445 // Make sure the TextTrackCueList order is up-to-date.
446 ensureTextTrackCueList().updateCueIndex(cue);
448 // ... and add it back again.
449 m_client->textTrackAddCue(this, cue);
452 int TextTrack::trackIndex()
454 ASSERT(m_mediaElement);
456 if (m_trackIndex == invalidTrackIndex)
457 m_trackIndex = m_mediaElement->textTracks().getTrackIndex(*this);
462 void TextTrack::invalidateTrackIndex()
464 m_trackIndex = invalidTrackIndex;
465 m_renderedTrackIndex = invalidTrackIndex;
468 bool TextTrack::isRendered()
470 return (m_kind == Kind::Captions || m_kind == Kind::Subtitles || m_kind == Kind::Forced)
471 && m_mode == Mode::Showing;
474 TextTrackCueList& TextTrack::ensureTextTrackCueList()
477 m_cues = TextTrackCueList::create();
481 int TextTrack::trackIndexRelativeToRenderedTracks()
483 ASSERT(m_mediaElement);
485 if (m_renderedTrackIndex == invalidTrackIndex)
486 m_renderedTrackIndex = m_mediaElement->textTracks().getTrackIndexRelativeToRenderedTracks(*this);
488 return m_renderedTrackIndex;
491 bool TextTrack::hasCue(TextTrackCue* cue, TextTrackCue::CueMatchRules match)
493 if (cue->startMediaTime() < MediaTime::zeroTime() || cue->endMediaTime() < MediaTime::zeroTime())
496 if (!m_cues || !m_cues->length())
499 size_t searchStart = 0;
500 size_t searchEnd = m_cues->length();
503 ASSERT(searchStart <= m_cues->length());
504 ASSERT(searchEnd <= m_cues->length());
506 TextTrackCue* existingCue;
508 // Cues in the TextTrackCueList are maintained in start time order.
509 if (searchStart == searchEnd) {
513 // If there is more than one cue with the same start time, back up to first one so we
514 // consider all of them.
515 while (searchStart >= 2 && cue->hasEquivalentStartTime(*m_cues->item(searchStart - 2)))
518 bool firstCompare = true;
522 firstCompare = false;
523 if (searchStart > m_cues->length())
526 existingCue = m_cues->item(searchStart - 1);
530 if (cue->startMediaTime() > (existingCue->startMediaTime() + startTimeVariance()))
533 if (existingCue->isEqual(*cue, match))
538 size_t index = (searchStart + searchEnd) / 2;
539 existingCue = m_cues->item(index);
540 if ((cue->startMediaTime() + startTimeVariance()) < existingCue->startMediaTime() || (match != TextTrackCue::IgnoreDuration && cue->hasEquivalentStartTime(*existingCue) && cue->endMediaTime() > existingCue->endMediaTime()))
543 searchStart = index + 1;
546 ASSERT_NOT_REACHED();
550 bool TextTrack::isMainProgramContent() const
552 // "Main program" content is intrinsic to the presentation of the media file, regardless of locale. Content such as
553 // directors commentary is not "main program" because it is not essential for the presentation. HTML5 doesn't have
554 // a way to express this in a machine-reable form, it is typically done with the track label, so we assume that caption
555 // tracks are main content and all other track types are not.
556 return m_kind == Kind::Captions;
559 bool TextTrack::containsOnlyForcedSubtitles() const
561 return m_kind == Kind::Forced;
564 #if ENABLE(MEDIA_SOURCE)
566 void TextTrack::setLanguage(const AtomicString& language)
568 // 11.1 language, on setting:
569 // 1. If the value being assigned to this attribute is not an empty string or a BCP 47 language
570 // tag[BCP47], then abort these steps.
571 // FIXME(123926): Validate the BCP47-ness of langague.
573 // 2. Update this attribute to the new value.
574 TrackBase::setLanguage(language);
576 // 3. If the sourceBuffer attribute on this track is not null, then queue a task to fire a simple
577 // event named change at sourceBuffer.textTracks.
579 m_sourceBuffer->textTracks()->scheduleChangeEvent();
581 // 4. Queue a task to fire a simple event named change at the TextTrackList object referenced by
582 // the textTracks attribute on the HTMLMediaElement.
584 mediaElement()->textTracks().scheduleChangeEvent();
589 } // namespace WebCore