Compare commits

..
25415 changed files with 1533391 additions and 517612 deletions

No files matched your search

+22
View File
@@ -187,6 +187,28 @@ devtools/client/framework/test/code_ugly*
devtools/server/tests/unit/babel_and_browserify_script_with_source_map.js
devtools/server/tests/unit/setBreakpoint*
# mobile/android/ exclusions
mobile/android/tests/
# Uses `#filter substitution`
mobile/android/b2gdroid/app/b2gdroid.js
mobile/android/app/mobile.js
mobile/android/chrome/content/healthreport-prefs.js
# Uses `#expand`
mobile/android/chrome/content/about.js
# Not much JS to lint and non-standard at that
mobile/android/installer/
mobile/android/locales/
# Non-standard `(catch ex if ...)`
mobile/android/chrome/content/browser.js
mobile/android/components/Snippets.js
# Bug 1178739: Ignore this file as a quick fix for "Illegal yield expression"
mobile/android/modules/HomeProvider.jsm
# services/ exclusions
# Uses `#filter substitution`
+3
View File
@@ -91,6 +91,9 @@ GPATH
# Git clone directory for updating web-platform-tests
testing/web-platform/sync/
# Android Gradle artifacts.
mobile/android/gradle/.gradle
# XCode project cruft
embedding/ios/GoannaEmbed/GoannaEmbed.xcodeproj/project.xcworkspace/xcuserdata
embedding/ios/GoannaEmbed/GoannaEmbed.xcodeproj/xcuserdata
+1 -2
View File
@@ -22,5 +22,4 @@
# changes to stick? As of bug 928195, this shouldn't be necessary! Please
# don't change CLOBBER for WebIDL changes any more.
Clobber master merge
Clobber for CSS flow-root implementation
+26 -5
View File
@@ -64,7 +64,9 @@ this.AccessFu = { // jshint ignore:line
if (this._enabled) {
this._disable();
}
if (Utils.win.navigator.mozSettings) {
if (Utils.MozBuildApp === 'mobile/android') {
Services.obs.removeObserver(this, 'Accessibility:Settings');
} else if (Utils.win.navigator.mozSettings) {
Utils.win.navigator.mozSettings.removeObserver(
SCREENREADER_SETTING, this.handleEvent);
}
@@ -583,7 +585,11 @@ var Output = {
get androidBridge() {
delete this.androidBridge;
this.androidBridge = null;
if (Utils.MozBuildApp === 'mobile/android') {
this.androidBridge = Services.androidBridge;
} else {
this.androidBridge = null;
}
return this.androidBridge;
},
@@ -809,6 +815,12 @@ var Input = {
target.blur();
}
}
if (Utils.MozBuildApp == 'mobile/android') {
// Return focus to native Android browser chrome.
Services.androidBridge.handleGeckoMessage(
{ type: 'ToggleChrome:Focus' });
}
break;
case aEvent.DOM_VK_RETURN:
if (this.editState.editing) {
@@ -825,9 +837,18 @@ var Input = {
},
moveToPoint: function moveToPoint(aRule, aX, aY) {
let win = Utils.win;
Utils.winUtils.sendMouseEvent('mousemove',
aX - win.mozInnerScreenX, aY - win.mozInnerScreenY, 0, 0, 0);
// XXX: Bug 1013408 - There is no alignment between the chrome window's
// viewport size and the content viewport size in Android. This makes
// sending mouse events beyond its bounds impossible.
if (Utils.MozBuildApp === 'mobile/android') {
let mm = Utils.getMessageManager(Utils.CurrentBrowser);
mm.sendAsyncMessage('AccessFu:MoveToPoint',
{rule: aRule, x: aX, y: aY, origin: 'top'});
} else {
let win = Utils.win;
Utils.winUtils.sendMouseEvent('mousemove',
aX - win.mozInnerScreenX, aY - win.mozInnerScreenY, 0, 0, 0);
}
},
moveCursor: function moveCursor(aAction, aRule, aInputType, aAdjustRange) {
+3 -1
View File
@@ -76,6 +76,8 @@ const EDGE = 0.1;
const TIMEOUT_MULTIPLIER = 1;
// A single pointer down/up sequence periodically precedes the tripple swipe
// gesture on Android. This delay acounts for that.
const IS_ANDROID = Utils.MozBuildApp === 'mobile/android' &&
Utils.AndroidSdkVersion >= 14;
/**
* A point object containing distance travelled data.
@@ -204,7 +206,7 @@ this.GestureTracker = { // jshint ignore:line
if (aDetail.type !== 'pointerdown') {
return;
}
let GestureConstructor = aGesture || Tap;
let GestureConstructor = aGesture || (IS_ANDROID ? DoubleTap : Tap);
this._create(GestureConstructor);
this._update(aDetail, aTimeStamp);
},
+1
View File
@@ -680,6 +680,7 @@ this.Presentation = { // jshint ignore:line
get presenters() {
delete this.presenters;
let presenterMap = {
'mobile/android': [VisualPresenter, AndroidPresenter],
'b2g': [VisualPresenter, B2GPresenter],
'browser': [VisualPresenter, B2GPresenter, AndroidPresenter]
};
+3 -1
View File
@@ -33,7 +33,9 @@ this.Utils = { // jshint ignore:line
_buildAppMap: {
'{3c2e2abc-06d4-11e1-ac3b-374f68613e61}': 'b2g',
'{d1bfe7d9-c01e-4237-998b-7b5f960a4314}': 'graphene',
'{ec8030f7-c20a-464f-9b0e-13a3a9e97384}': 'browser'
'{ec8030f7-c20a-464f-9b0e-13a3a9e97384}': 'browser',
'{aa3c5121-dab2-40e2-81ca-7ea25febc110}': 'mobile/android',
'{a23983c0-fd0e-11dc-95ff-0800200c9a66}': 'mobile/xul'
},
init: function Utils_init(aWindow) {
@@ -67,7 +67,7 @@
* Change scrollbar styles from hidden to auto. That makes us to create an
* accessible for scroll area.
*/
function changeScrollStyles(aContainerID, aScrollAreaID)
function changeScrollbarStyles(aContainerID, aScrollAreaID)
{
this.container = getAccessible(aContainerID);
this.scrollAreaNode = getNode(aScrollAreaID);
@@ -77,7 +77,7 @@
new invokerChecker(EVENT_REORDER, this.container)
];
this.invoke = function changeScrollStyles_invoke()
this.invoke = function changeScrollbarStyles_invoke()
{
var accTree =
{ SECTION: [] };
@@ -86,7 +86,7 @@
this.scrollAreaNode.style.overflow = "auto";
}
this.finalCheck = function changeScrollStyles_finalCheck()
this.finalCheck = function changeScrollbarStyles_finalCheck()
{
var accTree =
{ SECTION: [ // container
@@ -95,7 +95,7 @@
testAccessibleTree(this.container, accTree);
}
this.getID = function changeScrollStyles_getID()
this.getID = function changeScrollbarStyles_getID()
{
return "change scrollbar styles " + prettyName(aScrollAreaID);
}
@@ -114,7 +114,7 @@
gQueue = new eventQueue();
gQueue.push(new changeScrollRange("container", "scrollarea"));
gQueue.push(new changeScrollStyles("container2", "scrollarea2"));
gQueue.push(new changeScrollbarStyles("container2", "scrollarea2"));
gQueue.invoke(); // Will call SimpleTest.finish();
}
+6
View File
@@ -210,6 +210,12 @@ fi
AC_DEFUN([MOZ_ANDROID_INSTALL_TRACKING],
[
if test -n "$MOZ_INSTALL_TRACKING"; then
AC_SUBST(MOZ_INSTALL_TRACKING)
MOZ_ANDROID_AAR(play-services-ads, $ANDROID_GOOGLE_PLAY_SERVICES_VERSION, google, com/google/android/gms)
MOZ_ANDROID_AAR(play-services-basement, $ANDROID_GOOGLE_PLAY_SERVICES_VERSION, google, com/google/android/gms)
fi
])
dnl Configure an Android SDK.
-5
View File
@@ -63,11 +63,6 @@ def GeckoBinary(linkage='dependent', msvcrt='dynamic', mozglue=None):
LDFLAGS += ['-rdynamic']
if CONFIG['MOZ_MEMORY']:
USE_LIBS += ['memory']
if CONFIG['OS_ARCH'] == 'FreeBSD':
# Make sure this function is linked in, so that it is
# executed at executable load (it has the 'constructor'
# flag).
LDFLAGS += ['-u', 'jemalloc_FreeBSD_init']
elif mozglue == 'library':
LIBRARY_DEFINES['MOZ_HAS_MOZGLUE'] = True
if not CONFIG['MOZ_GLUE_IN_PROGRAM']:
+4
View File
@@ -90,6 +90,9 @@ SEARCH_PATHS = [
'testing/mozbase/manifestparser',
'testing/taskcluster',
'testing/tools/autotry',
'testing/web-platform',
'testing/web-platform/harness',
'testing/web-platform/tests/tools/wptserve',
'testing/xpcshell',
'xpcom/idl-parser',
]
@@ -118,6 +121,7 @@ MACH_MODULES = [
'testing/mochitest/mach_commands.py',
'testing/mozharness/mach_commands.py',
'testing/talos/mach_commands.py',
'testing/web-platform/mach_commands.py',
'testing/xpcshell/mach_commands.py',
'tools/docs/mach_commands.py',
'tools/lint/mach_commands.py',
+4
View File
@@ -36,6 +36,10 @@ def keyfile(desc, help=None, callback=lambda x: x):
def simple_keyfile(desc):
value = keyfile(desc)
set_config('MOZ_%s_KEY' % desc.upper().replace(' ', '_'), value)
# Only really required for MOZ_ADJUST_SDK_KEY currently still used in
# old-configure.
add_old_configure_assignment('MOZ_%s_KEY' % desc.upper().replace(' ', '_'),
value)
@template
-1
View File
@@ -226,7 +226,6 @@ def old_configure_options(*options):
'--enable-safe-browsing',
'--enable-sandbox',
'--enable-security-sqlstore',
'--enable-shared-media',
'--enable-signmar',
'--enable-simulator',
'--enable-small-chunk-size',
-2
View File
@@ -79,7 +79,6 @@ included_inclnames_to_ignore = set([
'prtypes.h', # NSPR
'selfhosted.out.h', # generated in $OBJDIR
'shellmoduleloader.out.h', # generated in $OBJDIR
'unicode/plurrule.h', # ICU
'unicode/timezone.h', # ICU
'unicode/ucal.h', # ICU
'unicode/uclean.h', # ICU
@@ -91,7 +90,6 @@ included_inclnames_to_ignore = set([
'unicode/unorm.h', # ICU
'unicode/unum.h', # ICU
'unicode/unumsys.h', # ICU
'unicode/upluralrules.h', # ICU
'unicode/ustring.h', # ICU
'unicode/utypes.h', # ICU
'vtune/VTuneWrapper.h' # VTune
Binary file not shown.
-7
View File
@@ -174,13 +174,6 @@ DEFAULT_GMAKE_FLAGS += NSS_SSL_ENABLE_ZLIB=
# Disable building of the test programs in security/nss/lib/zlib
DEFAULT_GMAKE_FLAGS += PROGRAMS=
# Disable AVX2 for poly1305
DEFAULT_GMAKE_FLAGS += NSS_DISABLE_AVX2=1
# Disable obsolete ciphers
DEFAULT_GMAKE_FLAGS += NSS_DISABLE_DEPRECATED_SEED=1
DEFAULT_GMAKE_FLAGS += NSS_DISABLE_DEPRECATED_RC2=1
# Disable creating .chk files. They will be generated from packager.mk
# When bug 681624 lands, we can replace CHECKLOC= with SKIP_SHLIBSIGN=1
DEFAULT_GMAKE_FLAGS += CHECKLOC=
-8
View File
@@ -32,14 +32,6 @@
# define moz_dont_include_mozalloc_for_cstdlib
#endif
#ifndef moz_dont_include_mozalloc_for_type_traits
# define moz_dont_include_mozalloc_for_type_traits
#endif
#ifndef moz_dont_include_mozalloc_for_limits
# define moz_dont_include_mozalloc_for_limits
#endif
// Include mozalloc after the STL header and all other headers it includes
// have been preprocessed.
#if !defined(MOZ_INCLUDE_MOZALLOC_H) && \
+1 -1
View File
@@ -10,4 +10,4 @@
# hardcoded milestones in the tree from these two files.
#--------------------------------------------------------
4.8.0
4.7.0
-3
View File
@@ -28,9 +28,6 @@ if CONFIG['HOST_OS_ARCH'] != 'WINNT':
# while the program here is in C.
HostProgram('nsinstall_real', c_only=True)
if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
DEFINES['GKMEDIAS_SHARED_LIBRARY'] = True
PYTHON_UNIT_TESTS += [
'tests/test_mozbuild_reading.py',
'tests/unit-expandlibs.py',
-16
View File
@@ -1287,22 +1287,6 @@ QtSparql/qsparqlresult.h
#if MOZ_TREE_PIXMAN!=1
pixman.h
#endif
#ifdef GKMEDIAS_SHARED_LIBRARY
vpx/vpx_codec.h
vpx/vpx_decoder.h
vpx/vpx_encoder.h
vpx/vp8cx.h
vpx/vp8dx.h
vpx_mem/vpx_mem.h
vorbis/codec.h
theora/theoradec.h
tremor/ivorbiscodec.h
speex/speex_resampler.h
ogg/ogg.h
ogg/os_types.h
nestegg/nestegg.h
cubeb/cubeb.h
#endif
gst/gst.h
gst/app/gstappsink.h
gst/app/gstappsrc.h
+1 -1
View File
@@ -94,7 +94,7 @@ exports.menuitems = [
},
key: {
id: "browserToolbox",
modifiers: "accel,alt,shift",
modifiers: isMac ? "accel,alt" : "accel,shift",
keytext: true
}
},
@@ -3038,7 +3038,6 @@ exports.CSS_PROPERTIES = {
"scroll-snap-points-y",
"scroll-snap-type-x",
"scroll-snap-type-y",
"scrollbar-width",
"shape-outside",
"shape-rendering",
"-moz-stack-sizing",
-41
View File
@@ -820,8 +820,6 @@ nsDocShell::nsDocShell()
, mParentCharsetSource(0)
, mJSRunToCompletionDepth(0)
, mTouchEventsOverride(nsIDocShell::TOUCHEVENTS_OVERRIDE_NONE)
, mStateFloodGuardCount(0)
, mStateFloodGuardReported(false)
{
AssertOriginAttributesMatchPrivateBrowsing();
mHistoryID = ++gDocshellIDCounter;
@@ -11835,27 +11833,6 @@ nsDocShell::SetReferrerPolicy(uint32_t aReferrerPolicy)
// nsDocShell: Session History
//*****************************************************************************
bool
nsDocShell::IsStateChangeFlooding()
{
// Issue #1688: Let's copy Firefox's strategy for state flooding here, so
// that our implementations are interoperable.
if (mStateFloodGuardCount > kStateUpdateLimit) {
TimeStamp now = TimeStamp::Now();
if (now - mStateFloodGuardUpdated > TimeDuration::FromSeconds(kRefreshTimeSecs)) {
mStateFloodGuardCount = 0;
mStateFloodGuardUpdated = now;
mStateFloodGuardReported = false;
return false;
}
return true;
}
mStateFloodGuardCount++;
return false;
}
NS_IMETHODIMP
nsDocShell::AddState(JS::Handle<JS::Value> aData, const nsAString& aTitle,
const nsAString& aURL, bool aReplace, JSContext* aCx)
@@ -11920,24 +11897,6 @@ nsDocShell::AddState(JS::Handle<JS::Value> aData, const nsAString& aTitle,
nsCOMPtr<nsIDocument> document = GetDocument();
NS_ENSURE_TRUE(document, NS_ERROR_FAILURE);
// If we're being flooded with state change requests, we should abort early
// from the state change logic.
if (IsStateChangeFlooding()) {
// Report a warning to the console to tell developers why their navigations
// failed.
// Do this only if not yet marked reported so we only report it once per
// flood interval.
if (!mStateFloodGuardReported) {
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
NS_LITERAL_CSTRING("PushState"),
document,
nsContentUtils::eDOM_PROPERTIES,
"PushStateFloodingPrevented");
mStateFloodGuardReported = true;
}
return NS_OK;
}
// Step A: Serialize aData using structured clone.
// https://html.spec.whatwg.org/multipage/history.html#dom-history-pushstate
// step 5.
-13
View File
@@ -1049,15 +1049,6 @@ private:
// as constants in the nsIDocShell.idl file.
uint32_t mTouchEventsOverride;
// Keep track how how many history state changes we're getting, to catch &
// prevent flooding.
int32_t mStateFloodGuardCount;
mozilla::TimeStamp mStateFloodGuardUpdated;
bool mStateFloodGuardReported;
// We have a limit of pushing 50 states to history every 10 seconds.
const int32_t kStateUpdateLimit = 50;
const double kRefreshTimeSecs = 10.0;
// Separate function to do the actual name (i.e. not _top, _self etc.)
// searching for FindItemWithName.
nsresult DoFindItemWithName(const nsAString& aName,
@@ -1073,10 +1064,6 @@ private:
void MaybeNotifyKeywordSearchLoading(const nsString& aProvider,
const nsString& aKeyword);
// Helper method for AddState which checks for excessive calls to PushState or
// ReplaceState.
bool IsStateChangeFlooding();
#ifdef DEBUG
// We're counting the number of |nsDocShells| to help find leaks
static unsigned long gNumberOfDocShells;
+2 -3
View File
@@ -10,7 +10,6 @@
#include "mozilla/dom/AnimationEffectTiming.h"
#include "mozilla/dom/KeyframeEffectBinding.h"
#include "mozilla/KeyframeUtils.h"
#include "mozilla/Preferences.h"
#include "nsContentUtils.h"
#include "nsDOMMutationObserver.h" // For nsAutoAnimationMutationBatch
#include "nsIScriptError.h"
@@ -136,9 +135,9 @@ void
KeyframeEffect::SetIterationComposite(
const IterationCompositeOperation& aIterationComposite)
{
// Ignore iterationComposite if the API is not enabled,
// Ignore iterationComposite if the Web Animations API is not enabled,
// then the default value 'Replace' will be used.
if (!Preferences::GetBool("dom.animations-api.compositing.enabled")) {
if (!AnimationUtils::IsCoreAPIEnabledForCaller()) {
return;
}
+1 -1
View File
@@ -1089,7 +1089,7 @@ KeyframeEffectReadOnly::CanThrottleTransformChanges(nsIFrame& aFrame) const
return true;
}
ScrollStyles ss = scrollable->GetScrollStyles();
ScrollbarStyles ss = scrollable->GetScrollbarStyles();
if (ss.mVertical == NS_STYLE_OVERFLOW_HIDDEN &&
ss.mHorizontal == NS_STYLE_OVERFLOW_HIDDEN &&
scrollable->GetLogicalScrollPosition() == nsPoint(0, 0)) {
+10 -20
View File
@@ -7,7 +7,6 @@
#include "mozilla/AnimationUtils.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/Move.h"
#include "mozilla/Preferences.h"
#include "mozilla/RangedArray.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/StyleAnimationValue.h"
@@ -22,7 +21,6 @@
#include "nsCSSPropertyIDSet.h"
#include "nsCSSProps.h"
#include "nsCSSPseudoElements.h" // For CSSPseudoElementType
#include "nsDocument.h"
#include "nsTArray.h"
#include <algorithm> // For std::stable_sort
@@ -402,7 +400,7 @@ GetKeyframeListFromPropertyIndexedKeyframe(JSContext* aCx,
ErrorResult& aRv);
static bool
HasImplicitKeyframeValues(const nsTArray<Keyframe>& aKeyframes,
RequiresAdditiveAnimation(const nsTArray<Keyframe>& aKeyframes,
nsIDocument* aDocument);
static void
@@ -469,13 +467,11 @@ KeyframeUtils::GetKeyframesFromObject(JSContext* aCx,
// says that if you don't have a keyframe at offset 0 or 1, then you should
// synthesize one using an additive zero value when you go to compose style.
// Until we implement additive animations we just throw if we encounter any
// set of keyframes that would put us in that situation and keyframes aren't
// explicitly force-enabled.
// set of keyframes that would put us in that situation.
if (!nsDocument::AreWebAnimationsImplicitKeyframesEnabled(aCx, nullptr) &&
HasImplicitKeyframeValues(keyframes, aDocument)) {
keyframes.Clear();
if (RequiresAdditiveAnimation(keyframes, aDocument)) {
aRv.Throw(NS_ERROR_DOM_ANIM_MISSING_PROPS_ERR);
keyframes.Clear();
}
return keyframes;
@@ -1334,16 +1330,10 @@ GetKeyframeListFromPropertyIndexedKeyframe(JSContext* aCx,
// No animation values for this property.
continue;
}
if (!Preferences::GetBool("dom.animations-api.implicit-keyframes.enabled") &&
count == 1) {
// We don't support implicit keyframes by preference.
aRv.Throw(NS_ERROR_DOM_ANIM_MISSING_PROPS_ERR);
return;
} else if (count == 1) {
// Implicit keyframes isn't implemented yet and so we can't
// support an animation that goes from the underlying value
// to this specified value.
// Throw an exception until we do support this.
if (count == 1) {
// We don't support additive values and so can't support an
// animation that goes from the underlying value to this
// specified value. Throw an exception until we do support this.
aRv.Throw(NS_ERROR_DOM_ANIM_MISSING_PROPS_ERR);
return;
}
@@ -1384,7 +1374,7 @@ GetKeyframeListFromPropertyIndexedKeyframe(JSContext* aCx,
* try to detect where we have an invalid value at 0%/100%.
*/
static bool
HasImplicitKeyframeValues(const nsTArray<Keyframe>& aKeyframes,
RequiresAdditiveAnimation(const nsTArray<Keyframe>& aKeyframes,
nsIDocument* aDocument)
{
// We are looking to see if that every property referenced in |aKeyframes|
@@ -1395,7 +1385,7 @@ HasImplicitKeyframeValues(const nsTArray<Keyframe>& aKeyframes,
// a document which we might not always have at the point where we want to
// perform this check.
//
// This is only a temporary measure until we implement implicit keyframes.
// This is only a temporary measure until we implement additive animation.
// So as long as this check catches most cases, and we don't do anything
// horrible in one of the cases we can't detect, it should be sufficient.
@@ -1,13 +1,13 @@
pref(dom.animations-api.core.enabled,true) load 1239889-1.html
pref(dom.animations-api.core.enabled,true) load 1244595-1.html
pref(dom.animations-api.core.enabled,true) pref(dom.animations-api.timelines.enabled,true) load 1216842-1.html
pref(dom.animations-api.core.enabled,true) pref(dom.animations-api.timelines.enabled,true) load 1216842-2.html
pref(dom.animations-api.core.enabled,true) pref(dom.animations-api.timelines.enabled,true) load 1216842-3.html
pref(dom.animations-api.core.enabled,true) pref(dom.animations-api.timelines.enabled,true) load 1216842-4.html
pref(dom.animations-api.core.enabled,true) pref(dom.animations-api.timelines.enabled,true) load 1216842-5.html
pref(dom.animations-api.core.enabled,true) pref(dom.animations-api.timelines.enabled,true) load 1216842-6.html
pref(dom.animations-api.core.enabled,true) load 1216842-1.html
pref(dom.animations-api.core.enabled,true) load 1216842-2.html
pref(dom.animations-api.core.enabled,true) load 1216842-3.html
pref(dom.animations-api.core.enabled,true) load 1216842-4.html
pref(dom.animations-api.core.enabled,true) load 1216842-5.html
pref(dom.animations-api.core.enabled,true) load 1216842-6.html
pref(dom.animations-api.core.enabled,true) load 1272475-1.html
pref(dom.animations-api.core.enabled,true) load 1272475-2.html
pref(dom.animations-api.core.enabled,true) load 1278485-1.html
pref(dom.animations-api.core.enabled,true) pref(dom.animations-api.timelines.enabled,true) load 1277272-1.html
pref(dom.animations-api.core.enabled,true) load 1277272-1.html
pref(dom.animations-api.core.enabled,true) load 1290535-1.html
-6
View File
@@ -1,10 +1,4 @@
[DEFAULT]
prefs =
dom.animations-api.compositing.enabled=true
dom.animations-api.core.enabled=true
dom.animations-api.getAnimations.enabled=true
dom.animations-api.implicit-keyframes.enabled=true
dom.animations-api.timelines.enabled=true
# Support files for chrome tests that we want to load over HTTP need
# to go in here, not chrome.ini.
support-files =
+10 -10
View File
@@ -745,7 +745,7 @@ Element::Scroll(const CSSIntPoint& aScroll, const ScrollOptions& aOptions)
if (aOptions.mBehavior == ScrollBehavior::Smooth) {
scrollMode = nsIScrollableFrame::SMOOTH_MSD;
} else if (aOptions.mBehavior == ScrollBehavior::Auto) {
ScrollStyles styles = sf->GetScrollStyles();
ScrollbarStyles styles = sf->GetScrollbarStyles();
if (styles.mScrollBehavior == NS_STYLE_SCROLL_BEHAVIOR_SMOOTH) {
scrollMode = nsIScrollableFrame::SMOOTH_MSD;
}
@@ -834,7 +834,7 @@ Element::SetScrollTop(int32_t aScrollTop)
nsIScrollableFrame* sf = GetScrollFrame();
if (sf) {
nsIScrollableFrame::ScrollMode scrollMode = nsIScrollableFrame::INSTANT;
if (sf->GetScrollStyles().mScrollBehavior == NS_STYLE_SCROLL_BEHAVIOR_SMOOTH) {
if (sf->GetScrollbarStyles().mScrollBehavior == NS_STYLE_SCROLL_BEHAVIOR_SMOOTH) {
scrollMode = nsIScrollableFrame::SMOOTH_MSD;
}
sf->ScrollToCSSPixels(CSSIntPoint(sf->GetScrollPositionCSSPixels().x,
@@ -856,7 +856,7 @@ Element::SetScrollLeft(int32_t aScrollLeft)
nsIScrollableFrame* sf = GetScrollFrame();
if (sf) {
nsIScrollableFrame::ScrollMode scrollMode = nsIScrollableFrame::INSTANT;
if (sf->GetScrollStyles().mScrollBehavior == NS_STYLE_SCROLL_BEHAVIOR_SMOOTH) {
if (sf->GetScrollbarStyles().mScrollBehavior == NS_STYLE_SCROLL_BEHAVIOR_SMOOTH) {
scrollMode = nsIScrollableFrame::SMOOTH_MSD;
}
@@ -1069,7 +1069,7 @@ ShadowRoot*
Element::GetShadowRootByMode() const
{
/**
* 1. Let shadow be context object???s shadow root.
* 1. Let shadow be context object’s shadow root.
* 2. If shadow is null or its mode is "closed", then return null.
*/
ShadowRoot* shadowRoot = GetShadowRoot();
@@ -1088,7 +1088,7 @@ already_AddRefed<ShadowRoot>
Element::AttachShadow(const ShadowRootInit& aInit, ErrorResult& aError)
{
/**
* 1. If context object???s namespace is not the HTML namespace,
* 1. If context object’s namespace is not the HTML namespace,
* then throw a "NotSupportedError" DOMException.
*/
if (!IsHTMLElement()) {
@@ -1097,7 +1097,7 @@ Element::AttachShadow(const ShadowRootInit& aInit, ErrorResult& aError)
}
/**
* 2. If context object???s local name is not
* 2. If context object’s local name is not
* a valid custom element name, "article", "aside", "blockquote",
* "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6",
* "header", "main" "nav", "p", "section", or "span",
@@ -1181,8 +1181,8 @@ Element::AttachShadowInternal(bool aClosed, ErrorResult& aError)
/**
* 4. Let shadow be a new shadow root whose node document is
* context object???s node document, host is context object,
* and mode is init???s mode.
* context object’s node document, host is context object,
* and mode is init’s mode.
*/
RefPtr<ShadowRoot> shadowRoot =
new ShadowRoot(this, aClosed, nodeInfo.forget(), protoBinding);
@@ -1190,7 +1190,7 @@ Element::AttachShadowInternal(bool aClosed, ErrorResult& aError)
shadowRoot->SetIsComposedDocParticipant(IsInComposedDoc());
/**
* 5. Set context object???s shadow root to shadow.
* 5. Set context object’s shadow root to shadow.
*/
SetShadowRoot(shadowRoot);
@@ -1890,7 +1890,7 @@ Element::UnbindFromTree(bool aDeep, bool aNullParent)
nsPresContext* presContext = presShell->GetPresContext();
if (presContext) {
MOZ_ASSERT(this !=
presContext->GetViewportScrollStylesOverrideNode(),
presContext->GetViewportScrollbarStylesOverrideNode(),
"Leaving behind a raw pointer to this node (as having "
"propagated scrollbar styles) - that's dangerous...");
}
+2
View File
@@ -16,6 +16,8 @@ namespace mozilla {
namespace dom {
class Promise;
// Make sure that any change to ScreenOrientationInternal values are
// also made in mobile/android/base/GeckoScreenOrientation.java
typedef uint32_t ScreenOrientationInternal;
static const ScreenOrientationInternal eScreenOrientation_None = 0;
+60 -4
View File
@@ -9140,6 +9140,10 @@ ShouldEscape(nsIContent* aParent)
nsGkAtoms::style, nsGkAtoms::script, nsGkAtoms::xmp,
nsGkAtoms::iframe, nsGkAtoms::noembed, nsGkAtoms::noframes,
nsGkAtoms::plaintext,
// Per the current spec noscript should be escaped in case
// scripts are disabled or if document doesn't have
// browsing context. However the latter seems to be a spec bug
// and Gecko hasn't traditionally done the former.
nsGkAtoms::noscript
};
static mozilla::BloomFilter<12, nsIAtom> sFilter;
@@ -9155,10 +9159,6 @@ ShouldEscape(nsIContent* aParent)
if (sFilter.mightContain(tag)) {
for (uint32_t i = 0; i < ArrayLength(nonEscapingElements); ++i) {
if (tag == nonEscapingElements[i]) {
if (MOZ_UNLIKELY(tag == nsGkAtoms::noscript) &&
MOZ_UNLIKELY(!aParent->OwnerDoc()->IsScriptEnabled())) {
return true;
}
return false;
}
}
@@ -9341,6 +9341,62 @@ nsContentUtils::SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible)
}
}
/* static */ void
nsContentUtils::GetPresentationURL(nsIDocShell* aDocShell, nsAString& aPresentationUrl)
{
MOZ_ASSERT(aDocShell);
// Simulate receiver context for web platform test
if (Preferences::GetBool("dom.presentation.testing.simulate-receiver")) {
nsCOMPtr<nsIDocument> doc;
nsCOMPtr<nsPIDOMWindowOuter> docShellWin =
do_QueryInterface(aDocShell->GetScriptGlobalObject());
if (docShellWin) {
doc = docShellWin->GetExtantDoc();
}
if (NS_WARN_IF(!doc)) {
return;
}
nsCOMPtr<nsIURI> uri = doc->GetDocumentURI();
if (NS_WARN_IF(!uri)) {
return;
}
nsAutoCString uriStr;
uri->GetSpec(uriStr);
aPresentationUrl = NS_ConvertUTF8toUTF16(uriStr);
return;
}
if (XRE_IsContentProcess()) {
nsCOMPtr<nsIDocShellTreeItem> sameTypeRoot;
aDocShell->GetSameTypeRootTreeItem(getter_AddRefs(sameTypeRoot));
nsCOMPtr<nsIDocShellTreeItem> root;
aDocShell->GetRootTreeItem(getter_AddRefs(root));
if (sameTypeRoot.get() == root.get()) {
// presentation URL is stored in TabChild for the top most
// <iframe mozbrowser> in content process.
TabChild* tabChild = TabChild::GetFrom(aDocShell);
if (tabChild) {
aPresentationUrl = tabChild->PresentationURL();
}
return;
}
}
nsCOMPtr<nsILoadContext> loadContext(do_QueryInterface(aDocShell));
nsCOMPtr<nsIDOMElement> topFrameElement;
loadContext->GetTopFrameElement(getter_AddRefs(topFrameElement));
if (!topFrameElement) {
return;
}
topFrameElement->GetAttribute(NS_LITERAL_STRING("mozpresentation"), aPresentationUrl);
}
/* static */ nsIDocShell*
nsContentUtils::GetDocShellForEventTarget(EventTarget* aTarget)
{
+6
View File
@@ -2679,6 +2679,12 @@ public:
static void SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible);
/*
* Return the associated presentation URL of the presented content.
* Will return empty string if the docshell is not in a presented content.
*/
static void GetPresentationURL(nsIDocShell* aDocShell, nsAString& aPresentationUrl);
/*
* Try to find the docshell corresponding to the given event target.
*/
+1 -28
View File
@@ -2923,33 +2923,6 @@ nsDocument::IsWebAnimationsEnabled(JSContext* /*unused*/, JSObject* /*unused*/)
Preferences::GetBool("dom.animations-api.core.enabled");
}
bool
nsDocument::AreWebAnimationsTimelinesEnabled(JSContext* /*unused*/, JSObject* /*unused*/)
{
MOZ_ASSERT(NS_IsMainThread());
return nsContentUtils::IsCallerChrome() ||
Preferences::GetBool("dom.animations-api.timelines.enabled");
}
bool
nsDocument::AreWebAnimationsImplicitKeyframesEnabled(JSContext* /*unused*/, JSObject* /*unused*/)
{
MOZ_ASSERT(NS_IsMainThread());
return nsContentUtils::IsCallerChrome() ||
Preferences::GetBool("dom.animations-api.implicit-keyframes.enabled");
}
bool
nsDocument::IsWebAnimationsGetAnimationsEnabled(JSContext* /*unused*/, JSObject* /*unused*/)
{
MOZ_ASSERT(NS_IsMainThread());
return nsContentUtils::IsCallerChrome() ||
Preferences::GetBool("dom.animations-api.getAnimations.enabled");
}
DocumentTimeline*
nsDocument::Timeline()
{
@@ -10595,7 +10568,7 @@ UpdateViewportScrollbarOverrideForFullscreen(nsIDocument* aDoc)
{
if (nsIPresShell* presShell = aDoc->GetShell()) {
if (nsPresContext* presContext = presShell->GetPresContext()) {
presContext->UpdateViewportScrollStylesOverride();
presContext->UpdateViewportScrollbarStylesOverride();
}
}
}
-4
View File
@@ -433,10 +433,6 @@ public:
static bool IsElementAnimateEnabled(JSContext* aCx, JSObject* aObject);
static bool IsWebAnimationsEnabled(JSContext* aCx, JSObject* aObject);
static bool AreWebAnimationsImplicitKeyframesEnabled(JSContext* aCx, JSObject* aObject);
static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx, JSObject* aObject);
static bool IsWebAnimationsGetAnimationsEnabled(JSContext* aCx, JSObject* aObject);
virtual mozilla::dom::DocumentTimeline* Timeline() override;
virtual void GetAnimations(
nsTArray<RefPtr<mozilla::dom::Animation>>& aAnimations) override;
+15 -1
View File
@@ -3102,6 +3102,14 @@ nsFrameLoader::ApplySandboxFlags(uint32_t sandboxFlags)
// The child can only add restrictions, never remove them.
sandboxFlags |= parentSandboxFlags;
// If this frame is a receiving browsing context, we should add
// sandboxed auxiliary navigation flag to sandboxFlags. See
// https://w3c.github.io/presentation-api/#creating-a-receiving-browsing-context
nsAutoString presentationURL;
nsContentUtils::GetPresentationURL(mDocShell, presentationURL);
if (!presentationURL.IsEmpty()) {
sandboxFlags |= SANDBOXED_AUXILIARY_NAVIGATION;
}
mDocShell->SetSandboxFlags(sandboxFlags);
}
}
@@ -3419,6 +3427,11 @@ nsFrameLoader::GetNewTabContext(MutableTabContext* aTabContext,
rv = PopulateUserContextIdFromAttribute(attrs);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString presentationURLStr;
mOwnerContent->GetAttr(kNameSpaceID_None,
nsGkAtoms::mozpresentation,
presentationURLStr);
nsCOMPtr<nsIDocShell> docShell = mOwnerContent->OwnerDoc()->GetDocShell();
nsCOMPtr<nsILoadContext> parentContext = do_QueryInterface(docShell);
NS_ENSURE_STATE(parentContext);
@@ -3446,7 +3459,8 @@ nsFrameLoader::GetNewTabContext(MutableTabContext* aTabContext,
containingApp,
showAccelerators,
showFocusRings,
attrs);
attrs,
presentationURLStr);
NS_ENSURE_STATE(tabContextUpdated);
return NS_OK;
+1
View File
@@ -1038,6 +1038,7 @@ GK_ATOM(predicate, "predicate")
GK_ATOM(prefix, "prefix")
GK_ATOM(preload, "preload")
GK_ATOM(prerendered, "prerendered")
GK_ATOM(mozpresentation, "mozpresentation")
GK_ATOM(preserve, "preserve")
GK_ATOM(preserveSpace, "preserve-space")
GK_ATOM(preventdefault, "preventdefault")
+3 -3
View File
@@ -8264,7 +8264,7 @@ nsGlobalWindow::ScrollTo(const CSSIntPoint& aScroll,
scroll.y = maxpx;
}
bool smoothScroll = sf->GetScrollStyles().IsSmoothScroll(aOptions.mBehavior);
bool smoothScroll = sf->GetScrollbarStyles().IsSmoothScroll(aOptions.mBehavior);
sf->ScrollToCSSPixels(scroll, smoothScroll
? nsIScrollableFrame::SMOOTH_MSD
@@ -8320,7 +8320,7 @@ nsGlobalWindow::ScrollByLines(int32_t numLines,
// It seems like it would make more sense for ScrollByLines to use
// SMOOTH mode, but tests seem to depend on the synchronous behaviour.
// Perhaps Web content does too.
bool smoothScroll = sf->GetScrollStyles().IsSmoothScroll(aOptions.mBehavior);
bool smoothScroll = sf->GetScrollbarStyles().IsSmoothScroll(aOptions.mBehavior);
sf->ScrollBy(nsIntPoint(0, numLines), nsIScrollableFrame::LINES,
smoothScroll
@@ -8341,7 +8341,7 @@ nsGlobalWindow::ScrollByPages(int32_t numPages,
// It seems like it would make more sense for ScrollByPages to use
// SMOOTH mode, but tests seem to depend on the synchronous behaviour.
// Perhaps Web content does too.
bool smoothScroll = sf->GetScrollStyles().IsSmoothScroll(aOptions.mBehavior);
bool smoothScroll = sf->GetScrollbarStyles().IsSmoothScroll(aOptions.mBehavior);
sf->ScrollBy(nsIntPoint(0, numPages), nsIScrollableFrame::PAGES,
smoothScroll
+2 -3
View File
@@ -299,11 +299,10 @@ nsJSUtils::CompileModule(JSContext* aCx,
NS_ENSURE_TRUE(xpc::Scriptability::Get(aEvaluationGlobal).Allowed(), NS_OK);
bool compileResult = JS::CompileModule(aCx, aCompileOptions, aSrcBuf, aModule);
if (!compileResult) {
if (!JS::CompileModule(aCx, aCompileOptions, aSrcBuf, aModule)) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
+3 -7
View File
@@ -930,7 +930,7 @@ ImageBitmap::CreateInternal(nsIGlobalObject* aGlobal, ImageData& aImageData,
const Maybe<IntRect>& aCropRect, ErrorResult& aRv)
{
// Copy data into SourceSurface.
RootedTypedArray<Uint8ClampedArray> array(RootingCx());
dom::Uint8ClampedArray array;
DebugOnly<bool> inited = array.Init(aImageData.GetDataObject());
MOZ_ASSERT(inited);
@@ -952,17 +952,13 @@ ImageBitmap::CreateInternal(nsIGlobalObject* aGlobal, ImageData& aImageData,
// Create and Crop the raw data into a layers::Image
RefPtr<layers::Image> data;
// The data could move during a GC; copy it out into a local buffer.
uint8_t* fixedData = array.Data();
if (NS_IsMainThread()) {
data = CreateImageFromRawData(imageSize, imageStride, FORMAT,
fixedData, dataLength,
array.Data(), dataLength,
aCropRect);
} else {
RefPtr<CreateImageFromRawDataInMainThreadSyncTask> task
= new CreateImageFromRawDataInMainThreadSyncTask(fixedData,
= new CreateImageFromRawDataInMainThreadSyncTask(array.Data(),
dataLength,
imageStride,
FORMAT,
-1
View File
@@ -690,7 +690,6 @@ private:
case CKM_AES_GCM:
gcmParams.pIv = mIv.Elements();
gcmParams.ulIvLen = mIv.Length();
gcmParams.ulIvBits = gcmParams.ulIvLen * 8;
gcmParams.pAAD = mAad.Elements();
gcmParams.ulAADLen = mAad.Length();
gcmParams.ulTagBits = mTagLength;
+2 -2
View File
@@ -2516,7 +2516,7 @@ EventStateManager::ComputeScrollTarget(nsIFrame* aTargetFrame,
return frameToScroll;
}
ScrollStyles ss = scrollableFrame->GetScrollStyles();
ScrollbarStyles ss = scrollableFrame->GetScrollbarStyles();
bool hiddenForV = (NS_STYLE_OVERFLOW_HIDDEN == ss.mVertical);
bool hiddenForH = (NS_STYLE_OVERFLOW_HIDDEN == ss.mHorizontal);
if ((hiddenForV && hiddenForH) ||
@@ -2609,7 +2609,7 @@ EventStateManager::DoScrollText(nsIScrollableFrame* aScrollableFrame,
ComputeScrollAmountForDefaultAction(aEvent, scrollAmountInDevPixels);
// Don't scroll around the axis whose overflow style is hidden.
ScrollStyles overflowStyle = aScrollableFrame->GetScrollStyles();
ScrollbarStyles overflowStyle = aScrollableFrame->GetScrollbarStyles();
if (overflowStyle.mHorizontal == NS_STYLE_OVERFLOW_HIDDEN) {
actualDevPixelScrollAmount.x = 0;
}
+1 -1
View File
@@ -866,7 +866,7 @@ HTMLInputElement::InitFilePicker(FilePickerType aType)
mode = static_cast<int16_t>(nsIFilePicker::modeOpen);
}
nsresult rv = filePicker->Init(win, title, mode, /*aRequireInteraction = */ true);
nsresult rv = filePicker->Init(win, title, mode);
NS_ENSURE_SUCCESS(rv, rv);
if (!okButtonLabel.IsEmpty()) {
+1 -5
View File
@@ -4614,12 +4614,8 @@ void HTMLMediaElement::DecodeError(const MediaResult& aError)
}
} else if (mReadyState == nsIDOMHTMLMediaElement::HAVE_NOTHING) {
NoSupportedMediaSourceError(aError.Description());
} else if (IsCORSSameOrigin()) {
Error(MEDIA_ERR_DECODE, aError.Description());
} else {
nsAutoCString eMessage;
eMessage.AssignLiteral("Failed to decode media");
Error(MEDIA_ERR_DECODE, eMessage);
Error(MEDIA_ERR_DECODE, aError.Description());
}
}
+3 -3
View File
@@ -137,9 +137,9 @@ HTMLMenuElement::ParseAttribute(int32_t aNamespaceID,
const nsAString& aValue,
nsAttrValue& aResult)
{
if (aNamespaceID == kNameSpaceID_None && aAttribute == nsGkAtoms::type &&
Preferences::GetBool("dom.menuitem.enabled")) {
bool success = aResult.ParseEnumValue(aValue, kMenuTypeTable, false);
if (aNamespaceID == kNameSpaceID_None && aAttribute == nsGkAtoms::type) {
bool success = aResult.ParseEnumValue(aValue, kMenuTypeTable,
false);
if (success) {
mType = aResult.GetEnumValue();
} else {
+2 -11
View File
@@ -7,21 +7,12 @@
#include "mozilla/BasicEvents.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/Preferences.h"
#include "mozilla/dom/HTMLMenuItemElementBinding.h"
#include "mozilla/dom/HTMLUnknownElement.h"
#include "nsAttrValueInlines.h"
#include "nsContentUtils.h"
nsGenericHTMLElement*
NS_NewHTMLMenuItemElement(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
mozilla::dom::FromParser aFromParser) {
if (mozilla::Preferences::GetBool("dom.menuitem.enabled")) {
return new mozilla::dom::HTMLMenuItemElement(aNodeInfo, aFromParser);
} else {
return new mozilla::dom::HTMLUnknownElement(aNodeInfo);
}
}
NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(MenuItem)
namespace mozilla {
namespace dom {
@@ -4,9 +4,6 @@ const kPage = "http://example.org/browser/" +
"dom/html/test/file_content_contextmenu.html";
add_task(function* () {
yield SpecialPowers.pushPrefEnv({
set: [["dom.menuitem.enabled", true]],
});
yield BrowserTestUtils.withNewTab({
gBrowser,
url: kPage
-2
View File
@@ -1,6 +1,4 @@
[DEFAULT]
prefs =
dom.menuitem.enabled=true # only for test_bug617528.html
support-files =
347174transform.xsl
347174transformable.xml
+1 -2
View File
@@ -248,8 +248,7 @@ FilePickerParent::CreateFilePicker()
return false;
}
return NS_SUCCEEDED(mFilePicker->Init(window, mTitle, mMode,
element->IsNodeOfType(nsINode::eHTML_FORM_CONTROL)));
return NS_SUCCEEDED(mFilePicker->Init(window, mTitle, mMode));
}
bool
+5
View File
@@ -48,6 +48,11 @@ struct FrameIPCTabContext
// Whether this TabContext should work in prerender mode.
bool isPrerendered;
// The requested presentation URL.
// This value would be empty if the TabContext isn't created for
// presented content.
nsString presentationURL;
// Keyboard indicator state inherited from the parent.
UIStateChangeType showAccelerators;
UIStateChangeType showFocusRings;
+5
View File
@@ -770,6 +770,11 @@ TabChild::NotifyTabContextUpdated(bool aIsPreallocated)
if (aIsPreallocated) {
nsDocShell::Cast(docShell)->SetOriginAttributes(OriginAttributesRef());
}
// Set SANDBOXED_AUXILIARY_NAVIGATION flag if this is a receiver page.
if (!PresentationURL().IsEmpty()) {
docShell->SetSandboxFlags(SANDBOXED_AUXILIARY_NAVIGATION);
}
}
void
+14 -2
View File
@@ -190,6 +190,12 @@ TabContext::OriginAttributesRef() const
return mOriginAttributes;
}
const nsAString&
TabContext::PresentationURL() const
{
return mPresentationURL;
}
UIStateChangeType
TabContext::ShowAccelerators() const
{
@@ -209,7 +215,8 @@ TabContext::SetTabContext(bool aIsMozBrowserElement,
mozIApplication* aAppFrameOwnerApp,
UIStateChangeType aShowAccelerators,
UIStateChangeType aShowFocusRings,
const DocShellOriginAttributes& aOriginAttributes)
const DocShellOriginAttributes& aOriginAttributes,
const nsAString& aPresentationURL)
{
NS_ENSURE_FALSE(mInitialized, false);
@@ -241,6 +248,7 @@ TabContext::SetTabContext(bool aIsMozBrowserElement,
mContainingAppId = containingAppId;
mOwnApp = aOwnApp;
mContainingApp = aAppFrameOwnerApp;
mPresentationURL = aPresentationURL;
mShowAccelerators = aShowAccelerators;
mShowFocusRings = aShowFocusRings;
return true;
@@ -253,6 +261,7 @@ TabContext::AsIPCTabContext() const
mContainingAppId,
mIsMozBrowserElement,
mIsPrerendered,
mPresentationURL,
mShowAccelerators,
mShowFocusRings));
}
@@ -276,6 +285,7 @@ MaybeInvalidTabContext::MaybeInvalidTabContext(const IPCTabContext& aParams)
bool isPrerendered = false;
uint32_t containingAppId = NO_APP_ID;
DocShellOriginAttributes originAttributes;
nsAutoString presentationURL;
UIStateChangeType showAccelerators = UIStateChangeType_NoChange;
UIStateChangeType showFocusRings = UIStateChangeType_NoChange;
@@ -338,6 +348,7 @@ MaybeInvalidTabContext::MaybeInvalidTabContext(const IPCTabContext& aParams)
isMozBrowserElement = ipcContext.isMozBrowserElement();
isPrerendered = ipcContext.isPrerendered();
containingAppId = ipcContext.frameOwnerAppId();
presentationURL = ipcContext.presentationURL();
showAccelerators = ipcContext.showAccelerators();
showFocusRings = ipcContext.showFocusRings();
originAttributes = ipcContext.originAttributes();
@@ -384,7 +395,8 @@ MaybeInvalidTabContext::MaybeInvalidTabContext(const IPCTabContext& aParams)
containingApp,
showAccelerators,
showFocusRings,
originAttributes);
originAttributes,
presentationURL);
if (!rv) {
mInvalidReason = "Couldn't initialize TabContext.";
}
+17 -3
View File
@@ -125,6 +125,12 @@ public:
*/
const DocShellOriginAttributes& OriginAttributesRef() const;
/**
* Returns the presentation URL associated with the tab if this tab is
* created for presented content
*/
const nsAString& PresentationURL() const;
UIStateChangeType ShowAccelerators() const;
UIStateChangeType ShowFocusRings() const;
@@ -163,7 +169,8 @@ protected:
mozIApplication* aAppFrameOwnerApp,
UIStateChangeType aShowAccelerators,
UIStateChangeType aShowFocusRings,
const DocShellOriginAttributes& aOriginAttributes);
const DocShellOriginAttributes& aOriginAttributes,
const nsAString& aPresentationURL);
/**
* Modify this TabContext to match the given TabContext. This is a special
@@ -218,6 +225,11 @@ private:
*/
DocShellOriginAttributes mOriginAttributes;
/**
* The requested presentation URL.
*/
nsString mPresentationURL;
/**
* Keyboard indicator state (focus rings, accelerators).
*/
@@ -245,7 +257,8 @@ public:
mozIApplication* aAppFrameOwnerApp,
UIStateChangeType aShowAccelerators,
UIStateChangeType aShowFocusRings,
const DocShellOriginAttributes& aOriginAttributes)
const DocShellOriginAttributes& aOriginAttributes,
const nsAString& aPresentationURL = EmptyString())
{
return TabContext::SetTabContext(aIsMozBrowserElement,
aIsPrerendered,
@@ -253,7 +266,8 @@ public:
aAppFrameOwnerApp,
aShowAccelerators,
aShowFocusRings,
aOriginAttributes);
aOriginAttributes,
aPresentationURL);
}
};
@@ -316,5 +316,3 @@ LargeAllocationRelatedBrowsingContexts=A Large-Allocation header was ignored due
LargeAllocationInIFrame=A Large-Allocation header was ignored due to the load occuring within an iframe.
# LOCALIZATION NOTE: Do not translate "Large-Allocation", as it is a literal header name
LargeAllocationNonE10S=A Large-Allocation header was ignored due to the document not being loaded out of process.
# LOCALIZATION NOTE: Do not translate "pushState" and "replaceState"
PushStateFloodingPrevented=Call to pushState or replaceState ignored due to excessive calls within a short timeframe.
-3
View File
@@ -145,9 +145,6 @@ IPDL_SOURCES += [
'PGMPVideoEncoder.ipdl',
]
if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
NO_VISIBILITY_FLAGS = True
# comment this out to use Unsafe Shmem for more performance
DEFINES['GMP_SAFE_SHMEM'] = True
@@ -0,0 +1,227 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "AndroidDecoderModule.h"
#include "AndroidBridge.h"
#include "MediaCodecDataDecoder.h"
#include "RemoteDataDecoder.h"
#include "MediaInfo.h"
#include "VPXDecoder.h"
#include "MediaPrefs.h"
#include "OpusDecoder.h"
#include "VorbisDecoder.h"
#include "nsPromiseFlatString.h"
#include "nsIGfxInfo.h"
#include "prlog.h"
#include <jni.h>
#undef LOG
#define LOG(arg, ...) MOZ_LOG(sAndroidDecoderModuleLog, \
mozilla::LogLevel::Debug, ("AndroidDecoderModule(%p)::%s: " arg, \
this, __func__, ##__VA_ARGS__))
using namespace mozilla;
using namespace mozilla::gl;
using namespace mozilla::java::sdk;
using media::TimeUnit;
namespace mozilla {
mozilla::LazyLogModule sAndroidDecoderModuleLog("AndroidDecoderModule");
static const char*
TranslateMimeType(const nsACString& aMimeType)
{
if (VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP8)) {
return "video/x-vnd.on2.vp8";
} else if (VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP9)) {
return "video/x-vnd.on2.vp9";
}
return PromiseFlatCString(aMimeType).get();
}
static bool
GetFeatureStatus(int32_t aFeature)
{
nsCOMPtr<nsIGfxInfo> gfxInfo = services::GetGfxInfo();
int32_t status = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;
nsCString discardFailureId;
if (!gfxInfo || NS_FAILED(gfxInfo->GetFeatureStatus(aFeature, discardFailureId, &status))) {
return false;
}
return status == nsIGfxInfo::FEATURE_STATUS_OK;
};
CryptoInfo::LocalRef
GetCryptoInfoFromSample(const MediaRawData* aSample)
{
auto& cryptoObj = aSample->mCrypto;
if (!cryptoObj.mValid) {
return nullptr;
}
CryptoInfo::LocalRef cryptoInfo;
nsresult rv = CryptoInfo::New(&cryptoInfo);
NS_ENSURE_SUCCESS(rv, nullptr);
uint32_t numSubSamples =
std::min<uint32_t>(cryptoObj.mPlainSizes.Length(), cryptoObj.mEncryptedSizes.Length());
uint32_t totalSubSamplesSize = 0;
for (auto& size : cryptoObj.mEncryptedSizes) {
totalSubSamplesSize += size;
}
// mPlainSizes is uint16_t, need to transform to uint32_t first.
nsTArray<uint32_t> plainSizes;
for (auto& size : cryptoObj.mPlainSizes) {
totalSubSamplesSize += size;
plainSizes.AppendElement(size);
}
uint32_t codecSpecificDataSize = aSample->Size() - totalSubSamplesSize;
// Size of codec specific data("CSD") for Android MediaCodec usage should be
// included in the 1st plain size.
plainSizes[0] += codecSpecificDataSize;
static const int kExpectedIVLength = 16;
auto tempIV(cryptoObj.mIV);
auto tempIVLength = tempIV.Length();
MOZ_ASSERT(tempIVLength <= kExpectedIVLength);
for (size_t i = tempIVLength; i < kExpectedIVLength; i++) {
// Padding with 0
tempIV.AppendElement(0);
}
auto numBytesOfPlainData = mozilla::jni::IntArray::New(
reinterpret_cast<int32_t*>(&plainSizes[0]),
plainSizes.Length());
auto numBytesOfEncryptedData =
mozilla::jni::IntArray::New(reinterpret_cast<const int32_t*>(&cryptoObj.mEncryptedSizes[0]),
cryptoObj.mEncryptedSizes.Length());
auto iv = mozilla::jni::ByteArray::New(reinterpret_cast<int8_t*>(&tempIV[0]),
tempIV.Length());
auto keyId = mozilla::jni::ByteArray::New(reinterpret_cast<const int8_t*>(&cryptoObj.mKeyId[0]),
cryptoObj.mKeyId.Length());
cryptoInfo->Set(numSubSamples,
numBytesOfPlainData,
numBytesOfEncryptedData,
keyId,
iv,
MediaCodec::CRYPTO_MODE_AES_CTR);
return cryptoInfo;
}
bool
AndroidDecoderModule::SupportsMimeType(const nsACString& aMimeType,
DecoderDoctorDiagnostics* aDiagnostics) const
{
if (!AndroidBridge::Bridge() ||
AndroidBridge::Bridge()->GetAPIVersion() < 16) {
return false;
}
if (aMimeType.EqualsLiteral("video/mp4") ||
aMimeType.EqualsLiteral("video/avc")) {
return true;
}
// When checking "audio/x-wav", CreateDecoder can cause a JNI ERROR by
// Accessing a stale local reference leading to a SIGSEGV crash.
// To avoid this we check for wav types here.
if (aMimeType.EqualsLiteral("audio/x-wav") ||
aMimeType.EqualsLiteral("audio/wave; codecs=1") ||
aMimeType.EqualsLiteral("audio/wave; codecs=6") ||
aMimeType.EqualsLiteral("audio/wave; codecs=7") ||
aMimeType.EqualsLiteral("audio/wave; codecs=65534")) {
return false;
}
if ((VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP8) &&
!GetFeatureStatus(nsIGfxInfo::FEATURE_VP8_HW_DECODE)) ||
(VPXDecoder::IsVPX(aMimeType, VPXDecoder::VP9) &&
!GetFeatureStatus(nsIGfxInfo::FEATURE_VP9_HW_DECODE))) {
return false;
}
// Prefer the gecko decoder for opus and vorbis; stagefright crashes
// on content demuxed from mp4.
if (OpusDataDecoder::IsOpus(aMimeType) ||
VorbisDataDecoder::IsVorbis(aMimeType)) {
LOG("Rejecting audio of type %s", aMimeType.Data());
return false;
}
return java::HardwareCodecCapabilityUtils::FindDecoderCodecInfoForMimeType(
nsCString(TranslateMimeType(aMimeType)));
}
already_AddRefed<MediaDataDecoder>
AndroidDecoderModule::CreateVideoDecoder(const CreateDecoderParams& aParams)
{
MediaFormat::LocalRef format;
const VideoInfo& config = aParams.VideoConfig();
NS_ENSURE_SUCCESS(MediaFormat::CreateVideoFormat(
TranslateMimeType(config.mMimeType),
config.mDisplay.width,
config.mDisplay.height,
&format), nullptr);
RefPtr<MediaDataDecoder> decoder = MediaPrefs::PDMAndroidRemoteCodecEnabled() ?
RemoteDataDecoder::CreateVideoDecoder(config,
format,
aParams.mCallback,
aParams.mImageContainer) :
MediaCodecDataDecoder::CreateVideoDecoder(config,
format,
aParams.mCallback,
aParams.mImageContainer);
return decoder.forget();
}
already_AddRefed<MediaDataDecoder>
AndroidDecoderModule::CreateAudioDecoder(const CreateDecoderParams& aParams)
{
const AudioInfo& config = aParams.AudioConfig();
MOZ_ASSERT(config.mBitDepth == 16, "We only handle 16-bit audio!");
MediaFormat::LocalRef format;
LOG("CreateAudioFormat with mimeType=%s, mRate=%d, channels=%d",
config.mMimeType.Data(), config.mRate, config.mChannels);
NS_ENSURE_SUCCESS(MediaFormat::CreateAudioFormat(
config.mMimeType,
config.mRate,
config.mChannels,
&format), nullptr);
RefPtr<MediaDataDecoder> decoder = MediaPrefs::PDMAndroidRemoteCodecEnabled() ?
RemoteDataDecoder::CreateAudioDecoder(config, format, aParams.mCallback) :
MediaCodecDataDecoder::CreateAudioDecoder(config, format, aParams.mCallback);
return decoder.forget();
}
PlatformDecoderModule::ConversionRequired
AndroidDecoderModule::DecoderNeedsConversion(const TrackInfo& aConfig) const
{
if (aConfig.IsVideo()) {
return ConversionRequired::kNeedAnnexB;
}
return ConversionRequired::kNeedNone;
}
} // mozilla
@@ -0,0 +1,34 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef AndroidDecoderModule_h_
#define AndroidDecoderModule_h_
#include "PlatformDecoderModule.h"
namespace mozilla {
class AndroidDecoderModule : public PlatformDecoderModule {
public:
already_AddRefed<MediaDataDecoder>
CreateVideoDecoder(const CreateDecoderParams& aParams) override;
already_AddRefed<MediaDataDecoder>
CreateAudioDecoder(const CreateDecoderParams& aParams) override;
AndroidDecoderModule() {}
virtual ~AndroidDecoderModule() {}
bool SupportsMimeType(const nsACString& aMimeType,
DecoderDoctorDiagnostics* aDiagnostics) const override;
ConversionRequired
DecoderNeedsConversion(const TrackInfo& aConfig) const override;
};
extern LazyLogModule sAndroidDecoderModuleLog;
} // namespace mozilla
#endif
@@ -0,0 +1,698 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "MediaCodecDataDecoder.h"
#include "AndroidBridge.h"
#include "AndroidSurfaceTexture.h"
#include "GeneratedJNINatives.h"
#include "GLImages.h"
#include "MediaData.h"
#include "MediaInfo.h"
#include "VPXDecoder.h"
#include "nsThreadUtils.h"
#include "nsPromiseFlatString.h"
#include "nsIGfxInfo.h"
#include "prlog.h"
#include <jni.h>
#undef LOG
#define LOG(arg, ...) MOZ_LOG(sAndroidDecoderModuleLog, \
mozilla::LogLevel::Debug, ("MediaCodecDataDecoder(%p)::%s: " arg, \
this, __func__, ##__VA_ARGS__))
using namespace mozilla;
using namespace mozilla::gl;
using namespace mozilla::java;
using namespace mozilla::java::sdk;
using media::TimeUnit;
namespace mozilla {
#define INVOKE_CALLBACK(Func, ...) \
if (mCallback) { \
mCallback->Func(__VA_ARGS__); \
} else { \
NS_WARNING("Callback not set"); \
}
static MediaCodec::LocalRef
CreateDecoder(const nsACString& aMimeType)
{
MediaCodec::LocalRef codec;
NS_ENSURE_SUCCESS(MediaCodec::CreateDecoderByType(TranslateMimeType(aMimeType),
&codec), nullptr);
return codec;
}
class VideoDataDecoder : public MediaCodecDataDecoder
{
public:
VideoDataDecoder(const VideoInfo& aConfig,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback,
layers::ImageContainer* aImageContainer)
: MediaCodecDataDecoder(MediaData::Type::VIDEO_DATA, aConfig.mMimeType,
aFormat, aCallback)
, mImageContainer(aImageContainer)
, mConfig(aConfig)
{
}
const char* GetDescriptionName() const override
{
return "Android MediaCodec video decoder";
}
RefPtr<InitPromise> Init() override
{
mSurfaceTexture = AndroidSurfaceTexture::Create();
if (!mSurfaceTexture) {
NS_WARNING("Failed to create SurfaceTexture for video decode\n");
return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
}
if (NS_FAILED(InitDecoder(mSurfaceTexture->JavaSurface()))) {
return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
}
return InitPromise::CreateAndResolve(TrackInfo::kVideoTrack, __func__);
}
void Cleanup() override
{
}
nsresult PostOutput(BufferInfo::Param aInfo, MediaFormat::Param aFormat,
const TimeUnit& aDuration) override
{
RefPtr<layers::Image> img =
new SurfaceTextureImage(mSurfaceTexture.get(), mConfig.mDisplay,
gl::OriginPos::BottomLeft);
nsresult rv;
int32_t flags;
NS_ENSURE_SUCCESS(rv = aInfo->Flags(&flags), rv);
bool isSync = !!(flags & MediaCodec::BUFFER_FLAG_SYNC_FRAME);
int32_t offset;
NS_ENSURE_SUCCESS(rv = aInfo->Offset(&offset), rv);
int64_t presentationTimeUs;
NS_ENSURE_SUCCESS(rv = aInfo->PresentationTimeUs(&presentationTimeUs), rv);
RefPtr<VideoData> v =
VideoData::CreateFromImage(mConfig,
offset,
presentationTimeUs,
aDuration.ToMicroseconds(),
img,
isSync,
presentationTimeUs,
gfx::IntRect(0, 0,
mConfig.mDisplay.width,
mConfig.mDisplay.height));
INVOKE_CALLBACK(Output, v);
return NS_OK;
}
protected:
layers::ImageContainer* mImageContainer;
const VideoInfo& mConfig;
RefPtr<AndroidSurfaceTexture> mSurfaceTexture;
};
class AudioDataDecoder : public MediaCodecDataDecoder
{
public:
AudioDataDecoder(const AudioInfo& aConfig, MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback)
: MediaCodecDataDecoder(MediaData::Type::AUDIO_DATA, aConfig.mMimeType,
aFormat, aCallback)
{
JNIEnv* const env = jni::GetEnvForThread();
jni::ByteBuffer::LocalRef buffer(env);
NS_ENSURE_SUCCESS_VOID(aFormat->GetByteBuffer(NS_LITERAL_STRING("csd-0"),
&buffer));
if (!buffer && aConfig.mCodecSpecificConfig->Length() >= 2) {
buffer = jni::ByteBuffer::New(
aConfig.mCodecSpecificConfig->Elements(),
aConfig.mCodecSpecificConfig->Length());
NS_ENSURE_SUCCESS_VOID(aFormat->SetByteBuffer(NS_LITERAL_STRING("csd-0"),
buffer));
}
}
const char* GetDescriptionName() const override
{
return "android audio decoder";
}
nsresult Output(BufferInfo::Param aInfo, void* aBuffer,
MediaFormat::Param aFormat, const TimeUnit& aDuration)
{
// The output on Android is always 16-bit signed
nsresult rv;
int32_t numChannels;
NS_ENSURE_SUCCESS(rv =
aFormat->GetInteger(NS_LITERAL_STRING("channel-count"), &numChannels), rv);
AudioConfig::ChannelLayout layout(numChannels);
if (!layout.IsValid()) {
return NS_ERROR_FAILURE;
}
int32_t sampleRate;
NS_ENSURE_SUCCESS(rv =
aFormat->GetInteger(NS_LITERAL_STRING("sample-rate"), &sampleRate), rv);
int32_t size;
NS_ENSURE_SUCCESS(rv = aInfo->Size(&size), rv);
int32_t offset;
NS_ENSURE_SUCCESS(rv = aInfo->Offset(&offset), rv);
#ifdef MOZ_SAMPLE_TYPE_S16
const int32_t numSamples = size / 2;
#else
#error We only support 16-bit integer PCM
#endif
const int32_t numFrames = numSamples / numChannels;
AlignedAudioBuffer audio(numSamples);
if (!audio) {
return NS_ERROR_OUT_OF_MEMORY;
}
const uint8_t* bufferStart = static_cast<uint8_t*>(aBuffer) + offset;
PodCopy(audio.get(), reinterpret_cast<const AudioDataValue*>(bufferStart),
numSamples);
int64_t presentationTimeUs;
NS_ENSURE_SUCCESS(rv = aInfo->PresentationTimeUs(&presentationTimeUs), rv);
RefPtr<AudioData> data = new AudioData(0, presentationTimeUs,
aDuration.ToMicroseconds(),
numFrames,
Move(audio),
numChannels,
sampleRate);
INVOKE_CALLBACK(Output, data);
return NS_OK;
}
};
MediaDataDecoder*
MediaCodecDataDecoder::CreateAudioDecoder(const AudioInfo& aConfig,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback)
{
return new AudioDataDecoder(aConfig, aFormat, aCallback);
}
MediaDataDecoder*
MediaCodecDataDecoder::CreateVideoDecoder(const VideoInfo& aConfig,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback,
layers::ImageContainer* aImageContainer)
{
return new VideoDataDecoder(aConfig, aFormat, aCallback, aImageContainer);
}
MediaCodecDataDecoder::MediaCodecDataDecoder(MediaData::Type aType,
const nsACString& aMimeType,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback)
: mType(aType)
, mMimeType(aMimeType)
, mFormat(aFormat)
, mCallback(aCallback)
, mInputBuffers(nullptr)
, mOutputBuffers(nullptr)
, mMonitor("MediaCodecDataDecoder::mMonitor")
, mState(ModuleState::kDecoding)
{
}
MediaCodecDataDecoder::~MediaCodecDataDecoder()
{
Shutdown();
}
RefPtr<MediaDataDecoder::InitPromise>
MediaCodecDataDecoder::Init()
{
nsresult rv = InitDecoder(nullptr);
TrackInfo::TrackType type =
(mType == MediaData::AUDIO_DATA ? TrackInfo::TrackType::kAudioTrack
: TrackInfo::TrackType::kVideoTrack);
return NS_SUCCEEDED(rv) ?
InitPromise::CreateAndResolve(type, __func__) :
InitPromise::CreateAndReject(
NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
}
nsresult
MediaCodecDataDecoder::InitDecoder(Surface::Param aSurface)
{
mDecoder = CreateDecoder(mMimeType);
if (!mDecoder) {
INVOKE_CALLBACK(Error,
MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__));
return NS_ERROR_FAILURE;
}
nsresult rv;
NS_ENSURE_SUCCESS(rv = mDecoder->Configure(mFormat, aSurface, nullptr, 0), rv);
NS_ENSURE_SUCCESS(rv = mDecoder->Start(), rv);
NS_ENSURE_SUCCESS(rv = ResetInputBuffers(), rv);
NS_ENSURE_SUCCESS(rv = ResetOutputBuffers(), rv);
nsCOMPtr<nsIRunnable> r = NewRunnableMethod(this, &MediaCodecDataDecoder::DecoderLoop);
rv = NS_NewNamedThread("MC Decoder", getter_AddRefs(mThread), r);
return rv;
}
// This is in usec, so that's 10ms.
static const int64_t kDecoderTimeout = 10000;
#define BREAK_ON_DECODER_ERROR() \
if (NS_FAILED(res)) { \
NS_WARNING("Exiting decoder loop due to exception"); \
if (mState == ModuleState::kDrainDecoder) { \
INVOKE_CALLBACK(DrainComplete); \
SetState(ModuleState::kDecoding); \
} \
INVOKE_CALLBACK(Error, MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__)); \
break; \
}
nsresult
MediaCodecDataDecoder::GetInputBuffer(
JNIEnv* aEnv, int aIndex, jni::Object::LocalRef* aBuffer)
{
MOZ_ASSERT(aEnv);
MOZ_ASSERT(!*aBuffer);
int numTries = 2;
while (numTries--) {
*aBuffer = jni::Object::LocalRef::Adopt(
aEnv->GetObjectArrayElement(mInputBuffers.Get(), aIndex));
if (*aBuffer) {
return NS_OK;
}
nsresult res = ResetInputBuffers();
if (NS_FAILED(res)) {
return res;
}
}
return NS_ERROR_FAILURE;
}
bool
MediaCodecDataDecoder::WaitForInput()
{
MonitorAutoLock lock(mMonitor);
while (mState == ModuleState::kDecoding && mQueue.empty()) {
// Signal that we require more input.
INVOKE_CALLBACK(InputExhausted);
lock.Wait();
}
return mState != ModuleState::kStopping;
}
already_AddRefed<MediaRawData>
MediaCodecDataDecoder::PeekNextSample()
{
MonitorAutoLock lock(mMonitor);
if (mState == ModuleState::kFlushing) {
mDecoder->Flush();
ClearQueue();
SetState(ModuleState::kDecoding);
lock.Notify();
return nullptr;
}
if (mQueue.empty()) {
if (mState == ModuleState::kDrainQueue) {
SetState(ModuleState::kDrainDecoder);
}
return nullptr;
}
// We're not stopping or flushing, so try to get a sample.
return RefPtr<MediaRawData>(mQueue.front()).forget();
}
nsresult
MediaCodecDataDecoder::QueueSample(const MediaRawData* aSample)
{
MOZ_ASSERT(aSample);
AutoLocalJNIFrame frame(jni::GetEnvForThread(), 1);
// We have a sample, try to feed it to the decoder.
int32_t inputIndex = -1;
nsresult res = mDecoder->DequeueInputBuffer(kDecoderTimeout, &inputIndex);
if (NS_FAILED(res)) {
return res;
}
if (inputIndex < 0) {
// There is no valid input buffer available.
return NS_ERROR_FAILURE;
}
jni::Object::LocalRef buffer(frame.GetEnv());
res = GetInputBuffer(frame.GetEnv(), inputIndex, &buffer);
if (NS_FAILED(res)) {
return res;
}
void* directBuffer = frame.GetEnv()->GetDirectBufferAddress(buffer.Get());
MOZ_ASSERT(frame.GetEnv()->GetDirectBufferCapacity(buffer.Get()) >=
aSample->Size(),
"Decoder buffer is not large enough for sample");
PodCopy(static_cast<uint8_t*>(directBuffer), aSample->Data(), aSample->Size());
CryptoInfo::LocalRef cryptoInfo = GetCryptoInfoFromSample(aSample);
if (cryptoInfo) {
res = mDecoder->QueueSecureInputBuffer(inputIndex, 0, cryptoInfo,
aSample->mTime, 0);
} else {
res = mDecoder->QueueInputBuffer(inputIndex, 0, aSample->Size(),
aSample->mTime, 0);
}
if (NS_FAILED(res)) {
return res;
}
mDurations.push_back(TimeUnit::FromMicroseconds(aSample->mDuration));
return NS_OK;
}
nsresult
MediaCodecDataDecoder::QueueEOS()
{
mMonitor.AssertCurrentThreadOwns();
nsresult res = NS_OK;
int32_t inputIndex = -1;
res = mDecoder->DequeueInputBuffer(kDecoderTimeout, &inputIndex);
if (NS_FAILED(res) || inputIndex < 0) {
return res;
}
res = mDecoder->QueueInputBuffer(inputIndex, 0, 0, 0,
MediaCodec::BUFFER_FLAG_END_OF_STREAM);
if (NS_SUCCEEDED(res)) {
SetState(ModuleState::kDrainWaitEOS);
mMonitor.Notify();
}
return res;
}
void
MediaCodecDataDecoder::HandleEOS(int32_t aOutputStatus)
{
MonitorAutoLock lock(mMonitor);
if (mState == ModuleState::kDrainWaitEOS) {
SetState(ModuleState::kDecoding);
mMonitor.Notify();
INVOKE_CALLBACK(DrainComplete);
}
mDecoder->ReleaseOutputBuffer(aOutputStatus, false);
}
Maybe<TimeUnit>
MediaCodecDataDecoder::GetOutputDuration()
{
if (mDurations.empty()) {
return Nothing();
}
const Maybe<TimeUnit> duration = Some(mDurations.front());
mDurations.pop_front();
return duration;
}
nsresult
MediaCodecDataDecoder::ProcessOutput(
BufferInfo::Param aInfo, MediaFormat::Param aFormat, int32_t aStatus)
{
AutoLocalJNIFrame frame(jni::GetEnvForThread(), 1);
const Maybe<TimeUnit> duration = GetOutputDuration();
if (!duration) {
// Some devices report failure in QueueSample while actually succeeding at
// it, in which case we get an output buffer without having a cached duration
// (bug 1273523).
return NS_OK;
}
const auto buffer = jni::Object::LocalRef::Adopt(
frame.GetEnv()->GetObjectArrayElement(mOutputBuffers.Get(), aStatus));
if (buffer) {
// The buffer will be null on Android L if we are decoding to a Surface.
void* directBuffer = frame.GetEnv()->GetDirectBufferAddress(buffer.Get());
Output(aInfo, directBuffer, aFormat, duration.value());
}
// The Surface will be updated at this point (for video).
mDecoder->ReleaseOutputBuffer(aStatus, true);
PostOutput(aInfo, aFormat, duration.value());
return NS_OK;
}
void
MediaCodecDataDecoder::DecoderLoop()
{
bool isOutputDone = false;
AutoLocalJNIFrame frame(jni::GetEnvForThread(), 1);
MediaFormat::LocalRef outputFormat(frame.GetEnv());
nsresult res = NS_OK;
while (WaitForInput()) {
RefPtr<MediaRawData> sample = PeekNextSample();
{
MonitorAutoLock lock(mMonitor);
if (mState == ModuleState::kDrainDecoder) {
MOZ_ASSERT(!sample, "Shouldn't have a sample when pushing EOF frame");
res = QueueEOS();
BREAK_ON_DECODER_ERROR();
}
}
if (sample) {
res = QueueSample(sample);
if (NS_SUCCEEDED(res)) {
// We've fed this into the decoder, so remove it from the queue.
MonitorAutoLock lock(mMonitor);
MOZ_RELEASE_ASSERT(mQueue.size(), "Queue may not be empty");
mQueue.pop_front();
isOutputDone = false;
}
}
if (isOutputDone) {
continue;
}
BufferInfo::LocalRef bufferInfo;
nsresult res = BufferInfo::New(&bufferInfo);
BREAK_ON_DECODER_ERROR();
int32_t outputStatus = -1;
res = mDecoder->DequeueOutputBuffer(bufferInfo, kDecoderTimeout,
&outputStatus);
BREAK_ON_DECODER_ERROR();
if (outputStatus == MediaCodec::INFO_TRY_AGAIN_LATER) {
// We might want to call mCallback->InputExhausted() here, but there seems
// to be some possible bad interactions here with the threading.
} else if (outputStatus == MediaCodec::INFO_OUTPUT_BUFFERS_CHANGED) {
res = ResetOutputBuffers();
BREAK_ON_DECODER_ERROR();
} else if (outputStatus == MediaCodec::INFO_OUTPUT_FORMAT_CHANGED) {
res = mDecoder->GetOutputFormat(ReturnTo(&outputFormat));
BREAK_ON_DECODER_ERROR();
} else if (outputStatus < 0) {
NS_WARNING("Unknown error from decoder!");
INVOKE_CALLBACK(Error,
MediaResult(NS_ERROR_DOM_MEDIA_DECODE_ERR,
__func__));
// Don't break here just in case it's recoverable. If it's not, other
// stuff will fail later and we'll bail out.
} else {
// We have a valid buffer index >= 0 here.
int32_t flags;
nsresult res = bufferInfo->Flags(&flags);
BREAK_ON_DECODER_ERROR();
if (flags & MediaCodec::BUFFER_FLAG_END_OF_STREAM) {
HandleEOS(outputStatus);
isOutputDone = true;
// We only queue empty EOF frames, so we're done for now.
continue;
}
res = ProcessOutput(bufferInfo, outputFormat, outputStatus);
BREAK_ON_DECODER_ERROR();
}
}
Cleanup();
// We're done.
MonitorAutoLock lock(mMonitor);
SetState(ModuleState::kShutdown);
mMonitor.Notify();
}
const char*
MediaCodecDataDecoder::ModuleStateStr(ModuleState aState) {
switch (aState) {
case ModuleState::kDecoding: return "Decoding";
case ModuleState::kFlushing: return "Flushing";
case ModuleState::kDrainQueue: return "DrainQueue";
case ModuleState::kDrainDecoder: return "DrainDecoder";
case ModuleState::kDrainWaitEOS: return "DrainWaitEOS";
case ModuleState::kStopping: return "Stopping";
case ModuleState::kShutdown: return "Shutdown";
default: MOZ_ASSERT_UNREACHABLE("Invalid state.");
}
return "Unknown";
}
bool
MediaCodecDataDecoder::SetState(ModuleState aState)
{
bool ok = true;
if (mState == ModuleState::kShutdown) {
ok = false;
} else if (mState == ModuleState::kStopping) {
ok = aState == ModuleState::kShutdown;
} else if (aState == ModuleState::kDrainDecoder) {
ok = mState == ModuleState::kDrainQueue;
} else if (aState == ModuleState::kDrainWaitEOS) {
ok = mState == ModuleState::kDrainDecoder;
}
if (ok) {
LOG("%s -> %s", ModuleStateStr(mState), ModuleStateStr(aState));
mState = aState;
} else {
LOG("Fail to transit from %s to %s state", ModuleStateStr(mState), ModuleStateStr(aState));
}
return ok;
}
void
MediaCodecDataDecoder::ClearQueue()
{
mMonitor.AssertCurrentThreadOwns();
mQueue.clear();
mDurations.clear();
}
void
MediaCodecDataDecoder::Input(MediaRawData* aSample)
{
MonitorAutoLock lock(mMonitor);
mQueue.push_back(aSample);
lock.NotifyAll();
}
nsresult
MediaCodecDataDecoder::ResetInputBuffers()
{
return mDecoder->GetInputBuffers(ReturnTo(&mInputBuffers));
}
nsresult
MediaCodecDataDecoder::ResetOutputBuffers()
{
return mDecoder->GetOutputBuffers(ReturnTo(&mOutputBuffers));
}
void
MediaCodecDataDecoder::Flush()
{
MonitorAutoLock lock(mMonitor);
if (!SetState(ModuleState::kFlushing)) {
return;
}
lock.Notify();
while (mState == ModuleState::kFlushing) {
lock.Wait();
}
}
void
MediaCodecDataDecoder::Drain()
{
MonitorAutoLock lock(mMonitor);
if (mState == ModuleState::kDrainDecoder ||
mState == ModuleState::kDrainQueue) {
return;
}
SetState(ModuleState::kDrainQueue);
lock.Notify();
}
void
MediaCodecDataDecoder::Shutdown()
{
MonitorAutoLock lock(mMonitor);
SetState(ModuleState::kStopping);
lock.Notify();
while (mThread && mState != ModuleState::kShutdown) {
lock.Wait();
}
if (mThread) {
mThread->Shutdown();
mThread = nullptr;
}
if (mDecoder) {
mDecoder->Stop();
mDecoder->Release();
mDecoder = nullptr;
}
}
} // mozilla
@@ -0,0 +1,126 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef MediaCodecDataDecoder_h_
#define MediaCodecDataDecoder_h_
#include "AndroidDecoderModule.h"
#include "MediaCodec.h"
#include "SurfaceTexture.h"
#include "TimeUnits.h"
#include "mozilla/Monitor.h"
#include "mozilla/Maybe.h"
#include <deque>
namespace mozilla {
typedef std::deque<RefPtr<MediaRawData>> SampleQueue;
class MediaCodecDataDecoder : public MediaDataDecoder {
public:
static MediaDataDecoder* CreateAudioDecoder(const AudioInfo& aConfig,
java::sdk::MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback);
static MediaDataDecoder* CreateVideoDecoder(const VideoInfo& aConfig,
java::sdk::MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback,
layers::ImageContainer* aImageContainer);
virtual ~MediaCodecDataDecoder();
RefPtr<MediaDataDecoder::InitPromise> Init() override;
void Flush() override;
void Drain() override;
void Shutdown() override;
void Input(MediaRawData* aSample) override;
const char* GetDescriptionName() const override
{
return "Android MediaCodec decoder";
}
protected:
enum class ModuleState : uint8_t {
kDecoding = 0,
kFlushing,
kDrainQueue,
kDrainDecoder,
kDrainWaitEOS,
kStopping,
kShutdown
};
friend class AndroidDecoderModule;
MediaCodecDataDecoder(MediaData::Type aType,
const nsACString& aMimeType,
java::sdk::MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback);
static const char* ModuleStateStr(ModuleState aState);
virtual nsresult InitDecoder(java::sdk::Surface::Param aSurface);
virtual nsresult Output(java::sdk::BufferInfo::Param aInfo, void* aBuffer,
java::sdk::MediaFormat::Param aFormat, const media::TimeUnit& aDuration)
{
return NS_OK;
}
virtual nsresult PostOutput(java::sdk::BufferInfo::Param aInfo,
java::sdk::MediaFormat::Param aFormat, const media::TimeUnit& aDuration)
{
return NS_OK;
}
virtual void Cleanup() {};
nsresult ResetInputBuffers();
nsresult ResetOutputBuffers();
nsresult GetInputBuffer(JNIEnv* env, int index, jni::Object::LocalRef* buffer);
bool WaitForInput();
already_AddRefed<MediaRawData> PeekNextSample();
nsresult QueueSample(const MediaRawData* aSample);
nsresult QueueEOS();
void HandleEOS(int32_t aOutputStatus);
Maybe<media::TimeUnit> GetOutputDuration();
nsresult ProcessOutput(java::sdk::BufferInfo::Param aInfo,
java::sdk::MediaFormat::Param aFormat,
int32_t aStatus);
// Sets decoder state and returns whether the new state has become effective.
bool SetState(ModuleState aState);
void DecoderLoop();
virtual void ClearQueue();
MediaData::Type mType;
nsAutoCString mMimeType;
java::sdk::MediaFormat::GlobalRef mFormat;
MediaDataDecoderCallback* mCallback;
java::sdk::MediaCodec::GlobalRef mDecoder;
jni::ObjectArray::GlobalRef mInputBuffers;
jni::ObjectArray::GlobalRef mOutputBuffers;
nsCOMPtr<nsIThread> mThread;
// Only these members are protected by mMonitor.
Monitor mMonitor;
ModuleState mState;
SampleQueue mQueue;
// Durations are stored in microseconds.
std::deque<media::TimeUnit> mDurations;
};
} // namespace mozilla
#endif
@@ -0,0 +1,489 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "AndroidDecoderModule.h"
#include "AndroidBridge.h"
#include "AndroidSurfaceTexture.h"
#include "FennecJNINatives.h"
#include "GLImages.h"
#include "MediaData.h"
#include "MediaInfo.h"
#include "VideoUtils.h"
#include "VPXDecoder.h"
#include "nsThreadUtils.h"
#include "nsPromiseFlatString.h"
#include "nsIGfxInfo.h"
#include "prlog.h"
#include <jni.h>
#include <deque>
#undef LOG
#define LOG(arg, ...) MOZ_LOG(sAndroidDecoderModuleLog, \
mozilla::LogLevel::Debug, ("RemoteDataDecoder(%p)::%s: " arg, \
this, __func__, ##__VA_ARGS__))
using namespace mozilla;
using namespace mozilla::gl;
using namespace mozilla::java;
using namespace mozilla::java::sdk;
using media::TimeUnit;
namespace mozilla {
class JavaCallbacksSupport
: public CodecProxy::NativeCallbacks::Natives<JavaCallbacksSupport>
{
public:
typedef CodecProxy::NativeCallbacks::Natives<JavaCallbacksSupport> Base;
using Base::AttachNative;
JavaCallbacksSupport(MediaDataDecoderCallback* aDecoderCallback)
: mDecoderCallback(aDecoderCallback)
{
MOZ_ASSERT(aDecoderCallback);
}
virtual ~JavaCallbacksSupport() {}
void OnInputExhausted()
{
if (mDecoderCallback) {
mDecoderCallback->InputExhausted();
}
}
virtual void HandleOutput(Sample::Param aSample) = 0;
void OnOutput(jni::Object::Param aSample)
{
if (mDecoderCallback) {
HandleOutput(Sample::Ref::From(aSample));
}
}
virtual void HandleOutputFormatChanged(MediaFormat::Param aFormat) {};
void OnOutputFormatChanged(jni::Object::Param aFormat)
{
if (mDecoderCallback) {
HandleOutputFormatChanged(MediaFormat::Ref::From(aFormat));
}
}
void OnError(bool aIsFatal)
{
if (mDecoderCallback) {
mDecoderCallback->Error(aIsFatal ?
MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__) :
MediaResult(NS_ERROR_DOM_MEDIA_DECODE_ERR, __func__));
}
}
void DisposeNative()
{
// TODO
}
void Cancel()
{
mDecoderCallback = nullptr;
}
protected:
MediaDataDecoderCallback* mDecoderCallback;
};
struct SampleTime final
{
SampleTime(int64_t aStart, int64_t aDuration)
: mStart(aStart)
, mDuration(aDuration)
{}
int64_t mStart;
int64_t mDuration;
};
class RemoteVideoDecoder final : public RemoteDataDecoder
{
public:
class CallbacksSupport final : public JavaCallbacksSupport
{
public:
CallbacksSupport(RemoteVideoDecoder* aDecoder, MediaDataDecoderCallback* aCallback)
: JavaCallbacksSupport(aCallback)
, mDecoder(aDecoder)
{}
virtual ~CallbacksSupport() {}
void HandleOutput(Sample::Param aSample) override
{
Maybe<int64_t> durationUs = mDecoder->mInputDurations.Get();
if (!durationUs) {
return;
}
BufferInfo::LocalRef info = aSample->Info();
int32_t flags;
bool ok = NS_SUCCEEDED(info->Flags(&flags));
MOZ_ASSERT(ok);
int32_t offset;
ok |= NS_SUCCEEDED(info->Offset(&offset));
MOZ_ASSERT(ok);
int64_t presentationTimeUs;
ok |= NS_SUCCEEDED(info->PresentationTimeUs(&presentationTimeUs));
MOZ_ASSERT(ok);
int32_t size;
ok |= NS_SUCCEEDED(info->Size(&size));
MOZ_ASSERT(ok);
NS_ENSURE_TRUE_VOID(ok);
if (size > 0) {
RefPtr<layers::Image> img =
new SurfaceTextureImage(mDecoder->mSurfaceTexture.get(), mDecoder->mConfig.mDisplay,
gl::OriginPos::BottomLeft);
RefPtr<VideoData> v =
VideoData::CreateFromImage(mDecoder->mConfig,
offset,
presentationTimeUs,
durationUs.value(),
img,
!!(flags & MediaCodec::BUFFER_FLAG_SYNC_FRAME),
presentationTimeUs,
gfx::IntRect(0, 0,
mDecoder->mConfig.mDisplay.width,
mDecoder->mConfig.mDisplay.height));
mDecoderCallback->Output(v);
}
if ((flags & MediaCodec::BUFFER_FLAG_END_OF_STREAM) != 0) {
mDecoderCallback->DrainComplete();
}
}
friend class RemoteDataDecoder;
private:
RemoteVideoDecoder* mDecoder;
};
RemoteVideoDecoder(const VideoInfo& aConfig,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback,
layers::ImageContainer* aImageContainer)
: RemoteDataDecoder(MediaData::Type::VIDEO_DATA, aConfig.mMimeType,
aFormat, aCallback)
, mImageContainer(aImageContainer)
, mConfig(aConfig)
{
}
RefPtr<InitPromise> Init() override
{
mSurfaceTexture = AndroidSurfaceTexture::Create();
if (!mSurfaceTexture) {
NS_WARNING("Failed to create SurfaceTexture for video decode\n");
return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
}
if (!jni::IsFennec()) {
NS_WARNING("Remote decoding not supported in non-Fennec environment\n");
return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
}
// Register native methods.
JavaCallbacksSupport::Init();
mJavaCallbacks = CodecProxy::NativeCallbacks::New();
JavaCallbacksSupport::AttachNative(mJavaCallbacks,
mozilla::MakeUnique<CallbacksSupport>(this, mCallback));
mJavaDecoder = CodecProxy::Create(mFormat, mSurfaceTexture->JavaSurface(), mJavaCallbacks);
if (mJavaDecoder == nullptr) {
return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
}
mInputDurations.Clear();
return InitPromise::CreateAndResolve(TrackInfo::kVideoTrack, __func__);
}
void Flush() override
{
mInputDurations.Clear();
RemoteDataDecoder::Flush();
}
void Drain() override
{
RemoteDataDecoder::Drain();
mInputDurations.Put(0);
}
void Input(MediaRawData* aSample) override
{
RemoteDataDecoder::Input(aSample);
mInputDurations.Put(aSample->mDuration);
}
private:
class DurationQueue {
public:
void Clear()
{
mValues.clear();
}
void Put(int64_t aDurationUs)
{
mValues.emplace_back(aDurationUs);
}
Maybe<int64_t> Get()
{
if (mValues.empty()) {
return Nothing();
}
auto value = Some(mValues.front());
mValues.pop_front();
return value;
}
private:
std::deque<int64_t> mValues;
};
layers::ImageContainer* mImageContainer;
const VideoInfo& mConfig;
RefPtr<AndroidSurfaceTexture> mSurfaceTexture;
DurationQueue mInputDurations;
};
class RemoteAudioDecoder final : public RemoteDataDecoder
{
public:
RemoteAudioDecoder(const AudioInfo& aConfig,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback)
: RemoteDataDecoder(MediaData::Type::AUDIO_DATA, aConfig.mMimeType,
aFormat, aCallback)
, mConfig(aConfig)
{
JNIEnv* const env = jni::GetEnvForThread();
bool formatHasCSD = false;
NS_ENSURE_SUCCESS_VOID(aFormat->ContainsKey(NS_LITERAL_STRING("csd-0"), &formatHasCSD));
if (!formatHasCSD && aConfig.mCodecSpecificConfig->Length() >= 2) {
jni::ByteBuffer::LocalRef buffer(env);
buffer = jni::ByteBuffer::New(
aConfig.mCodecSpecificConfig->Elements(),
aConfig.mCodecSpecificConfig->Length());
NS_ENSURE_SUCCESS_VOID(aFormat->SetByteBuffer(NS_LITERAL_STRING("csd-0"),
buffer));
}
}
RefPtr<InitPromise> Init() override
{
// Register native methods.
JavaCallbacksSupport::Init();
mJavaCallbacks = CodecProxy::NativeCallbacks::New();
JavaCallbacksSupport::AttachNative(mJavaCallbacks,
mozilla::MakeUnique<CallbacksSupport>(this, mCallback));
mJavaDecoder = CodecProxy::Create(mFormat, nullptr, mJavaCallbacks);
if (mJavaDecoder == nullptr) {
return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
}
return InitPromise::CreateAndResolve(TrackInfo::kAudioTrack, __func__);
}
private:
class CallbacksSupport final : public JavaCallbacksSupport
{
public:
CallbacksSupport(RemoteAudioDecoder* aDecoder, MediaDataDecoderCallback* aCallback)
: JavaCallbacksSupport(aCallback)
, mDecoder(aDecoder)
{}
virtual ~CallbacksSupport() {}
void HandleOutput(Sample::Param aSample) override
{
BufferInfo::LocalRef info = aSample->Info();
int32_t flags;
bool ok = NS_SUCCEEDED(info->Flags(&flags));
MOZ_ASSERT(ok);
int32_t offset;
ok |= NS_SUCCEEDED(info->Offset(&offset));
MOZ_ASSERT(ok);
int64_t presentationTimeUs;
ok |= NS_SUCCEEDED(info->PresentationTimeUs(&presentationTimeUs));
MOZ_ASSERT(ok);
int32_t size;
ok |= NS_SUCCEEDED(info->Size(&size));
MOZ_ASSERT(ok);
NS_ENSURE_TRUE_VOID(ok);
if (size > 0) {
#ifdef MOZ_SAMPLE_TYPE_S16
const int32_t numSamples = size / 2;
#else
#error We only support 16-bit integer PCM
#endif
const int32_t numFrames = numSamples / mOutputChannels;
AlignedAudioBuffer audio(numSamples);
if (!audio) {
return;
}
jni::ByteBuffer::LocalRef dest = jni::ByteBuffer::New(audio.get(), size);
aSample->WriteToByteBuffer(dest);
RefPtr<AudioData> data = new AudioData(0, presentationTimeUs,
FramesToUsecs(numFrames, mOutputSampleRate).value(),
numFrames,
Move(audio),
mOutputChannels,
mOutputSampleRate);
mDecoderCallback->Output(data);
}
if ((flags & MediaCodec::BUFFER_FLAG_END_OF_STREAM) != 0) {
mDecoderCallback->DrainComplete();
return;
}
}
void HandleOutputFormatChanged(MediaFormat::Param aFormat) override
{
aFormat->GetInteger(NS_LITERAL_STRING("channel-count"), &mOutputChannels);
AudioConfig::ChannelLayout layout(mOutputChannels);
if (!layout.IsValid()) {
mDecoderCallback->Error(MediaResult(
NS_ERROR_DOM_MEDIA_FATAL_ERR,
RESULT_DETAIL("Invalid channel layout:%d", mOutputChannels)));
return;
}
aFormat->GetInteger(NS_LITERAL_STRING("sample-rate"), &mOutputSampleRate);
LOG("Audio output format changed: channels:%d sample rate:%d", mOutputChannels, mOutputSampleRate);
}
private:
RemoteAudioDecoder* mDecoder;
int32_t mOutputChannels;
int32_t mOutputSampleRate;
};
const AudioInfo& mConfig;
};
MediaDataDecoder*
RemoteDataDecoder::CreateAudioDecoder(const AudioInfo& aConfig,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback)
{
return new RemoteAudioDecoder(aConfig, aFormat, aCallback);
}
MediaDataDecoder*
RemoteDataDecoder::CreateVideoDecoder(const VideoInfo& aConfig,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback,
layers::ImageContainer* aImageContainer)
{
return new RemoteVideoDecoder(aConfig, aFormat, aCallback, aImageContainer);
}
RemoteDataDecoder::RemoteDataDecoder(MediaData::Type aType,
const nsACString& aMimeType,
MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback)
: mType(aType)
, mMimeType(aMimeType)
, mFormat(aFormat)
, mCallback(aCallback)
{
}
void
RemoteDataDecoder::Flush()
{
mJavaDecoder->Flush();
}
void
RemoteDataDecoder::Drain()
{
BufferInfo::LocalRef bufferInfo;
nsresult rv = BufferInfo::New(&bufferInfo);
NS_ENSURE_SUCCESS_VOID(rv);
bufferInfo->Set(0, 0, -1, MediaCodec::BUFFER_FLAG_END_OF_STREAM);
mJavaDecoder->Input(nullptr, bufferInfo, nullptr);
}
void
RemoteDataDecoder::Shutdown()
{
LOG("");
MOZ_ASSERT(mJavaDecoder && mJavaCallbacks);
mJavaDecoder->Release();
mJavaDecoder = nullptr;
JavaCallbacksSupport::GetNative(mJavaCallbacks)->Cancel();
mJavaCallbacks = nullptr;
mFormat = nullptr;
}
void
RemoteDataDecoder::Input(MediaRawData* aSample)
{
MOZ_ASSERT(aSample != nullptr);
jni::ByteBuffer::LocalRef bytes = jni::ByteBuffer::New(const_cast<uint8_t*>(aSample->Data()),
aSample->Size());
BufferInfo::LocalRef bufferInfo;
nsresult rv = BufferInfo::New(&bufferInfo);
if (NS_FAILED(rv)) {
mCallback->Error(MediaResult(NS_ERROR_OUT_OF_MEMORY, __func__));
return;
}
bufferInfo->Set(0, aSample->Size(), aSample->mTime, 0);
mJavaDecoder->Input(bytes, bufferInfo, GetCryptoInfoFromSample(aSample));
}
} // mozilla
@@ -0,0 +1,62 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef RemoteDataDecoder_h_
#define RemoteDataDecoder_h_
#include "AndroidDecoderModule.h"
#include "FennecJNIWrappers.h"
#include "SurfaceTexture.h"
#include "TimeUnits.h"
#include "mozilla/Monitor.h"
#include "mozilla/Maybe.h"
#include <deque>
namespace mozilla {
class RemoteDataDecoder : public MediaDataDecoder {
public:
static MediaDataDecoder* CreateAudioDecoder(const AudioInfo& aConfig,
java::sdk::MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback);
static MediaDataDecoder* CreateVideoDecoder(const VideoInfo& aConfig,
java::sdk::MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback,
layers::ImageContainer* aImageContainer);
virtual ~RemoteDataDecoder() {}
void Flush() override;
void Drain() override;
void Shutdown() override;
void Input(MediaRawData* aSample) override;
const char* GetDescriptionName() const override
{
return "android remote decoder";
}
protected:
RemoteDataDecoder(MediaData::Type aType,
const nsACString& aMimeType,
java::sdk::MediaFormat::Param aFormat,
MediaDataDecoderCallback* aCallback);
MediaData::Type mType;
nsAutoCString mMimeType;
java::sdk::MediaFormat::GlobalRef mFormat;
MediaDataDecoderCallback* mCallback;
java::CodecProxy::GlobalRef mJavaDecoder;
java::CodecProxy::NativeCallbacks::GlobalRef mJavaCallbacks;
};
} // namespace mozilla
#endif
+10
View File
@@ -80,6 +80,16 @@ if CONFIG['MOZ_APPLEMEDIA']:
include('/ipc/chromium/chromium-config.mozbuild')
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
EXPORTS += [
'android/AndroidDecoderModule.h',
]
SOURCES += [
'android/AndroidDecoderModule.cpp',
'android/MediaCodecDataDecoder.cpp',
'android/RemoteDataDecoder.cpp',
]
FINAL_LIBRARY = 'xul'
if CONFIG['GNU_CXX']:
+10 -11
View File
@@ -42,20 +42,19 @@ ReverbInputBuffer::ReverbInputBuffer(size_t length)
void ReverbInputBuffer::write(const float* sourceP, size_t numberOfFrames)
{
// m_writeIndex is atomic and checked by other threads, so only touch
// it at the start and end.
size_t index = m_writeIndex;
size_t bufferLength = m_buffer.Length();
bool isCopySafe = m_writeIndex + numberOfFrames <= bufferLength;
MOZ_ASSERT(isCopySafe);
if (!isCopySafe)
return;
size_t bufferLength = m_buffer.Length();
size_t newIndex = index + numberOfFrames;
memcpy(m_buffer.Elements() + m_writeIndex, sourceP, sizeof(float) * numberOfFrames);
MOZ_RELEASE_ASSERT(newIndex <= bufferLength);
m_writeIndex += numberOfFrames;
MOZ_ASSERT(m_writeIndex <= bufferLength);
memcpy(m_buffer.Elements() + index, sourceP, sizeof(float) * numberOfFrames);
if (newIndex >= bufferLength) {
m_writeIndex = 0;
}
if (m_writeIndex >= bufferLength)
m_writeIndex = 0;
}
float* ReverbInputBuffer::directReadFrom(int* readIndex, size_t numberOfFrames)
+1 -2
View File
@@ -30,7 +30,6 @@
#define ReverbInputBuffer_h
#include "nsTArray.h"
#include "mozilla/Atomics.h"
#include "mozilla/MemoryReporting.h"
namespace WebCore {
@@ -64,7 +63,7 @@ public:
private:
nsTArray<float> m_buffer;
mozilla::Atomic<size_t, mozilla::ReleaseAcquire> m_writeIndex;
size_t m_writeIndex;
};
} // namespace WebCore
+1 -5
View File
@@ -5,7 +5,6 @@
#ifndef mozilla_dom_MessagePortParent_h
#define mozilla_dom_MessagePortParent_h
#include "mozilla/WeakPtr.h"
#include "mozilla/dom/PMessagePortParent.h"
namespace mozilla {
@@ -13,8 +12,7 @@ namespace dom {
class MessagePortService;
class MessagePortParent final : public PMessagePortParent,
public SupportsWeakPtr<MessagePortParent>
class MessagePortParent final : public PMessagePortParent
{
public:
explicit MessagePortParent(const nsID& aUUID);
@@ -42,8 +40,6 @@ public:
const nsID& aDestinationUUID,
const uint32_t& aSequenceID);
MOZ_DECLARE_WEAKREFERENCE_TYPENAME(MessagePortParent)
private:
virtual bool RecvPostMessages(nsTArray<MessagePortMessage>&& aMessages)
override;
+3 -8
View File
@@ -9,7 +9,6 @@
#include "mozilla/ipc/BackgroundParent.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/Unused.h"
#include "mozilla/WeakPtr.h"
#include "nsTArray.h"
using mozilla::ipc::AssertIsOnBackgroundThread;
@@ -60,7 +59,7 @@ public:
{
uint32_t mSequenceID;
// MessagePortParent keeps the service alive, and we don't want a cycle.
WeakPtr<MessagePortParent> mParent;
MessagePortParent* mParent;
};
FallibleTArray<NextParent> mNextParents;
@@ -276,13 +275,9 @@ MessagePortService::CloseAll(const nsID& aUUID, bool aForced)
data->mParent->Close();
}
for (const MessagePortServiceData::NextParent& nextParent : data->mNextParents) {
MessagePortParent* const parent = nextParent.mParent;
if (parent) {
parent->CloseAndDelete();
}
for (const MessagePortServiceData::NextParent& parent : data->mNextParents) {
parent.mParent->CloseAndDelete();
}
data->mNextParents.Clear();
nsID destinationUUID = data->mDestinationUUID;
+7 -6
View File
@@ -46,6 +46,7 @@
#if defined(MOZ_X11)
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "X11UndefineNone.h"
#endif
#endif
@@ -268,12 +269,12 @@ typedef struct
* the parameters to the Windows API IMMNotificationClient object.
* This is the value of the NPNVaudioDeviceChangeDetails variable.
*/
typedef struct _NPAudioDeviceChangeDetails
{
int32_t flow;
int32_t role;
const wchar_t* defaultDevice; // this pointer is only valid during the call
// to NPPSetValue.
typedef struct _NPAudioDeviceChangeDetails
{
int32_t flow;
int32_t role;
const wchar_t* defaultDevice; // this pointer is only valid during the call
// to NPPSetValue.
} NPAudioDeviceChangeDetails;
#endif /* XP_WIN */
+37 -30
View File
@@ -599,38 +599,31 @@ ScriptLoader::CreateModuleScript(ModuleLoadRequest* aRequest)
return rv;
}
static bool
CreateTypeError(JSContext* aCx, ModuleScript* aScript, const nsString& aMessage,
JS::MutableHandle<JS::Value> aError)
{
JS::Rooted<JSObject*> module(aCx, aScript->ModuleRecord());
JS::Rooted<JSScript*> script(aCx, JS::GetModuleScript(aCx, module));
JS::Rooted<JSString*> filename(aCx);
filename = JS_NewStringCopyZ(aCx, JS_GetScriptFilename(script));
if (!filename) {
return false;
}
JS::Rooted<JSString*> message(aCx, JS_NewUCStringCopyZ(aCx, aMessage.get()));
if (!message) {
return false;
}
return JS::CreateError(aCx, JSEXN_TYPEERR, nullptr, filename, 0, 0, nullptr,
message, aError);
}
static nsresult
HandleResolveFailure(JSContext* aCx, ModuleScript* aScript,
const nsAString& aSpecifier)
const nsAString& aSpecifier,
uint32_t aLineNumber, uint32_t aColumnNumber)
{
// TODO: How can we get the line number of the failed import?
nsAutoCString url;
aScript->BaseURL()->GetAsciiSpec(url);
JS::Rooted<JSString*> filename(aCx);
filename = JS_NewStringCopyZ(aCx, url.get());
if (!filename) {
return NS_ERROR_OUT_OF_MEMORY;
}
nsAutoString message(NS_LITERAL_STRING("Error resolving module specifier: "));
message.Append(aSpecifier);
JS::Rooted<JSString*> string(aCx, JS_NewUCStringCopyZ(aCx, message.get()));
if (!string) {
return NS_ERROR_OUT_OF_MEMORY;
}
JS::Rooted<JS::Value> error(aCx);
if (!CreateTypeError(aCx, aScript, message, &error)) {
if (!JS::CreateError(aCx, JSEXN_TYPEERR, nullptr, filename, aLineNumber,
aColumnNumber, nullptr, string, &error)) {
return NS_ERROR_OUT_OF_MEMORY;
}
@@ -685,28 +678,37 @@ ResolveRequestedModules(ModuleLoadRequest* aRequest, nsCOMArray<nsIURI>* aUrlsOu
JSContext* cx = jsapi.cx();
JS::Rooted<JSObject*> moduleRecord(cx, ms->ModuleRecord());
JS::Rooted<JSObject*> specifiers(cx, JS::GetRequestedModules(cx, moduleRecord));
JS::Rooted<JSObject*> requestedModules(cx);
requestedModules = JS::GetRequestedModules(cx, moduleRecord);
MOZ_ASSERT(requestedModules);
uint32_t length;
if (!JS_GetArrayLength(cx, specifiers, &length)) {
if (!JS_GetArrayLength(cx, requestedModules, &length)) {
return NS_ERROR_FAILURE;
}
JS::Rooted<JS::Value> val(cx);
JS::Rooted<JS::Value> element(cx);
for (uint32_t i = 0; i < length; i++) {
if (!JS_GetElement(cx, specifiers, i, &val)) {
if (!JS_GetElement(cx, requestedModules, i, &element)) {
return NS_ERROR_FAILURE;
}
JS::Rooted<JSString*> str(cx, JS::GetRequestedModuleSpecifier(cx, element));
MOZ_ASSERT(str);
nsAutoJSString specifier;
if (!specifier.init(cx, val)) {
if (!specifier.init(cx, str)) {
return NS_ERROR_FAILURE;
}
// Let url be the result of resolving a module specifier given module script and requested.
nsCOMPtr<nsIURI> uri = ResolveModuleSpecifier(ms, specifier);
if (!uri) {
nsresult rv = HandleResolveFailure(cx, ms, specifier);
uint32_t lineNumber = 0;
uint32_t columnNumber = 0;
JS::GetRequestedModuleSourcePos(cx, element, &lineNumber, &columnNumber);
nsresult rv = HandleResolveFailure(cx, ms, specifier, lineNumber, columnNumber);
NS_ENSURE_SUCCESS(rv, rv);
return NS_ERROR_FAILURE;
}
@@ -806,6 +808,11 @@ HostResolveImportedModule(JSContext* aCx, JS::Handle<JSObject*> aModule,
auto script = static_cast<ModuleScript*>(value.toPrivate());
MOZ_ASSERT(script->ModuleRecord() == aModule);
// FIXME: in-line module scripts apparently pass a null specifier?
// At least make sure that doesn't crash the browser.
if (!aSpecifier)
return nullptr;
// Let url be the result of resolving a module specifier given referencing
// module script and specifier.
nsAutoJSString string;
@@ -149,16 +149,8 @@ nsContentSecurityManager::CheckFTPSubresourceLoad(nsIChannel* aChannel)
nsIPrincipal* triggeringPrincipal = loadInfo->TriggeringPrincipal();
nsCOMPtr<nsIURI> tURI;
triggeringPrincipal->GetURI(getter_AddRefs(tURI));
if (!tURI) {
// We don't have a triggering principal URI, meaning this isn't actually
// a subresource, but rather a top-level document, i.e. something we can
// display in-browser and might be saving as-is. Allow the load.
return NS_OK;
}
bool isTrigFtpURI = (NS_SUCCEEDED(tURI->SchemeIs("ftp", &isTrigFtpURI)) && isTrigFtpURI);
if (isTrigFtpURI) {
// The document loading this resource is also on FTP, satisfying the SOP.
// Allow the load.
return NS_OK;
}
@@ -496,6 +496,8 @@ var interfaceNamesInGlobalScope =
"HTMLMediaElement",
// IMPORTANT: Do not change this list without review from a DOM peer!
"HTMLMenuElement",
// IMPORTANT: Do not change this list without review from a DOM peer!
"HTMLMenuItemElement",
// IMPORTANT: Do not change this list without review from a DOM peer!
"HTMLMetaElement",
// IMPORTANT: Do not change this list without review from a DOM peer!
@@ -71,6 +71,7 @@
['map', 'Map'],
['mark', ''],
['menu', 'Menu'],
['menuitem', 'MenuItem'],
['meta', 'Meta'],
['meter', 'Meter'],
['nav', ''],
+1 -1
View File
@@ -23,6 +23,6 @@ interface Animatable {
[Func="nsDocument::IsElementAnimateEnabled", Throws]
Animation animate(object? keyframes,
optional UnrestrictedDoubleOrKeyframeAnimationOptions options);
[Func="nsDocument::IsWebAnimationsGetAnimationsEnabled"]
[Func="nsDocument::IsWebAnimationsEnabled"]
sequence<Animation> getAnimations(optional AnimationFilter filter);
};
+1 -1
View File
@@ -19,7 +19,7 @@ interface Animation : EventTarget {
attribute DOMString id;
[Func="nsDocument::IsWebAnimationsEnabled", Pure]
attribute AnimationEffectReadOnly? effect;
[Func="nsDocument::AreWebAnimationsTimelinesEnabled"]
[Func="nsDocument::IsWebAnimationsEnabled"]
attribute AnimationTimeline? timeline;
[BinaryName="startTimeAsDouble"]
attribute double? startTime;
+1 -1
View File
@@ -10,7 +10,7 @@
* liability, trademark and document use rules apply.
*/
[Func="nsDocument::AreWebAnimationsTimelinesEnabled"]
[Func="nsDocument::IsWebAnimationsEnabled"]
interface AnimationTimeline {
[BinaryName="currentTimeAsDouble"]
readonly attribute double? currentTime;
+1 -1
View File
@@ -15,7 +15,7 @@
// this interface.
// What we implement here is a minimal subset of the two definitions which we
// ship behind a pref until the specification issues have been resolved.
[Func="nsDocument::IsWebAnimationsGetAnimationsEnabled"]
[Func="nsDocument::IsWebAnimationsEnabled"]
interface CSSPseudoElement {
readonly attribute DOMString type;
readonly attribute Element parentElement;
+2 -2
View File
@@ -312,9 +312,9 @@ partial interface Document {
// http://w3c.github.io/web-animations/#extensions-to-the-document-interface
partial interface Document {
[Func="nsDocument::AreWebAnimationsTimelinesEnabled"]
[Func="nsDocument::IsWebAnimationsEnabled"]
readonly attribute DocumentTimeline timeline;
[Func="nsDocument::IsWebAnimationsGetAnimationsEnabled"]
[Func="nsDocument::IsWebAnimationsEnabled"]
sequence<Animation> getAnimations();
};
+1 -1
View File
@@ -14,7 +14,7 @@ dictionary DocumentTimelineOptions {
DOMHighResTimeStamp originTime = 0;
};
[Func="nsDocument::AreWebAnimationsTimelinesEnabled",
[Func="nsDocument::IsWebAnimationsEnabled",
Constructor (optional DocumentTimelineOptions options)]
interface DocumentTimeline : AnimationTimeline {
};
-1
View File
@@ -82,7 +82,6 @@ interface GlobalEventHandlers {
attribute EventHandler onseeked;
attribute EventHandler onseeking;
attribute EventHandler onselect;
[Pref="dom.menuitem.enabled"]
attribute EventHandler onshow;
//(Not implemented)attribute EventHandler onsort;
attribute EventHandler onstalled;
+3 -1
View File
@@ -49,8 +49,10 @@ interface HTMLElement : Element {
attribute DOMString contentEditable;
[Pure]
readonly attribute boolean isContentEditable;
[Pure, Pref="dom.menuitem.enabled"]
[Pure]
readonly attribute HTMLMenuElement? contextMenu;
//[SetterThrows]
// attribute HTMLMenuElement? contextMenu;
[CEReactions, SetterThrows, Pure]
attribute boolean spellcheck;
+2 -2
View File
@@ -17,9 +17,9 @@ interface MenuBuilder;
// http://www.whatwg.org/specs/web-apps/current-work/#the-menu-element
[HTMLConstructor]
interface HTMLMenuElement : HTMLElement {
[CEReactions, SetterThrows, Pref="dom.menuitem.enabled"]
[CEReactions, SetterThrows]
attribute DOMString type;
[CEReactions, SetterThrows, Pref="dom.menuitem.enabled"]
[CEReactions, SetterThrows]
attribute DOMString label;
};
+1 -1
View File
@@ -12,7 +12,7 @@
*/
// http://www.whatwg.org/specs/web-apps/current-work/#the-menuitem-element
[HTMLConstructor, Pref="dom.menuitem.enabled"]
[HTMLConstructor]
interface HTMLMenuItemElement : HTMLElement {
[CEReactions, SetterThrows]
attribute DOMString type;
+1 -1
View File
@@ -6392,7 +6392,7 @@ WorkerPrivate::GarbageCollectInternal(JSContext* aCx, bool aShrinking,
if (aShrinking || aCollectChildren) {
JS::PrepareForFullGC(aCx);
if (aShrinking && mSyncLoopStack.IsEmpty()) {
if (aShrinking) {
JS::GCForReason(aCx, GC_SHRINK, JS::gcreason::DOM_WORKER);
if (!aCollectChildren) {
@@ -27,7 +27,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1135764
}
addLoadEvent(function() {
SpecialPowers.pushPrefEnv(
{ "set": [[ "dom.animations-api.timelines.enabled", true]] },
{ "set": [[ "dom.animations-api.core.enabled", true]] },
function() {
var ifr = document.querySelector("iframe");
ifr.onload = function() {
+11
View File
@@ -16,6 +16,9 @@
#endif
#include "mozilla/Tuple.h"
#if defined(MOZ_WIDGET_ANDROID)
#include "nsDebug.h"
#endif
#include "Point.h"
#include "BaseRect.h"
#include "Matrix.h"
@@ -138,6 +141,9 @@ struct BasicLogger
// in the appropriate places in that method.
static bool ShouldOutputMessage(int aLevel) {
if (LoggingPrefs::sGfxLogLevel >= aLevel) {
#if defined(MOZ_WIDGET_ANDROID)
return true;
#else
#if defined(MOZ_LOGGING)
if (MOZ_LOG_TEST(GetGFX2DLog(), PRLogLevelForLevel(aLevel))) {
return true;
@@ -147,6 +153,7 @@ struct BasicLogger
(aLevel < LOG_DEBUG)) {
return true;
}
#endif
}
return false;
}
@@ -167,6 +174,9 @@ struct BasicLogger
// make the corresponding change in the ShouldOutputMessage method
// above.
if (LoggingPrefs::sGfxLogLevel >= aLevel) {
#if defined(MOZ_WIDGET_ANDROID)
printf_stderr("%s%s", aString.c_str(), aNoNewline ? "" : "\n");
#else
#if defined(MOZ_LOGGING)
if (MOZ_LOG_TEST(GetGFX2DLog(), PRLogLevelForLevel(aLevel))) {
PR_LogPrint("%s%s", aString.c_str(), aNoNewline ? "" : "\n");
@@ -176,6 +186,7 @@ struct BasicLogger
(aLevel < LOG_DEBUG)) {
printf("%s%s", aString.c_str(), aNoNewline ? "" : "\n");
}
#endif
}
}
};
+1 -1
View File
@@ -303,7 +303,7 @@ SkBitmap ImageOperations::ResizeSubpixel(const SkBitmap& source,
return result;
#else
return SkBitmap();
#endif // OS_POSIX && !OS_MACOSX
#endif // OS_POSIX && !OS_MACOSX && !defined(OS_ANDROID)
}
// static
+2 -2
View File
@@ -201,12 +201,12 @@ FINAL_LIBRARY = 'xul'
for var in ('USE_CAIRO', 'MOZ2D_HAS_MOZ_CAIRO'):
DEFINES[var] = True
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('gtk2', 'gtk3'):
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gtk2', 'gtk3'):
DEFINES['MOZ_ENABLE_FREETYPE'] = True
CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('gtk2', 'gtk3'):
if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gtk2', 'gtk3'):
CXXFLAGS += CONFIG['CAIRO_FT_CFLAGS']
LOCAL_INCLUDES += CONFIG['SKIA_INCLUDES']
-8
View File
@@ -172,14 +172,6 @@ EXPORTS.angle.KHR += [ 'include/KHR/khrplatform.h' ]
LOCAL_INCLUDES += [ 'include', 'src', 'src/common/third_party/numerics' ]
if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
NO_VISIBILITY_FLAGS = True
# This tells ANGLE to build the translator with declspec(dllexport) on Windows
# which we need to get these symbols exported from gkmedias
DEFINES['COMPONENT_BUILD'] = True
DEFINES['ANGLE_TRANSLATOR_IMPLEMENTATION'] = True
# We allow warnings for third-party code that can be updated from upstream.
ALLOW_COMPILER_WARNINGS = True
+3 -12
View File
@@ -863,22 +863,13 @@ gl::ErrorOrResult<GLuint> InternalFormat::computeDepthPitch(GLenum formatType,
GLint rowLength,
GLint imageHeight) const
{
CheckedNumeric<GLuint> pixelsHeight(imageHeight > 0 ? static_cast<GLuint>(imageHeight)
: static_cast<GLuint>(height));
CheckedNumeric<GLuint> rowCount;
if (compressed) {
CheckedNumeric<GLuint> checkedBlockHeight(compressedBlockHeight);
rowCount = (pixelsHeight + checkedBlockHeight - 1u) / checkedBlockHeight;
} else {
rowCount = pixelsHeight;
}
GLuint rows =
(imageHeight > 0 ? static_cast<GLuint>(imageHeight) : static_cast<GLuint>(height));
GLuint rowPitch = 0;
ANGLE_TRY_RESULT(computeRowPitch(formatType, width, alignment, rowLength), rowPitch);
CheckedNumeric<GLuint> checkedRowPitch(rowPitch);
auto depthPitch = checkedRowPitch * rowCount;
auto depthPitch = checkedRowPitch * rows;
ANGLE_TRY_CHECKED_MATH(depthPitch);
return depthPitch.ValueOrDie();
}
+5
View File
@@ -242,6 +242,11 @@ if CONFIG['CLANG_CL']:
'-Wno-unused-variable',
]
# See bug 386897.
if CONFIG['GNU_CC'] and CONFIG['OS_TARGET'] == 'Android' and CONFIG['MOZ_OPTIMIZE']:
CFLAGS += ['-O2']
CXXFLAGS += ['-O2']
if CONFIG['MOZ_X11']:
CFLAGS += CONFIG['XCFLAGS']
+4
View File
@@ -156,3 +156,7 @@ if CONFIG['CLANG_CL']:
CFLAGS += [
'-Wno-unused-variable',
]
# See bug 386897.
if CONFIG['OS_TARGET'] == 'Android' and CONFIG['MOZ_OPTIMIZE']:
CFLAGS += ['-O2']
+10
View File
@@ -94,6 +94,16 @@ PIXMAN_BEGIN_DECLS
#if defined (_SVR4) || defined (SVR4) || defined (__OpenBSD__) || defined (_sgi) || defined (__sun) || defined (sun) || defined (__digital__) || defined (__HP_cc)
# include <inttypes.h>
/* VS 2010 (_MSC_VER 1600) has stdint.h */
#elif defined (_MSC_VER) && _MSC_VER < 1600
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
# include <stdint.h>
#endif
+260
View File
@@ -0,0 +1,260 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
// vim:set ts=2 sts=2 sw=2 et cin:
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef MOZ_WIDGET_ANDROID
#include <map>
#include <android/native_window_jni.h>
#include <android/log.h>
#include "AndroidSurfaceTexture.h"
#include "gfxImageSurface.h"
#include "gfxPrefs.h"
#include "AndroidBridge.h"
#include "nsThreadUtils.h"
#include "mozilla/gfx/Matrix.h"
#include "GeneratedJNINatives.h"
#include "GLContext.h"
using namespace mozilla;
namespace mozilla {
namespace gl {
class AndroidSurfaceTexture::Listener
: public java::SurfaceTextureListener::Natives<Listener>
{
using Base = java::SurfaceTextureListener::Natives<Listener>;
const nsCOMPtr<nsIRunnable> mCallback;
public:
using Base::AttachNative;
using Base::DisposeNative;
Listener(nsIRunnable* aCallback) : mCallback(aCallback) {}
void OnFrameAvailable()
{
if (NS_IsMainThread()) {
mCallback->Run();
return;
}
NS_DispatchToMainThread(mCallback);
}
};
already_AddRefed<AndroidSurfaceTexture>
AndroidSurfaceTexture::Create()
{
return Create(nullptr, 0);
}
already_AddRefed<AndroidSurfaceTexture>
AndroidSurfaceTexture::Create(GLContext* aContext, GLuint aTexture)
{
RefPtr<AndroidSurfaceTexture> st = new AndroidSurfaceTexture();
if (!st->Init(aContext, aTexture)) {
printf_stderr("Failed to initialize AndroidSurfaceTexture");
st = nullptr;
}
return st.forget();
}
nsresult
AndroidSurfaceTexture::Attach(GLContext* aContext, PRIntervalTime aTimeout)
{
MonitorAutoLock lock(mMonitor);
if (mAttachedContext == aContext) {
NS_WARNING("Tried to attach same GLContext to AndroidSurfaceTexture");
return NS_OK;
}
if (!CanDetach()) {
return NS_ERROR_NOT_AVAILABLE;
}
while (mAttachedContext) {
// Wait until it's detached (or we time out)
if (NS_FAILED(lock.Wait(aTimeout))) {
return NS_ERROR_NOT_AVAILABLE;
}
}
MOZ_ASSERT(aContext->IsOwningThreadCurrent(), "Trying to attach GLContext from different thread");
aContext->fGenTextures(1, &mTexture);
if (NS_FAILED(mSurfaceTexture->AttachToGLContext(mTexture))) {
return NS_ERROR_NOT_AVAILABLE;
}
mAttachedContext = aContext;
mAttachedContext->MakeCurrent();
return NS_OK;
}
nsresult
AndroidSurfaceTexture::Detach()
{
MonitorAutoLock lock(mMonitor);
if (!CanDetach() ||
!mAttachedContext ||
!mAttachedContext->IsOwningThreadCurrent())
{
return NS_ERROR_FAILURE;
}
mAttachedContext->MakeCurrent();
mSurfaceTexture->DetachFromGLContext();
mTexture = 0;
mAttachedContext = nullptr;
lock.NotifyAll();
return NS_OK;
}
bool
AndroidSurfaceTexture::CanDetach() const
{
// The API for attach/detach only exists on 16+, and PowerVR has some sort of
// fencing issue. Additionally, attach/detach seems to be busted on at least
// some Mali adapters (400MP2 for sure, bug 1131793)
return AndroidBridge::Bridge()->GetAPIVersion() >= 16 &&
(!mAttachedContext || mAttachedContext->Vendor() != GLVendor::Imagination) &&
(!mAttachedContext || mAttachedContext->Vendor() != GLVendor::ARM /* Mali */) &&
gfxPrefs::SurfaceTextureDetachEnabled();
}
bool
AndroidSurfaceTexture::Init(GLContext* aContext, GLuint aTexture)
{
if (!aTexture && !CanDetach()) {
// We have no texture and cannot initialize detached, bail out
return false;
}
if (NS_WARN_IF(NS_FAILED(
java::sdk::SurfaceTexture::New(aTexture, ReturnTo(&mSurfaceTexture))))) {
return false;
}
if (!aTexture) {
mSurfaceTexture->DetachFromGLContext();
}
mAttachedContext = aContext;
if (NS_WARN_IF(NS_FAILED(
java::sdk::Surface::New(mSurfaceTexture, ReturnTo(&mSurface))))) {
return false;
}
mNativeWindow = ANativeWindow_fromSurface(jni::GetEnvForThread(),
mSurface.Get());
MOZ_ASSERT(mNativeWindow, "Failed to create native window from surface");
return true;
}
AndroidSurfaceTexture::AndroidSurfaceTexture()
: mTexture(0)
, mSurfaceTexture()
, mSurface()
, mAttachedContext(nullptr)
, mMonitor("AndroidSurfaceTexture")
{
}
AndroidSurfaceTexture::~AndroidSurfaceTexture()
{
if (mSurfaceTexture) {
SetFrameAvailableCallback(nullptr);
mSurfaceTexture = nullptr;
}
if (mNativeWindow) {
ANativeWindow_release(mNativeWindow);
mNativeWindow = nullptr;
}
}
void
AndroidSurfaceTexture::UpdateTexImage()
{
mSurfaceTexture->UpdateTexImage();
}
void
AndroidSurfaceTexture::GetTransformMatrix(gfx::Matrix4x4& aMatrix) const
{
JNIEnv* const env = jni::GetEnvForThread();
auto jarray = jni::FloatArray::LocalRef::Adopt(env, env->NewFloatArray(16));
mSurfaceTexture->GetTransformMatrix(jarray);
jfloat* array = env->GetFloatArrayElements(jarray.Get(), nullptr);
aMatrix._11 = array[0];
aMatrix._12 = array[1];
aMatrix._13 = array[2];
aMatrix._14 = array[3];
aMatrix._21 = array[4];
aMatrix._22 = array[5];
aMatrix._23 = array[6];
aMatrix._24 = array[7];
aMatrix._31 = array[8];
aMatrix._32 = array[9];
aMatrix._33 = array[10];
aMatrix._34 = array[11];
aMatrix._41 = array[12];
aMatrix._42 = array[13];
aMatrix._43 = array[14];
aMatrix._44 = array[15];
env->ReleaseFloatArrayElements(jarray.Get(), array, 0);
}
void
AndroidSurfaceTexture::SetFrameAvailableCallback(nsIRunnable* aRunnable)
{
java::SurfaceTextureListener::LocalRef newListener;
if (aRunnable) {
newListener = java::SurfaceTextureListener::New();
Listener::AttachNative(newListener, MakeUnique<Listener>(aRunnable));
}
if (aRunnable || mListener) {
MOZ_ALWAYS_TRUE(NS_SUCCEEDED(
mSurfaceTexture->SetOnFrameAvailableListener(newListener)));
}
if (mListener) {
Listener::DisposeNative(java::SurfaceTextureListener::LocalRef(
newListener.Env(), mListener));
}
mListener = newListener;
}
void
AndroidSurfaceTexture::SetDefaultSize(mozilla::gfx::IntSize size)
{
mSurfaceTexture->SetDefaultBufferSize(size.width, size.height);
}
} // gl
} // mozilla
#endif // MOZ_WIDGET_ANDROID
+107
View File
@@ -0,0 +1,107 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
// vim:set ts=2 sts=2 sw=2 et cin:
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef AndroidSurfaceTexture_h__
#define AndroidSurfaceTexture_h__
#ifdef MOZ_WIDGET_ANDROID
#include <jni.h>
#include <android/native_window.h>
#include "nsIRunnable.h"
#include "gfxPlatform.h"
#include "GLDefs.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/MatrixFwd.h"
#include "mozilla/Monitor.h"
#include "GeneratedJNIWrappers.h"
#include "SurfaceTexture.h"
namespace mozilla {
namespace gl {
class GLContext;
/**
* This class is a wrapper around Android's SurfaceTexture class.
* Usage is pretty much exactly like the Java class, so see
* the Android documentation for details.
*/
class AndroidSurfaceTexture {
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(AndroidSurfaceTexture)
public:
// The SurfaceTexture is created in an attached state. This method requires
// Android Ice Cream Sandwich.
static already_AddRefed<AndroidSurfaceTexture> Create(GLContext* aGLContext, GLuint aTexture);
// Here the SurfaceTexture will be created in a detached state. You must call
// Attach() with the GLContext you wish to composite with. It must be done
// on the thread where that GLContext is current. This method requires
// Android Jelly Bean.
static already_AddRefed<AndroidSurfaceTexture> Create();
// If we are on Jelly Bean, the SurfaceTexture can be detached and reattached
// to allow consumption from different GLContexts. It is recommended to only
// attach while you are consuming in order to allow this.
//
// Only one GLContext may be attached at any given time. If another is already
// attached, we try to wait for it to become detached.
nsresult Attach(GLContext* aContext, PRIntervalTime aTiemout = PR_INTERVAL_NO_TIMEOUT);
nsresult Detach();
// Ability to detach is based on API version (16+), and we also block PowerVR
// since it has some type of fencing problem. Bug 1100126.
bool CanDetach() const;
GLContext* AttachedContext() const { return mAttachedContext; }
ANativeWindow* NativeWindow() const {
return mNativeWindow;
}
// This attaches the updated data to the TEXTURE_EXTERNAL target
void UpdateTexImage();
void GetTransformMatrix(mozilla::gfx::Matrix4x4& aMatrix) const;
void SetDefaultSize(mozilla::gfx::IntSize size);
// The callback is guaranteed to be called on the main thread even
// if the upstream callback is received on a different thread
void SetFrameAvailableCallback(nsIRunnable* aRunnable);
GLuint Texture() const { return mTexture; }
const java::sdk::Surface::Ref& JavaSurface() const { return mSurface; }
private:
class Listener;
AndroidSurfaceTexture();
~AndroidSurfaceTexture();
bool Init(GLContext* aContext, GLuint aTexture);
GLuint mTexture;
java::sdk::SurfaceTexture::GlobalRef mSurfaceTexture;
java::sdk::Surface::GlobalRef mSurface;
java::SurfaceTextureListener::GlobalRef mListener;
GLContext* mAttachedContext;
ANativeWindow* mNativeWindow;
Monitor mMonitor;
};
}
}
#endif
#endif
+119 -1
View File
@@ -14,6 +14,12 @@
#include "mozilla/gfx/Matrix.h"
#include "mozilla/UniquePtr.h"
#ifdef MOZ_WIDGET_ANDROID
#include "AndroidSurfaceTexture.h"
#include "GLImages.h"
#include "GLLibraryEGL.h"
#endif
#ifdef XP_MACOSX
#include "MacIOSurfaceImage.h"
#include "GLContextCGL.h"
@@ -140,6 +146,26 @@ GLBlitHelper::InitTexQuadProgram(BlitType target)
vTexCoord * uTexCoordMult); \n\
} \n\
";
#ifdef ANDROID /* MOZ_WIDGET_ANDROID */
const char kTexExternalBlit_FragShaderSource[] = "\
#version 100 \n\
#extension GL_OES_EGL_image_external : require \n\
#ifdef GL_FRAGMENT_PRECISION_HIGH \n\
precision highp float; \n\
#else \n\
precision mediump float; \n\
#endif \n\
varying vec2 vTexCoord; \n\
uniform mat4 uTextureTransform; \n\
uniform samplerExternalOES uTexUnit; \n\
\n\
void main() \n\
{ \n\
gl_FragColor = texture2D(uTexUnit, \n\
(uTextureTransform * vec4(vTexCoord, 0.0, 1.0)).xy); \n\
} \n\
";
#endif
/* From Rec601:
[R] [1.1643835616438356, 0.0, 1.5960267857142858] [ Y - 16]
[G] = [1.1643835616438358, -0.3917622900949137, -0.8129676472377708] x [Cb - 128]
@@ -231,6 +257,14 @@ GLBlitHelper::InitTexQuadProgram(BlitType target)
fragShaderPtr = &mTex2DRectBlit_FragShader;
fragShaderSource = kTex2DRectBlit_FragShaderSource;
break;
#ifdef ANDROID
case ConvertSurfaceTexture:
case ConvertGralloc:
programPtr = &mTexExternalBlit_Program;
fragShaderPtr = &mTexExternalBlit_FragShader;
fragShaderSource = kTexExternalBlit_FragShaderSource;
break;
#endif
case ConvertPlanarYCbCr:
programPtr = &mTexYUVPlanarBlit_Program;
fragShaderPtr = &mTexYUVPlanarBlit_FragShader;
@@ -364,6 +398,10 @@ GLBlitHelper::InitTexQuadProgram(BlitType target)
// Cache and set attribute and uniform
mGL->fUseProgram(program);
switch (target) {
#ifdef ANDROID
case ConvertSurfaceTexture:
case ConvertGralloc:
#endif
case BlitTex2D:
case BlitTexRect:
case ConvertEGLImage: {
@@ -640,6 +678,67 @@ GLBlitHelper::BindAndUploadEGLImage(EGLImage image, GLuint target)
mGL->fEGLImageTargetTexture2D(target, image);
}
#ifdef MOZ_WIDGET_ANDROID
#define ATTACH_WAIT_MS 50
bool
GLBlitHelper::BlitSurfaceTextureImage(layers::SurfaceTextureImage* stImage)
{
AndroidSurfaceTexture* surfaceTexture = stImage->GetSurfaceTexture();
ScopedBindTextureUnit boundTU(mGL, LOCAL_GL_TEXTURE0);
if (NS_FAILED(surfaceTexture->Attach(mGL, PR_MillisecondsToInterval(ATTACH_WAIT_MS))))
return false;
// UpdateTexImage() changes the EXTERNAL binding, so save it here
// so we can restore it after.
int oldBinding = 0;
mGL->fGetIntegerv(LOCAL_GL_TEXTURE_BINDING_EXTERNAL, &oldBinding);
surfaceTexture->UpdateTexImage();
gfx::Matrix4x4 transform;
surfaceTexture->GetTransformMatrix(transform);
mGL->fUniformMatrix4fv(mTextureTransformLoc, 1, false, &transform._11);
mGL->fDrawArrays(LOCAL_GL_TRIANGLE_STRIP, 0, 4);
surfaceTexture->Detach();
mGL->fBindTexture(LOCAL_GL_TEXTURE_EXTERNAL, oldBinding);
return true;
}
bool
GLBlitHelper::BlitEGLImageImage(layers::EGLImageImage* image)
{
EGLImage eglImage = image->GetImage();
EGLSync eglSync = image->GetSync();
if (eglSync) {
EGLint status = sEGLLibrary.fClientWaitSync(EGL_DISPLAY(), eglSync, 0, LOCAL_EGL_FOREVER);
if (status != LOCAL_EGL_CONDITION_SATISFIED) {
return false;
}
}
ScopedBindTextureUnit boundTU(mGL, LOCAL_GL_TEXTURE0);
int oldBinding = 0;
mGL->fGetIntegerv(LOCAL_GL_TEXTURE_BINDING_2D, &oldBinding);
BindAndUploadEGLImage(eglImage, LOCAL_GL_TEXTURE_2D);
mGL->fDrawArrays(LOCAL_GL_TRIANGLE_STRIP, 0, 4);
mGL->fBindTexture(LOCAL_GL_TEXTURE_2D, oldBinding);
return true;
}
#endif
bool
GLBlitHelper::BlitPlanarYCbCrImage(layers::PlanarYCbCrImage* yuvImage)
{
@@ -736,6 +835,16 @@ GLBlitHelper::BlitImageToFramebuffer(layers::Image* srcImage,
srcOrigin = OriginPos::BottomLeft;
break;
#ifdef MOZ_WIDGET_ANDROID
case ImageFormat::SURFACE_TEXTURE:
type = ConvertSurfaceTexture;
srcOrigin = srcImage->AsSurfaceTextureImage()->GetOriginPos();
break;
case ImageFormat::EGLIMAGE:
type = ConvertEGLImage;
srcOrigin = srcImage->AsEGLImageImage()->GetOriginPos();
break;
#endif
#ifdef XP_MACOSX
case ImageFormat::MAC_IOSURFACE:
type = ConvertMacIOSurfaceImage;
@@ -768,6 +877,14 @@ GLBlitHelper::BlitImageToFramebuffer(layers::Image* srcImage,
return ret;
}
#ifdef MOZ_WIDGET_ANDROID
case ConvertSurfaceTexture:
return BlitSurfaceTextureImage(static_cast<layers::SurfaceTextureImage*>(srcImage));
case ConvertEGLImage:
return BlitEGLImageImage(static_cast<layers::EGLImageImage*>(srcImage));
#endif
#ifdef XP_MACOSX
case ConvertMacIOSurfaceImage:
return BlitMacIOSurfaceImage(srcImage->AsMacIOSurfaceImage());
@@ -866,7 +983,8 @@ GLBlitHelper::BlitFramebufferToTexture(GLuint srcFB, GLuint destTex,
GLenum destTarget,
bool internalFBs)
{
MOZ_ASSERT(!srcFB || mGL->fIsFramebuffer(srcFB));
// On the Android 4.3 emulator, IsFramebuffer may return false incorrectly.
MOZ_ASSERT_IF(mGL->Renderer() != GLRenderer::AndroidEmulator, !srcFB || mGL->fIsFramebuffer(srcFB));
MOZ_ASSERT(mGL->fIsTexture(destTex));
if (mGL->IsSupported(GLFeature::framebuffer_blit)) {
+5
View File
@@ -107,6 +107,11 @@ class GLBlitHelper final
void BindAndUploadEGLImage(EGLImage image, GLuint target);
bool BlitPlanarYCbCrImage(layers::PlanarYCbCrImage* yuvImage);
#ifdef MOZ_WIDGET_ANDROID
// Blit onto the current FB.
bool BlitSurfaceTextureImage(layers::SurfaceTextureImage* stImage);
bool BlitEGLImageImage(layers::EGLImageImage* eglImage);
#endif
#ifdef XP_MACOSX
bool BlitMacIOSurfaceImage(layers::MacIOSurfaceImage* ioImage);
#endif
+91 -6
View File
@@ -10,6 +10,9 @@
#include <string.h>
#include <ctype.h>
#include <vector>
#ifdef MOZ_WIDGET_ANDROID
#include <sys/mman.h>
#endif
#include "GLBlitHelper.h"
#include "GLReadTexImageHelper.h"
@@ -44,6 +47,10 @@
#include "nsCocoaFeatures.h"
#endif
#ifdef MOZ_WIDGET_ANDROID
#include "AndroidBridge.h"
#endif
namespace mozilla {
namespace gl {
@@ -227,7 +234,7 @@ ParseGLSLVersion(GLContext* gl, uint32_t* out_version)
}
if (!versionString) {
MOZ_ASSERT(false, "LOCAL_GL_SHADING_LANGUAGE_VERSION undefined, returning 100");
// This happens on the Android emulators. We'll just return 100
*out_version = 100;
return true;
}
@@ -1049,6 +1056,28 @@ GLContext::InitWithPrefixImpl(const char* prefix, bool trygl)
// prevents occasional driver crash.
mNeedsFlushBeforeDeleteFB = true;
}
#ifdef MOZ_WIDGET_ANDROID
if (mWorkAroundDriverBugs &&
(Renderer() == GLRenderer::AdrenoTM305 ||
Renderer() == GLRenderer::AdrenoTM320 ||
Renderer() == GLRenderer::AdrenoTM330) &&
AndroidBridge::Bridge()->GetAPIVersion() < 21) {
// Bug 1164027. Driver crashes when functions such as
// glTexImage2D fail due to virtual memory exhaustion.
mTextureAllocCrashesOnMapFailure = true;
}
#endif
#if MOZ_WIDGET_ANDROID
if (mWorkAroundDriverBugs &&
Renderer() == GLRenderer::SGX540 &&
AndroidBridge::Bridge()->GetAPIVersion() <= 15) {
// Bug 1288446. Driver sometimes crashes when uploading data to a
// texture if the render target has changed since the texture was
// rendered from. Calling glCheckFramebufferStatus after
// glFramebufferTexture2D prevents the crash.
mNeedsCheckAfterAttachTextureToFb = true;
}
#endif
mMaxTextureImageSize = mMaxTextureSize;
@@ -1781,6 +1810,17 @@ GLContext::InitExtensions()
MarkExtensionUnsupported(OES_EGL_sync);
}
#ifdef MOZ_WIDGET_ANDROID
if (Vendor() == GLVendor::Imagination &&
Renderer() == GLRenderer::SGX544MP &&
AndroidBridge::Bridge()->GetAPIVersion() < 21)
{
// Bug 1026404
MarkExtensionUnsupported(OES_EGL_image);
MarkExtensionUnsupported(OES_EGL_image_external);
}
#endif
if (Vendor() == GLVendor::ARM &&
(Renderer() == GLRenderer::Mali400MP ||
Renderer() == GLRenderer::Mali450MP))
@@ -1789,6 +1829,16 @@ GLContext::InitExtensions()
MarkExtensionUnsupported(OES_EGL_image_external);
}
if (Renderer() == GLRenderer::AndroidEmulator) {
// the Android emulator, which we use to run B2G reftests on,
// doesn't expose the OES_rgb8_rgba8 extension, but it seems to
// support it (tautologically, as it only runs on desktop GL).
MarkExtensionSupported(OES_rgb8_rgba8);
// there seems to be a similar issue for EXT_texture_format_BGRA8888
// on the Android 4.3 emulator
MarkExtensionSupported(EXT_texture_format_BGRA8888);
}
if (Vendor() == GLVendor::VMware &&
Renderer() == GLRenderer::GalliumLlvmpipe)
{
@@ -1807,8 +1857,8 @@ GLContext::InitExtensions()
// textures with glCompressedTexSubImage2D. Works on Intel HD 4000
// and Intel HD 5000/Iris that I tested.
// Bug 1124996: Appears to be the same on OSX Yosemite (10.10)
if (nsCocoaFeatures::macOSVersionMajor() == 10 &&
nsCocoaFeatures::macOSVersionMinor() >= 9 &&
if (nsCocoaFeatures::OSXVersionMajor() == 10 &&
nsCocoaFeatures::OSXVersionMinor() >= 9 &&
Renderer() == GLRenderer::IntelHD3000)
{
MarkExtensionUnsupported(EXT_texture_compression_s3tc);
@@ -1987,7 +2037,8 @@ GLContext::AttachBuffersToFB(GLuint colorTex, GLuint colorRB,
colorTex,
0);
} else if (colorRB) {
MOZ_ASSERT(fIsRenderbuffer(colorRB));
// On the Android 4.3 emulator, IsRenderbuffer may return false incorrectly.
MOZ_ASSERT_IF(Renderer() != GLRenderer::AndroidEmulator, fIsRenderbuffer(colorRB));
fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER,
LOCAL_GL_COLOR_ATTACHMENT0,
LOCAL_GL_RENDERBUFFER,
@@ -1995,7 +2046,7 @@ GLContext::AttachBuffersToFB(GLuint colorTex, GLuint colorRB,
}
if (depthRB) {
MOZ_ASSERT(fIsRenderbuffer(depthRB));
MOZ_ASSERT_IF(Renderer() != GLRenderer::AndroidEmulator, fIsRenderbuffer(depthRB));
fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER,
LOCAL_GL_DEPTH_ATTACHMENT,
LOCAL_GL_RENDERBUFFER,
@@ -2003,7 +2054,7 @@ GLContext::AttachBuffersToFB(GLuint colorTex, GLuint colorRB,
}
if (stencilRB) {
MOZ_ASSERT(fIsRenderbuffer(stencilRB));
MOZ_ASSERT_IF(Renderer() != GLRenderer::AndroidEmulator, fIsRenderbuffer(stencilRB));
fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER,
LOCAL_GL_STENCIL_ATTACHMENT,
LOCAL_GL_RENDERBUFFER,
@@ -2883,6 +2934,29 @@ GLContext::fDeleteFramebuffers(GLsizei n, const GLuint* names)
TRACKING_CONTEXT(DeletedFramebuffers(this, n, names));
}
#ifdef MOZ_WIDGET_ANDROID
/**
* Conservatively estimate whether there is enough available
* contiguous virtual address space to map a newly allocated texture.
*/
static bool
WillTextureMapSucceed(GLsizei width, GLsizei height, GLenum format, GLenum type)
{
bool willSucceed = false;
// Some drivers leave large gaps between textures, so require
// there to be double the actual size of the texture available.
size_t size = width * height * GetBytesPerTexel(format, type) * 2;
void *p = mmap(nullptr, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p != MAP_FAILED) {
willSucceed = true;
munmap(p, size);
}
return willSucceed;
}
#endif // MOZ_WIDGET_ANDROID
void
GLContext::fTexImage2D(GLenum target, GLint level, GLint internalformat,
GLsizei width, GLsizei height, GLint border,
@@ -2895,6 +2969,17 @@ GLContext::fTexImage2D(GLenum target, GLint level, GLint internalformat,
height = -1;
border = -1;
}
#if MOZ_WIDGET_ANDROID
if (mTextureAllocCrashesOnMapFailure) {
// We have no way of knowing whether this texture already has
// storage allocated for it, and therefore whether this check
// is necessary. We must therefore assume it does not and
// always perform the check.
if (!WillTextureMapSucceed(width, height, internalformat, type)) {
return;
}
}
#endif
raw_fTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
+13
View File
@@ -788,10 +788,18 @@ private:
static void AssertNotPassingStackBufferToTheGL(const void* ptr);
#ifdef MOZ_WIDGET_ANDROID
// Record the name of the GL call for better hang stacks on Android.
#define BEFORE_GL_CALL \
PROFILER_LABEL_FUNC( \
js::ProfileEntry::Category::GRAPHICS);\
BeforeGLCall(MOZ_FUNCTION_NAME)
#else
#define BEFORE_GL_CALL \
do { \
BeforeGLCall(MOZ_FUNCTION_NAME); \
} while (0)
#endif
#define AFTER_GL_CALL \
do { \
@@ -807,7 +815,12 @@ private:
#else // ifdef MOZ_GL_DEBUG
#ifdef MOZ_WIDGET_ANDROID
// Record the name of the GL call for better hang stacks on Android.
#define BEFORE_GL_CALL PROFILER_LABEL_FUNC(js::ProfileEntry::Category::GRAPHICS)
#else
#define BEFORE_GL_CALL do { } while (0)
#endif
#define AFTER_GL_CALL do { } while (0)
#define TRACKING_CONTEXT(a) do {} while (0)
#define ASSERT_NOT_PASSING_STACK_BUFFER_TO_GL(ptr) do {} while (0)
+83
View File
@@ -11,7 +11,20 @@
#define GET_NATIVE_WINDOW(aWidget) ((EGLNativeWindowType)aWidget->GetNativeData(NS_NATIVE_WINDOW))
#endif
#ifdef MOZ_WIDGET_ANDROID
#define GET_JAVA_SURFACE(aWidget) (aWidget->GetNativeData(NS_JAVA_SURFACE))
#endif
#if defined(XP_UNIX)
#ifdef MOZ_WIDGET_ANDROID
#include <android/native_window.h>
#include <android/native_window_jni.h>
#endif
#ifdef ANDROID
#include <android/log.h>
#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Android" , ## args)
#endif
#define GLES2_LIB "libGLESv2.so"
#define GLES2_LIB2 "libGLESv2.so.2"
@@ -151,8 +164,22 @@ CreateSurfaceForWindow(nsIWidget* widget, const EGLConfig& config) {
EGLSurface newSurface = nullptr;
MOZ_ASSERT(widget);
#ifdef MOZ_WIDGET_ANDROID
void* javaSurface = GET_JAVA_SURFACE(widget);
if (!javaSurface) {
MOZ_CRASH("GFX: Failed to get Java surface.\n");
}
JNIEnv* const env = jni::GetEnvForThread();
ANativeWindow* const nativeWindow = ANativeWindow_fromSurface(
env, reinterpret_cast<jobject>(javaSurface));
newSurface = sEGLLibrary.fCreateWindowSurface(
sEGLLibrary.fGetDisplay(EGL_DEFAULT_DISPLAY),
config, nativeWindow, 0);
ANativeWindow_release(nativeWindow);
#else
newSurface = sEGLLibrary.fCreateWindowSurface(EGL_DISPLAY(), config,
GET_NATIVE_WINDOW(widget), 0);
#endif
return newSurface;
}
@@ -202,6 +229,11 @@ GLContextEGL::~GLContextEGL()
bool
GLContextEGL::Init()
{
#if defined(ANDROID)
// We can't use LoadApitraceLibrary here because the GLContext
// expects its own handle to the GL library
if (!OpenLibrary(APITRACE_LIB))
#endif
if (!OpenLibrary(GLES2_LIB)) {
#if defined(XP_UNIX)
if (!OpenLibrary(GLES2_LIB2)) {
@@ -400,8 +432,10 @@ GLContextEGL::GetWSIInfo(nsCString* const out) const
out->AppendLiteral("\nEGL_EXTENSIONS: ");
out->Append((const char*)sEGLLibrary.fQueryString(EGL_DISPLAY(), LOCAL_EGL_EXTENSIONS));
#ifndef ANDROID // This query will crash some old android.
out->AppendLiteral("\nEGL_EXTENSIONS(nullptr): ");
out->Append((const char*)sEGLLibrary.fQueryString(nullptr, LOCAL_EGL_EXTENSIONS));
#endif
}
// hold a reference to the given surface
@@ -651,6 +685,18 @@ CreateConfig(EGLConfig* aConfig, nsIWidget* aWidget)
{
int32_t depth = gfxPlatform::GetPlatform()->GetScreenDepth();
if (!CreateConfig(aConfig, depth, aWidget)) {
#ifdef MOZ_WIDGET_ANDROID
// Bug 736005
// Android doesn't always support 16 bit so also try 24 bit
if (depth == 16) {
return CreateConfig(aConfig, 24, aWidget);
}
// Bug 970096
// Some devices that have 24 bit screens only support 16 bit OpenGL?
if (depth == 24) {
return CreateConfig(aConfig, 16, aWidget);
}
#endif
return false;
} else {
return true;
@@ -725,6 +771,43 @@ GLContextProviderEGL::CreateForWindow(nsIWidget* aWidget, bool aForceAccelerated
return gl.forget();
}
#if defined(ANDROID)
EGLSurface
GLContextProviderEGL::CreateEGLSurface(void* aWindow)
{
nsCString discardFailureId;
if (!sEGLLibrary.EnsureInitialized(false, &discardFailureId)) {
MOZ_CRASH("GFX: Failed to load EGL library 4!\n");
}
EGLConfig config;
if (!CreateConfig(&config, static_cast<nsIWidget*>(aWindow))) {
MOZ_CRASH("GFX: Failed to create EGLConfig 2!\n");
}
MOZ_ASSERT(aWindow);
EGLSurface surface = sEGLLibrary.fCreateWindowSurface(EGL_DISPLAY(), config, aWindow,
0);
if (surface == EGL_NO_SURFACE) {
MOZ_CRASH("GFX: Failed to create EGLSurface 2!\n");
}
return surface;
}
void
GLContextProviderEGL::DestroyEGLSurface(EGLSurface surface)
{
nsCString discardFailureId;
if (!sEGLLibrary.EnsureInitialized(false, &discardFailureId)) {
MOZ_CRASH("GFX: Failed to load EGL library 5!\n");
}
sEGLLibrary.fDestroySurface(EGL_DISPLAY(), surface);
}
#endif // defined(ANDROID)
static void
FillContextAttribs(bool alpha, bool depth, bool stencil, bool bpp16,
bool es3, nsTArray<EGLint>* out)
+8
View File
@@ -10,6 +10,9 @@
#ifndef GL_CONTEXT_PROVIDER_NAME
#error GL_CONTEXT_PROVIDER_NAME not defined
#endif
#if defined(ANDROID)
typedef void* EGLSurface;
#endif // defined(ANDROID)
class GL_CONTEXT_PROVIDER_NAME
{
@@ -108,6 +111,11 @@ public:
static already_AddRefed<GLContext>
CreateWrappingExisting(void* aContext, void* aSurface);
#if defined(ANDROID)
static EGLSurface CreateEGLSurface(void* aWindow);
static void DestroyEGLSurface(EGLSurface surface);
#endif // defined(ANDROID)
/**
* Get a pointer to the global context, creating it if it doesn't exist.
*/
+70 -2
View File
@@ -54,6 +54,46 @@ static const char* sEGLExtensionNames[] = {
"EGL_ANGLE_platform_angle_d3d"
};
#if defined(ANDROID)
static PRLibrary* LoadApitraceLibrary()
{
// Initialization of gfx prefs here is only needed during the unit tests...
gfxPrefs::GetSingleton();
if (!gfxPrefs::UseApitrace()) {
return nullptr;
}
static PRLibrary* sApitraceLibrary = nullptr;
if (sApitraceLibrary)
return sApitraceLibrary;
nsCString logFile = Preferences::GetCString("gfx.apitrace.logfile");
if (logFile.IsEmpty()) {
logFile = "firefox.trace";
}
// The firefox process can't write to /data/local, but it can write
// to $GRE_HOME/
nsAutoCString logPath;
logPath.AppendPrintf("%s/%s", getenv("GRE_HOME"), logFile.get());
// apitrace uses the TRACE_FILE environment variable to determine where
// to log trace output to
printf_stderr("Logging GL tracing output to %s", logPath.get());
setenv("TRACE_FILE", logPath.get(), false);
printf_stderr("Attempting load of %s\n", APITRACE_LIB);
sApitraceLibrary = PR_LoadLibrary(APITRACE_LIB);
return sApitraceLibrary;
}
#endif // ANDROID
#ifdef XP_WIN
// see the comment in GLLibraryEGL::EnsureInitialized() for the rationale here.
static PRLibrary*
@@ -308,8 +348,13 @@ GLLibraryEGL::EnsureInitialized(bool forceAccel, nsACString* const out_failureId
#else // !Windows
// On non-Windows we use system copies of libEGL. We look for
// libEGL.so and libEGL.so.1 in that order.
// On non-Windows (Android) we use system copies of libEGL. We look for
// the APITrace lib, libEGL.so, and libEGL.so.1 in that order.
#if defined(ANDROID)
if (!mEGLLibrary)
mEGLLibrary = LoadApitraceLibrary();
#endif
if (!mEGLLibrary) {
printf_stderr("Attempting load of libEGL.so\n");
@@ -548,6 +593,24 @@ GLLibraryEGL::EnsureInitialized(bool forceAccel, nsACString* const out_failureId
MarkExtensionUnsupported(KHR_image_pixmap);
}
if (IsExtensionSupported(ANDROID_native_fence_sync)) {
GLLibraryLoader::SymLoadStruct nativeFenceSymbols[] = {
{ (PRFuncPtr*) &mSymbols.fDupNativeFenceFDANDROID, { "eglDupNativeFenceFDANDROID", nullptr } },
{ nullptr, { nullptr } }
};
bool success = GLLibraryLoader::LoadSymbols(mEGLLibrary,
&nativeFenceSymbols[0],
lookupFunction);
if (!success) {
NS_ERROR("EGL supports ANDROID_native_fence_sync without exposing its functions!");
MarkExtensionUnsupported(ANDROID_native_fence_sync);
mSymbols.fDupNativeFenceFDANDROID = nullptr;
}
}
mInitialized = true;
return true;
}
@@ -579,7 +642,12 @@ GLLibraryEGL::InitClientExtensions()
const char* rawExtString = nullptr;
#ifndef ANDROID
// Bug 1209612: Crashes on a number of android drivers.
// Ideally we would only blocklist this there, but for now we don't need the client
// extension list on ANDROID (we mostly need it on ANGLE), and we'd rather not crash.
rawExtString = (const char*)fQueryString(nullptr, LOCAL_EGL_EXTENSIONS);
#endif
if (!rawExtString) {
if (shouldDumpExts) {
Loaded 100 of 25415 files, more files were not shown because too many files have changed in this diff. Show more