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 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.media;
import android.content.Context;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.util.ArrayMap;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.CaptioningManager;
import android.view.accessibility.CaptioningManager.CaptionStyle;
import android.view.accessibility.CaptioningManager.CaptioningChangeListener;
import android.widget.LinearLayout;
import com.android.internal.widget.SubtitleView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/** @hide */
public class WebVttRenderer extends SubtitleController.Renderer {
private final Context mContext;
private WebVttRenderingWidget mRenderingWidget;
public WebVttRenderer(Context context) {
mContext = context;
}
@Override
public boolean supports(MediaFormat format) {
if (format.containsKey(MediaFormat.KEY_MIME)) {
return format.getString(MediaFormat.KEY_MIME).equals("text/vtt");
}
return false;
}
@Override
public SubtitleTrack createTrack(MediaFormat format) {
if (mRenderingWidget == null) {
mRenderingWidget = new WebVttRenderingWidget(mContext);
}
return new WebVttTrack(mRenderingWidget, format);
}
}
/** @hide */
class TextTrackCueSpan {
long mTimestampMs;
boolean mEnabled;
String mText;
TextTrackCueSpan(String text, long timestamp) {
mTimestampMs = timestamp;
mText = text;
// spans with timestamp will be enabled by Cue.onTime
mEnabled = (mTimestampMs < 0);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof TextTrackCueSpan)) {
return false;
}
TextTrackCueSpan span = (TextTrackCueSpan) o;
return mTimestampMs == span.mTimestampMs &&
mText.equals(span.mText);
}
}
/**
* @hide
*
* Extract all text without style, but with timestamp spans.
*/
class UnstyledTextExtractor implements Tokenizer.OnTokenListener {
StringBuilder mLine = new StringBuilder();
Vector<TextTrackCueSpan[]> mLines = new Vector<TextTrackCueSpan[]>();
Vector<TextTrackCueSpan> mCurrentLine = new Vector<TextTrackCueSpan>();
long mLastTimestamp;
UnstyledTextExtractor() {
init();
}
private void init() {
mLine.delete(0, mLine.length());
mLines.clear();
mCurrentLine.clear();
mLastTimestamp = -1;
}
@Override
public void onData(String s) {
mLine.append(s);
}
@Override
public void onStart(String tag, String[] classes, String annotation) { }
@Override
public void onEnd(String tag) { }
@Override
public void onTimeStamp(long timestampMs) {
// finish any prior span
if (mLine.length() > 0 && timestampMs != mLastTimestamp) {
mCurrentLine.add(
new TextTrackCueSpan(mLine.toString(), mLastTimestamp));
mLine.delete(0, mLine.length());
}
mLastTimestamp = timestampMs;
}
@Override
public void onLineEnd() {
// finish any pending span
if (mLine.length() > 0) {
mCurrentLine.add(
new TextTrackCueSpan(mLine.toString(), mLastTimestamp));
mLine.delete(0, mLine.length());
}
TextTrackCueSpan[] spans = new TextTrackCueSpan[mCurrentLine.size()];
mCurrentLine.toArray(spans);
mCurrentLine.clear();
mLines.add(spans);
}
public TextTrackCueSpan[][] getText() {
// for politeness, finish last cue-line if it ends abruptly
if (mLine.length() > 0 || mCurrentLine.size() > 0) {
onLineEnd();
}
TextTrackCueSpan[][] lines = new TextTrackCueSpan[mLines.size()][];
mLines.toArray(lines);
init();
return lines;
}
}
/**
* @hide
*
* Tokenizer tokenizes the WebVTT Cue Text into tags and data
*/
class Tokenizer {
private static final String TAG = "Tokenizer";
private TokenizerPhase mPhase;
private TokenizerPhase mDataTokenizer;
private TokenizerPhase mTagTokenizer;
private OnTokenListener mListener;
private String mLine;
private int mHandledLen;
interface TokenizerPhase {
TokenizerPhase start();
void tokenize();
}
class DataTokenizer implements TokenizerPhase {
// includes both WebVTT data && escape state
private StringBuilder mData;
public TokenizerPhase start() {
mData = new StringBuilder();
return this;
}
private boolean replaceEscape(String escape, String replacement, int pos) {
if (mLine.startsWith(escape, pos)) {
mData.append(mLine.substring(mHandledLen, pos));
mData.append(replacement);
mHandledLen = pos + escape.length();
pos = mHandledLen - 1;
return true;
}
return false;
}
@Override
public void tokenize() {
int end = mLine.length();
for (int pos = mHandledLen; pos < mLine.length(); pos++) {
if (mLine.charAt(pos) == '&') {
if (replaceEscape("&", "&", pos) ||
replaceEscape("<", "<", pos) ||
replaceEscape(">", ">", pos) ||
replaceEscape("‎", "\u200e", pos) ||
replaceEscape("‏", "\u200f", pos) ||
replaceEscape(" ", "\u00a0", pos)) {
continue;
}
} else if (mLine.charAt(pos) == '<') {
end = pos;
mPhase = mTagTokenizer.start();
break;
}
}
mData.append(mLine.substring(mHandledLen, end));
// yield mData
mListener.onData(mData.toString());
mData.delete(0, mData.length());
mHandledLen = end;
}
}
class TagTokenizer implements TokenizerPhase {
private boolean mAtAnnotation;
private String mName, mAnnotation;
public TokenizerPhase start() {
mName = mAnnotation = "";
mAtAnnotation = false;
return this;
}
@Override
public void tokenize() {
if (!mAtAnnotation)
mHandledLen++;
if (mHandledLen < mLine.length()) {
String[] parts;
/**
* Collect annotations and end-tags to closing >. Collect tag
* name to closing bracket or next white-space.
*/
if (mAtAnnotation || mLine.charAt(mHandledLen) == '/') {
parts = mLine.substring(mHandledLen).split(">");
} else {
parts = mLine.substring(mHandledLen).split("[\t\f >]");
}
String part = mLine.substring(
mHandledLen, mHandledLen + parts[0].length());
mHandledLen += parts[0].length();
if (mAtAnnotation) {
mAnnotation += " " + part;
} else {
mName = part;
}
}
mAtAnnotation = true;
if (mHandledLen < mLine.length() && mLine.charAt(mHandledLen) == '>') {
yield_tag();
mPhase = mDataTokenizer.start();
mHandledLen++;
}
}
private void yield_tag() {
if (mName.startsWith("/")) {
mListener.onEnd(mName.substring(1));
} else if (mName.length() > 0 && Character.isDigit(mName.charAt(0))) {
// timestamp
try {
long timestampMs = WebVttParser.parseTimestampMs(mName);
mListener.onTimeStamp(timestampMs);
} catch (NumberFormatException e) {
Log.d(TAG, "invalid timestamp tag: <" + mName + ">");
}
} else {
mAnnotation = mAnnotation.replaceAll("\\s+", " ");
if (mAnnotation.startsWith(" ")) {
mAnnotation = mAnnotation.substring(1);
}
if (mAnnotation.endsWith(" ")) {
mAnnotation = mAnnotation.substring(0, mAnnotation.length() - 1);
}
String[] classes = null;
int dotAt = mName.indexOf('.');
if (dotAt >= 0) {
classes = mName.substring(dotAt + 1).split("\\.");
mName = mName.substring(0, dotAt);
}
mListener.onStart(mName, classes, mAnnotation);
}
}
}
Tokenizer(OnTokenListener listener) {
mDataTokenizer = new DataTokenizer();
mTagTokenizer = new TagTokenizer();
reset();
mListener = listener;
}
void reset() {
mPhase = mDataTokenizer.start();
}
void tokenize(String s) {
mHandledLen = 0;
mLine = s;
while (mHandledLen < mLine.length()) {
mPhase.tokenize();
}
/* we are finished with a line unless we are in the middle of a tag */
if (!(mPhase instanceof TagTokenizer)) {
// yield END-OF-LINE
mListener.onLineEnd();
}
}
interface OnTokenListener {
void onData(String s);
void onStart(String tag, String[] classes, String annotation);
void onEnd(String tag);
void onTimeStamp(long timestampMs);
void onLineEnd();
}
}
/** @hide */
class TextTrackRegion {
final static int SCROLL_VALUE_NONE = 300;
final static int SCROLL_VALUE_SCROLL_UP = 301;
String mId;
float mWidth;
int mLines;
float mAnchorPointX, mAnchorPointY;
float mViewportAnchorPointX, mViewportAnchorPointY;
int mScrollValue;
TextTrackRegion() {
mId = "";
mWidth = 100;
mLines = 3;
mAnchorPointX = mViewportAnchorPointX = 0.f;
mAnchorPointY = mViewportAnchorPointY = 100.f;
mScrollValue = SCROLL_VALUE_NONE;
}
public String toString() {
StringBuilder res = new StringBuilder(" {id:\"").append(mId)
.append("\", width:").append(mWidth)
.append(", lines:").append(mLines)
.append(", anchorPoint:(").append(mAnchorPointX)
.append(", ").append(mAnchorPointY)
.append("), viewportAnchorPoints:").append(mViewportAnchorPointX)
.append(", ").append(mViewportAnchorPointY)
.append("), scrollValue:")
.append(mScrollValue == SCROLL_VALUE_NONE ? "none" :
mScrollValue == SCROLL_VALUE_SCROLL_UP ? "scroll_up" :
"INVALID")
.append("}");
return res.toString();
}
}
/** @hide */
class TextTrackCue extends SubtitleTrack.Cue {
final static int WRITING_DIRECTION_HORIZONTAL = 100;
final static int WRITING_DIRECTION_VERTICAL_RL = 101;
final static int WRITING_DIRECTION_VERTICAL_LR = 102;
final static int ALIGNMENT_MIDDLE = 200;
final static int ALIGNMENT_START = 201;
final static int ALIGNMENT_END = 202;
final static int ALIGNMENT_LEFT = 203;
final static int ALIGNMENT_RIGHT = 204;
private static final String TAG = "TTCue";
String mId;
boolean mPauseOnExit;
int mWritingDirection;
String mRegionId;
boolean mSnapToLines;
Integer mLinePosition; // null means AUTO
boolean mAutoLinePosition;
int mTextPosition;
int mSize;
int mAlignment;
// Vector<String> mText;
String[] mStrings;
TextTrackCueSpan[][] mLines;
TextTrackRegion mRegion;
TextTrackCue() {
mId = "";
mPauseOnExit = false;
mWritingDirection = WRITING_DIRECTION_HORIZONTAL;
mRegionId = "";
mSnapToLines = true;
mLinePosition = null /* AUTO */;
mTextPosition = 50;
mSize = 100;
mAlignment = ALIGNMENT_MIDDLE;
mLines = null;
mRegion = null;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof TextTrackCue)) {
return false;
}
if (this == o) {
return true;
}
try {
TextTrackCue cue = (TextTrackCue) o;
boolean res = mId.equals(cue.mId) &&
mPauseOnExit == cue.mPauseOnExit &&
mWritingDirection == cue.mWritingDirection &&
mRegionId.equals(cue.mRegionId) &&
mSnapToLines == cue.mSnapToLines &&
mAutoLinePosition == cue.mAutoLinePosition &&
(mAutoLinePosition ||
((mLinePosition != null && mLinePosition.equals(cue.mLinePosition)) ||
(mLinePosition == null && cue.mLinePosition == null))) &&
mTextPosition == cue.mTextPosition &&
mSize == cue.mSize &&
mAlignment == cue.mAlignment &&
mLines.length == cue.mLines.length;
if (res == true) {
for (int line = 0; line < mLines.length; line++) {
if (!Arrays.equals(mLines[line], cue.mLines[line])) {
return false;
}
}
}
return res;
} catch(IncompatibleClassChangeError e) {
return false;
}
}
public StringBuilder appendStringsToBuilder(StringBuilder builder) {
if (mStrings == null) {
builder.append("null");
} else {
builder.append("[");
boolean first = true;
for (String s: mStrings) {
if (!first) {
builder.append(", ");
}
if (s == null) {
builder.append("null");
} else {
builder.append("\"");
builder.append(s);
builder.append("\"");
}
first = false;
}
builder.append("]");
}
return builder;
}
public StringBuilder appendLinesToBuilder(StringBuilder builder) {
if (mLines == null) {
builder.append("null");
} else {
builder.append("[");
boolean first = true;
for (TextTrackCueSpan[] spans: mLines) {
if (!first) {
builder.append(", ");
}
if (spans == null) {
builder.append("null");
} else {
builder.append("\"");
boolean innerFirst = true;
long lastTimestamp = -1;
for (TextTrackCueSpan span: spans) {
if (!innerFirst) {
builder.append(" ");
}
if (span.mTimestampMs != lastTimestamp) {
builder.append("<")
.append(WebVttParser.timeToString(
span.mTimestampMs))
.append(">");
lastTimestamp = span.mTimestampMs;
}
builder.append(span.mText);
innerFirst = false;
}
builder.append("\"");
}
first = false;
}
builder.append("]");
}
return builder;
}
public String toString() {
StringBuilder res = new StringBuilder();
res.append(WebVttParser.timeToString(mStartTimeMs))
.append(" --> ").append(WebVttParser.timeToString(mEndTimeMs))
.append(" {id:\"").append(mId)
.append("\", pauseOnExit:").append(mPauseOnExit)
.append(", direction:")
.append(mWritingDirection == WRITING_DIRECTION_HORIZONTAL ? "horizontal" :
mWritingDirection == WRITING_DIRECTION_VERTICAL_LR ? "vertical_lr" :
mWritingDirection == WRITING_DIRECTION_VERTICAL_RL ? "vertical_rl" :
"INVALID")
.append(", regionId:\"").append(mRegionId)
.append("\", snapToLines:").append(mSnapToLines)
.append(", linePosition:").append(mAutoLinePosition ? "auto" :
mLinePosition)
.append(", textPosition:").append(mTextPosition)
.append(", size:").append(mSize)
.append(", alignment:")
.append(mAlignment == ALIGNMENT_END ? "end" :
mAlignment == ALIGNMENT_LEFT ? "left" :
mAlignment == ALIGNMENT_MIDDLE ? "middle" :
mAlignment == ALIGNMENT_RIGHT ? "right" :
mAlignment == ALIGNMENT_START ? "start" : "INVALID")
.append(", text:");
appendStringsToBuilder(res).append("}");
return res.toString();
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public void onTime(long timeMs) {
for (TextTrackCueSpan[] line: mLines) {
for (TextTrackCueSpan span: line) {
span.mEnabled = timeMs >= span.mTimestampMs;
}
}
}
}
/**
* Supporting July 10 2013 draft version
*
* @hide
*/
class WebVttParser {
private static final String TAG = "WebVttParser";
private Phase mPhase;
private TextTrackCue mCue;
private Vector<String> mCueTexts;
private WebVttCueListener mListener;
private String mBuffer;
WebVttParser(WebVttCueListener listener) {
mPhase = mParseStart;
mBuffer = ""; /* mBuffer contains up to 1 incomplete line */
mListener = listener;
mCueTexts = new Vector<String>();
}
/* parsePercentageString */
public static float parseFloatPercentage(String s)
throws NumberFormatException {
if (!s.endsWith("%")) {
throw new NumberFormatException("does not end in %");
}
s = s.substring(0, s.length() - 1);
// parseFloat allows an exponent or a sign
if (s.matches(".*[^0-9.].*")) {
throw new NumberFormatException("contains an invalid character");
}
try {
float value = Float.parseFloat(s);
if (value < 0.0f || value > 100.0f) {
throw new NumberFormatException("is out of range");
}
return value;
} catch (NumberFormatException e) {
throw new NumberFormatException("is not a number");
}
}
public static int parseIntPercentage(String s) throws NumberFormatException {
if (!s.endsWith("%")) {
throw new NumberFormatException("does not end in %");
}
s = s.substring(0, s.length() - 1);
// parseInt allows "-0" that returns 0, so check for non-digits
if (s.matches(".*[^0-9].*")) {
throw new NumberFormatException("contains an invalid character");
}
try {
int value = Integer.parseInt(s);
if (value < 0 || value > 100) {
throw new NumberFormatException("is out of range");
}
return value;
} catch (NumberFormatException e) {
throw new NumberFormatException("is not a number");
}
}
public static long parseTimestampMs(String s) throws NumberFormatException {
if (!s.matches("(\\d+:)?[0-5]\\d:[0-5]\\d\\.\\d{3}")) {
throw new NumberFormatException("has invalid format");
}
String[] parts = s.split("\\.", 2);
long value = 0;
for (String group: parts[0].split(":")) {
value = value * 60 + Long.parseLong(group);
}
return value * 1000 + Long.parseLong(parts[1]);
}
public static String timeToString(long timeMs) {
return String.format("%d:%02d:%02d.%03d",
timeMs / 3600000, (timeMs / 60000) % 60,
(timeMs / 1000) % 60, timeMs % 1000);
}
public void parse(String s) {
boolean trailingCR = false;
mBuffer = (mBuffer + s.replace("\0", "\ufffd")).replace("\r\n", "\n");
/* keep trailing '\r' in case matching '\n' arrives in next packet */
if (mBuffer.endsWith("\r")) {
trailingCR = true;
mBuffer = mBuffer.substring(0, mBuffer.length() - 1);
}
String[] lines = mBuffer.split("[\r\n]");
for (int i = 0; i < lines.length - 1; i++) {
mPhase.parse(lines[i]);
}
mBuffer = lines[lines.length - 1];
if (trailingCR)
mBuffer += "\r";
}
public void eos() {
if (mBuffer.endsWith("\r")) {
mBuffer = mBuffer.substring(0, mBuffer.length() - 1);
}
mPhase.parse(mBuffer);
mBuffer = "";
yieldCue();
mPhase = mParseStart;
}
public void yieldCue() {
if (mCue != null && mCueTexts.size() > 0) {
mCue.mStrings = new String[mCueTexts.size()];
mCueTexts.toArray(mCue.mStrings);
mCueTexts.clear();
mListener.onCueParsed(mCue);
}
mCue = null;
}
interface Phase {
void parse(String line);
}
final private Phase mSkipRest = new Phase() {
@Override
public void parse(String line) { }
};
final private Phase mParseStart = new Phase() { // 5-9
@Override
public void parse(String line) {
if (line.startsWith("\ufeff")) {
line = line.substring(1);
}
if (!line.equals("WEBVTT") &&
!line.startsWith("WEBVTT ") &&
!line.startsWith("WEBVTT\t")) {
log_warning("Not a WEBVTT header", line);
mPhase = mSkipRest;
} else {
mPhase = mParseHeader;
}
}
};
final private Phase mParseHeader = new Phase() { // 10-13
TextTrackRegion parseRegion(String s) {
TextTrackRegion region = new TextTrackRegion();
for (String setting: s.split(" +")) {
int equalAt = setting.indexOf('=');
if (equalAt <= 0 || equalAt == setting.length() - 1) {
continue;
}
String name = setting.substring(0, equalAt);
String value = setting.substring(equalAt + 1);
if (name.equals("id")) {
region.mId = value;
} else if (name.equals("width")) {
try {
region.mWidth = parseFloatPercentage(value);
} catch (NumberFormatException e) {
log_warning("region setting", name,
"has invalid value", e.getMessage(), value);
}
} else if (name.equals("lines")) {
if (value.matches(".*[^0-9].*")) {
log_warning("lines", name, "contains an invalid character", value);
} else {
try {
region.mLines = Integer.parseInt(value);
assert(region.mLines >= 0); // lines contains only digits
} catch (NumberFormatException e) {
log_warning("region setting", name, "is not numeric", value);
}
}
} else if (name.equals("regionanchor") ||
name.equals("viewportanchor")) {
int commaAt = value.indexOf(",");
if (commaAt < 0) {
log_warning("region setting", name, "contains no comma", value);
continue;
}
String anchorX = value.substring(0, commaAt);
String anchorY = value.substring(commaAt + 1);
float x, y;
try {
x = parseFloatPercentage(anchorX);
} catch (NumberFormatException e) {
log_warning("region setting", name,
"has invalid x component", e.getMessage(), anchorX);
continue;
}
try {
y = parseFloatPercentage(anchorY);
} catch (NumberFormatException e) {
log_warning("region setting", name,
"has invalid y component", e.getMessage(), anchorY);
continue;
}
if (name.charAt(0) == 'r') {
region.mAnchorPointX = x;
region.mAnchorPointY = y;
} else {
region.mViewportAnchorPointX = x;
region.mViewportAnchorPointY = y;
}
} else if (name.equals("scroll")) {
if (value.equals("up")) {
region.mScrollValue =
TextTrackRegion.SCROLL_VALUE_SCROLL_UP;
} else {
log_warning("region setting", name, "has invalid value", value);
}
}
}
return region;
}
@Override
public void parse(String line) {
if (line.length() == 0) {
mPhase = mParseCueId;
} else if (line.contains("-->")) {
mPhase = mParseCueTime;
mPhase.parse(line);
} else {
int colonAt = line.indexOf(':');
if (colonAt <= 0 || colonAt >= line.length() - 1) {
log_warning("meta data header has invalid format", line);
}
String name = line.substring(0, colonAt);
String value = line.substring(colonAt + 1);
if (name.equals("Region")) {
TextTrackRegion region = parseRegion(value);
mListener.onRegionParsed(region);
}
}
}
};
final private Phase mParseCueId = new Phase() {
@Override
public void parse(String line) {
if (line.length() == 0) {
return;
}
assert(mCue == null);
if (line.equals("NOTE") || line.startsWith("NOTE ")) {
mPhase = mParseCueText;
}
mCue = new TextTrackCue();
mCueTexts.clear();
mPhase = mParseCueTime;
if (line.contains("-->")) {
mPhase.parse(line);
} else {
mCue.mId = line;
}
}
};
final private Phase mParseCueTime = new Phase() {
@Override
public void parse(String line) {
int arrowAt = line.indexOf("-->");
if (arrowAt < 0) {
mCue = null;
mPhase = mParseCueId;
return;
}
String start = line.substring(0, arrowAt).trim();
// convert only initial and first other white-space to space
String rest = line.substring(arrowAt + 3)
.replaceFirst("^\\s+", "").replaceFirst("\\s+", " ");
int spaceAt = rest.indexOf(' ');
String end = spaceAt > 0 ? rest.substring(0, spaceAt) : rest;
rest = spaceAt > 0 ? rest.substring(spaceAt + 1) : "";
mCue.mStartTimeMs = parseTimestampMs(start);
mCue.mEndTimeMs = parseTimestampMs(end);
for (String setting: rest.split(" +")) {
int colonAt = setting.indexOf(':');
if (colonAt <= 0 || colonAt == setting.length() - 1) {
continue;
}
String name = setting.substring(0, colonAt);
String value = setting.substring(colonAt + 1);
if (name.equals("region")) {
mCue.mRegionId = value;
} else if (name.equals("vertical")) {
if (value.equals("rl")) {
mCue.mWritingDirection =
TextTrackCue.WRITING_DIRECTION_VERTICAL_RL;
} else if (value.equals("lr")) {
mCue.mWritingDirection =
TextTrackCue.WRITING_DIRECTION_VERTICAL_LR;
} else {
log_warning("cue setting", name, "has invalid value", value);
}
} else if (name.equals("line")) {
try {
/* TRICKY: we know that there are no spaces in value */
assert(value.indexOf(' ') < 0);
if (value.endsWith("%")) {
mCue.mSnapToLines = false;
mCue.mLinePosition = parseIntPercentage(value);
} else if (value.matches(".*[^0-9].*")) {
log_warning("cue setting", name,
"contains an invalid character", value);
} else {
mCue.mSnapToLines = true;
mCue.mLinePosition = Integer.parseInt(value);
}
} catch (NumberFormatException e) {
log_warning("cue setting", name,
"is not numeric or percentage", value);
}
// TODO: add support for optional alignment value [,start|middle|end]
} else if (name.equals("position")) {
try {
mCue.mTextPosition = parseIntPercentage(value);
} catch (NumberFormatException e) {
log_warning("cue setting", name,
"is not numeric or percentage", value);
}
} else if (name.equals("size")) {
try {
mCue.mSize = parseIntPercentage(value);
} catch (NumberFormatException e) {
log_warning("cue setting", name,
"is not numeric or percentage", value);
}
} else if (name.equals("align")) {
if (value.equals("start")) {
mCue.mAlignment = TextTrackCue.ALIGNMENT_START;
} else if (value.equals("middle")) {
mCue.mAlignment = TextTrackCue.ALIGNMENT_MIDDLE;
} else if (value.equals("end")) {
mCue.mAlignment = TextTrackCue.ALIGNMENT_END;
} else if (value.equals("left")) {
mCue.mAlignment = TextTrackCue.ALIGNMENT_LEFT;
} else if (value.equals("right")) {
mCue.mAlignment = TextTrackCue.ALIGNMENT_RIGHT;
} else {
log_warning("cue setting", name, "has invalid value", value);
continue;
}
}
}
if (mCue.mLinePosition != null ||
mCue.mSize != 100 ||
(mCue.mWritingDirection !=
TextTrackCue.WRITING_DIRECTION_HORIZONTAL)) {
mCue.mRegionId = "";
}
mPhase = mParseCueText;
}
};
/* also used for notes */
final private Phase mParseCueText = new Phase() {
@Override
public void parse(String line) {
if (line.length() == 0) {
yieldCue();
mPhase = mParseCueId;
return;
} else if (mCue != null) {
mCueTexts.add(line);
}
}
};
private void log_warning(
String nameType, String name, String message,
String subMessage, String value) {
Log.w(this.getClass().getName(), nameType + " '" + name + "' " +
message + " ('" + value + "' " + subMessage + ")");
}
private void log_warning(
String nameType, String name, String message, String value) {
Log.w(this.getClass().getName(), nameType + " '" + name + "' " +
message + " ('" + value + "')");
}
private void log_warning(String message, String value) {
Log.w(this.getClass().getName(), message + " ('" + value + "')");
}
}
/** @hide */
interface WebVttCueListener {
void onCueParsed(TextTrackCue cue);
void onRegionParsed(TextTrackRegion region);
}
/** @hide */
class WebVttTrack extends SubtitleTrack implements WebVttCueListener {
private static final String TAG = "WebVttTrack";
private final WebVttParser mParser = new WebVttParser(this);
private final UnstyledTextExtractor mExtractor =
new UnstyledTextExtractor();
private final Tokenizer mTokenizer = new Tokenizer(mExtractor);
private final Vector<Long> mTimestamps = new Vector<Long>();
private final WebVttRenderingWidget mRenderingWidget;
private final Map<String, TextTrackRegion> mRegions =
new HashMap<String, TextTrackRegion>();
private Long mCurrentRunID;
WebVttTrack(WebVttRenderingWidget renderingWidget, MediaFormat format) {
super(format);
mRenderingWidget = renderingWidget;
}
@Override
public WebVttRenderingWidget getRenderingWidget() {
return mRenderingWidget;
}
@Override
public void onData(byte[] data, boolean eos, long runID) {
try {
String str = new String(data, "UTF-8");
// implement intermixing restriction for WebVTT only for now
synchronized(mParser) {
if (mCurrentRunID != null && runID != mCurrentRunID) {
throw new IllegalStateException(
"Run #" + mCurrentRunID +
" in progress. Cannot process run #" + runID);
}
mCurrentRunID = runID;
mParser.parse(str);
if (eos) {
finishedRun(runID);
mParser.eos();
mRegions.clear();
mCurrentRunID = null;
}
}
} catch (java.io.UnsupportedEncodingException e) {
Log.w(TAG, "subtitle data is not UTF-8 encoded: " + e);
}
}
@Override
public void onCueParsed(TextTrackCue cue) {
synchronized (mParser) {
// resolve region
if (cue.mRegionId.length() != 0) {
cue.mRegion = mRegions.get(cue.mRegionId);
}
if (DEBUG) Log.v(TAG, "adding cue " + cue);
// tokenize text track string-lines into lines of spans
mTokenizer.reset();
for (String s: cue.mStrings) {
mTokenizer.tokenize(s);
}
cue.mLines = mExtractor.getText();
if (DEBUG) Log.v(TAG, cue.appendLinesToBuilder(
cue.appendStringsToBuilder(
new StringBuilder()).append(" simplified to: "))
.toString());
// extract inner timestamps
for (TextTrackCueSpan[] line: cue.mLines) {
for (TextTrackCueSpan span: line) {
if (span.mTimestampMs > cue.mStartTimeMs &&
span.mTimestampMs < cue.mEndTimeMs &&
!mTimestamps.contains(span.mTimestampMs)) {
mTimestamps.add(span.mTimestampMs);
}
}
}
if (mTimestamps.size() > 0) {
cue.mInnerTimesMs = new long[mTimestamps.size()];
for (int ix=0; ix < mTimestamps.size(); ++ix) {
cue.mInnerTimesMs[ix] = mTimestamps.get(ix);
}
mTimestamps.clear();
} else {
cue.mInnerTimesMs = null;
}
cue.mRunID = mCurrentRunID;
}
addCue(cue);
}
@Override
public void onRegionParsed(TextTrackRegion region) {
synchronized(mParser) {
mRegions.put(region.mId, region);
}
}
@Override
public void updateView(Vector<SubtitleTrack.Cue> activeCues) {
if (!mVisible) {
// don't keep the state if we are not visible
return;
}
if (DEBUG && mTimeProvider != null) {
try {
Log.d(TAG, "at " +
(mTimeProvider.getCurrentTimeUs(false, true) / 1000) +
" ms the active cues are:");
} catch (IllegalStateException e) {
Log.d(TAG, "at (illegal state) the active cues are:");
}
}
if (mRenderingWidget != null) {
mRenderingWidget.setActiveCues(activeCues);
}
}
}
/**
* Widget capable of rendering WebVTT captions.
*
* @hide
*/
class WebVttRenderingWidget extends ViewGroup implements SubtitleTrack.RenderingWidget {
private static final boolean DEBUG = false;
private static final CaptionStyle DEFAULT_CAPTION_STYLE = CaptionStyle.DEFAULT;
private static final int DEBUG_REGION_BACKGROUND = 0x800000FF;
private static final int DEBUG_CUE_BACKGROUND = 0x80FF0000;
/** WebVtt specifies line height as 5.3% of the viewport height. */
private static final float LINE_HEIGHT_RATIO = 0.0533f;
/** Map of active regions, used to determine enter/exit. */
private final ArrayMap<TextTrackRegion, RegionLayout> mRegionBoxes =
new ArrayMap<TextTrackRegion, RegionLayout>();
/** Map of active cues, used to determine enter/exit. */
private final ArrayMap<TextTrackCue, CueLayout> mCueBoxes =
new ArrayMap<TextTrackCue, CueLayout>();
/** Captioning manager, used to obtain and track caption properties. */
private final CaptioningManager mManager;
/** Callback for rendering changes. */
private OnChangedListener mListener;
/** Current caption style. */
private CaptionStyle mCaptionStyle;
/** Current font size, computed from font scaling factor and height. */
private float mFontSize;
/** Whether a caption style change listener is registered. */
private boolean mHasChangeListener;
public WebVttRenderingWidget(Context context) {
this(context, null);
}
public WebVttRenderingWidget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WebVttRenderingWidget(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public WebVttRenderingWidget(
Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
// Cannot render text over video when layer type is hardware.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mManager = (CaptioningManager) context.getSystemService(Context.CAPTIONING_SERVICE);
mCaptionStyle = mManager.getUserStyle();
mFontSize = mManager.getFontScale() * getHeight() * LINE_HEIGHT_RATIO;
}
@Override
public void setSize(int width, int height) {
final int widthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int heightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
measure(widthSpec, heightSpec);
layout(0, 0, width, height);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
manageChangeListener();
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
manageChangeListener();
}
@Override
public void setOnChangedListener(OnChangedListener listener) {
mListener = listener;
}
@Override
public void setVisible(boolean visible) {
if (visible) {
setVisibility(View.VISIBLE);
} else {
setVisibility(View.GONE);
}
manageChangeListener();
}
/**
* Manages whether this renderer is listening for caption style changes.
*/
private void manageChangeListener() {
final boolean needsListener = isAttachedToWindow() && getVisibility() == View.VISIBLE;
if (mHasChangeListener != needsListener) {
mHasChangeListener = needsListener;
if (needsListener) {
mManager.addCaptioningChangeListener(mCaptioningListener);
final CaptionStyle captionStyle = mManager.getUserStyle();
final float fontSize = mManager.getFontScale() * getHeight() * LINE_HEIGHT_RATIO;
setCaptionStyle(captionStyle, fontSize);
} else {
mManager.removeCaptioningChangeListener(mCaptioningListener);
}
}
}
public void setActiveCues(Vector<SubtitleTrack.Cue> activeCues) {
final Context context = getContext();
final CaptionStyle captionStyle = mCaptionStyle;
final float fontSize = mFontSize;
prepForPrune();
// Ensure we have all necessary cue and region boxes.
final int count = activeCues.size();
for (int i = 0; i < count; i++) {
final TextTrackCue cue = (TextTrackCue) activeCues.get(i);
final TextTrackRegion region = cue.mRegion;
if (region != null) {
RegionLayout regionBox = mRegionBoxes.get(region);
if (regionBox == null) {
regionBox = new RegionLayout(context, region, captionStyle, fontSize);
mRegionBoxes.put(region, regionBox);
addView(regionBox, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
regionBox.put(cue);
} else {
CueLayout cueBox = mCueBoxes.get(cue);
if (cueBox == null) {
cueBox = new CueLayout(context, cue, captionStyle, fontSize);
mCueBoxes.put(cue, cueBox);
addView(cueBox, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
cueBox.update();
cueBox.setOrder(i);
}
}
prune();
// Force measurement and layout.
final int width = getWidth();
final int height = getHeight();
setSize(width, height);
if (mListener != null) {
mListener.onChanged(this);
}
}
private void setCaptionStyle(CaptionStyle captionStyle, float fontSize) {
captionStyle = DEFAULT_CAPTION_STYLE.applyStyle(captionStyle);
mCaptionStyle = captionStyle;
mFontSize = fontSize;
final int cueCount = mCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mCueBoxes.valueAt(i);
cueBox.setCaptionStyle(captionStyle, fontSize);
}
final int regionCount = mRegionBoxes.size();
for (int i = 0; i < regionCount; i++) {
final RegionLayout regionBox = mRegionBoxes.valueAt(i);
regionBox.setCaptionStyle(captionStyle, fontSize);
}
}
/**
* Remove inactive cues and regions.
*/
private void prune() {
int regionCount = mRegionBoxes.size();
for (int i = 0; i < regionCount; i++) {
final RegionLayout regionBox = mRegionBoxes.valueAt(i);
if (regionBox.prune()) {
removeView(regionBox);
mRegionBoxes.removeAt(i);
regionCount--;
i--;
}
}
int cueCount = mCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mCueBoxes.valueAt(i);
if (!cueBox.isActive()) {
removeView(cueBox);
mCueBoxes.removeAt(i);
cueCount--;
i--;
}
}
}
/**
* Reset active cues and regions.
*/
private void prepForPrune() {
final int regionCount = mRegionBoxes.size();
for (int i = 0; i < regionCount; i++) {
final RegionLayout regionBox = mRegionBoxes.valueAt(i);
regionBox.prepForPrune();
}
final int cueCount = mCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mCueBoxes.valueAt(i);
cueBox.prepForPrune();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int regionCount = mRegionBoxes.size();
for (int i = 0; i < regionCount; i++) {
final RegionLayout regionBox = mRegionBoxes.valueAt(i);
regionBox.measureForParent(widthMeasureSpec, heightMeasureSpec);
}
final int cueCount = mCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mCueBoxes.valueAt(i);
cueBox.measureForParent(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int viewportWidth = r - l;
final int viewportHeight = b - t;
setCaptionStyle(mCaptionStyle,
mManager.getFontScale() * LINE_HEIGHT_RATIO * viewportHeight);
final int regionCount = mRegionBoxes.size();
for (int i = 0; i < regionCount; i++) {
final RegionLayout regionBox = mRegionBoxes.valueAt(i);
layoutRegion(viewportWidth, viewportHeight, regionBox);
}
final int cueCount = mCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mCueBoxes.valueAt(i);
layoutCue(viewportWidth, viewportHeight, cueBox);
}
}
/**
* Lays out a region within the viewport. The region handles layout for
* contained cues.
*/
private void layoutRegion(
int viewportWidth, int viewportHeight,
RegionLayout regionBox) {
final TextTrackRegion region = regionBox.getRegion();
final int regionHeight = regionBox.getMeasuredHeight();
final int regionWidth = regionBox.getMeasuredWidth();
// TODO: Account for region anchor point.
final float x = region.mViewportAnchorPointX;
final float y = region.mViewportAnchorPointY;
final int left = (int) (x * (viewportWidth - regionWidth) / 100);
final int top = (int) (y * (viewportHeight - regionHeight) / 100);
regionBox.layout(left, top, left + regionWidth, top + regionHeight);
}
/**
* Lays out a cue within the viewport.
*/
private void layoutCue(
int viewportWidth, int viewportHeight, CueLayout cueBox) {
final TextTrackCue cue = cueBox.getCue();
final int direction = getLayoutDirection();
final int absAlignment = resolveCueAlignment(direction, cue.mAlignment);
final boolean cueSnapToLines = cue.mSnapToLines;
int size = 100 * cueBox.getMeasuredWidth() / viewportWidth;
// Determine raw x-position.
int xPosition;
switch (absAlignment) {
case TextTrackCue.ALIGNMENT_LEFT:
xPosition = cue.mTextPosition;
break;
case TextTrackCue.ALIGNMENT_RIGHT:
xPosition = cue.mTextPosition - size;
break;
case TextTrackCue.ALIGNMENT_MIDDLE:
default:
xPosition = cue.mTextPosition - size / 2;
break;
}
// Adjust x-position for layout.
if (direction == LAYOUT_DIRECTION_RTL) {
xPosition = 100 - xPosition;
}
// If the text track cue snap-to-lines flag is set, adjust
// x-position and size for padding. This is equivalent to placing the
// cue within the title-safe area.
if (cueSnapToLines) {
final int paddingLeft = 100 * getPaddingLeft() / viewportWidth;
final int paddingRight = 100 * getPaddingRight() / viewportWidth;
if (xPosition < paddingLeft && xPosition + size > paddingLeft) {
xPosition += paddingLeft;
size -= paddingLeft;
}
final float rightEdge = 100 - paddingRight;
if (xPosition < rightEdge && xPosition + size > rightEdge) {
size -= paddingRight;
}
}
// Compute absolute left position and width.
final int left = xPosition * viewportWidth / 100;
final int width = size * viewportWidth / 100;
// Determine initial y-position.
final int yPosition = calculateLinePosition(cueBox);
// Compute absolute final top position and height.
final int height = cueBox.getMeasuredHeight();
final int top;
if (yPosition < 0) {
// TODO: This needs to use the actual height of prior boxes.
top = viewportHeight + yPosition * height;
} else {
top = yPosition * (viewportHeight - height) / 100;
}
// Layout cue in final position.
cueBox.layout(left, top, left + width, top + height);
}
/**
* Calculates the line position for a cue.
* <p>
* If the resulting position is negative, it represents a bottom-aligned
* position relative to the number of active cues. Otherwise, it represents
* a percentage [0-100] of the viewport height.
*/
private int calculateLinePosition(CueLayout cueBox) {
final TextTrackCue cue = cueBox.getCue();
final Integer linePosition = cue.mLinePosition;
final boolean snapToLines = cue.mSnapToLines;
final boolean autoPosition = (linePosition == null);
if (!snapToLines && !autoPosition && (linePosition < 0 || linePosition > 100)) {
// Invalid line position defaults to 100.
return 100;
} else if (!autoPosition) {
// Use the valid, supplied line position.
return linePosition;
} else if (!snapToLines) {
// Automatic, non-snapped line position defaults to 100.
return 100;
} else {
// Automatic snapped line position uses active cue order.
return -(cueBox.mOrder + 1);
}
}
/**
* Resolves cue alignment according to the specified layout direction.
*/
private static int resolveCueAlignment(int layoutDirection, int alignment) {
switch (alignment) {
case TextTrackCue.ALIGNMENT_START:
return layoutDirection == View.LAYOUT_DIRECTION_LTR ?
TextTrackCue.ALIGNMENT_LEFT : TextTrackCue.ALIGNMENT_RIGHT;
case TextTrackCue.ALIGNMENT_END:
return layoutDirection == View.LAYOUT_DIRECTION_LTR ?
TextTrackCue.ALIGNMENT_RIGHT : TextTrackCue.ALIGNMENT_LEFT;
}
return alignment;
}
private final CaptioningChangeListener mCaptioningListener = new CaptioningChangeListener() {
@Override
public void onFontScaleChanged(float fontScale) {
final float fontSize = fontScale * getHeight() * LINE_HEIGHT_RATIO;
setCaptionStyle(mCaptionStyle, fontSize);
}
@Override
public void onUserStyleChanged(CaptionStyle userStyle) {
setCaptionStyle(userStyle, mFontSize);
}
};
/**
* A text track region represents a portion of the video viewport and
* provides a rendering area for text track cues.
*/
private static class RegionLayout extends LinearLayout {
private final ArrayList<CueLayout> mRegionCueBoxes = new ArrayList<CueLayout>();
private final TextTrackRegion mRegion;
private CaptionStyle mCaptionStyle;
private float mFontSize;
public RegionLayout(Context context, TextTrackRegion region, CaptionStyle captionStyle,
float fontSize) {
super(context);
mRegion = region;
mCaptionStyle = captionStyle;
mFontSize = fontSize;
// TODO: Add support for vertical text
setOrientation(VERTICAL);
if (DEBUG) {
setBackgroundColor(DEBUG_REGION_BACKGROUND);
} else {
setBackgroundColor(captionStyle.windowColor);
}
}
public void setCaptionStyle(CaptionStyle captionStyle, float fontSize) {
mCaptionStyle = captionStyle;
mFontSize = fontSize;
final int cueCount = mRegionCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mRegionCueBoxes.get(i);
cueBox.setCaptionStyle(captionStyle, fontSize);
}
setBackgroundColor(captionStyle.windowColor);
}
/**
* Performs the parent's measurement responsibilities, then
* automatically performs its own measurement.
*/
public void measureForParent(int widthMeasureSpec, int heightMeasureSpec) {
final TextTrackRegion region = mRegion;
final int specWidth = MeasureSpec.getSize(widthMeasureSpec);
final int specHeight = MeasureSpec.getSize(heightMeasureSpec);
final int width = (int) region.mWidth;
// Determine the absolute maximum region size as the requested size.
final int size = width * specWidth / 100;
widthMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.AT_MOST);
measure(widthMeasureSpec, heightMeasureSpec);
}
/**
* Prepares this region for pruning by setting all tracks as inactive.
* <p>
* Tracks that are added or updated using {@link #put(TextTrackCue)}
* after this calling this method will be marked as active.
*/
public void prepForPrune() {
final int cueCount = mRegionCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mRegionCueBoxes.get(i);
cueBox.prepForPrune();
}
}
/**
* Adds a {@link TextTrackCue} to this region. If the track had already
* been added, updates its active state.
*
* @param cue
*/
public void put(TextTrackCue cue) {
final int cueCount = mRegionCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mRegionCueBoxes.get(i);
if (cueBox.getCue() == cue) {
cueBox.update();
return;
}
}
final CueLayout cueBox = new CueLayout(getContext(), cue, mCaptionStyle, mFontSize);
mRegionCueBoxes.add(cueBox);
addView(cueBox, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (getChildCount() > mRegion.mLines) {
removeViewAt(0);
}
}
/**
* Remove all inactive tracks from this region.
*
* @return true if this region is empty and should be pruned
*/
public boolean prune() {
int cueCount = mRegionCueBoxes.size();
for (int i = 0; i < cueCount; i++) {
final CueLayout cueBox = mRegionCueBoxes.get(i);
if (!cueBox.isActive()) {
mRegionCueBoxes.remove(i);
removeView(cueBox);
cueCount--;
i--;
}
}
return mRegionCueBoxes.isEmpty();
}
/**
* @return the region data backing this layout
*/
public TextTrackRegion getRegion() {
return mRegion;
}
}
/**
* A text track cue is the unit of time-sensitive data in a text track,
* corresponding for instance for subtitles and captions to the text that
* appears at a particular time and disappears at another time.
* <p>
* A single cue may contain multiple {@link SpanLayout}s, each representing a
* single line of text.
*/
private static class CueLayout extends LinearLayout {
public final TextTrackCue mCue;
private CaptionStyle mCaptionStyle;
private float mFontSize;
private boolean mActive;
private int mOrder;
public CueLayout(
Context context, TextTrackCue cue, CaptionStyle captionStyle, float fontSize) {
super(context);
mCue = cue;
mCaptionStyle = captionStyle;
mFontSize = fontSize;
// TODO: Add support for vertical text.
final boolean horizontal = cue.mWritingDirection
== TextTrackCue.WRITING_DIRECTION_HORIZONTAL;
setOrientation(horizontal ? VERTICAL : HORIZONTAL);
switch (cue.mAlignment) {
case TextTrackCue.ALIGNMENT_END:
setGravity(Gravity.END);
break;
case TextTrackCue.ALIGNMENT_LEFT:
setGravity(Gravity.LEFT);
break;
case TextTrackCue.ALIGNMENT_MIDDLE:
setGravity(horizontal
? Gravity.CENTER_HORIZONTAL : Gravity.CENTER_VERTICAL);
break;
case TextTrackCue.ALIGNMENT_RIGHT:
setGravity(Gravity.RIGHT);
break;
case TextTrackCue.ALIGNMENT_START:
setGravity(Gravity.START);
break;
}
if (DEBUG) {
setBackgroundColor(DEBUG_CUE_BACKGROUND);
}
update();
}
public void setCaptionStyle(CaptionStyle style, float fontSize) {
mCaptionStyle = style;
mFontSize = fontSize;
final int n = getChildCount();
for (int i = 0; i < n; i++) {
final View child = getChildAt(i);
if (child instanceof SpanLayout) {
((SpanLayout) child).setCaptionStyle(style, fontSize);
}
}
}
public void prepForPrune() {
mActive = false;
}
public void update() {
mActive = true;
removeAllViews();
final int cueAlignment = resolveCueAlignment(getLayoutDirection(), mCue.mAlignment);
final Alignment alignment;
switch (cueAlignment) {
case TextTrackCue.ALIGNMENT_LEFT:
alignment = Alignment.ALIGN_LEFT;
break;
case TextTrackCue.ALIGNMENT_RIGHT:
alignment = Alignment.ALIGN_RIGHT;
break;
case TextTrackCue.ALIGNMENT_MIDDLE:
default:
alignment = Alignment.ALIGN_CENTER;
}
final CaptionStyle captionStyle = mCaptionStyle;
final float fontSize = mFontSize;
final TextTrackCueSpan[][] lines = mCue.mLines;
final int lineCount = lines.length;
for (int i = 0; i < lineCount; i++) {
final SpanLayout lineBox = new SpanLayout(getContext(), lines[i]);
lineBox.setAlignment(alignment);
lineBox.setCaptionStyle(captionStyle, fontSize);
addView(lineBox, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* Performs the parent's measurement responsibilities, then
* automatically performs its own measurement.
*/
public void measureForParent(int widthMeasureSpec, int heightMeasureSpec) {
final TextTrackCue cue = mCue;
final int specWidth = MeasureSpec.getSize(widthMeasureSpec);
final int specHeight = MeasureSpec.getSize(heightMeasureSpec);
final int direction = getLayoutDirection();
final int absAlignment = resolveCueAlignment(direction, cue.mAlignment);
// Determine the maximum size of cue based on its starting position
// and the direction in which it grows.
final int maximumSize;
switch (absAlignment) {
case TextTrackCue.ALIGNMENT_LEFT:
maximumSize = 100 - cue.mTextPosition;
break;
case TextTrackCue.ALIGNMENT_RIGHT:
maximumSize = cue.mTextPosition;
break;
case TextTrackCue.ALIGNMENT_MIDDLE:
if (cue.mTextPosition <= 50) {
maximumSize = cue.mTextPosition * 2;
} else {
maximumSize = (100 - cue.mTextPosition) * 2;
}
break;
default:
maximumSize = 0;
}
// Determine absolute maximum cue size as the smaller of the
// requested size and the maximum theoretical size.
final int size = Math.min(cue.mSize, maximumSize) * specWidth / 100;
widthMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.AT_MOST);
measure(widthMeasureSpec, heightMeasureSpec);
}
/**
* Sets the order of this cue in the list of active cues.
*
* @param order the order of this cue in the list of active cues
*/
public void setOrder(int order) {
mOrder = order;
}
/**
* @return whether this cue is marked as active
*/
public boolean isActive() {
return mActive;
}
/**
* @return the cue data backing this layout
*/
public TextTrackCue getCue() {
return mCue;
}
}
/**
* A text track line represents a single line of text within a cue.
* <p>
* A single line may contain multiple spans, each representing a section of
* text that may be enabled or disabled at a particular time.
*/
private static class SpanLayout extends SubtitleView {
private final SpannableStringBuilder mBuilder = new SpannableStringBuilder();
private final TextTrackCueSpan[] mSpans;
public SpanLayout(Context context, TextTrackCueSpan[] spans) {
super(context);
mSpans = spans;
update();
}
public void update() {
final SpannableStringBuilder builder = mBuilder;
final TextTrackCueSpan[] spans = mSpans;
builder.clear();
builder.clearSpans();
final int spanCount = spans.length;
for (int i = 0; i < spanCount; i++) {
final TextTrackCueSpan span = spans[i];
if (span.mEnabled) {
builder.append(spans[i].mText);
}
}
setText(builder);
}
public void setCaptionStyle(CaptionStyle captionStyle, float fontSize) {
setBackgroundColor(captionStyle.backgroundColor);
setForegroundColor(captionStyle.foregroundColor);
setEdgeColor(captionStyle.edgeColor);
setEdgeType(captionStyle.edgeType);
setTypeface(captionStyle.getTypeface());
setTextSize(fontSize);
}
}
}
|