This source file includes following definitions.
- parseFloatPercentageValue
- parseFloatPercentageValuePair
- m_client
- getNewCues
- getNewRegions
- parseBytes
- flush
- parse
- flushPendingCue
- hasRequiredFileIdentifier
- collectMetadataHeader
- collectCueId
- collectTimingsAndSettings
- collectCueText
- recoverCue
- ignoreBadCue
- buildFromString
- createDocumentFragmentFromCueText
- createNewCue
- resetCueValues
- createNewRegion
- collectTimeStamp
- collectTimeStamp
- tokenToNodeType
- constructTreeFromToken
#include "config.h"
#include "core/html/track/vtt/VTTParser.h"
#include "core/dom/Document.h"
#include "core/dom/ProcessingInstruction.h"
#include "core/dom/Text.h"
#include "core/html/track/vtt/VTTElement.h"
#include "core/html/track/vtt/VTTScanner.h"
#include "platform/text/SegmentedString.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
using namespace HTMLNames;
const double secondsPerHour = 3600;
const double secondsPerMinute = 60;
const double secondsPerMillisecond = 0.001;
const unsigned fileIdentifierLength = 6;
bool VTTParser::parseFloatPercentageValue(VTTScanner& valueScanner, float& percentage)
{
float number;
if (!valueScanner.scanFloat(number))
return false;
if (!valueScanner.scan('%'))
return false;
if (number < 0 || number > 100)
return false;
percentage = number;
return true;
}
bool VTTParser::parseFloatPercentageValuePair(VTTScanner& valueScanner, char delimiter, FloatPoint& valuePair)
{
float firstCoord;
if (!parseFloatPercentageValue(valueScanner, firstCoord))
return false;
if (!valueScanner.scan(delimiter))
return false;
float secondCoord;
if (!parseFloatPercentageValue(valueScanner, secondCoord))
return false;
valuePair = FloatPoint(firstCoord, secondCoord);
return true;
}
VTTParser::VTTParser(VTTParserClient* client, Document& document)
: m_document(&document)
, m_state(Initial)
, m_decoder(TextResourceDecoder::create("text/plain", UTF8Encoding()))
, m_currentStartTime(0)
, m_currentEndTime(0)
, m_client(client)
{
}
void VTTParser::getNewCues(Vector<RefPtr<VTTCue> >& outputCues)
{
outputCues = m_cuelist;
m_cuelist.clear();
}
void VTTParser::getNewRegions(Vector<RefPtr<VTTRegion> >& outputRegions)
{
outputRegions = m_regionList;
m_regionList.clear();
}
void VTTParser::parseBytes(const char* data, unsigned length)
{
String textData = m_decoder->decode(data, length);
m_lineReader.append(textData);
parse();
}
void VTTParser::flush()
{
String textData = m_decoder->flush();
m_lineReader.append(textData);
m_lineReader.setEndOfStream();
parse();
flushPendingCue();
}
void VTTParser::parse()
{
String line;
while (m_lineReader.getLine(line)) {
switch (m_state) {
case Initial:
if (!hasRequiredFileIdentifier(line)) {
if (m_client)
m_client->fileFailedToParse();
return;
}
m_state = Header;
break;
case Header:
collectMetadataHeader(line);
if (line.isEmpty()) {
if (m_client && m_regionList.size())
m_client->newRegionsParsed();
m_state = Id;
break;
}
if (line.contains("-->"))
m_state = recoverCue(line);
break;
case Id:
if (line.isEmpty())
break;
resetCueValues();
m_state = collectCueId(line);
break;
case TimingsAndSettings:
if (line.isEmpty()) {
m_state = Id;
break;
}
m_state = collectTimingsAndSettings(line);
break;
case CueText:
m_state = collectCueText(line);
break;
case BadCue:
m_state = ignoreBadCue(line);
break;
}
}
}
void VTTParser::flushPendingCue()
{
ASSERT(m_lineReader.isAtEndOfStream());
if (m_state == CueText)
createNewCue();
}
bool VTTParser::hasRequiredFileIdentifier(const String& line)
{
if (!line.startsWith("WEBVTT", fileIdentifierLength))
return false;
if (line.length() > fileIdentifierLength && !isASpace(line[fileIdentifierLength]))
return false;
return true;
}
void VTTParser::collectMetadataHeader(const String& line)
{
DEFINE_STATIC_LOCAL(const AtomicString, regionHeaderName, ("Region", AtomicString::ConstructFromLiteral));
if (!RuntimeEnabledFeatures::webVTTRegionsEnabled())
return;
size_t colonPosition = line.find(':');
if (colonPosition == kNotFound)
return;
String headerName = line.substring(0, colonPosition);
if (headerName == regionHeaderName) {
String headerValue = line.substring(colonPosition + 1);
createNewRegion(headerValue);
}
}
VTTParser::ParseState VTTParser::collectCueId(const String& line)
{
if (line.contains("-->"))
return collectTimingsAndSettings(line);
m_currentId = AtomicString(line);
return TimingsAndSettings;
}
VTTParser::ParseState VTTParser::collectTimingsAndSettings(const String& line)
{
VTTScanner input(line);
input.skipWhile<isASpace>();
if (!collectTimeStamp(input, m_currentStartTime))
return BadCue;
input.skipWhile<isASpace>();
if (!input.scan("-->"))
return BadCue;
input.skipWhile<isASpace>();
if (!collectTimeStamp(input, m_currentEndTime))
return BadCue;
input.skipWhile<isASpace>();
m_currentSettings = input.restOfInputAsString();
return CueText;
}
VTTParser::ParseState VTTParser::collectCueText(const String& line)
{
if (line.isEmpty()) {
createNewCue();
return Id;
}
if (line.contains("-->")) {
createNewCue();
return recoverCue(line);
}
if (!m_currentContent.isEmpty())
m_currentContent.append("\n");
m_currentContent.append(line);
return CueText;
}
VTTParser::ParseState VTTParser::recoverCue(const String& line)
{
resetCueValues();
return collectTimingsAndSettings(line);
}
VTTParser::ParseState VTTParser::ignoreBadCue(const String& line)
{
if (line.isEmpty())
return Id;
if (line.contains("-->"))
return recoverCue(line);
return BadCue;
}
class VTTTreeBuilder {
public:
VTTTreeBuilder(Document& document)
: m_document(document) { }
PassRefPtr<DocumentFragment> buildFromString(const String& cueText);
private:
void constructTreeFromToken(Document&);
VTTToken m_token;
RefPtr<ContainerNode> m_currentNode;
Vector<AtomicString> m_languageStack;
Document& m_document;
};
PassRefPtr<DocumentFragment> VTTTreeBuilder::buildFromString(const String& cueText)
{
RefPtr<DocumentFragment> fragment = DocumentFragment::create(m_document);
if (cueText.isEmpty()) {
fragment->parserAppendChild(Text::create(m_document, ""));
return fragment;
}
m_currentNode = fragment;
VTTTokenizer tokenizer(cueText);
m_languageStack.clear();
while (tokenizer.nextToken(m_token))
constructTreeFromToken(m_document);
return fragment.release();
}
PassRefPtr<DocumentFragment> VTTParser::createDocumentFragmentFromCueText(Document& document, const String& cueText)
{
VTTTreeBuilder treeBuilder(document);
return treeBuilder.buildFromString(cueText);
}
void VTTParser::createNewCue()
{
RefPtr<VTTCue> cue = VTTCue::create(*m_document, m_currentStartTime, m_currentEndTime, m_currentContent.toString());
cue->setId(m_currentId);
cue->parseSettings(m_currentSettings);
m_cuelist.append(cue);
if (m_client)
m_client->newCuesParsed();
}
void VTTParser::resetCueValues()
{
m_currentId = emptyAtom;
m_currentSettings = emptyString();
m_currentStartTime = 0;
m_currentEndTime = 0;
m_currentContent.clear();
}
void VTTParser::createNewRegion(const String& headerValue)
{
if (headerValue.isEmpty())
return;
RefPtr<VTTRegion> region = VTTRegion::create();
region->setRegionSettings(headerValue);
for (size_t i = 0; i < m_regionList.size(); ++i) {
if (m_regionList[i]->id() == region->id()) {
m_regionList.remove(i);
break;
}
}
m_regionList.append(region);
}
bool VTTParser::collectTimeStamp(const String& line, double& timeStamp)
{
VTTScanner input(line);
return collectTimeStamp(input, timeStamp);
}
bool VTTParser::collectTimeStamp(VTTScanner& input, double& timeStamp)
{
enum Mode { Minutes, Hours };
Mode mode = Minutes;
int value1;
unsigned value1Digits = input.scanDigits(value1);
if (!value1Digits)
return false;
if (value1Digits != 2 || value1 > 59)
mode = Hours;
int value2;
if (!input.scan(':') || input.scanDigits(value2) != 2)
return false;
int value3;
if (mode == Hours || input.match(':')) {
if (!input.scan(':') || input.scanDigits(value3) != 2)
return false;
} else {
value3 = value2;
value2 = value1;
value1 = 0;
}
int value4;
if (!input.scan('.') || input.scanDigits(value4) != 3)
return false;
if (value2 > 59 || value3 > 59)
return false;
timeStamp = (value1 * secondsPerHour) + (value2 * secondsPerMinute) + value3 + (value4 * secondsPerMillisecond);
return true;
}
static VTTNodeType tokenToNodeType(VTTToken& token)
{
switch (token.name().length()) {
case 1:
if (token.name()[0] == 'c')
return VTTNodeTypeClass;
if (token.name()[0] == 'v')
return VTTNodeTypeVoice;
if (token.name()[0] == 'b')
return VTTNodeTypeBold;
if (token.name()[0] == 'i')
return VTTNodeTypeItalic;
if (token.name()[0] == 'u')
return VTTNodeTypeUnderline;
break;
case 2:
if (token.name()[0] == 'r' && token.name()[1] == 't')
return VTTNodeTypeRubyText;
break;
case 4:
if (token.name()[0] == 'r' && token.name()[1] == 'u' && token.name()[2] == 'b' && token.name()[3] == 'y')
return VTTNodeTypeRuby;
if (token.name()[0] == 'l' && token.name()[1] == 'a' && token.name()[2] == 'n' && token.name()[3] == 'g')
return VTTNodeTypeLanguage;
break;
}
return VTTNodeTypeNone;
}
void VTTTreeBuilder::constructTreeFromToken(Document& document)
{
switch (m_token.type()) {
case VTTTokenTypes::Character: {
RefPtr<Text> child = Text::create(document, m_token.characters());
m_currentNode->parserAppendChild(child);
break;
}
case VTTTokenTypes::StartTag: {
VTTNodeType nodeType = tokenToNodeType(m_token);
if (nodeType == VTTNodeTypeNone)
break;
VTTNodeType currentType = m_currentNode->isVTTElement() ? toVTTElement(m_currentNode.get())->webVTTNodeType() : VTTNodeTypeNone;
if (nodeType == VTTNodeTypeRubyText && currentType != VTTNodeTypeRuby)
break;
RefPtr<VTTElement> child = VTTElement::create(nodeType, &document);
if (!m_token.classes().isEmpty())
child->setAttribute(classAttr, m_token.classes());
if (nodeType == VTTNodeTypeVoice) {
child->setAttribute(VTTElement::voiceAttributeName(), m_token.annotation());
} else if (nodeType == VTTNodeTypeLanguage) {
m_languageStack.append(m_token.annotation());
child->setAttribute(VTTElement::langAttributeName(), m_languageStack.last());
}
if (!m_languageStack.isEmpty())
child->setLanguage(m_languageStack.last());
m_currentNode->parserAppendChild(child);
m_currentNode = child;
break;
}
case VTTTokenTypes::EndTag: {
VTTNodeType nodeType = tokenToNodeType(m_token);
if (nodeType == VTTNodeTypeNone)
break;
if (!m_currentNode->isVTTElement())
break;
VTTNodeType currentType = toVTTElement(m_currentNode.get())->webVTTNodeType();
bool matchesCurrent = nodeType == currentType;
if (!matchesCurrent) {
if (currentType == VTTNodeTypeRubyText && nodeType == VTTNodeTypeRuby) {
if (m_currentNode->parentNode())
m_currentNode = m_currentNode->parentNode();
} else {
break;
}
}
if (nodeType == VTTNodeTypeLanguage)
m_languageStack.removeLast();
if (m_currentNode->parentNode())
m_currentNode = m_currentNode->parentNode();
break;
}
case VTTTokenTypes::TimestampTag: {
String charactersString = m_token.characters();
double parsedTimeStamp;
if (VTTParser::collectTimeStamp(charactersString, parsedTimeStamp))
m_currentNode->parserAppendChild(ProcessingInstruction::create(document, "timestamp", charactersString));
break;
}
default:
break;
}
}
}