merge mozilla-inbound to mozilla-central a=merge
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Wed, 21 Jan 2015 14:21:49 +0100
changeset 224887 0f2b4a7a9daff18d5ae09e2e526f8f29b7b58be0
parent 224886 4135f5372644d89621d19079d7a393717a23f9e6 (current diff)
parent 224834 1533b263c457a802d3ad3bcd7aac92069f37e901 (diff)
child 224888 bd7d13e5875c5003667658b50668a8eda4688621
child 224996 6c60a49af63e74cbc80aef42cc4ade4d765ada5b
child 225023 26f23dfdca44764493d3c14037bdf82a6634530b
push id54370
push usercbook@mozilla.com
push dateWed, 21 Jan 2015 13:32:49 +0000
treeherdermozilla-inbound@bd7d13e5875c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone38.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
merge mozilla-inbound to mozilla-central a=merge
dom/base/test/TestCSPParser.cpp
dom/base/test/csp/chrome.ini
dom/base/test/csp/file_CSP.css
dom/base/test/csp/file_CSP.sjs
dom/base/test/csp/file_CSP_bug663567.xsl
dom/base/test/csp/file_CSP_bug663567_allows.xml
dom/base/test/csp/file_CSP_bug663567_allows.xml^headers^
dom/base/test/csp/file_CSP_bug663567_blocks.xml
dom/base/test/csp/file_CSP_bug663567_blocks.xml^headers^
dom/base/test/csp/file_CSP_bug802872.html
dom/base/test/csp/file_CSP_bug802872.html^headers^
dom/base/test/csp/file_CSP_bug802872.js
dom/base/test/csp/file_CSP_bug802872.sjs
dom/base/test/csp/file_CSP_bug885433_allows.html
dom/base/test/csp/file_CSP_bug885433_allows.html^headers^
dom/base/test/csp/file_CSP_bug885433_blocks.html
dom/base/test/csp/file_CSP_bug885433_blocks.html^headers^
dom/base/test/csp/file_CSP_bug888172.html
dom/base/test/csp/file_CSP_bug888172.sjs
dom/base/test/csp/file_CSP_bug909029_none.html
dom/base/test/csp/file_CSP_bug909029_none.html^headers^
dom/base/test/csp/file_CSP_bug909029_star.html
dom/base/test/csp/file_CSP_bug909029_star.html^headers^
dom/base/test/csp/file_CSP_bug910139.sjs
dom/base/test/csp/file_CSP_bug910139.xml
dom/base/test/csp/file_CSP_bug910139.xsl
dom/base/test/csp/file_CSP_bug941404.html
dom/base/test/csp/file_CSP_bug941404_xhr.html
dom/base/test/csp/file_CSP_bug941404_xhr.html^headers^
dom/base/test/csp/file_CSP_evalscript_main.html
dom/base/test/csp/file_CSP_evalscript_main.html^headers^
dom/base/test/csp/file_CSP_evalscript_main.js
dom/base/test/csp/file_CSP_evalscript_main_allowed.html
dom/base/test/csp/file_CSP_evalscript_main_allowed.html^headers^
dom/base/test/csp/file_CSP_evalscript_main_allowed.js
dom/base/test/csp/file_CSP_frameancestors.sjs
dom/base/test/csp/file_CSP_frameancestors_main.html
dom/base/test/csp/file_CSP_frameancestors_main.js
dom/base/test/csp/file_CSP_inlinescript_main.html
dom/base/test/csp/file_CSP_inlinescript_main.html^headers^
dom/base/test/csp/file_CSP_inlinescript_main_allowed.html
dom/base/test/csp/file_CSP_inlinescript_main_allowed.html^headers^
dom/base/test/csp/file_CSP_inlinestyle_main.html
dom/base/test/csp/file_CSP_inlinestyle_main.html^headers^
dom/base/test/csp/file_CSP_inlinestyle_main_allowed.html
dom/base/test/csp/file_CSP_inlinestyle_main_allowed.html^headers^
dom/base/test/csp/file_CSP_main.html
dom/base/test/csp/file_CSP_main.html^headers^
dom/base/test/csp/file_CSP_main.js
dom/base/test/csp/file_base-uri.html
dom/base/test/csp/file_bug836922_npolicies.html
dom/base/test/csp/file_bug836922_npolicies.html^headers^
dom/base/test/csp/file_bug836922_npolicies_ro_violation.sjs
dom/base/test/csp/file_bug836922_npolicies_violation.sjs
dom/base/test/csp/file_bug886164.html
dom/base/test/csp/file_bug886164.html^headers^
dom/base/test/csp/file_bug886164_2.html
dom/base/test/csp/file_bug886164_2.html^headers^
dom/base/test/csp/file_bug886164_3.html
dom/base/test/csp/file_bug886164_3.html^headers^
dom/base/test/csp/file_bug886164_4.html
dom/base/test/csp/file_bug886164_4.html^headers^
dom/base/test/csp/file_bug886164_5.html
dom/base/test/csp/file_bug886164_5.html^headers^
dom/base/test/csp/file_bug886164_6.html
dom/base/test/csp/file_bug886164_6.html^headers^
dom/base/test/csp/file_connect-src.html
dom/base/test/csp/file_csp_allow_https_schemes.html
dom/base/test/csp/file_csp_bug768029.html
dom/base/test/csp/file_csp_bug768029.sjs
dom/base/test/csp/file_csp_bug773891.html
dom/base/test/csp/file_csp_bug773891.sjs
dom/base/test/csp/file_csp_invalid_source_expression.html
dom/base/test/csp/file_csp_path_matching.html
dom/base/test/csp/file_csp_path_matching.js
dom/base/test/csp/file_csp_path_matching_redirect.html
dom/base/test/csp/file_csp_path_matching_redirect_server.sjs
dom/base/test/csp/file_csp_redirects_main.html
dom/base/test/csp/file_csp_redirects_page.sjs
dom/base/test/csp/file_csp_redirects_resource.sjs
dom/base/test/csp/file_csp_referrerdirective.html
dom/base/test/csp/file_csp_report.html
dom/base/test/csp/file_csp_testserver.sjs
dom/base/test/csp/file_form-action.html
dom/base/test/csp/file_hash_source.html
dom/base/test/csp/file_hash_source.html^headers^
dom/base/test/csp/file_leading_wildcard.html
dom/base/test/csp/file_multi_policy_injection_bypass.html
dom/base/test/csp/file_multi_policy_injection_bypass.html^headers^
dom/base/test/csp/file_multi_policy_injection_bypass_2.html
dom/base/test/csp/file_multi_policy_injection_bypass_2.html^headers^
dom/base/test/csp/file_nonce_source.html
dom/base/test/csp/file_nonce_source.html^headers^
dom/base/test/csp/file_policyuri_regression_from_multipolicy.html
dom/base/test/csp/file_policyuri_regression_from_multipolicy.html^headers^
dom/base/test/csp/file_policyuri_regression_from_multipolicy_policy
dom/base/test/csp/file_redirect_content.sjs
dom/base/test/csp/file_redirect_report.sjs
dom/base/test/csp/file_report_uri_missing_in_report_only_header.html
dom/base/test/csp/file_report_uri_missing_in_report_only_header.html^headers^
dom/base/test/csp/file_self_none_as_hostname_confusion.html
dom/base/test/csp/file_self_none_as_hostname_confusion.html^headers^
dom/base/test/csp/file_subframe_run_js_if_allowed.html
dom/base/test/csp/file_subframe_run_js_if_allowed.html^headers^
dom/base/test/csp/file_worker_redirect.html
dom/base/test/csp/file_worker_redirect.sjs
dom/base/test/csp/mochitest.ini
dom/base/test/csp/referrerdirective.sjs
dom/base/test/csp/test_301_redirect.html
dom/base/test/csp/test_302_redirect.html
dom/base/test/csp/test_303_redirect.html
dom/base/test/csp/test_307_redirect.html
dom/base/test/csp/test_CSP.html
dom/base/test/csp/test_CSP_bug663567.html
dom/base/test/csp/test_CSP_bug802872.html
dom/base/test/csp/test_CSP_bug885433.html
dom/base/test/csp/test_CSP_bug888172.html
dom/base/test/csp/test_CSP_bug909029.html
dom/base/test/csp/test_CSP_bug910139.html
dom/base/test/csp/test_CSP_bug941404.html
dom/base/test/csp/test_CSP_evalscript.html
dom/base/test/csp/test_CSP_frameancestors.html
dom/base/test/csp/test_CSP_inlinescript.html
dom/base/test/csp/test_CSP_inlinestyle.html
dom/base/test/csp/test_CSP_referrerdirective.html
dom/base/test/csp/test_base-uri.html
dom/base/test/csp/test_bug836922_npolicies.html
dom/base/test/csp/test_bug886164.html
dom/base/test/csp/test_bug949549.html
dom/base/test/csp/test_connect-src.html
dom/base/test/csp/test_csp_allow_https_schemes.html
dom/base/test/csp/test_csp_bug768029.html
dom/base/test/csp/test_csp_bug773891.html
dom/base/test/csp/test_csp_invalid_source_expression.html
dom/base/test/csp/test_csp_path_matching.html
dom/base/test/csp/test_csp_path_matching_redirect.html
dom/base/test/csp/test_csp_redirects.html
dom/base/test/csp/test_csp_report.html
dom/base/test/csp/test_form-action.html
dom/base/test/csp/test_hash_source.html
dom/base/test/csp/test_leading_wildcard.html
dom/base/test/csp/test_multi_policy_injection_bypass.html
dom/base/test/csp/test_nonce_source.html
dom/base/test/csp/test_policyuri_regression_from_multipolicy.html
dom/base/test/csp/test_report_uri_missing_in_report_only_header.html
dom/base/test/csp/test_self_none_as_hostname_confusion.html
dom/base/test/csp/test_subframe_run_js_if_allowed.html
dom/base/test/csp/test_worker_redirect.html
dom/base/test/file_CrossSiteXHR_cache_server.sjs
dom/base/test/file_CrossSiteXHR_inner.html
dom/base/test/file_CrossSiteXHR_inner.jar
dom/base/test/file_CrossSiteXHR_inner_data.sjs
dom/base/test/file_CrossSiteXHR_server.sjs
dom/base/test/mixedcontentblocker/bug803225_test_mailto.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_blankTarget.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_grandchild.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure_grandchild.html
dom/base/test/mixedcontentblocker/file_mixed_content_main.html
dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225.html
dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225_websocket_wsh.py
dom/base/test/mixedcontentblocker/file_mixed_content_server.sjs
dom/base/test/mixedcontentblocker/mochitest.ini
dom/base/test/mixedcontentblocker/test_mixed_content_blocker.html
dom/base/test/mixedcontentblocker/test_mixed_content_blocker_bug803225.html
dom/base/test/mixedcontentblocker/test_mixed_content_blocker_frameNavigation.html
dom/base/test/test_CrossSiteXHR.html
dom/base/test/test_CrossSiteXHR_cache.html
dom/base/test/test_CrossSiteXHR_origin.html
dom/base/test/unit/test_cspreports.js
media/libjpeg/README-turbo.txt
media/libjpeg/config.h
media/libjpeg/genTables.py
media/libjpeg/simd/jcclrmmx.asm
media/libjpeg/simd/jcclrss2-64.asm
media/libjpeg/simd/jcclrss2.asm
media/libjpeg/simd/jccolmmx.asm
media/libjpeg/simd/jccolss2-64.asm
media/libjpeg/simd/jccolss2.asm
media/libjpeg/simd/jcgrammx.asm
media/libjpeg/simd/jcgrass2-64.asm
media/libjpeg/simd/jcgrass2.asm
media/libjpeg/simd/jcgrymmx.asm
media/libjpeg/simd/jcgryss2-64.asm
media/libjpeg/simd/jcgryss2.asm
media/libjpeg/simd/jcqnt3dn.asm
media/libjpeg/simd/jcqntmmx.asm
media/libjpeg/simd/jcqnts2f-64.asm
media/libjpeg/simd/jcqnts2f.asm
media/libjpeg/simd/jcqnts2i-64.asm
media/libjpeg/simd/jcqnts2i.asm
media/libjpeg/simd/jcqntsse.asm
media/libjpeg/simd/jcsammmx.asm
media/libjpeg/simd/jcsamss2-64.asm
media/libjpeg/simd/jcsamss2.asm
media/libjpeg/simd/jdclrmmx.asm
media/libjpeg/simd/jdclrss2-64.asm
media/libjpeg/simd/jdclrss2.asm
media/libjpeg/simd/jdcolmmx.asm
media/libjpeg/simd/jdcolss2-64.asm
media/libjpeg/simd/jdcolss2.asm
media/libjpeg/simd/jdmermmx.asm
media/libjpeg/simd/jdmerss2-64.asm
media/libjpeg/simd/jdmerss2.asm
media/libjpeg/simd/jdmrgmmx.asm
media/libjpeg/simd/jdmrgss2-64.asm
media/libjpeg/simd/jdmrgss2.asm
media/libjpeg/simd/jdsammmx.asm
media/libjpeg/simd/jdsamss2-64.asm
media/libjpeg/simd/jdsamss2.asm
media/libjpeg/simd/jf3dnflt.asm
media/libjpeg/simd/jfmmxfst.asm
media/libjpeg/simd/jfmmxint.asm
media/libjpeg/simd/jfss2fst-64.asm
media/libjpeg/simd/jfss2fst.asm
media/libjpeg/simd/jfss2int-64.asm
media/libjpeg/simd/jfss2int.asm
media/libjpeg/simd/jfsseflt-64.asm
media/libjpeg/simd/jfsseflt.asm
media/libjpeg/simd/ji3dnflt.asm
media/libjpeg/simd/jimmxfst.asm
media/libjpeg/simd/jimmxint.asm
media/libjpeg/simd/jimmxred.asm
media/libjpeg/simd/jiss2flt-64.asm
media/libjpeg/simd/jiss2flt.asm
media/libjpeg/simd/jiss2fst-64.asm
media/libjpeg/simd/jiss2fst.asm
media/libjpeg/simd/jiss2int-64.asm
media/libjpeg/simd/jiss2int.asm
media/libjpeg/simd/jiss2red-64.asm
media/libjpeg/simd/jiss2red.asm
media/libjpeg/simd/jisseflt.asm
media/libjpeg/simd/jsimdcfg.inc
media/libjpeg/simd/moz.build
netwerk/base/public/NetStatistics.h
netwerk/base/public/ReferrerPolicy.h
netwerk/base/public/moz.build
netwerk/base/public/mozIThirdPartyUtil.idl
netwerk/base/public/netCore.h
netwerk/base/public/nsASocketHandler.h
netwerk/base/public/nsAsyncRedirectVerifyHelper.h
netwerk/base/public/nsIApplicationCache.idl
netwerk/base/public/nsIApplicationCacheChannel.idl
netwerk/base/public/nsIApplicationCacheContainer.idl
netwerk/base/public/nsIApplicationCacheService.idl
netwerk/base/public/nsIArrayBufferInputStream.idl
netwerk/base/public/nsIAsyncStreamCopier.idl
netwerk/base/public/nsIAsyncStreamCopier2.idl
netwerk/base/public/nsIAsyncVerifyRedirectCallback.idl
netwerk/base/public/nsIAuthInformation.idl
netwerk/base/public/nsIAuthModule.idl
netwerk/base/public/nsIAuthPrompt.idl
netwerk/base/public/nsIAuthPrompt2.idl
netwerk/base/public/nsIAuthPromptAdapterFactory.idl
netwerk/base/public/nsIAuthPromptCallback.idl
netwerk/base/public/nsIAuthPromptProvider.idl
netwerk/base/public/nsIBackgroundFileSaver.idl
netwerk/base/public/nsIBrowserSearchService.idl
netwerk/base/public/nsIBufferedStreams.idl
netwerk/base/public/nsIByteRangeRequest.idl
netwerk/base/public/nsICacheInfoChannel.idl
netwerk/base/public/nsICachingChannel.idl
netwerk/base/public/nsICancelable.idl
netwerk/base/public/nsIChannel.idl
netwerk/base/public/nsIChannelEventSink.idl
netwerk/base/public/nsIChildChannel.idl
netwerk/base/public/nsIClassOfService.idl
netwerk/base/public/nsIContentSniffer.idl
netwerk/base/public/nsICryptoFIPSInfo.idl
netwerk/base/public/nsICryptoHMAC.idl
netwerk/base/public/nsICryptoHash.idl
netwerk/base/public/nsIDashboard.idl
netwerk/base/public/nsIDashboardEventNotifier.idl
netwerk/base/public/nsIDivertableChannel.idl
netwerk/base/public/nsIDownloader.idl
netwerk/base/public/nsIEncodedChannel.idl
netwerk/base/public/nsIExternalProtocolHandler.idl
netwerk/base/public/nsIFileStreams.idl
netwerk/base/public/nsIFileURL.idl
netwerk/base/public/nsIForcePendingChannel.idl
netwerk/base/public/nsIHttpPushListener.idl
netwerk/base/public/nsIIOService.idl
netwerk/base/public/nsIIOService2.idl
netwerk/base/public/nsIIncrementalDownload.idl
netwerk/base/public/nsIInputStreamChannel.idl
netwerk/base/public/nsIInputStreamPump.idl
netwerk/base/public/nsILoadContextInfo.idl
netwerk/base/public/nsILoadGroup.idl
netwerk/base/public/nsILoadGroupChild.idl
netwerk/base/public/nsIMIMEInputStream.idl
netwerk/base/public/nsIMultiPartChannel.idl
netwerk/base/public/nsINSSErrorsService.idl
netwerk/base/public/nsINestedURI.idl
netwerk/base/public/nsINetAddr.idl
netwerk/base/public/nsINetUtil.idl
netwerk/base/public/nsINetworkInterceptController.idl
netwerk/base/public/nsINetworkLinkService.idl
netwerk/base/public/nsINetworkPredictor.idl
netwerk/base/public/nsINetworkPredictorVerifier.idl
netwerk/base/public/nsINetworkProperties.idl
netwerk/base/public/nsINullChannel.idl
netwerk/base/public/nsIParentChannel.idl
netwerk/base/public/nsIParentRedirectingChannel.idl
netwerk/base/public/nsIPermission.idl
netwerk/base/public/nsIPermissionManager.idl
netwerk/base/public/nsIPrivateBrowsingChannel.idl
netwerk/base/public/nsIProgressEventSink.idl
netwerk/base/public/nsIPrompt.idl
netwerk/base/public/nsIProtocolHandler.idl
netwerk/base/public/nsIProtocolProxyCallback.idl
netwerk/base/public/nsIProtocolProxyFilter.idl
netwerk/base/public/nsIProtocolProxyService.idl
netwerk/base/public/nsIProtocolProxyService2.idl
netwerk/base/public/nsIProxiedChannel.idl
netwerk/base/public/nsIProxiedProtocolHandler.idl
netwerk/base/public/nsIProxyInfo.idl
netwerk/base/public/nsIRandomGenerator.idl
netwerk/base/public/nsIRedirectChannelRegistrar.idl
netwerk/base/public/nsIRedirectHistory.idl
netwerk/base/public/nsIRedirectResultListener.idl
netwerk/base/public/nsIRequest.idl
netwerk/base/public/nsIRequestObserver.idl
netwerk/base/public/nsIRequestObserverProxy.idl
netwerk/base/public/nsIResumableChannel.idl
netwerk/base/public/nsISecretDecoderRing.idl
netwerk/base/public/nsISecureBrowserUI.idl
netwerk/base/public/nsISecurityEventSink.idl
netwerk/base/public/nsISecurityInfoProvider.idl
netwerk/base/public/nsISerializationHelper.idl
netwerk/base/public/nsIServerSocket.idl
netwerk/base/public/nsISimpleStreamListener.idl
netwerk/base/public/nsISiteSecurityService.idl
netwerk/base/public/nsISocketTransport.idl
netwerk/base/public/nsISocketTransportService.idl
netwerk/base/public/nsISpeculativeConnect.idl
netwerk/base/public/nsIStandardURL.idl
netwerk/base/public/nsIStreamListener.idl
netwerk/base/public/nsIStreamListenerTee.idl
netwerk/base/public/nsIStreamLoader.idl
netwerk/base/public/nsIStreamTransportService.idl
netwerk/base/public/nsIStreamingProtocolController.idl
netwerk/base/public/nsIStreamingProtocolService.idl
netwerk/base/public/nsISyncStreamListener.idl
netwerk/base/public/nsISystemProxySettings.idl
netwerk/base/public/nsITLSServerSocket.idl
netwerk/base/public/nsIThreadRetargetableRequest.idl
netwerk/base/public/nsIThreadRetargetableStreamListener.idl
netwerk/base/public/nsITimedChannel.idl
netwerk/base/public/nsITraceableChannel.idl
netwerk/base/public/nsITransport.idl
netwerk/base/public/nsIUDPSocket.idl
netwerk/base/public/nsIUDPSocketFilter.idl
netwerk/base/public/nsIURI.idl
netwerk/base/public/nsIURIChecker.idl
netwerk/base/public/nsIURIClassifier.idl
netwerk/base/public/nsIURIWithPrincipal.idl
netwerk/base/public/nsIURL.idl
netwerk/base/public/nsIURLParser.idl
netwerk/base/public/nsIUnicharStreamLoader.idl
netwerk/base/public/nsIUploadChannel.idl
netwerk/base/public/nsIUploadChannel2.idl
netwerk/base/public/nsNetUtil.h
netwerk/base/public/nsPILoadGroupInternal.idl
netwerk/base/public/nsPISocketTransportService.idl
netwerk/base/public/nsReadLine.h
netwerk/base/public/nsStreamListenerWrapper.h
netwerk/base/public/nsURIHashKey.h
netwerk/base/public/security-prefs.js
netwerk/base/src/ADivertableParentChannel.h
netwerk/base/src/ArrayBufferInputStream.cpp
netwerk/base/src/ArrayBufferInputStream.h
netwerk/base/src/AutoClose.h
netwerk/base/src/BackgroundFileSaver.cpp
netwerk/base/src/BackgroundFileSaver.h
netwerk/base/src/ChannelDiverterChild.cpp
netwerk/base/src/ChannelDiverterChild.h
netwerk/base/src/ChannelDiverterParent.cpp
netwerk/base/src/ChannelDiverterParent.h
netwerk/base/src/Dashboard.cpp
netwerk/base/src/Dashboard.h
netwerk/base/src/DashboardTypes.h
netwerk/base/src/EventTokenBucket.cpp
netwerk/base/src/EventTokenBucket.h
netwerk/base/src/LoadContextInfo.cpp
netwerk/base/src/LoadContextInfo.h
netwerk/base/src/NetUtil.jsm
netwerk/base/src/NetworkActivityMonitor.cpp
netwerk/base/src/NetworkActivityMonitor.h
netwerk/base/src/OfflineObserver.cpp
netwerk/base/src/OfflineObserver.h
netwerk/base/src/Predictor.cpp
netwerk/base/src/Predictor.h
netwerk/base/src/PrivateBrowsingChannel.h
netwerk/base/src/ProxyAutoConfig.cpp
netwerk/base/src/ProxyAutoConfig.h
netwerk/base/src/RedirectChannelRegistrar.cpp
netwerk/base/src/RedirectChannelRegistrar.h
netwerk/base/src/StreamingProtocolService.cpp
netwerk/base/src/StreamingProtocolService.h
netwerk/base/src/TLSServerSocket.cpp
netwerk/base/src/TLSServerSocket.h
netwerk/base/src/Tickler.cpp
netwerk/base/src/Tickler.h
netwerk/base/src/moz.build
netwerk/base/src/nsAsyncRedirectVerifyHelper.cpp
netwerk/base/src/nsAsyncStreamCopier.cpp
netwerk/base/src/nsAsyncStreamCopier.h
netwerk/base/src/nsAuthInformationHolder.cpp
netwerk/base/src/nsAuthInformationHolder.h
netwerk/base/src/nsAutodialQt.cpp
netwerk/base/src/nsAutodialQt.h
netwerk/base/src/nsAutodialWin.cpp
netwerk/base/src/nsAutodialWin.h
netwerk/base/src/nsBase64Encoder.cpp
netwerk/base/src/nsBase64Encoder.h
netwerk/base/src/nsBaseChannel.cpp
netwerk/base/src/nsBaseChannel.h
netwerk/base/src/nsBaseContentStream.cpp
netwerk/base/src/nsBaseContentStream.h
netwerk/base/src/nsBufferedStreams.cpp
netwerk/base/src/nsBufferedStreams.h
netwerk/base/src/nsChannelClassifier.cpp
netwerk/base/src/nsChannelClassifier.h
netwerk/base/src/nsDNSPrefetch.cpp
netwerk/base/src/nsDNSPrefetch.h
netwerk/base/src/nsDirectoryIndexStream.cpp
netwerk/base/src/nsDirectoryIndexStream.h
netwerk/base/src/nsDownloader.cpp
netwerk/base/src/nsDownloader.h
netwerk/base/src/nsFileStreams.cpp
netwerk/base/src/nsFileStreams.h
netwerk/base/src/nsIOService.cpp
netwerk/base/src/nsIOService.h
netwerk/base/src/nsIncrementalDownload.cpp
netwerk/base/src/nsInputStreamChannel.cpp
netwerk/base/src/nsInputStreamChannel.h
netwerk/base/src/nsInputStreamPump.cpp
netwerk/base/src/nsInputStreamPump.h
netwerk/base/src/nsLoadGroup.cpp
netwerk/base/src/nsLoadGroup.h
netwerk/base/src/nsMIMEInputStream.cpp
netwerk/base/src/nsMIMEInputStream.h
netwerk/base/src/nsMediaFragmentURIParser.cpp
netwerk/base/src/nsMediaFragmentURIParser.h
netwerk/base/src/nsNativeConnectionHelper.cpp
netwerk/base/src/nsNativeConnectionHelper.h
netwerk/base/src/nsNetAddr.cpp
netwerk/base/src/nsNetAddr.h
netwerk/base/src/nsNetSegmentUtils.h
netwerk/base/src/nsNetUtil.cpp
netwerk/base/src/nsPACMan.cpp
netwerk/base/src/nsPACMan.h
netwerk/base/src/nsPreloadedStream.cpp
netwerk/base/src/nsPreloadedStream.h
netwerk/base/src/nsProtocolProxyService.cpp
netwerk/base/src/nsProtocolProxyService.h
netwerk/base/src/nsProxyInfo.cpp
netwerk/base/src/nsProxyInfo.h
netwerk/base/src/nsRequestObserverProxy.cpp
netwerk/base/src/nsRequestObserverProxy.h
netwerk/base/src/nsSerializationHelper.cpp
netwerk/base/src/nsSerializationHelper.h
netwerk/base/src/nsServerSocket.cpp
netwerk/base/src/nsServerSocket.h
netwerk/base/src/nsSimpleNestedURI.cpp
netwerk/base/src/nsSimpleNestedURI.h
netwerk/base/src/nsSimpleStreamListener.cpp
netwerk/base/src/nsSimpleStreamListener.h
netwerk/base/src/nsSimpleURI.cpp
netwerk/base/src/nsSimpleURI.h
netwerk/base/src/nsSocketTransport2.cpp
netwerk/base/src/nsSocketTransport2.h
netwerk/base/src/nsSocketTransportService2.cpp
netwerk/base/src/nsSocketTransportService2.h
netwerk/base/src/nsStandardURL.cpp
netwerk/base/src/nsStandardURL.h
netwerk/base/src/nsStreamListenerTee.cpp
netwerk/base/src/nsStreamListenerTee.h
netwerk/base/src/nsStreamListenerWrapper.cpp
netwerk/base/src/nsStreamLoader.cpp
netwerk/base/src/nsStreamLoader.h
netwerk/base/src/nsStreamTransportService.cpp
netwerk/base/src/nsStreamTransportService.h
netwerk/base/src/nsSyncStreamListener.cpp
netwerk/base/src/nsSyncStreamListener.h
netwerk/base/src/nsTemporaryFileInputStream.cpp
netwerk/base/src/nsTemporaryFileInputStream.h
netwerk/base/src/nsTransportUtils.cpp
netwerk/base/src/nsTransportUtils.h
netwerk/base/src/nsUDPSocket.cpp
netwerk/base/src/nsUDPSocket.h
netwerk/base/src/nsURIChecker.cpp
netwerk/base/src/nsURIChecker.h
netwerk/base/src/nsURLHelper.cpp
netwerk/base/src/nsURLHelper.h
netwerk/base/src/nsURLHelperOSX.cpp
netwerk/base/src/nsURLHelperUnix.cpp
netwerk/base/src/nsURLHelperWin.cpp
netwerk/base/src/nsURLParsers.cpp
netwerk/base/src/nsURLParsers.h
netwerk/base/src/nsUnicharStreamLoader.cpp
netwerk/base/src/nsUnicharStreamLoader.h
netwerk/streamconv/public/moz.build
netwerk/streamconv/public/mozITXTToHTMLConv.idl
netwerk/streamconv/public/nsIDirIndex.idl
netwerk/streamconv/public/nsIDirIndexListener.idl
netwerk/streamconv/public/nsIStreamConverter.idl
netwerk/streamconv/public/nsIStreamConverterService.idl
netwerk/streamconv/public/nsITXTToHTMLConv.idl
netwerk/streamconv/src/moz.build
netwerk/streamconv/src/nsStreamConverterService.cpp
netwerk/streamconv/src/nsStreamConverterService.h
--- a/CLOBBER
+++ b/CLOBBER
@@ -17,9 +17,10 @@
 #
 # Modifying this file will now automatically clobber the buildbot machines \o/
 #
 
 # Are you updating CLOBBER because you think it's needed for your WebIDL
 # changes to stick? As of bug 928195, this shouldn't be necessary! Please
 # don't change CLOBBER for WebIDL changes any more.
 
-Bug 1121297 - Converted VolatileBuffer's CPP tests to GTests
+Bug 1100184 - Lots of file moves from the /netwerk flattening and zero faith
+in the build system to properly handle them.
--- a/b2g/gaia/run-b2g.c
+++ b/b2g/gaia/run-b2g.c
@@ -24,16 +24,17 @@ int main(int argc, char* argv[], char* e
     cwd = realpath(dirname(argv[0]), NULL);
     full_path = (char*) malloc(strlen(cwd) + strlen(B2G_NAME) + 2);
     if (!full_path) {
         error(NOMEM);
         return -2;
     }
     full_profile_path = (char*) malloc(strlen(cwd) + strlen(GAIA_PATH) + 2);
     if (!full_profile_path) {
+        free(full_path);
         error(NOMEM);
         return -2;
     }
     sprintf(full_path, "%s/%s", cwd, B2G_NAME);
     sprintf(full_profile_path, "%s/%s", cwd, GAIA_PATH);
     free(cwd);
     printf("Running: %s --profile %s\n", full_path, full_profile_path);
     fflush(stdout);
--- a/browser/modules/ProcessHangMonitor.jsm
+++ b/browser/modules/ProcessHangMonitor.jsm
@@ -15,20 +15,20 @@ Cu.import("resource://gre/modules/Servic
 
 /**
  * This JSM is responsible for observing content process hang reports
  * and asking the user what to do about them. See nsIHangReport for
  * the platform interface.
  */
 
 /**
- * If a hang hasn't been reported for more than 5 seconds, assume the
+ * If a hang hasn't been reported for more than 10 seconds, assume the
  * content process has gotten unstuck (and hide the hang notification).
  */
-const HANG_EXPIRATION_TIME = 5000;
+const HANG_EXPIRATION_TIME = 10000;
 
 let ProcessHangMonitor = {
   /**
    * Collection of hang reports that haven't expired or been dismissed
    * by the user. The keys are nsIHangReports and values keys are
    * timers. Each time the hang is reported, the timer is refreshed so
    * it expires after HANG_EXPIRATION_TIME.
    */
--- a/build/clang-plugin/tests/TestNoArithmeticExprInArgument.cpp
+++ b/build/clang-plugin/tests/TestNoArithmeticExprInArgument.cpp
@@ -5,19 +5,19 @@ struct X {
   void baz(int) MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT;
 };
 
 int operator+(int, X);
 int operator+(X, int);
 int operator++(X);
 
 void badArithmeticsInArgs() {
-  int a;
+  int a = 1;
   typedef int myint;
-  myint b;
+  myint b = 2;
   X goodObj1(a);
   goodObj1.baz(b);
   X badObj1(a + b); // expected-error{{cannot pass an arithmetic expression of built-in types to 'X'}}
   X badObj2 = X(a ? 0 : ++a); // expected-error{{cannot pass an arithmetic expression of built-in types to 'X'}}
   X badObj3(~a); // expected-error{{cannot pass an arithmetic expression of built-in types to 'X'}}
   badObj1.baz(a - 1 - b); // expected-error{{cannot pass an arithmetic expression of built-in types to 'baz'}}
   badObj1.baz(++a); // expected-error{{cannot pass an arithmetic expression of built-in types to 'baz'}}
   badObj1.baz(a++); // expected-error{{cannot pass an arithmetic expression of built-in types to 'baz'}}
--- a/chrome/moz.build
+++ b/chrome/moz.build
@@ -30,17 +30,17 @@ include('/ipc/chromium/chromium-config.m
 
 FINAL_LIBRARY = 'xul'
 
 GENERATED_INCLUDES += [
     '/xpcom',
 ]
 
 LOCAL_INCLUDES += [
-    '/netwerk/base/src',
+    '/netwerk/base',
     '/netwerk/protocol/res',
     '/xpcom/components'
 ]
 
 if CONFIG['MOZ_ENABLE_GTK']:
     CXXFLAGS += CONFIG['TK_CFLAGS']
 
 FAIL_ON_WARNINGS = True
--- a/configure.in
+++ b/configure.in
@@ -2206,27 +2206,25 @@ ia64*-hpux*)
         WIN32_CONSOLE_EXE_LDFLAGS=-SUBSYSTEM:CONSOLE,$WIN32_SUBSYSTEM_VERSION
         WIN32_GUI_EXE_LDFLAGS=-SUBSYSTEM:WINDOWS,$WIN32_SUBSYSTEM_VERSION
         DSO_LDOPTS=-SUBSYSTEM:WINDOWS,$WIN32_SUBSYSTEM_VERSION
         _USE_CPP_INCLUDE_FLAG=1
         _DEFINES_CFLAGS='-FI $(DEPTH)/dist/include/mozilla-config.h -DMOZILLA_CLIENT'
         _DEFINES_CXXFLAGS='-FI $(DEPTH)/dist/include/mozilla-config.h -DMOZILLA_CLIENT'
         CFLAGS="$CFLAGS -W3 -Gy"
         CXXFLAGS="$CXXFLAGS -W3 -Gy"
-        if test "$_CC_SUITE" -ge "11" -a "$CPU_ARCH" = "x86"; then
+        if test "$CPU_ARCH" = "x86"; then
             dnl VS2012+ defaults to -arch:SSE2.
             CFLAGS="$CFLAGS -arch:IA32"
             CXXFLAGS="$CXXFLAGS -arch:IA32"
         fi
-        if test "$_CC_SUITE" -ge "12"; then
-            dnl VS2013+ requires -FS when parallel building by make -jN.
-            dnl If nothing, compiler sometimes causes C1041 error.
-            CFLAGS="$CFLAGS -FS"
-            CXXFLAGS="$CXXFLAGS -FS"
-        fi
+        dnl VS2013+ requires -FS when parallel building by make -jN.
+        dnl If nothing, compiler sometimes causes C1041 error.
+        CFLAGS="$CFLAGS -FS"
+        CXXFLAGS="$CXXFLAGS -FS"
         # khuey says we can safely ignore MSVC warning C4251
         # MSVC warning C4244 (implicit type conversion may lose data) warns
         # and requires workarounds for perfectly valid code.  Also, GCC/clang
         # don't warn about it by default. So for consistency/sanity, we turn
         # it off on MSVC, too.
         # MSVC warning C4267 warns for narrowing type conversions from size_t
         # to 32-bit integer types on 64-bit platforms.  Since this is virtually
         # the same thing as C4244, we disable C4267, too.
@@ -2278,20 +2276,18 @@ ia64*-hpux*)
         dnl XXX: should be -LTCG:PGOPTIMIZE, but that fails on libxul.
         dnl Probably also a compiler bug, but what can you do?
         PROFILE_USE_LDFLAGS="-LTCG:PGUPDATE"
         LDFLAGS="$LDFLAGS -DYNAMICBASE"
         dnl Minimum reqiurement of Gecko is VS2010 or later which supports
         dnl both SSSE3 and SSE4.1.
         HAVE_TOOLCHAIN_SUPPORT_MSSSE3=1
         HAVE_TOOLCHAIN_SUPPORT_MSSE4_1=1
-        if test "$_CC_SUITE" -ge "11"; then
-            dnl allow AVX2 code from VS2012
-            HAVE_X86_AVX2=1
-        fi
+        dnl allow AVX2 code from VS2012
+        HAVE_X86_AVX2=1
         MOZ_MEMORY=1
     fi
     AC_DEFINE(HAVE_SNPRINTF)
     AC_DEFINE(_WINDOWS)
     AC_DEFINE(WIN32)
     AC_DEFINE(XP_WIN)
     AC_DEFINE(XP_WIN32)
     AC_DEFINE(HW_THREADS)
@@ -3881,16 +3877,18 @@ VPX_AS_CONVERSION=
 VPX_ASM_SUFFIX=
 VPX_X86_ASM=
 VPX_ARM_ASM=
 LIBJPEG_TURBO_AS=
 LIBJPEG_TURBO_ASFLAGS=
 LIBJPEG_TURBO_X86_ASM=
 LIBJPEG_TURBO_X64_ASM=
 LIBJPEG_TURBO_ARM_ASM=
+LIBJPEG_TURBO_ARM64_ASM=
+LIBJPEG_TURBO_MIPS_ASM=
 MOZ_PERMISSIONS=1
 MOZ_PLACES=1
 MOZ_SOCIAL=1
 MOZ_PREF_EXTENSIONS=1
 MOZ_PROFILELOCKING=1
 MOZ_REFLOW_PERF=
 MOZ_SAFE_BROWSING=
 MOZ_HELP_VIEWER=
@@ -6149,16 +6147,24 @@ if test -n "$MOZ_LIBJPEG_TURBO"; then
   WINNT:x86_64)
     LIBJPEG_TURBO_ASFLAGS="-f win64 -rnasm -pnasm -D__x86_64__ -DPIC -DWIN64 -DMSVC"
     LIBJPEG_TURBO_X64_ASM=1
   ;;
   *:arm*)
     LIBJPEG_TURBO_ASFLAGS="-march=armv7-a -mfpu=neon"
     LIBJPEG_TURBO_ARM_ASM=1
   ;;
+  *:aarch64*)
+    LIBJPEG_TURBO_ASFLAGS="-march=armv8-a"
+    LIBJPEG_TURBO_ARM64_ASM=1
+  ;;
+  *:mips*)
+    LIBJPEG_TURBO_ASFLAGS="-mdspr2"
+    LIBJPEG_TURBO_MIPS_ASM=1
+  ;;
   *:x86|*:i?86)
     if $CC -E -dM -</dev/null | grep -q __ELF__; then
       LIBJPEG_TURBO_ASFLAGS="-f elf32 -rnasm -pnasm -DPIC -DELF"
       LIBJPEG_TURBO_X86_ASM=1
     fi
   ;;
   *:x86_64)
     if $CC -E -dM -</dev/null | grep -q __ELF__; then
@@ -8826,16 +8832,18 @@ AC_SUBST(VPX_ARM_ASM)
 AC_SUBST(VPX_NEED_OBJ_INT_EXTRACT)
 AC_SUBST(MOZ_INSTRUMENT_EVENT_LOOP)
 AC_SUBST(MOZ_CODE_COVERAGE)
 AC_SUBST(LIBJPEG_TURBO_AS)
 AC_SUBST(LIBJPEG_TURBO_ASFLAGS)
 AC_SUBST(LIBJPEG_TURBO_X86_ASM)
 AC_SUBST(LIBJPEG_TURBO_X64_ASM)
 AC_SUBST(LIBJPEG_TURBO_ARM_ASM)
+AC_SUBST(LIBJPEG_TURBO_ARM64_ASM)
+AC_SUBST(LIBJPEG_TURBO_MIPS_ASM)
 
 AC_SUBST(MOZ_PACKAGE_JSSHELL)
 AC_SUBST(MOZ_FOLD_LIBS)
 
 AC_SUBST(MOZ_ENABLE_SZIP)
 AC_SUBST(MOZ_SZIP_FLAGS)
 
 dnl Host JavaScript runtime, if any, to use during cross compiles.
--- a/dom/base/moz.build
+++ b/dom/base/moz.build
@@ -406,17 +406,17 @@ LOCAL_INCLUDES += [
     '/js/ipc',
     '/js/xpconnect/src',
     '/js/xpconnect/wrappers',
     '/layout/base',
     '/layout/generic',
     '/layout/style',
     '/layout/svg',
     '/layout/xul',
-    '/netwerk/base/src',
+    '/netwerk/base',
     '/widget',
     '/xpcom/ds',
 ]
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
     LOCAL_INCLUDES += [
         '../fmradio',
         '../system/gonk',
--- a/dom/events/Event.cpp
+++ b/dom/events/Event.cpp
@@ -504,16 +504,18 @@ Event::PreventDefaultInternal(bool aCall
   mEvent->mFlags.mDefaultPrevented = true;
 
   // Note that even if preventDefault() has already been called by chrome,
   // a call of preventDefault() by content needs to overwrite
   // mDefaultPreventedByContent to true because in such case, defaultPrevented
   // must be true when web apps check it after they call preventDefault().
   if (!aCalledByDefaultHandler) {
     mEvent->mFlags.mDefaultPreventedByContent = true;
+  } else {
+    mEvent->mFlags.mDefaultPreventedByChrome = true;
   }
 
   if (!IsTrusted()) {
     return;
   }
 
   WidgetDragEvent* dragEvent = mEvent->AsDragEvent();
   if (!dragEvent) {
@@ -564,16 +566,18 @@ Event::InitEvent(const nsAString& aEvent
   }
 
   SetEventType(aEventTypeArg);
 
   mEvent->mFlags.mBubbles = aCanBubbleArg;
   mEvent->mFlags.mCancelable = aCancelableArg;
 
   mEvent->mFlags.mDefaultPrevented = false;
+  mEvent->mFlags.mDefaultPreventedByContent = false;
+  mEvent->mFlags.mDefaultPreventedByChrome = false;
 
   // Clearing the old targets, so that the event is targeted correctly when
   // re-dispatching it.
   mEvent->target = nullptr;
   mEvent->originalTarget = nullptr;
   return NS_OK;
 }
 
--- a/dom/html/HTMLMediaElement.cpp
+++ b/dom/html/HTMLMediaElement.cpp
@@ -199,17 +199,17 @@ protected:
   bool IsCancelled() {
     return mElement->GetCurrentLoadID() != mLoadID;
   }
 
   nsRefPtr<HTMLMediaElement> mElement;
   uint32_t mLoadID;
 };
 
-class nsAsyncEventRunner : public nsMediaEvent
+class HTMLMediaElement::nsAsyncEventRunner : public nsMediaEvent
 {
 private:
   nsString mName;
 
 public:
   nsAsyncEventRunner(const nsAString& aName, HTMLMediaElement* aElement) :
     nsMediaEvent(aElement), mName(aName)
   {
--- a/dom/html/HTMLMediaElement.h
+++ b/dom/html/HTMLMediaElement.h
@@ -212,18 +212,16 @@ public:
   virtual void NotifySuspendedByCache(bool aIsSuspended) MOZ_FINAL MOZ_OVERRIDE;
 
   // Called by the media decoder and the video frame to get the
   // ImageContainer containing the video data.
   virtual VideoFrameContainer* GetVideoFrameContainer() MOZ_FINAL MOZ_OVERRIDE;
   layers::ImageContainer* GetImageContainer();
 
   // Dispatch events
-  using nsGenericHTMLElement::DispatchEvent;
-  virtual nsresult DispatchEvent(const nsAString& aName) MOZ_FINAL MOZ_OVERRIDE;
   virtual nsresult DispatchAsyncEvent(const nsAString& aName) MOZ_FINAL MOZ_OVERRIDE;
 
   // Dispatch events that were raised while in the bfcache
   nsresult DispatchPendingMediaEvents();
 
   // Called by the decoder when some data has been downloaded or
   // buffering/seeking has ended. aNextFrameAvailable is true when
   // the data for the next frame is available. This method will
@@ -975,16 +973,21 @@ protected:
   // in the element's list of text tracks whose text track mode is not disabled
   // and whose text track readiness state is loading.
   void PopulatePendingTextTrackList();
 
   // Gets a reference to the MediaElement's TextTrackManager. If the
   // MediaElement doesn't yet have one then it will create it.
   TextTrackManager* GetOrCreateTextTrackManager();
 
+  class nsAsyncEventRunner;
+  using nsGenericHTMLElement::DispatchEvent;
+  // For nsAsyncEventRunner.
+  nsresult DispatchEvent(const nsAString& aName);
+
   // The current decoder. Load() has been called on this decoder.
   // At most one of mDecoder and mSrcStream can be non-null.
   nsRefPtr<MediaDecoder> mDecoder;
 
   // A reference to the VideoFrameContainer which contains the current frame
   // of video to display.
   nsRefPtr<VideoFrameContainer> mVideoFrameContainer;
 
--- a/dom/html/moz.build
+++ b/dom/html/moz.build
@@ -236,12 +236,12 @@ LOCAL_INCLUDES += [
     '/dom/xul',
     '/editor/libeditor',
     '/editor/txmgr',
     '/layout/forms',
     '/layout/generic',
     '/layout/style',
     '/layout/tables',
     '/layout/xul',
-    '/netwerk/base/src',
+    '/netwerk/base',
 ]
 
 FINAL_LIBRARY = 'xul'
new file mode 100644
--- /dev/null
+++ b/dom/html/test/file_fullscreen-esc-context-menu.html
@@ -0,0 +1,100 @@
+<!DOCTYPE html>
+<html lang="en">
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=910532
+
+Verify that an ESC key press canceling the context menu
+won't exit DOM fullscreen.
+-->
+<head>
+  <meta charset="UTF-8">
+  <title>Text for bug 910532</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <script type="application/javascript" src="file_fullscreen-utils.js"></script>
+  <style>
+    body:-moz-full-screen {
+      background-color: red;
+    }
+  </style>
+</head>
+<body>
+<script type="application/javascript">
+
+const Ci = SpecialPowers.Ci;
+
+SimpleTest.requestFlakyTimeout("We need to wait a small time to confirm " +
+  "that the first ESC key does not exit fullscreen.");
+
+function ok(condition, msg) {
+  opener.ok(condition, "[esc-context-menu] " + msg);
+}
+
+function is(a, b, msg) {
+  opener.is(a, b, "[esc-context-menu] " + msg);
+}
+
+var contextMenu;
+var escapeSent = 0;
+
+function sendEscape() {
+  escapeSent++;
+  synthesizeKey("VK_ESCAPE", {});
+}
+
+function begin() {
+  // Copy from browser/base/content/test/general/test_contextmenu.html
+  var chromeWin = SpecialPowers.wrap(window)
+                    .QueryInterface(Ci.nsIInterfaceRequestor)
+                    .getInterface(Ci.nsIWebNavigation)
+                    .QueryInterface(Ci.nsIDocShellTreeItem)
+                    .rootTreeItem
+                    .QueryInterface(Ci.nsIInterfaceRequestor)
+                    .getInterface(Ci.nsIDOMWindow)
+                    .QueryInterface(Ci.nsIDOMChromeWindow);
+  contextMenu = chromeWin.document.getElementById("contentAreaContextMenu");
+  ok(contextMenu, "Got context menu XUL");
+
+  addFullscreenChangeContinuation("enter", fullscreenEntered);
+  SpecialPowers.setBoolPref("full-screen-api.approval-required", false);
+  document.body.mozRequestFullScreen();
+}
+
+function finish() {
+  SpecialPowers.clearUserPref("full-screen-api.approval-required");
+  opener.nextTest();
+}
+
+function fullscreenEntered(event) {
+  ok(document.mozFullScreen, "Should have entered fullscreen mode");
+  is(document.mozFullScreenElement, document.body, "FSE should be doc");
+  contextMenu.addEventListener("popupshown", contextMenuOpened, false);
+  is(contextMenu.state, "closed", "Should not have opened context menu");
+  synthesizeMouseAtCenter(document.body, {type: 'contextmenu', button: 2});
+}
+
+function contextMenuOpened(event) {
+  contextMenu.removeEventListener("popupshown", contextMenuOpened);
+  is(contextMenu.state, "open", "Should have opened context menu");
+  addFullscreenChangeContinuation("exit", fullscreenExited);
+  contextMenu.addEventListener("popuphidden", contextMenuClosed, false);
+  sendEscape();
+}
+
+function contextMenuClosed(event) {
+  is(contextMenu.state, "closed", "Should have closed context menu");
+  setTimeout(function () {
+    ok(document.mozFullScreen, "Should still be in fullscreen mode");
+    sendEscape();
+  }, 100);
+}
+
+function fullscreenExited(event) {
+  is(escapeSent, 2, "Only the second escape should exit fullscreen");
+  ok(!document.mozFullScreen, "Should have left fullscreen mode");
+  finish();
+}
+
+</script>
+</body>
+</html>
--- a/dom/html/test/mochitest.ini
+++ b/dom/html/test/mochitest.ini
@@ -46,16 +46,17 @@ support-files =
   file_bug893537.html
   file_formSubmission_img.jpg
   file_formSubmission_text.txt
   file_fullscreen-ancestor-stacking-context.html
   file_fullscreen-api-keys.html
   file_fullscreen-api.html
   file_fullscreen-denied-inner.html
   file_fullscreen-denied.html
+  file_fullscreen-esc-context-menu.html
   file_fullscreen-esc-exit-inner.html
   file_fullscreen-esc-exit.html
   file_fullscreen-hidden.html
   file_fullscreen-multiple-inner.html
   file_fullscreen-multiple.html
   file_fullscreen-navigation.html
   file_fullscreen-plugins.html
   file_fullscreen-rollback.html
--- a/dom/html/test/test_fullscreen-api.html
+++ b/dom/html/test/test_fullscreen-api.html
@@ -34,16 +34,17 @@ SimpleTest.requestFlakyTimeout("untriage
 
 // Run the tests which go full-screen in new windows, as mochitests normally
 // run in an iframe, which by default will not have the allowfullscreen
 // attribute set, so full-screen won't work.
 var gTestWindows = [
   "file_fullscreen-ancestor-stacking-context.html",
   "file_fullscreen-multiple.html",
   "file_fullscreen-rollback.html",
+  "file_fullscreen-esc-context-menu.html",
   "file_fullscreen-esc-exit.html",
   "file_fullscreen-denied.html",
   "file_fullscreen-api.html",
   "file_fullscreen-api-keys.html",
   "file_fullscreen-plugins.html",
   "file_fullscreen-hidden.html",
   "file_fullscreen-svg-element.html",
   "file_fullscreen-navigation.html"
--- a/dom/ipc/moz.build
+++ b/dom/ipc/moz.build
@@ -127,17 +127,17 @@ LOCAL_INCLUDES += [
     '/dom/workers',
     '/editor/libeditor',
     '/embedding/components/printingui/ipc',
     '/extensions/cookie',
     '/extensions/spellcheck/src',
     '/hal/sandbox',
     '/js/ipc',
     '/layout/base',
-    '/netwerk/base/src',
+    '/netwerk/base',
     '/toolkit/xre',
     '/uriloader/exthandler',
     '/widget',
     '/xpcom/base',
     '/xpcom/threads',
 ]
 
 DEFINES['BIN_SUFFIX'] = '"%s"' % CONFIG['BIN_SUFFIX']
--- a/dom/jsurl/moz.build
+++ b/dom/jsurl/moz.build
@@ -11,14 +11,14 @@ EXPORTS += [
 UNIFIED_SOURCES += [
     'nsJSProtocolHandler.cpp',
 ]
 
 FAIL_ON_WARNINGS = True
 
 LOCAL_INCLUDES += [
     "/dom/base",
-    "/netwerk/base/src",
+    "/netwerk/base",
 ]
 
 FINAL_LIBRARY = 'xul'
 
 MOCHITEST_MANIFESTS += ['test/mochitest.ini']
--- a/dom/media/MediaDecoder.cpp
+++ b/dom/media/MediaDecoder.cpp
@@ -1248,17 +1248,17 @@ void MediaDecoder::DurationChanged()
   mDuration = mDecoderStateMachine ? mDecoderStateMachine->GetDuration() : -1;
   // Duration has changed so we should recompute playback rate
   UpdatePlaybackRate();
 
   SetInfinite(mDuration == -1);
 
   if (mOwner && oldDuration != mDuration && !IsInfinite()) {
     DECODER_LOG("Duration changed to %lld", mDuration);
-    mOwner->DispatchEvent(NS_LITERAL_STRING("durationchange"));
+    mOwner->DispatchAsyncEvent(NS_LITERAL_STRING("durationchange"));
   }
 }
 
 void MediaDecoder::SetDuration(double aDuration)
 {
   MOZ_ASSERT(NS_IsMainThread());
   if (mozilla::IsInfinite(aDuration)) {
     SetInfinite(true);
--- a/dom/media/MediaDecoderOwner.h
+++ b/dom/media/MediaDecoderOwner.h
@@ -16,19 +16,16 @@ class HTMLMediaElement;
 }
 
 class MediaDecoderOwner
 {
 public:
   // Called by the media decoder to indicate that the download is progressing.
   virtual void DownloadProgressed() = 0;
 
-  // Dispatch a synchronous event to the decoder owner
-  virtual nsresult DispatchEvent(const nsAString& aName) = 0;
-
   // Dispatch an asynchronous event to the decoder owner
   virtual nsresult DispatchAsyncEvent(const nsAString& aName) = 0;
 
   /**
    * Fires a timeupdate event. If aPeriodic is true, the event will only
    * be fired if we've not fired a timeupdate event (for any reason) in the
    * last 250ms, as required by the spec when the current time is periodically
    * increasing during playback.
--- a/dom/media/PeerConnection.js
+++ b/dom/media/PeerConnection.js
@@ -328,79 +328,102 @@ RTCPeerConnection.prototype = {
       rtcConfig.iceServers =
         JSON.parse(Services.prefs.getCharPref("media.peerconnection.default_iceservers"));
     }
     this._winID = this._win.QueryInterface(Ci.nsIInterfaceRequestor)
       .getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID;
     this._mustValidateRTCConfiguration(rtcConfig,
         "RTCPeerConnection constructor passed invalid RTCConfiguration");
     if (_globalPCList._networkdown || !this._win.navigator.onLine) {
-      throw new this._win.DOMError("InvalidStateError",
-          "Can't create RTCPeerConnections when the network is down");
+      throw new this._win.DOMException(
+          "Can't create RTCPeerConnections when the network is down",
+          "InvalidStateError");
     }
 
     this.makeGetterSetterEH("onaddstream");
     this.makeGetterSetterEH("onaddtrack");
     this.makeGetterSetterEH("onicecandidate");
     this.makeGetterSetterEH("onnegotiationneeded");
     this.makeGetterSetterEH("onsignalingstatechange");
     this.makeGetterSetterEH("onremovestream");
     this.makeGetterSetterEH("ondatachannel");
     this.makeGetterSetterEH("oniceconnectionstatechange");
     this.makeGetterSetterEH("onidentityresult");
     this.makeGetterSetterEH("onpeeridentity");
     this.makeGetterSetterEH("onidpassertionerror");
     this.makeGetterSetterEH("onidpvalidationerror");
 
     this._pc = new this._win.PeerConnectionImpl();
-    this._taskChain = this._win.Promise.resolve();
+    this._operationsChain = this._win.Promise.resolve();
 
     this.__DOM_IMPL__._innerObject = this;
     this._observer = new this._win.PeerConnectionObserver(this.__DOM_IMPL__);
 
     // Add a reference to the PeerConnection to global list (before init).
     _globalPCList.addPC(this);
 
     this._impl.initialize(this._observer, this._win, rtcConfig,
                           Services.tm.currentThread);
     this._initIdp();
     _globalPCList.notifyLifecycleObservers(this, "initialized");
   },
 
   get _impl() {
     if (!this._pc) {
-      throw new this._win.DOMError("InvalidStateError",
-          "RTCPeerConnection is gone (did you enter Offline mode?)");
+      throw new this._win.DOMException(
+          "RTCPeerConnection is gone (did you enter Offline mode?)",
+          "InvalidStateError");
     }
     return this._pc;
   },
 
   _initIdp: function() {
     let prefName = "media.peerconnection.identity.timeout";
     let idpTimeout = Services.prefs.getIntPref(prefName);
     let warningFunc = this.logWarning.bind(this);
     this._localIdp = new PeerConnectionIdp(this._win, idpTimeout, warningFunc,
                                            this.dispatchEvent.bind(this));
     this._remoteIdp = new PeerConnectionIdp(this._win, idpTimeout, warningFunc,
                                             this.dispatchEvent.bind(this));
   },
 
-  /**
-   * Add a function to the task chain.
-   *   onSuccess - legacy callback (optional)
-   *   onError   - legacy callback (optional)
-   */
-  _queue: function(func, onSuccess, onError) {
-    let p = this._taskChain.then(() => {
-      this._checkClosed(); // TODO: Move outside promise once Bug 1107592 is fixed.
+  // Add a function to the internal operations chain.
+
+  _chain: function(func) {
+    this._checkClosed(); // out here DOMException line-numbers work.
+    let p = this._operationsChain.then(() => {
+      // Don't _checkClosed() inside the chain, because it throws, and spec
+      // behavior as of this writing is to NOT reject outstanding promises on
+      // close. This is what happens most of the time anyways, as the c++ code
+      // stops calling us once closed, hanging the chain. However, c++ may
+      // already have queued tasks on us, so if we're one of those then sit back.
+      if (!this._closed) {
+        return func();
+      }
+    });
+    // don't propagate errors in the operations chain (this is a fork of p).
+    this._operationsChain = p.catch(() => {});
+    return p;
+  },
+
+  // This wrapper helps implement legacy callbacks in a manner that produces
+  // correct line-numbers in errors, provided that methods validate their inputs
+  // before putting themselves on the pc's operations chain.
+
+  _legacyCatch: function(onSuccess, onError, func) {
+    if (!onSuccess) {
       return func();
-    });
-    this._taskChain = p.catch(() => {}); // don't propagate errors in taskChain!
-    return onSuccess? p.then(this._wrapLegacyCallback(onSuccess),
-                             this._wrapLegacyCallback(onError)) : p;
+    }
+    try {
+      return func().then(this._wrapLegacyCallback(onSuccess),
+                         this._wrapLegacyCallback(onError));
+    } catch (e) {
+      this._wrapLegacyCallback(onError)(e);
+      return this._win.Promise.resolve(); // avoid webidl TypeError
+    }
   },
 
   _wrapLegacyCallback: function(func) {
     return result => {
       try {
         func && func(result);
       } catch (e) {
         this.logErrorAndCallOnError(e);
@@ -412,65 +435,64 @@ RTCPeerConnection.prototype = {
    * An RTCConfiguration looks like this:
    *
    * { "iceServers": [ { url:"stun:stun.example.org" },
    *                   { url:"turn:turn.example.org",
    *                     username:"jib", credential:"mypass"} ] }
    *
    * WebIDL normalizes structure for us, so we test well-formed stun/turn urls,
    * but not validity of servers themselves, before passing along to C++.
-   * ErrorMsg is passed in to detail which array-entry failed, if any.
+   *
+   *   msg - Error message to detail which array-entry failed, if any.
    */
-  _mustValidateRTCConfiguration: function(rtcConfig, errorMsg) {
-    var errorCtor = this._win.DOMError;
-    var warningFunc = this.logWarning.bind(this);
-    function nicerNewURI(uriStr, errorMsg) {
-      let ios = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);
+  _mustValidateRTCConfiguration: function(rtcConfig, msg) {
+    let ios = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);
+
+    let nicerNewURI = uriStr => {
       try {
         return ios.newURI(uriStr, null, null);
       } catch (e if (e.result == Cr.NS_ERROR_MALFORMED_URI)) {
-        throw new errorCtor("", errorMsg + " - malformed URI: " + uriStr);
+        throw new this._win.DOMException(msg + " - malformed URI: " + uriStr,
+                                         "SyntaxError");
       }
-    }
-    function mustValidateServer(server) {
+    };
+
+    rtcConfig.iceServers.forEach(server => {
       if (!server.url) {
-        throw new errorCtor("", errorMsg + " - missing url");
+        throw new this._win.DOMException(msg + " - missing url", "InvalidAccessError");
       }
-      let url = nicerNewURI(server.url, errorMsg);
+      let url = nicerNewURI(server.url);
       if (url.scheme in { turn:1, turns:1 }) {
         if (!server.username) {
-          throw new errorCtor("", errorMsg + " - missing username: " + server.url);
+          throw new this._win.DOMException(msg + " - missing username: " + server.url,
+                                           "InvalidAccessError");
         }
         if (!server.credential) {
-          throw new errorCtor("", errorMsg + " - missing credential: " +
-                              server.url);
+          throw new this._win.DOMException(msg + " - missing credential: " + server.url,
+                                           "InvalidAccessError");
         }
       }
       else if (!(url.scheme in { stun:1, stuns:1 })) {
-        throw new errorCtor("", errorMsg + " - improper scheme: " + url.scheme);
+        throw new this._win.DOMException(msg + " - improper scheme: " + url.scheme,
+                                         "SyntaxError");
       }
       if (url.scheme in { stuns:1, turns:1 }) {
-        warningFunc(url.scheme.toUpperCase() + " is not yet supported.", null, 0);
+        this.logWarning(url.scheme.toUpperCase() + " is not yet supported.", null, 0);
       }
-    }
-    if (rtcConfig.iceServers) {
-      let len = rtcConfig.iceServers.length;
-      for (let i=0; i < len; i++) {
-        mustValidateServer (rtcConfig.iceServers[i], errorMsg);
-      }
-    }
+    });
   },
 
   // Ideally, this should be of the form _checkState(state),
   // where the state is taken from an enumeration containing
   // the valid peer connection states defined in the WebRTC
   // spec. See Bug 831756.
   _checkClosed: function() {
     if (this._closed) {
-      throw new this._win.DOMError("InvalidStateError", "Peer connection is closed");
+      throw new this._win.DOMException("Peer connection is closed",
+                                       "InvalidStateError");
     }
   },
 
   dispatchEvent: function(event) {
     // PC can close while events are firing if there is an async dispatch
     // in c++ land
     if (!this._closed) {
       this.__DOM_IMPL__.dispatchEvent(event);
@@ -524,237 +546,178 @@ RTCPeerConnection.prototype = {
     Object.defineProperty(this, name,
                           {
                             get:function()  { return this.getEH(name); },
                             set:function(h) { return this.setEH(name, h); }
                           });
   },
 
   createOffer: function(optionsOrOnSuccess, onError, options) {
-
-    // TODO: Remove old constraint-like RTCOptions support soon (Bug 1064223).
-    // Note that webidl bindings make o.mandatory implicit but not o.optional.
-    function convertLegacyOptions(o) {
-      // Detect (mandatory OR optional) AND no other top-level members.
-      let lcy = ((o.mandatory && Object.keys(o.mandatory).length) || o.optional) &&
-                Object.keys(o).length == (o.mandatory? 1 : 0) + (o.optional? 1 : 0);
-      if (!lcy) {
-        return false;
-      }
-      let old = o.mandatory || {};
-      if (o.mandatory) {
-        delete o.mandatory;
-      }
-      if (o.optional) {
-        o.optional.forEach(one => {
-          // The old spec had optional as an array of objects w/1 attribute each.
-          // Assumes our JS-webidl bindings only populate passed-in properties.
-          let key = Object.keys(one)[0];
-          if (key && old[key] === undefined) {
-            old[key] = one[key];
-          }
-        });
-        delete o.optional;
-      }
-      o.offerToReceiveAudio = old.OfferToReceiveAudio;
-      o.offerToReceiveVideo = old.OfferToReceiveVideo;
-      o.mozDontOfferDataChannel = old.MozDontOfferDataChannel;
-      o.mozBundleOnly = old.MozBundleOnly;
-      Object.keys(o).forEach(k => {
-        if (o[k] === undefined) {
-          delete o[k];
-        }
-      });
-      return true;
-    }
-
     let onSuccess;
-    if (optionsOrOnSuccess && typeof optionsOrOnSuccess === "function") {
+    if (typeof optionsOrOnSuccess == "function") {
       onSuccess = optionsOrOnSuccess;
     } else {
       options = optionsOrOnSuccess;
-      onError = undefined;
     }
-    if (options && convertLegacyOptions(options)) {
-      this.logWarning(
-          "Mandatory/optional in createOffer options is deprecated! Use " +
-          JSON.stringify(options) + " instead (note the case difference)!",
-          null, 0);
-    }
-    return this._queue(() => this._createOffer(options), onSuccess, onError);
-  },
+    return this._legacyCatch(onSuccess, onError, () => {
 
-  _createOffer: function(options) {
-    return new this._win.Promise((resolve, reject) => {
-      this._onCreateOfferSuccess = resolve;
-      this._onCreateOfferFailure = reject;
-      this._impl.createOffer(options);
-    });
-  },
+      // TODO: Remove old constraint-like RTCOptions support soon (Bug 1064223).
+      // Note that webidl bindings make o.mandatory implicit but not o.optional.
+      function convertLegacyOptions(o) {
+        // Detect (mandatory OR optional) AND no other top-level members.
+        let lcy = ((o.mandatory && Object.keys(o.mandatory).length) || o.optional) &&
+                  Object.keys(o).length == (o.mandatory? 1 : 0) + (o.optional? 1 : 0);
+        if (!lcy) {
+          return false;
+        }
+        let old = o.mandatory || {};
+        if (o.mandatory) {
+          delete o.mandatory;
+        }
+        if (o.optional) {
+          o.optional.forEach(one => {
+            // The old spec had optional as an array of objects w/1 attribute each.
+            // Assumes our JS-webidl bindings only populate passed-in properties.
+            let key = Object.keys(one)[0];
+            if (key && old[key] === undefined) {
+              old[key] = one[key];
+            }
+          });
+          delete o.optional;
+        }
+        o.offerToReceiveAudio = old.OfferToReceiveAudio;
+        o.offerToReceiveVideo = old.OfferToReceiveVideo;
+        o.mozDontOfferDataChannel = old.MozDontOfferDataChannel;
+        o.mozBundleOnly = old.MozBundleOnly;
+        Object.keys(o).forEach(k => {
+          if (o[k] === undefined) {
+            delete o[k];
+          }
+        });
+        return true;
+      }
 
-  _createAnswer: function() {
-    return new this._win.Promise((resolve, reject) => {
-      if (!this.remoteDescription) {
-        throw new this._win.DOMError("InvalidStateError",
-                                     "setRemoteDescription not called");
+      if (options && convertLegacyOptions(options)) {
+        this.logWarning(
+            "Mandatory/optional in createOffer options is deprecated! Use " +
+            JSON.stringify(options) + " instead (note the case difference)!",
+            null, 0);
       }
-      if (this.remoteDescription.type != "offer") {
-        throw new this._win.DOMError("InvalidStateError",
-                                     "No outstanding offer");
-      }
-      this._onCreateAnswerSuccess = resolve;
-      this._onCreateAnswerFailure = reject;
-      this._impl.createAnswer();
+      return this._chain(() => new this._win.Promise((resolve, reject) => {
+        this._onCreateOfferSuccess = resolve;
+        this._onCreateOfferFailure = reject;
+        this._impl.createOffer(options);
+      }));
     });
   },
 
   createAnswer: function(onSuccess, onError) {
-    return this._queue(() => this._createAnswer(), onSuccess, onError);
+    return this._legacyCatch(onSuccess, onError, () => {
+      return this._chain(() => new this._win.Promise((resolve, reject) => {
+        // We give up line-numbers in errors by doing this here, but do all
+        // state-checks inside the chain, to support the legacy feature that
+        // callers don't have to wait for setRemoteDescription to finish.
+        if (!this.remoteDescription) {
+          throw new this._win.DOMException("setRemoteDescription not called",
+                                           "InvalidStateError");
+        }
+        if (this.remoteDescription.type != "offer") {
+          throw new this._win.DOMException("No outstanding offer",
+                                           "InvalidStateError");
+        }
+        this._onCreateAnswerSuccess = resolve;
+        this._onCreateAnswerFailure = reject;
+        this._impl.createAnswer();
+      }));
+    });
   },
 
   setLocalDescription: function(desc, onSuccess, onError) {
-    this._localType = desc.type;
+    return this._legacyCatch(onSuccess, onError, () => {
+      this._localType = desc.type;
 
-    let type;
-    switch (desc.type) {
-      case "offer":
-        type = Ci.IPeerConnection.kActionOffer;
-        break;
-      case "answer":
-        type = Ci.IPeerConnection.kActionAnswer;
-        break;
-      case "pranswer":
-        throw new this._win.DOMError("NotSupportedError", "pranswer not yet implemented");
-      default:
-        throw new this._win.DOMError("InvalidParameterError",
-            "Invalid type " + desc.type + " provided to setLocalDescription");
-    }
-
-    return this._queue(() => this._setLocalDescription(type, desc.sdp),
-                       onSuccess, onError);
-  },
-
-  _setLocalDescription: function(type, sdp) {
-    return new this._win.Promise((resolve, reject) => {
-      this._onSetLocalDescriptionSuccess = resolve;
-      this._onSetLocalDescriptionFailure = reject;
-      this._impl.setLocalDescription(type, sdp);
+      let type;
+      switch (desc.type) {
+        case "offer":
+          type = Ci.IPeerConnection.kActionOffer;
+          break;
+        case "answer":
+          type = Ci.IPeerConnection.kActionAnswer;
+          break;
+        case "pranswer":
+          throw new this._win.DOMException("pranswer not yet implemented",
+                                           "NotSupportedError");
+        default:
+          throw new this._win.DOMException(
+              "Invalid type " + desc.type + " provided to setLocalDescription",
+              "InvalidParameterError");
+      }
+      return this._chain(() => new this._win.Promise((resolve, reject) => {
+        this._onSetLocalDescriptionSuccess = resolve;
+        this._onSetLocalDescriptionFailure = reject;
+        this._impl.setLocalDescription(type, desc.sdp);
+      }));
     });
   },
 
   setRemoteDescription: function(desc, onSuccess, onError) {
-    this._remoteType = desc.type;
-
-    let type;
-    switch (desc.type) {
-      case "offer":
-        type = Ci.IPeerConnection.kActionOffer;
-        break;
-      case "answer":
-        type = Ci.IPeerConnection.kActionAnswer;
-        break;
-      case "pranswer":
-        throw new this._win.DOMError("NotSupportedError", "pranswer not yet implemented");
-      default:
-        throw new this._win.DOMError("InvalidParameterError",
-            "Invalid type " + desc.type + " provided to setRemoteDescription");
-    }
-
-    // Have to get caller's origin outside of Promise constructor and pass it in
-    let origin = Cu.getWebIDLCallerPrincipal().origin;
-
-    return this._queue(() => this._setRemoteDescription(type, desc.sdp, origin),
-                       onSuccess, onError);
-  },
+    return this._legacyCatch(onSuccess, onError, () => {
+      this._remoteType = desc.type;
 
-  /**
-   * Takes a result from the IdP and checks it against expectations.
-   * If OK, generates events.
-   * Returns true if it is either present and valid, or if there is no
-   * need for identity.
-   */
-  _processIdpResult: function(message) {
-    let good = !!message;
-    // This might be a valid assertion, but if we are constrained to a single peer
-    // identity, then we also need to make sure that the assertion matches
-    if (good && this._impl.peerIdentity) {
-      good = (message.identity === this._impl.peerIdentity);
-    }
-    if (good) {
-      this._impl.peerIdentity = message.identity;
-      this._peerIdentity = new this._win.RTCIdentityAssertion(
-        this._remoteIdp.provider, message.identity);
-      this.dispatchEvent(new this._win.Event("peeridentity"));
-    }
-    return good;
-  },
+      let type;
+      switch (desc.type) {
+        case "offer":
+          type = Ci.IPeerConnection.kActionOffer;
+          break;
+        case "answer":
+          type = Ci.IPeerConnection.kActionAnswer;
+          break;
+        case "pranswer":
+          throw new this._win.DOMException("pranswer not yet implemented",
+                                           "NotSupportedError");
+        default:
+          throw new this._win.DOMException(
+              "Invalid type " + desc.type + " provided to setRemoteDescription",
+              "InvalidParameterError");
+      }
 
-  _setRemoteDescription: function(type, sdp, origin) {
-    return new this._win.Promise((resolve, reject) =>
-      this._setRemoteDescriptionImpl(type, sdp, origin, resolve, reject));
-  },
+      // Get caller's origin before chaining and pass it in
+      let origin = Cu.getWebIDLCallerPrincipal().origin;
+
+      return this._chain(() => {
+        let expectedIdentity = this._impl.peerIdentity;
 
-  _setRemoteDescriptionImpl: function(type, sdp, origin, onSuccess, onError) {
-    let idpComplete = false;
-    let setRemoteComplete = false;
-    let idpError = null;
-    let isDone = false;
-
-    // we can run the IdP validation in parallel with setRemoteDescription this
-    // complicates much more than would be ideal, but it ensures that the IdP
-    // doesn't hold things up too much when it's not on the critical path
-    let allDone = () => {
-      if (!setRemoteComplete || !idpComplete || isDone) {
-        return;
-      }
-      // May be null if the user didn't supply success/failure callbacks.
-      // Violation of spec, but we allow it for now
-      onSuccess();
-      isDone = true;
-    };
-
-    let setRemoteDone = () => {
-      setRemoteComplete = true;
-      allDone();
-    };
+        // Do setRemoteDescription and identity validation in parallel
+        let p = new this._win.Promise((resolve, reject) => {
+          this._onSetRemoteDescriptionSuccess = resolve;
+          this._onSetRemoteDescriptionFailure = reject;
+          this._impl.setRemoteDescription(type, desc.sdp);
+        });
 
-    // If we aren't waiting for something specific, allow this
-    // to complete asynchronously.
-    let idpDone;
-    if (!this._impl.peerIdentity) {
-      idpDone = this._processIdpResult.bind(this);
-      idpComplete = true; // lie about this for allDone()
-    } else {
-      idpDone = message => {
-        let idpGood = this._processIdpResult(message);
-        if (!idpGood) {
-          // iff we are waiting for a very specific peerIdentity
-          // call the error callback directly and then close
-          idpError = "Peer Identity mismatch, expected: " +
-            this._impl.peerIdentity;
-          onError(idpError);
-          this.close();
-        } else {
-          idpComplete = true;
-          allDone();
-        }
-      };
-    }
-
-    try {
-      this._remoteIdp.verifyIdentityFromSDP(sdp, origin, idpDone);
-    } catch (e) {
-      // if processing the SDP for identity doesn't work
-      this.logWarning(e.message, e.fileName, e.lineNumber);
-      idpDone(null);
-    }
-
-    this._onSetRemoteDescriptionSuccess = setRemoteDone;
-    this._onSetRemoteDescriptionFailure = onError;
-    this._impl.setRemoteDescription(type, sdp);
+        let pp = new Promise(resolve =>
+            this._remoteIdp.verifyIdentityFromSDP(desc.sdp, origin, resolve))
+        .then(msg => {
+          // If this pc has an identity already, then identity in sdp must match
+          if (expectedIdentity && (!msg || msg.identity !== expectedIdentity)) {
+            throw new this._win.DOMException(
+                "Peer Identity mismatch, expected: " + expectedIdentity,
+                "IncompatibleSessionDescriptionError");
+          }
+          if (msg) {
+            // Set new identity and generate an event.
+            this._impl.peerIdentity = msg.identity;
+            this._peerIdentity = new this._win.RTCIdentityAssertion(
+              this._remoteIdp.provider, msg.identity);
+            this.dispatchEvent(new this._win.Event("peeridentity"));
+          }
+        });
+        // Only wait for Idp validation if we need identity matching.
+        return expectedIdentity? this._win.Promise.all([p, pp]).then(() => {}) : p;
+      });
+    });
   },
 
   setIdentityProvider: function(provider, protocol, username) {
     this._checkClosed();
     this._localIdp.setIdentityProvider(provider, protocol, username);
   },
 
   _gotIdentityAssertion: function(assertion){
@@ -772,73 +735,74 @@ RTCPeerConnection.prototype = {
       }
     };
 
     this._localIdp.getIdentityAssertion(this._impl.fingerprint,
                                         gotAssertion);
   },
 
   updateIce: function(config) {
-    throw new this._win.DOMError("NotSupportedError", "updateIce not yet implemented");
+    throw new this._win.DOMException("updateIce not yet implemented",
+                                     "NotSupportedError");
   },
 
-  addIceCandidate: function(cand, onSuccess, onError) {
-    if (!cand.candidate && !cand.sdpMLineIndex) {
-      throw new this._win.DOMError("InvalidParameterError",
-          "Invalid candidate passed to addIceCandidate!");
-    }
-    return this._queue(() => this._addIceCandidate(cand), onSuccess, onError);
-  },
-
-  _addIceCandidate: function(cand) {
-    return new this._win.Promise((resolve, reject) => {
-      this._onAddIceCandidateSuccess = resolve;
-      this._onAddIceCandidateError = reject;
-
-      this._impl.addIceCandidate(cand.candidate, cand.sdpMid || "",
-                                 cand.sdpMLineIndex);
+  addIceCandidate: function(c, onSuccess, onError) {
+    return this._legacyCatch(onSuccess, onError, () => {
+      if (!c.candidate && !c.sdpMLineIndex) {
+        throw new this._win.DOMException("Invalid candidate passed to addIceCandidate!",
+                                         "InvalidParameterError");
+      }
+      return this._chain(() => new this._win.Promise((resolve, reject) => {
+        this._onAddIceCandidateSuccess = resolve;
+        this._onAddIceCandidateError = reject;
+        this._impl.addIceCandidate(c.candidate, c.sdpMid || "", c.sdpMLineIndex);
+      }));
     });
   },
 
   addStream: function(stream) {
     stream.getTracks().forEach(track => this.addTrack(track, stream));
   },
 
   removeStream: function(stream) {
      // Bug 844295: Not implementing this functionality.
-     throw new this._win.DOMError("NotSupportedError", "removeStream not yet implemented");
+     throw new this._win.DOMException("removeStream not yet implemented",
+                                      "NotSupportedError");
   },
 
   getStreamById: function(id) {
-    throw new this._win.DOMError("NotSupportedError", "getStreamById not yet implemented");
+    throw new this._win.DOMException("getStreamById not yet implemented",
+                                     "NotSupportedError");
   },
 
   addTrack: function(track, stream) {
     if (stream.currentTime === undefined) {
-      throw new this._win.DOMError("InvalidParameterError", "invalid stream.");
+      throw new this._win.DOMException("invalid stream.", "InvalidParameterError");
     }
-    if (stream.getTracks().indexOf(track) == -1) {
-      throw new this._win.DOMError("InvalidParameterError", "track is not in stream.");
+    if (stream.getTracks().indexOf(track) < 0) {
+      throw new this._win.DOMException("track is not in stream.",
+                                       "InvalidParameterError");
     }
     this._checkClosed();
     this._impl.addTrack(track, stream);
     let sender = this._win.RTCRtpSender._create(this._win,
                                                 new RTCRtpSender(this, track,
                                                                  stream));
     this._senders.push({ sender: sender, stream: stream });
     return sender;
   },
 
   removeTrack: function(sender) {
      // Bug 844295: Not implementing this functionality.
-     throw new this._win.DOMError("NotSupportedError", "removeTrack not yet implemented");
+     throw new this._win.DOMException("removeTrack not yet implemented",
+                                      "NotSupportedError");
   },
 
   _replaceTrack: function(sender, withTrack) {
-    // TODO: Do a (sender._stream.getTracks().indexOf(track) == -1) check
+    // TODO: Do a (sender._stream.getTracks().indexOf(track) < 0) check
     //       on both track args someday.
     //
     // The proposed API will be that both tracks must already be in the same
     // stream. However, since our MediaStreams currently are limited to one
     // track per type, we allow replacement with an outside track not already
     // in the same stream.
     //
     // Since a track may be replaced more than once, the track being replaced
@@ -956,24 +920,22 @@ RTCPeerConnection.prototype = {
 
   changeIceConnectionState: function(state) {
     this._iceConnectionState = state;
     _globalPCList.notifyLifecycleObservers(this, "iceconnectionstatechange");
     this.dispatchEvent(new this._win.Event("iceconnectionstatechange"));
   },
 
   getStats: function(selector, onSuccess, onError) {
-    return this._queue(() => this._getStats(selector), onSuccess, onError);
-  },
-
-  _getStats: function(selector) {
-    return new this._win.Promise((resolve, reject) => {
-      this._onGetStatsSuccess = resolve;
-      this._onGetStatsFailure = reject;
-      this._impl.getStats(selector);
+    return this._legacyCatch(onSuccess, onError, () => {
+      return this._chain(() => new this._win.Promise((resolve, reject) => {
+        this._onGetStatsSuccess = resolve;
+        this._onGetStatsFailure = reject;
+        this._impl.getStats(selector);
+      }));
     });
   },
 
   createDataChannel: function(label, dict) {
     this._checkClosed();
     if (dict == undefined) {
       dict = {};
     }
@@ -990,20 +952,20 @@ RTCPeerConnection.prototype = {
       dict.negotiated = dict.preset;
       this.logWarning("Deprecated RTCDataChannelInit dictionary entry preset used!", null, 0);
     }
     if (dict.stream != undefined) {
       dict.id = dict.stream;
       this.logWarning("Deprecated RTCDataChannelInit dictionary entry stream used!", null, 0);
     }
 
-    if (dict.maxRetransmitTime != undefined &&
-        dict.maxRetransmits != undefined) {
-      throw new this._win.DOMError("InvalidParameterError",
-          "Both maxRetransmitTime and maxRetransmits cannot be provided");
+    if (dict.maxRetransmitTime !== null && dict.maxRetransmits !== null) {
+      throw new this._win.DOMException(
+          "Both maxRetransmitTime and maxRetransmits cannot be provided",
+          "InvalidParameterError");
     }
     let protocol;
     if (dict.protocol == undefined) {
       protocol = "";
     } else {
       protocol = dict.protocol;
     }
 
@@ -1038,32 +1000,32 @@ PeerConnectionObserver.prototype = {
   QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
                                          Ci.nsIDOMGlobalPropertyInitializer]),
   init: function(win) { this._win = win; },
 
   __init: function(dompc) {
     this._dompc = dompc._innerObject;
   },
 
-  newError: function(code, message) {
+  newError: function(message, code) {
     // These strings must match those defined in the WebRTC spec.
     const reasonName = [
       "",
       "InternalError",
       "InvalidCandidateError",
       "InvalidParameter",
       "InvalidStateError",
       "InvalidSessionDescriptionError",
       "IncompatibleSessionDescriptionError",
       "InternalError",
       "IncompatibleMediaStreamTrackError",
       "InternalError"
     ];
     let name = reasonName[Math.min(code, reasonName.length - 1)];
-    return new this._dompc._win.DOMError(name, message);
+    return new this._dompc._win.DOMException(message, name);
   },
 
   dispatchEvent: function(event) {
     this._dompc.dispatchEvent(event);
   },
 
   onCreateOfferSuccess: function(sdp) {
     let pc = this._dompc;
@@ -1074,60 +1036,60 @@ PeerConnectionObserver.prototype = {
         pc._gotIdentityAssertion(assertion);
       }
       pc._onCreateOfferSuccess(new pc._win.mozRTCSessionDescription({ type: "offer",
                                                                       sdp: sdp }));
     }.bind(this));
   },
 
   onCreateOfferError: function(code, message) {
-    this._dompc._onCreateOfferFailure(this.newError(code, message));
+    this._dompc._onCreateOfferFailure(this.newError(message, code));
   },
 
   onCreateAnswerSuccess: function(sdp) {
     let pc = this._dompc;
     let fp = pc._impl.fingerprint;
     let origin = Cu.getWebIDLCallerPrincipal().origin;
     pc._localIdp.appendIdentityToSDP(sdp, fp, origin, function(sdp, assertion) {
       if (assertion) {
         pc._gotIdentityAssertion(assertion);
       }
       pc._onCreateAnswerSuccess(new pc._win.mozRTCSessionDescription({ type: "answer",
                                                                        sdp: sdp }));
     }.bind(this));
   },
 
   onCreateAnswerError: function(code, message) {
-    this._dompc._onCreateAnswerFailure(this.newError(code, message));
+    this._dompc._onCreateAnswerFailure(this.newError(message, code));
   },
 
   onSetLocalDescriptionSuccess: function() {
     this._dompc._onSetLocalDescriptionSuccess();
   },
 
   onSetRemoteDescriptionSuccess: function() {
     this._dompc._onSetRemoteDescriptionSuccess();
   },
 
   onSetLocalDescriptionError: function(code, message) {
     this._localType = null;
-    this._dompc._onSetLocalDescriptionFailure(this.newError(code, message));
+    this._dompc._onSetLocalDescriptionFailure(this.newError(message, code));
   },
 
   onSetRemoteDescriptionError: function(code, message) {
     this._remoteType = null;
-    this._dompc._onSetRemoteDescriptionFailure(this.newError(code, message));
+    this._dompc._onSetRemoteDescriptionFailure(this.newError(message, code));
   },
 
   onAddIceCandidateSuccess: function() {
     this._dompc._onAddIceCandidateSuccess();
   },
 
   onAddIceCandidateError: function(code, message) {
-    this._dompc._onAddIceCandidateError(this.newError(code, message));
+    this._dompc._onAddIceCandidateError(this.newError(message, code));
   },
 
   onIceCandidate: function(level, mid, candidate) {
     if (candidate == "") {
       this.foundIceCandidate(null);
     } else {
       this.foundIceCandidate(new this._dompc._win.mozRTCIceCandidate(
           {
@@ -1245,17 +1207,17 @@ PeerConnectionObserver.prototype = {
     let chromeobj = new RTCStatsReport(this._dompc._win, dict);
     let webidlobj = this._dompc._win.RTCStatsReport._create(this._dompc._win,
                                                             chromeobj);
     chromeobj.makeStatsPublic();
     this._dompc._onGetStatsSuccess(webidlobj);
   },
 
   onGetStatsError: function(code, message) {
-    this._dompc._onGetStatsFailure(this.newError(code, message));
+    this._dompc._onGetStatsFailure(this.newError(message, code));
   },
 
   onAddStream: function(stream) {
     let ev = new this._dompc._win.MediaStreamEvent("addstream",
                                                    { stream: stream });
     this.dispatchEvent(ev);
   },
 
@@ -1282,17 +1244,17 @@ PeerConnectionObserver.prototype = {
     pc._onReplaceTrackSender = null;
     pc._onReplaceTrackSuccess();
   },
 
   onReplaceTrackError: function(code, message) {
     var pc = this._dompc;
     pc._onReplaceTrackWithTrack = null;
     pc._onReplaceTrackSender = null;
-    pc._onReplaceTrackError(this.newError(code, message));
+    pc._onReplaceTrackError(this.newError(message, code));
   },
 
   foundIceCandidate: function(cand) {
     this.dispatchEvent(new this._dompc._win.RTCPeerConnectionIceEvent("icecandidate",
                                                                       { candidate: cand } ));
   },
 
   notifyDataChannel: function(channel) {
@@ -1328,17 +1290,17 @@ function RTCRtpSender(pc, track, stream)
 }
 RTCRtpSender.prototype = {
   classDescription: "RTCRtpSender",
   classID: PC_SENDER_CID,
   contractID: PC_SENDER_CONTRACT,
   QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports]),
 
   replaceTrack: function(withTrack) {
-    return this._pc._queue(() => this._pc._replaceTrack(this, withTrack));
+    return this._pc._chain(() => this._pc._replaceTrack(this, withTrack));
   }
 };
 
 function RTCRtpReceiver(pc, track) {
   this.pc = pc;
   this.track = track;
 }
 RTCRtpReceiver.prototype = {
--- a/dom/media/PeerConnectionIdp.jsm
+++ b/dom/media/PeerConnectionIdp.jsm
@@ -90,19 +90,22 @@ PeerConnectionIdp.prototype = {
       m = sdp.match(PeerConnectionIdp._fingerprintPattern);
     }
 
     return Object.keys(fingerprints).map(k => fingerprints[k]);
   },
 
   _getIdentityFromSdp: function(sdp) {
     // a=identity is session level
+    let idMatch;
     let mLineMatch = sdp.match(PeerConnectionIdp._mLinePattern);
-    let sessionLevel = sdp.substring(0, mLineMatch.index);
-    let idMatch = sessionLevel.match(PeerConnectionIdp._identityPattern);
+    if (mLineMatch) {
+      let sessionLevel = sdp.substring(0, mLineMatch.index);
+      idMatch = sessionLevel.match(PeerConnectionIdp._identityPattern);
+    }
     if (idMatch) {
       let assertion = {};
       try {
         assertion = JSON.parse(atob(idMatch[1]));
       } catch (e) {
         this.reportError("validation",
                          "invalid identity assertion: " + e);
       } // for JSON.parse
--- a/dom/media/fmp4/wmf/WMFVideoMFTManager.cpp
+++ b/dom/media/fmp4/wmf/WMFVideoMFTManager.cpp
@@ -13,16 +13,17 @@
 #include "DXVA2Manager.h"
 #include "nsThreadUtils.h"
 #include "Layers.h"
 #include "mozilla/layers/LayersTypes.h"
 #include "mp4_demuxer/AnnexB.h"
 #include "mp4_demuxer/DecoderData.h"
 #include "prlog.h"
 #include "gfx2DGlue.h"
+#include "gfxWindowsPlatform.h"
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* GetDemuxerLog();
 #define LOG(...) PR_LOG(GetDemuxerLog(), PR_LOG_DEBUG, (__VA_ARGS__))
 #else
 #define LOG(...)
 #endif
 
@@ -144,16 +145,20 @@ WMFVideoMFTManager::InitializeDXVA()
   // to a halt, and makes playback performance *worse*.
   if (!mDXVAEnabled ||
       (mLayersBackend != LayersBackend::LAYERS_D3D9 &&
        mLayersBackend != LayersBackend::LAYERS_D3D10 &&
        mLayersBackend != LayersBackend::LAYERS_D3D11)) {
     return false;
   }
 
+  if (gfxWindowsPlatform::GetPlatform()->IsWARP()) {
+    return false;
+  }
+
   // The DXVA manager must be created on the main thread.
   nsRefPtr<CreateDXVAManagerEvent> event(new CreateDXVAManagerEvent());
   NS_DispatchToMainThread(event, NS_DISPATCH_SYNC);
   mDXVA2Manager = event->mDXVA2Manager;
 
   return mDXVA2Manager != nullptr;
 }
 
--- a/dom/media/fmp4/wmf/moz.build
+++ b/dom/media/fmp4/wmf/moz.build
@@ -17,8 +17,10 @@ UNIFIED_SOURCES += [
     'WMFDecoderModule.cpp',
     'WMFMediaDataDecoder.cpp',
     'WMFVideoMFTManager.cpp',
 ]
 
 FINAL_LIBRARY = 'xul'
 
 FAIL_ON_WARNINGS = True
+
+CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
--- a/dom/media/gmp/GMPChild.cpp
+++ b/dom/media/gmp/GMPChild.cpp
@@ -312,17 +312,17 @@ GMPChild::PreLoadLibraries(const std::st
   nsCOMPtr<nsIFile> infoFile;
   GetInfoFile(aPluginPath, infoFile);
 
   nsString path;
   infoFile->GetPath(path);
 
   std::ifstream stream;
 #ifdef _MSC_VER
-  stream.open(path.get());
+  stream.open(static_cast<const wchar_t*>(path.get()));
 #else
   stream.open(NS_ConvertUTF16toUTF8(path).get());
 #endif
   if (!stream.good()) {
     NS_WARNING("Failure opening info file for required DLLs");
     return false;
   }
 
--- a/dom/media/gtest/MockMediaDecoderOwner.h
+++ b/dom/media/gtest/MockMediaDecoderOwner.h
@@ -8,20 +8,16 @@
 #include "MediaDecoderOwner.h"
 
 namespace mozilla
 {
 
 class MockMediaDecoderOwner : public MediaDecoderOwner
 {
 public:
-  virtual nsresult DispatchEvent(const nsAString& aName) MOZ_OVERRIDE
-  {
-    return NS_OK;
-  }
   virtual nsresult DispatchAsyncEvent(const nsAString& aName) MOZ_OVERRIDE
   {
     return NS_OK;
   }
   virtual void FireTimeUpdate(bool aPeriodic) MOZ_OVERRIDE {}
   virtual bool GetPaused() MOZ_OVERRIDE { return false; }
   virtual void MetadataLoaded(const MediaInfo* aInfo,
                               nsAutoPtr<const MetadataTags> aTags) MOZ_OVERRIDE
--- a/dom/media/mediasource/TrackBuffer.cpp
+++ b/dom/media/mediasource/TrackBuffer.cpp
@@ -334,17 +334,17 @@ TrackBuffer::EvictData(double aPlaybackT
         buffered->GetEndTime() < 0.0) {
       MSE_DEBUG("TrackBuffer(%p):EvictData remove empty decoders=%d", this, i);
       RemoveDecoder(decoders[i]);
     }
   }
 
   bool evicted = toEvict < (totalSize - aThreshold);
   if (evicted) {
-    nsRefPtr<TimeRanges> ranges = new TimeRanges();
+    nsRefPtr<dom::TimeRanges> ranges = new dom::TimeRanges();
     mCurrentDecoder->GetBuffered(ranges);
     *aBufferStartTime = std::max(0.0, ranges->GetStartTime());
   }
 
   return evicted;
 }
 
 void
--- a/dom/media/mediasource/test/test_DurationUpdated.html
+++ b/dom/media/mediasource/test/test_DurationUpdated.html
@@ -22,35 +22,35 @@ runWithMSE(function (ms, v) {
     fetchWithXHR("seek.webm", function (arrayBuffer) {
       sb.appendBuffer(new Uint8Array(arrayBuffer, 0, 318));
       sb.addEventListener("updateend", function () {
         updateCount++;
         if (updateCount == 1) {
           v.addEventListener("loadedmetadata", function () {
             v.addEventListener("durationchange", function () {
               durationChangeCount++;
-              if (durationChangeCount == 1) {
-                sb.addEventListener('updateend', function(e) {
-                  sb.removeEventListener('updateend', arguments.callee);
-                  sb.appendBuffer(new Uint8Array(arrayBuffer, 318));
-                });
-              }
             });
             // Set mediasource duration to 0, so future appendBuffer
             // will update the mediasource duration
             // setting ms.duration will fire updatestart/update/updateend
-            //  event as per w3c spec
+            // event as per w3c spec followed by a durationchange
             ms.duration = 0;
           });
+        } else if (updateCount == 2) {
+          // will fire updatestart/update/updateend
+          // and a durationchange
+          sb.appendBuffer(new Uint8Array(arrayBuffer, 318));
+        } else if (updateCount == 3) {
+          // this will not fire durationchange as new duration == old duration
+          ms.endOfStream();
         }
       });
     });
   });
-
-  v.addEventListener("loadeddata", function () {
+  ms.addEventListener("sourceended", function () {
     // XXX: Duration should be exactly 4.0, see bug 1065207.
     is(durationChangeCount, 2, "durationchange not fired as many times as expected");
     ok(Math.abs(v.duration - 4) <= 0.002, "Video has correct duration");
     SimpleTest.finish();
   });
 });
 
 </script>
--- a/dom/media/moz.build
+++ b/dom/media/moz.build
@@ -246,17 +246,17 @@ FAIL_ON_WARNINGS = True
 MSVC_ENABLE_PGO = True
 
 LOCAL_INCLUDES += [
     '/caps',
     '/dom/base',
     '/dom/camera',
     '/layout/generic',
     '/layout/xul',
-    '/netwerk/base/src',
+    '/netwerk/base',
 ]
 
 if CONFIG['MOZ_DIRECTSHOW']:
     LOCAL_INCLUDES += [
         '/media/webrtc/trunk/webrtc/modules/video_capture/windows',
     ]
 
 if CONFIG['MOZ_WEBRTC']:
--- a/dom/media/omx/MediaCodecProxy.cpp
+++ b/dom/media/omx/MediaCodecProxy.cpp
@@ -506,35 +506,43 @@ bool MediaCodecProxy::Prepare()
     return false;
   }
 
   return true;
 }
 
 bool MediaCodecProxy::UpdateOutputBuffers()
 {
-  if (mCodec == nullptr) {
-    MCP_LOG("MediaCodec has not been inited from input!");
-    return false;
+  // Read Lock for mCodec
+  {
+    RWLock::AutoRLock autolock(mCodecLock);
+    if (mCodec == nullptr) {
+      MCP_LOG("MediaCodec has not been inited from UpdateOutputBuffers");
+      return false;
+    }
   }
 
   status_t err = getOutputBuffers(&mOutputBuffers);
   if (err != OK){
     MCP_LOG("Couldn't update output buffers from MediaCodec");
     return false;
   }
   return true;
 }
 
 status_t MediaCodecProxy::Input(const uint8_t* aData, uint32_t aDataSize,
                                 int64_t aTimestampUsecs, uint64_t aflags)
 {
-  if (mCodec == nullptr) {
-    MCP_LOG("MediaCodec has not been inited from input!");
-    return NO_INIT;
+  // Read Lock for mCodec
+  {
+    RWLock::AutoRLock autolock(mCodecLock);
+    if (mCodec == nullptr) {
+      MCP_LOG("MediaCodec has not been inited from input!");
+      return NO_INIT;
+    }
   }
 
   size_t index;
   status_t err = dequeueInputBuffer(&index, TIMEOUT_DEQUEUE_INPUTBUFFER_MS);
   if (err != OK) {
     MCP_LOG("dequeueInputBuffer returned %d", err);
     return err;
   }
@@ -555,19 +563,23 @@ status_t MediaCodecProxy::Input(const ui
     MCP_LOG("queueInputBuffer returned %d", err);
     return err;
   }
   return err;
 }
 
 status_t MediaCodecProxy::Output(MediaBuffer** aBuffer, int64_t aTimeoutUs)
 {
-  if (mCodec == nullptr) {
-    MCP_LOG("MediaCodec has not been inited from output!");
-    return NO_INIT;
+  // Read Lock for mCodec
+  {
+    RWLock::AutoRLock autolock(mCodecLock);
+    if (mCodec == nullptr) {
+      MCP_LOG("MediaCodec has not been inited from output!");
+      return NO_INIT;
+    }
   }
 
   size_t index = 0;
   size_t offset = 0;
   size_t size = 0;
   int64_t timeUs = 0;
   uint32_t flags = 0;
 
--- a/dom/media/omx/MediaCodecReader.cpp
+++ b/dom/media/omx/MediaCodecReader.cpp
@@ -28,16 +28,17 @@
 #include "mozilla/TimeStamp.h"
 #include "mozilla/layers/GrallocTextureClient.h"
 
 #include "gfx2DGlue.h"
 
 #include "MediaStreamSource.h"
 #include "MediaTaskQueue.h"
 #include "MP3FrameParser.h"
+#include "nsMimeTypes.h"
 #include "nsThreadUtils.h"
 #include "ImageContainer.h"
 #include "SharedThreadPool.h"
 #include "VideoFrameContainer.h"
 #include "VideoUtils.h"
 
 using namespace android;
 
@@ -683,17 +684,19 @@ MediaCodecReader::ReadMetadata(MediaInfo
                                MetadataTags** aTags)
 {
   MOZ_ASSERT(mDecoder->OnDecodeThread(), "Should be on decode thread.");
 
   if (!ReallocateResources()) {
     return NS_ERROR_FAILURE;
   }
 
-  if (!TriggerIncrementalParser()) {
+  bool incrementalParserNeeded =
+    mDecoder->GetResource()->GetContentType().EqualsASCII(AUDIO_MP3);
+  if (incrementalParserNeeded && !TriggerIncrementalParser()) {
     return NS_ERROR_FAILURE;
   }
 
   // Bug 1050667, both MediaDecoderStateMachine and MediaCodecReader
   // relies on IsWaitingMediaResources() function. And the waiting state will be
   // changed by binder thread, so we store the waiting state in a cache value to
   // make them in the same waiting state.
   UpdateIsWaitingMediaResources();
@@ -1414,20 +1417,20 @@ MediaCodecReader::TriggerIncrementalPars
       return true;
     }
 
     mParseDataFromCache = true;
     mNextParserPosition = INT64_C(0);
     mParsedDataLength = INT64_C(0);
 
     // MP3 file duration
-    mMP3FrameParser = new MP3FrameParser(mDecoder->GetResource()->GetLength());
     const char* mime = nullptr;
     if (mMetaData->findCString(kKeyMIMEType, &mime) &&
         !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG)) {
+      mMP3FrameParser = new MP3FrameParser(mDecoder->GetResource()->GetLength());
       {
         MonitorAutoUnlock monUnlock(mParserMonitor);
         // trigger parsing logic and wait for finishing parsing data in the beginning.
         nsRefPtr<SignalObject> signalObject = new SignalObject("MediaCodecReader::UpdateDuration()");
         if (ProcessCachedData(INT64_C(0), signalObject) > INT64_C(0)) {
           signalObject->Wait();
         }
       }
--- a/dom/media/webaudio/blink/Biquad.cpp
+++ b/dom/media/webaudio/blink/Biquad.cpp
@@ -21,24 +21,24 @@
  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-// For M_PI from cmath
-#ifdef _MSC_VER
-#  define _USE_MATH_DEFINES
-#endif
+// For M_PI
+// VS2015 requires <math.h> to be used; <cmath> doesn't seem to honor
+// _USE_MATH_DEFINES.
+#define _USE_MATH_DEFINES
+#include <math.h>
 
 #include "Biquad.h"
 
-#include <cmath>
 #include <float.h>
 #include <algorithm>
 
 namespace WebCore {
 
 Biquad::Biquad()
 {
     // Initialize as pass-thru (straight-wire, no filter effect)
--- a/dom/media/wmf/WMFReader.cpp
+++ b/dom/media/wmf/WMFReader.cpp
@@ -12,16 +12,17 @@
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/dom/TimeRanges.h"
 #include "mozilla/dom/HTMLMediaElement.h"
 #include "mozilla/Preferences.h"
 #include "DXVA2Manager.h"
 #include "ImageContainer.h"
 #include "Layers.h"
 #include "mozilla/layers/LayersTypes.h"
+#include "gfxWindowsPlatform.h"
 
 #ifndef MOZ_SAMPLE_TYPE_FLOAT32
 #error We expect 32bit float audio samples on desktop for the Windows Media Foundation media backend.
 #endif
 
 #include "MediaDecoder.h"
 #include "VideoUtils.h"
 #include "gfx2DGlue.h"
@@ -105,16 +106,20 @@ WMFReader::InitializeDXVA()
 
   LayersBackend backend = layerManager->GetCompositorBackendType();
   if (backend != LayersBackend::LAYERS_D3D9 &&
       backend != LayersBackend::LAYERS_D3D10 &&
       backend != LayersBackend::LAYERS_D3D11) {
     return false;
   }
 
+  if (gfxWindowsPlatform::GetPlatform()->IsWARP()) {
+    return false;
+  }
+
   mDXVA2Manager = DXVA2Manager::Create();
 
   return mDXVA2Manager != nullptr;
 }
 
 nsresult
 WMFReader::Init(MediaDecoderReader* aCloneDonor)
 {
--- a/dom/media/wmf/moz.build
+++ b/dom/media/wmf/moz.build
@@ -25,8 +25,10 @@ SOURCES += [
 ]
 
 FAIL_ON_WARNINGS = True
 
 FINAL_LIBRARY = 'xul'
 
 if CONFIG['OS_ARCH'] == 'WINNT':
     DEFINES['NOMINMAX'] = True
+
+CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
--- a/dom/security/moz.build
+++ b/dom/security/moz.build
@@ -24,10 +24,10 @@ UNIFIED_SOURCES += [
     'nsMixedContentBlocker.cpp',
 ]
 
 FAIL_ON_WARNINGS = True
 
 FINAL_LIBRARY = 'xul'
 LOCAL_INCLUDES += [
     '/caps',
-    '/netwerk/base/src',
+    '/netwerk/base',
 ]
--- a/gfx/2d/DrawEventRecorder.h
+++ b/gfx/2d/DrawEventRecorder.h
@@ -7,17 +7,17 @@
 #define MOZILLA_GFX_DRAWEVENTRECORDER_H_
 
 #include "2D.h"
 #include "RecordedEvent.h"
 #include <ostream>
 #include <fstream>
 
 #if defined(_MSC_VER)
-#include <hash_set>
+#include <unordered_set>
 #else
 #include <set>
 #endif
 
 namespace mozilla {
 namespace gfx {
 
 class PathRecording;
@@ -48,17 +48,17 @@ public:
   }
 
 protected:
   std::ostream *mOutputStream;
 
   virtual void Flush() = 0;
 
 #if defined(_MSC_VER)
-  typedef stdext::hash_set<const void*> ObjectSet;
+  typedef std::unordered_set<const void*> ObjectSet;
 #else
   typedef std::set<const void*> ObjectSet;
 #endif
 
   ObjectSet mStoredPaths;
   ObjectSet mStoredScaledFonts;
 };
 
--- a/gfx/2d/DrawTargetD2D.h
+++ b/gfx/2d/DrawTargetD2D.h
@@ -9,21 +9,17 @@
 #include "2D.h"
 #include "PathD2D.h"
 #include <d3d10_1.h>
 #include "HelpersD2D.h"
 
 #include <vector>
 #include <sstream>
 
-#ifdef _MSC_VER
-#include <hash_set>
-#else
 #include <unordered_set>
-#endif
 
 struct IDWriteFactory;
 
 namespace mozilla {
 namespace gfx {
 
 class SourceSurfaceD2DTarget;
 class SourceSurfaceD2D;
@@ -160,21 +156,17 @@ public:
 
 private:
   TemporaryRef<ID2D1Bitmap>
   GetBitmapForSurface(SourceSurface *aSurface,
                       Rect &aSource);
   friend class AutoSaveRestoreClippedOut;
   friend class SourceSurfaceD2DTarget;
 
-#ifdef _MSC_VER
-  typedef stdext::hash_set<DrawTargetD2D*> TargetSet;
-#else
   typedef std::unordered_set<DrawTargetD2D*> TargetSet;
-#endif
 
   bool InitD2DRenderTarget();
   void PrepareForDrawing(ID2D1RenderTarget *aRT);
 
   // This function will mark the surface as changing, and make sure any
   // copy-on-write snapshots are notified.
   void MarkChanged();
   void FlushTransformToRT() {
--- a/gfx/2d/DrawTargetD2D1.h
+++ b/gfx/2d/DrawTargetD2D1.h
@@ -10,21 +10,17 @@
 #include <d3d11.h>
 #include <d2d1_1.h>
 #include "PathD2D.h"
 #include "HelpersD2D.h"
 
 #include <vector>
 #include <sstream>
 
-#ifdef _MSC_VER
-#include <hash_set>
-#else
 #include <unordered_set>
-#endif
 
 struct IDWriteFactory;
 
 namespace mozilla {
 namespace gfx {
 
 class SourceSurfaceD2D1;
 class GradientStopsD2D;
@@ -149,21 +145,17 @@ public:
   }
 
   static uint64_t mVRAMUsageDT;
   static uint64_t mVRAMUsageSS;
 
 private:
   friend class SourceSurfaceD2D1;
 
-#ifdef _MSC_VER
-  typedef stdext::hash_set<DrawTargetD2D1*> TargetSet;
-#else
   typedef std::unordered_set<DrawTargetD2D1*> TargetSet;
-#endif
 
   // This function will mark the surface as changing, and make sure any
   // copy-on-write snapshots are notified.
   void MarkChanged();
   void PrepareForDrawing(CompositionOp aOp, const Pattern &aPattern);
   void FinalizeDrawing(CompositionOp aOp, const Pattern &aPattern);
   void FlushTransformToDC() {
     if (mTransformDirty) {
--- a/gfx/layers/LayerScope.cpp
+++ b/gfx/layers/LayerScope.cpp
@@ -1,9 +1,10 @@
-/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim:set ts=4 sw=4 sts=4 et: */
 /* 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/. */
 
 /* This must occur *after* layers/PLayers.h to avoid typedefs conflicts. */
 #include "LayerScope.h"
 
 #include "nsAppRunner.h"
@@ -360,16 +361,18 @@ private:
 
 StaticAutoPtr<LayerScopeWebSocketManager> WebSocketHelper::sWebSocketManager;
 
 /*
  * DebugGLData is the base class of
  * 1. DebugGLFrameStatusData (Frame start/end packet)
  * 2. DebugGLColorData (Color data packet)
  * 3. DebugGLTextureData (Texture data packet)
+ * 4. DebugGLLayersData (Layers Tree data packet)
+ * 5. DebugGLMetaData (Meta data packet)
  */
 class DebugGLData: public LinkedListElement<DebugGLData> {
 public:
     explicit DebugGLData(Packet::DataType aDataType)
         : mDataType(aDataType)
     { }
 
     virtual ~DebugGLData() { }
@@ -561,16 +564,47 @@ public:
             return false;
         return true;
     }
 
 protected:
     UniquePtr<Packet> mPacket;
 };
 
+class DebugGLMetaData : public DebugGLData
+{
+public:
+    DebugGLMetaData(Packet::DataType aDataType,
+                    bool aValue)
+        : DebugGLData(aDataType),
+          mComposedByHwc(aValue)
+    { }
+
+    explicit DebugGLMetaData(Packet::DataType aDataType)
+        : DebugGLData(aDataType),
+          mComposedByHwc(false)
+    { }
+
+    virtual bool Write() MOZ_OVERRIDE {
+        Packet packet;
+        packet.set_type(mDataType);
+
+        MetaPacket* mp = packet.mutable_meta();
+        mp->set_composedbyhwc(mComposedByHwc);
+
+        if (!WriteToStream(packet))
+            return false;
+        return true;
+    }
+
+protected:
+    bool mComposedByHwc;
+};
+
+
 class DebugListener : public nsIServerSocketListener
 {
     virtual ~DebugListener() { }
 
 public:
 
     NS_DECL_THREADSAFE_ISUPPORTS
 
@@ -1000,16 +1034,26 @@ LayerScope::CheckSendable()
 void
 LayerScope::CleanLayer()
 {
     if (CheckSendable()) {
         WebSocketHelper::GetSocketManager()->CleanDebugData();
     }
 }
 
+
+void
+LayerScope::SetHWComposed()
+{
+    if (CheckSendable()) {
+        WebSocketHelper::GetSocketManager()->AppendDebugData(
+            new DebugGLMetaData(Packet::META, true));
+    }
+}
+
 // ----------------------------------------------
 // LayerScopeAutoFrame implementation
 // ----------------------------------------------
 LayerScopeAutoFrame::LayerScopeAutoFrame(int64_t aFrameStamp)
 {
     // Do Begin Frame
     BeginFrame(aFrameStamp);
 }
--- a/gfx/layers/LayerScope.h
+++ b/gfx/layers/LayerScope.h
@@ -1,9 +1,10 @@
-/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim:set ts=4 sw=4 sts=4 et: */
 /* 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 GFX_LAYERSCOPE_H
 #define GFX_LAYERSCOPE_H
 
 #include <stdint.h>
@@ -29,16 +30,17 @@ public:
                                 int aWidth,
                                 int aHeight);
     static void SendLayer(LayerComposite* aLayer,
                           int aWidth,
                           int aHeight);
     static void SendLayerDump(UniquePtr<layerscope::Packet> aPacket);
     static bool CheckSendable();
     static void CleanLayer();
+    static void SetHWComposed();
 
 private:
     static void Init();
 };
 
 // Perform BeginFrame and EndFrame automatically
 class LayerScopeAutoFrame {
 public:
--- a/gfx/layers/composite/LayerManagerComposite.cpp
+++ b/gfx/layers/composite/LayerManagerComposite.cpp
@@ -657,16 +657,17 @@ LayerManagerComposite::Render()
 
   // We can't use composert2D if we have layer effects, so only get it
   // when we don't have any effects.
   if (!haveLayerEffects) {
     composer2D = mCompositor->GetWidget()->GetComposer2D();
   }
 
   if (!mTarget && composer2D && composer2D->TryRender(mRoot, mGeometryChanged)) {
+    LayerScope::SetHWComposed();
     if (mFPS) {
       double fps = mFPS->mCompositionFps.AddFrameAndGetFps(TimeStamp::Now());
       if (gfxPrefs::LayersDrawFPS()) {
         printf_stderr("HWComposer: FPS is %g\n", fps);
       }
     }
     mCompositor->EndFrameForExternalComposition(Matrix());
     // Reset the invalid region as compositing is done
--- a/gfx/layers/protobuf/LayerScopePacket.pb.cc
+++ b/gfx/layers/protobuf/LayerScopePacket.pb.cc
@@ -20,16 +20,17 @@ void protobuf_ShutdownFile_LayerScopePac
   delete TexturePacket::default_instance_;
   delete LayersPacket::default_instance_;
   delete LayersPacket_Layer::default_instance_;
   delete LayersPacket_Layer_Size::default_instance_;
   delete LayersPacket_Layer_Rect::default_instance_;
   delete LayersPacket_Layer_Region::default_instance_;
   delete LayersPacket_Layer_Matrix::default_instance_;
   delete LayersPacket_Layer_Shadow::default_instance_;
+  delete MetaPacket::default_instance_;
   delete Packet::default_instance_;
 }
 
 void protobuf_AddDesc_LayerScopePacket_2eproto() {
   static bool already_here = false;
   if (already_here) return;
   already_here = true;
   GOOGLE_PROTOBUF_VERIFY_VERSION;
@@ -39,27 +40,29 @@ void protobuf_AddDesc_LayerScopePacket_2
   TexturePacket::default_instance_ = new TexturePacket();
   LayersPacket::default_instance_ = new LayersPacket();
   LayersPacket_Layer::default_instance_ = new LayersPacket_Layer();
   LayersPacket_Layer_Size::default_instance_ = new LayersPacket_Layer_Size();
   LayersPacket_Layer_Rect::default_instance_ = new LayersPacket_Layer_Rect();
   LayersPacket_Layer_Region::default_instance_ = new LayersPacket_Layer_Region();
   LayersPacket_Layer_Matrix::default_instance_ = new LayersPacket_Layer_Matrix();
   LayersPacket_Layer_Shadow::default_instance_ = new LayersPacket_Layer_Shadow();
+  MetaPacket::default_instance_ = new MetaPacket();
   Packet::default_instance_ = new Packet();
   FramePacket::default_instance_->InitAsDefaultInstance();
   ColorPacket::default_instance_->InitAsDefaultInstance();
   TexturePacket::default_instance_->InitAsDefaultInstance();
   LayersPacket::default_instance_->InitAsDefaultInstance();
   LayersPacket_Layer::default_instance_->InitAsDefaultInstance();
   LayersPacket_Layer_Size::default_instance_->InitAsDefaultInstance();
   LayersPacket_Layer_Rect::default_instance_->InitAsDefaultInstance();
   LayersPacket_Layer_Region::default_instance_->InitAsDefaultInstance();
   LayersPacket_Layer_Matrix::default_instance_->InitAsDefaultInstance();
   LayersPacket_Layer_Shadow::default_instance_->InitAsDefaultInstance();
+  MetaPacket::default_instance_->InitAsDefaultInstance();
   Packet::default_instance_->InitAsDefaultInstance();
   ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_LayerScopePacket_2eproto);
 }
 
 // Force AddDescriptors() to be called at static initialization time.
 struct StaticDescriptorInitializer_LayerScopePacket_2eproto {
   StaticDescriptorInitializer_LayerScopePacket_2eproto() {
     protobuf_AddDesc_LayerScopePacket_2eproto();
@@ -3025,85 +3028,247 @@ void LayersPacket::Swap(LayersPacket* ot
 
 ::std::string LayersPacket::GetTypeName() const {
   return "mozilla.layers.layerscope.LayersPacket";
 }
 
 
 // ===================================================================
 
+#ifndef _MSC_VER
+const int MetaPacket::kComposedByHwcFieldNumber;
+#endif  // !_MSC_VER
+
+MetaPacket::MetaPacket()
+  : ::google::protobuf::MessageLite() {
+  SharedCtor();
+}
+
+void MetaPacket::InitAsDefaultInstance() {
+}
+
+MetaPacket::MetaPacket(const MetaPacket& from)
+  : ::google::protobuf::MessageLite() {
+  SharedCtor();
+  MergeFrom(from);
+}
+
+void MetaPacket::SharedCtor() {
+  _cached_size_ = 0;
+  composedbyhwc_ = false;
+  ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+MetaPacket::~MetaPacket() {
+  SharedDtor();
+}
+
+void MetaPacket::SharedDtor() {
+  if (this != default_instance_) {
+  }
+}
+
+void MetaPacket::SetCachedSize(int size) const {
+  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+  _cached_size_ = size;
+  GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const MetaPacket& MetaPacket::default_instance() {
+  if (default_instance_ == NULL) protobuf_AddDesc_LayerScopePacket_2eproto();  return *default_instance_;
+}
+
+MetaPacket* MetaPacket::default_instance_ = NULL;
+
+MetaPacket* MetaPacket::New() const {
+  return new MetaPacket;
+}
+
+void MetaPacket::Clear() {
+  if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+    composedbyhwc_ = false;
+  }
+  ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+bool MetaPacket::MergePartialFromCodedStream(
+    ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
+  ::google::protobuf::uint32 tag;
+  while ((tag = input->ReadTag()) != 0) {
+    switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+      // optional bool composedByHwc = 1;
+      case 1: {
+        if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+            ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
+          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+                   bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
+                 input, &composedbyhwc_)));
+          set_has_composedbyhwc();
+        } else {
+          goto handle_uninterpreted;
+        }
+        if (input->ExpectAtEnd()) return true;
+        break;
+      }
+      
+      default: {
+      handle_uninterpreted:
+        if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+            ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+          return true;
+        }
+        DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
+        break;
+      }
+    }
+  }
+  return true;
+#undef DO_
+}
+
+void MetaPacket::SerializeWithCachedSizes(
+    ::google::protobuf::io::CodedOutputStream* output) const {
+  // optional bool composedByHwc = 1;
+  if (has_composedbyhwc()) {
+    ::google::protobuf::internal::WireFormatLite::WriteBool(1, this->composedbyhwc(), output);
+  }
+  
+}
+
+int MetaPacket::ByteSize() const {
+  int total_size = 0;
+  
+  if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+    // optional bool composedByHwc = 1;
+    if (has_composedbyhwc()) {
+      total_size += 1 + 1;
+    }
+    
+  }
+  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+  _cached_size_ = total_size;
+  GOOGLE_SAFE_CONCURRENT_WRITES_END();
+  return total_size;
+}
+
+void MetaPacket::CheckTypeAndMergeFrom(
+    const ::google::protobuf::MessageLite& from) {
+  MergeFrom(*::google::protobuf::down_cast<const MetaPacket*>(&from));
+}
+
+void MetaPacket::MergeFrom(const MetaPacket& from) {
+  GOOGLE_CHECK_NE(&from, this);
+  if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+    if (from.has_composedbyhwc()) {
+      set_composedbyhwc(from.composedbyhwc());
+    }
+  }
+}
+
+void MetaPacket::CopyFrom(const MetaPacket& from) {
+  if (&from == this) return;
+  Clear();
+  MergeFrom(from);
+}
+
+bool MetaPacket::IsInitialized() const {
+  
+  return true;
+}
+
+void MetaPacket::Swap(MetaPacket* other) {
+  if (other != this) {
+    std::swap(composedbyhwc_, other->composedbyhwc_);
+    std::swap(_has_bits_[0], other->_has_bits_[0]);
+    std::swap(_cached_size_, other->_cached_size_);
+  }
+}
+
+::std::string MetaPacket::GetTypeName() const {
+  return "mozilla.layers.layerscope.MetaPacket";
+}
+
+
+// ===================================================================
+
 bool Packet_DataType_IsValid(int value) {
   switch(value) {
     case 1:
     case 2:
     case 3:
     case 4:
     case 5:
+    case 6:
       return true;
     default:
       return false;
   }
 }
 
 #ifndef _MSC_VER
 const Packet_DataType Packet::FRAMESTART;
 const Packet_DataType Packet::FRAMEEND;
 const Packet_DataType Packet::COLOR;
 const Packet_DataType Packet::TEXTURE;
 const Packet_DataType Packet::LAYERS;
+const Packet_DataType Packet::META;
 const Packet_DataType Packet::DataType_MIN;
 const Packet_DataType Packet::DataType_MAX;
 const int Packet::DataType_ARRAYSIZE;
 #endif  // _MSC_VER
 #ifndef _MSC_VER
 const int Packet::kTypeFieldNumber;
 const int Packet::kFrameFieldNumber;
 const int Packet::kColorFieldNumber;
 const int Packet::kTextureFieldNumber;
 const int Packet::kLayersFieldNumber;
+const int Packet::kMetaFieldNumber;
 #endif  // !_MSC_VER
 
 Packet::Packet()
   : ::google::protobuf::MessageLite() {
   SharedCtor();
 }
 
 void Packet::InitAsDefaultInstance() {
   frame_ = const_cast< ::mozilla::layers::layerscope::FramePacket*>(&::mozilla::layers::layerscope::FramePacket::default_instance());
   color_ = const_cast< ::mozilla::layers::layerscope::ColorPacket*>(&::mozilla::layers::layerscope::ColorPacket::default_instance());
   texture_ = const_cast< ::mozilla::layers::layerscope::TexturePacket*>(&::mozilla::layers::layerscope::TexturePacket::default_instance());
   layers_ = const_cast< ::mozilla::layers::layerscope::LayersPacket*>(&::mozilla::layers::layerscope::LayersPacket::default_instance());
+  meta_ = const_cast< ::mozilla::layers::layerscope::MetaPacket*>(&::mozilla::layers::layerscope::MetaPacket::default_instance());
 }
 
 Packet::Packet(const Packet& from)
   : ::google::protobuf::MessageLite() {
   SharedCtor();
   MergeFrom(from);
 }
 
 void Packet::SharedCtor() {
   _cached_size_ = 0;
   type_ = 1;
   frame_ = NULL;
   color_ = NULL;
   texture_ = NULL;
   layers_ = NULL;
+  meta_ = NULL;
   ::memset(_has_bits_, 0, sizeof(_has_bits_));
 }
 
 Packet::~Packet() {
   SharedDtor();
 }
 
 void Packet::SharedDtor() {
   if (this != default_instance_) {
     delete frame_;
     delete color_;
     delete texture_;
     delete layers_;
+    delete meta_;
   }
 }
 
 void Packet::SetCachedSize(int size) const {
   GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
   _cached_size_ = size;
   GOOGLE_SAFE_CONCURRENT_WRITES_END();
 }
@@ -3127,16 +3292,19 @@ void Packet::Clear() {
       if (color_ != NULL) color_->::mozilla::layers::layerscope::ColorPacket::Clear();
     }
     if (has_texture()) {
       if (texture_ != NULL) texture_->::mozilla::layers::layerscope::TexturePacket::Clear();
     }
     if (has_layers()) {
       if (layers_ != NULL) layers_->::mozilla::layers::layerscope::LayersPacket::Clear();
     }
+    if (has_meta()) {
+      if (meta_ != NULL) meta_->::mozilla::layers::layerscope::MetaPacket::Clear();
+    }
   }
   ::memset(_has_bits_, 0, sizeof(_has_bits_));
 }
 
 bool Packet::MergePartialFromCodedStream(
     ::google::protobuf::io::CodedInputStream* input) {
 #define DO_(EXPRESSION) if (!(EXPRESSION)) return false
   ::google::protobuf::uint32 tag;
@@ -3207,16 +3375,30 @@ bool Packet::MergePartialFromCodedStream
         if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
             ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
          parse_layers:
           DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
                input, mutable_layers()));
         } else {
           goto handle_uninterpreted;
         }
+        if (input->ExpectTag(50)) goto parse_meta;
+        break;
+      }
+      
+      // optional .mozilla.layers.layerscope.MetaPacket meta = 6;
+      case 6: {
+        if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+            ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
+         parse_meta:
+          DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+               input, mutable_meta()));
+        } else {
+          goto handle_uninterpreted;
+        }
         if (input->ExpectAtEnd()) return true;
         break;
       }
       
       default: {
       handle_uninterpreted:
         if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
             ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
@@ -3258,16 +3440,22 @@ void Packet::SerializeWithCachedSizes(
   }
   
   // optional .mozilla.layers.layerscope.LayersPacket layers = 5;
   if (has_layers()) {
     ::google::protobuf::internal::WireFormatLite::WriteMessage(
       5, this->layers(), output);
   }
   
+  // optional .mozilla.layers.layerscope.MetaPacket meta = 6;
+  if (has_meta()) {
+    ::google::protobuf::internal::WireFormatLite::WriteMessage(
+      6, this->meta(), output);
+  }
+  
 }
 
 int Packet::ByteSize() const {
   int total_size = 0;
   
   if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
     // required .mozilla.layers.layerscope.Packet.DataType type = 1;
     if (has_type()) {
@@ -3298,16 +3486,23 @@ int Packet::ByteSize() const {
     
     // optional .mozilla.layers.layerscope.LayersPacket layers = 5;
     if (has_layers()) {
       total_size += 1 +
         ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
           this->layers());
     }
     
+    // optional .mozilla.layers.layerscope.MetaPacket meta = 6;
+    if (has_meta()) {
+      total_size += 1 +
+        ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+          this->meta());
+    }
+    
   }
   GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
   _cached_size_ = total_size;
   GOOGLE_SAFE_CONCURRENT_WRITES_END();
   return total_size;
 }
 
 void Packet::CheckTypeAndMergeFrom(
@@ -3328,16 +3523,19 @@ void Packet::MergeFrom(const Packet& fro
       mutable_color()->::mozilla::layers::layerscope::ColorPacket::MergeFrom(from.color());
     }
     if (from.has_texture()) {
       mutable_texture()->::mozilla::layers::layerscope::TexturePacket::MergeFrom(from.texture());
     }
     if (from.has_layers()) {
       mutable_layers()->::mozilla::layers::layerscope::LayersPacket::MergeFrom(from.layers());
     }
+    if (from.has_meta()) {
+      mutable_meta()->::mozilla::layers::layerscope::MetaPacket::MergeFrom(from.meta());
+    }
   }
 }
 
 void Packet::CopyFrom(const Packet& from) {
   if (&from == this) return;
   Clear();
   MergeFrom(from);
 }
@@ -3359,16 +3557,17 @@ bool Packet::IsInitialized() const {
 
 void Packet::Swap(Packet* other) {
   if (other != this) {
     std::swap(type_, other->type_);
     std::swap(frame_, other->frame_);
     std::swap(color_, other->color_);
     std::swap(texture_, other->texture_);
     std::swap(layers_, other->layers_);
+    std::swap(meta_, other->meta_);
     std::swap(_has_bits_[0], other->_has_bits_[0]);
     std::swap(_cached_size_, other->_cached_size_);
   }
 }
 
 ::std::string Packet::GetTypeName() const {
   return "mozilla.layers.layerscope.Packet";
 }
--- a/gfx/layers/protobuf/LayerScopePacket.pb.h
+++ b/gfx/layers/protobuf/LayerScopePacket.pb.h
@@ -38,16 +38,17 @@ class ColorPacket;
 class TexturePacket;
 class LayersPacket;
 class LayersPacket_Layer;
 class LayersPacket_Layer_Size;
 class LayersPacket_Layer_Rect;
 class LayersPacket_Layer_Region;
 class LayersPacket_Layer_Matrix;
 class LayersPacket_Layer_Shadow;
+class MetaPacket;
 class Packet;
 
 enum LayersPacket_Layer_LayerType {
   LayersPacket_Layer_LayerType_UnknownLayer = 0,
   LayersPacket_Layer_LayerType_LayerManager = 1,
   LayersPacket_Layer_LayerType_ContainerLayer = 2,
   LayersPacket_Layer_LayerType_PaintedLayer = 3,
   LayersPacket_Layer_LayerType_CanvasLayer = 4,
@@ -84,21 +85,22 @@ const LayersPacket_Layer_Filter LayersPa
 const LayersPacket_Layer_Filter LayersPacket_Layer_Filter_Filter_MAX = LayersPacket_Layer_Filter_FILTER_SENTINEL;
 const int LayersPacket_Layer_Filter_Filter_ARRAYSIZE = LayersPacket_Layer_Filter_Filter_MAX + 1;
 
 enum Packet_DataType {
   Packet_DataType_FRAMESTART = 1,
   Packet_DataType_FRAMEEND = 2,
   Packet_DataType_COLOR = 3,
   Packet_DataType_TEXTURE = 4,
-  Packet_DataType_LAYERS = 5
+  Packet_DataType_LAYERS = 5,
+  Packet_DataType_META = 6
 };
 bool Packet_DataType_IsValid(int value);
 const Packet_DataType Packet_DataType_DataType_MIN = Packet_DataType_FRAMESTART;
-const Packet_DataType Packet_DataType_DataType_MAX = Packet_DataType_LAYERS;
+const Packet_DataType Packet_DataType_DataType_MAX = Packet_DataType_META;
 const int Packet_DataType_DataType_ARRAYSIZE = Packet_DataType_DataType_MAX + 1;
 
 // ===================================================================
 
 class FramePacket : public ::google::protobuf::MessageLite {
  public:
   FramePacket();
   virtual ~FramePacket();
@@ -1224,16 +1226,85 @@ class LayersPacket : public ::google::pr
   friend void protobuf_AssignDesc_LayerScopePacket_2eproto();
   friend void protobuf_ShutdownFile_LayerScopePacket_2eproto();
   
   void InitAsDefaultInstance();
   static LayersPacket* default_instance_;
 };
 // -------------------------------------------------------------------
 
+class MetaPacket : public ::google::protobuf::MessageLite {
+ public:
+  MetaPacket();
+  virtual ~MetaPacket();
+  
+  MetaPacket(const MetaPacket& from);
+  
+  inline MetaPacket& operator=(const MetaPacket& from) {
+    CopyFrom(from);
+    return *this;
+  }
+  
+  static const MetaPacket& default_instance();
+  
+  void Swap(MetaPacket* other);
+  
+  // implements Message ----------------------------------------------
+  
+  MetaPacket* New() const;
+  void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);
+  void CopyFrom(const MetaPacket& from);
+  void MergeFrom(const MetaPacket& from);
+  void Clear();
+  bool IsInitialized() const;
+  
+  int ByteSize() const;
+  bool MergePartialFromCodedStream(
+      ::google::protobuf::io::CodedInputStream* input);
+  void SerializeWithCachedSizes(
+      ::google::protobuf::io::CodedOutputStream* output) const;
+  int GetCachedSize() const { return _cached_size_; }
+  private:
+  void SharedCtor();
+  void SharedDtor();
+  void SetCachedSize(int size) const;
+  public:
+  
+  ::std::string GetTypeName() const;
+  
+  // nested types ----------------------------------------------------
+  
+  // accessors -------------------------------------------------------
+  
+  // optional bool composedByHwc = 1;
+  inline bool has_composedbyhwc() const;
+  inline void clear_composedbyhwc();
+  static const int kComposedByHwcFieldNumber = 1;
+  inline bool composedbyhwc() const;
+  inline void set_composedbyhwc(bool value);
+  
+  // @@protoc_insertion_point(class_scope:mozilla.layers.layerscope.MetaPacket)
+ private:
+  inline void set_has_composedbyhwc();
+  inline void clear_has_composedbyhwc();
+  
+  bool composedbyhwc_;
+  
+  mutable int _cached_size_;
+  ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32];
+  
+  friend void  protobuf_AddDesc_LayerScopePacket_2eproto();
+  friend void protobuf_AssignDesc_LayerScopePacket_2eproto();
+  friend void protobuf_ShutdownFile_LayerScopePacket_2eproto();
+  
+  void InitAsDefaultInstance();
+  static MetaPacket* default_instance_;
+};
+// -------------------------------------------------------------------
+
 class Packet : public ::google::protobuf::MessageLite {
  public:
   Packet();
   virtual ~Packet();
   
   Packet(const Packet& from);
   
   inline Packet& operator=(const Packet& from) {
@@ -1271,16 +1342,17 @@ class Packet : public ::google::protobuf
   // nested types ----------------------------------------------------
   
   typedef Packet_DataType DataType;
   static const DataType FRAMESTART = Packet_DataType_FRAMESTART;
   static const DataType FRAMEEND = Packet_DataType_FRAMEEND;
   static const DataType COLOR = Packet_DataType_COLOR;
   static const DataType TEXTURE = Packet_DataType_TEXTURE;
   static const DataType LAYERS = Packet_DataType_LAYERS;
+  static const DataType META = Packet_DataType_META;
   static inline bool DataType_IsValid(int value) {
     return Packet_DataType_IsValid(value);
   }
   static const DataType DataType_MIN =
     Packet_DataType_DataType_MIN;
   static const DataType DataType_MAX =
     Packet_DataType_DataType_MAX;
   static const int DataType_ARRAYSIZE =
@@ -1322,37 +1394,48 @@ class Packet : public ::google::protobuf
   // optional .mozilla.layers.layerscope.LayersPacket layers = 5;
   inline bool has_layers() const;
   inline void clear_layers();
   static const int kLayersFieldNumber = 5;
   inline const ::mozilla::layers::layerscope::LayersPacket& layers() const;
   inline ::mozilla::layers::layerscope::LayersPacket* mutable_layers();
   inline ::mozilla::layers::layerscope::LayersPacket* release_layers();
   
+  // optional .mozilla.layers.layerscope.MetaPacket meta = 6;
+  inline bool has_meta() const;
+  inline void clear_meta();
+  static const int kMetaFieldNumber = 6;
+  inline const ::mozilla::layers::layerscope::MetaPacket& meta() const;
+  inline ::mozilla::layers::layerscope::MetaPacket* mutable_meta();
+  inline ::mozilla::layers::layerscope::MetaPacket* release_meta();
+  
   // @@protoc_insertion_point(class_scope:mozilla.layers.layerscope.Packet)
  private:
   inline void set_has_type();
   inline void clear_has_type();
   inline void set_has_frame();
   inline void clear_has_frame();
   inline void set_has_color();
   inline void clear_has_color();
   inline void set_has_texture();
   inline void clear_has_texture();
   inline void set_has_layers();
   inline void clear_has_layers();
+  inline void set_has_meta();
+  inline void clear_has_meta();
   
   ::mozilla::layers::layerscope::FramePacket* frame_;
   ::mozilla::layers::layerscope::ColorPacket* color_;
   ::mozilla::layers::layerscope::TexturePacket* texture_;
   ::mozilla::layers::layerscope::LayersPacket* layers_;
+  ::mozilla::layers::layerscope::MetaPacket* meta_;
   int type_;
   
   mutable int _cached_size_;
-  ::google::protobuf::uint32 _has_bits_[(5 + 31) / 32];
+  ::google::protobuf::uint32 _has_bits_[(6 + 31) / 32];
   
   friend void  protobuf_AddDesc_LayerScopePacket_2eproto();
   friend void protobuf_AssignDesc_LayerScopePacket_2eproto();
   friend void protobuf_ShutdownFile_LayerScopePacket_2eproto();
   
   void InitAsDefaultInstance();
   static Packet* default_instance_;
 };
@@ -2519,16 +2602,42 @@ LayersPacket::layer() const {
 }
 inline ::google::protobuf::RepeatedPtrField< ::mozilla::layers::layerscope::LayersPacket_Layer >*
 LayersPacket::mutable_layer() {
   return &layer_;
 }
 
 // -------------------------------------------------------------------
 
+// MetaPacket
+
+// optional bool composedByHwc = 1;
+inline bool MetaPacket::has_composedbyhwc() const {
+  return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void MetaPacket::set_has_composedbyhwc() {
+  _has_bits_[0] |= 0x00000001u;
+}
+inline void MetaPacket::clear_has_composedbyhwc() {
+  _has_bits_[0] &= ~0x00000001u;
+}
+inline void MetaPacket::clear_composedbyhwc() {
+  composedbyhwc_ = false;
+  clear_has_composedbyhwc();
+}
+inline bool MetaPacket::composedbyhwc() const {
+  return composedbyhwc_;
+}
+inline void MetaPacket::set_composedbyhwc(bool value) {
+  set_has_composedbyhwc();
+  composedbyhwc_ = value;
+}
+
+// -------------------------------------------------------------------
+
 // Packet
 
 // required .mozilla.layers.layerscope.Packet.DataType type = 1;
 inline bool Packet::has_type() const {
   return (_has_bits_[0] & 0x00000001u) != 0;
 }
 inline void Packet::set_has_type() {
   _has_bits_[0] |= 0x00000001u;
@@ -2660,16 +2769,45 @@ inline ::mozilla::layers::layerscope::La
 }
 inline ::mozilla::layers::layerscope::LayersPacket* Packet::release_layers() {
   clear_has_layers();
   ::mozilla::layers::layerscope::LayersPacket* temp = layers_;
   layers_ = NULL;
   return temp;
 }
 
+// optional .mozilla.layers.layerscope.MetaPacket meta = 6;
+inline bool Packet::has_meta() const {
+  return (_has_bits_[0] & 0x00000020u) != 0;
+}
+inline void Packet::set_has_meta() {
+  _has_bits_[0] |= 0x00000020u;
+}
+inline void Packet::clear_has_meta() {
+  _has_bits_[0] &= ~0x00000020u;
+}
+inline void Packet::clear_meta() {
+  if (meta_ != NULL) meta_->::mozilla::layers::layerscope::MetaPacket::Clear();
+  clear_has_meta();
+}
+inline const ::mozilla::layers::layerscope::MetaPacket& Packet::meta() const {
+  return meta_ != NULL ? *meta_ : *default_instance_->meta_;
+}
+inline ::mozilla::layers::layerscope::MetaPacket* Packet::mutable_meta() {
+  set_has_meta();
+  if (meta_ == NULL) meta_ = new ::mozilla::layers::layerscope::MetaPacket;
+  return meta_;
+}
+inline ::mozilla::layers::layerscope::MetaPacket* Packet::release_meta() {
+  clear_has_meta();
+  ::mozilla::layers::layerscope::MetaPacket* temp = meta_;
+  meta_ = NULL;
+  return temp;
+}
+
 
 // @@protoc_insertion_point(namespace_scope)
 
 }  // namespace layerscope
 }  // namespace layers
 }  // namespace mozilla
 
 // @@protoc_insertion_point(global_scope)
--- a/gfx/layers/protobuf/LayerScopePacket.proto
+++ b/gfx/layers/protobuf/LayerScopePacket.proto
@@ -1,8 +1,10 @@
+/* vim:set ts=2 sw=2 sts=2 et: */
+
 option optimize_for = LITE_RUNTIME;
 
 package mozilla.layers.layerscope;
 
 message FramePacket {
   optional uint64 value = 1;
 }
 
@@ -103,25 +105,31 @@ message LayersPacket {
     // Ref Layer
     optional uint64 refID = 103;
     // Readback Layer
     optional Size size = 104;
   }
   repeated Layer layer = 1;
 }
 
+message MetaPacket {
+  optional bool composedByHwc = 1;
+}
+
 // We only need to use this Packet.
 // Other packet definitions are just type defines
 message Packet {
   enum DataType {
     FRAMESTART = 1;
     FRAMEEND = 2;
     COLOR = 3;
     TEXTURE = 4;
     LAYERS = 5;
+    META = 6;
   }
   required DataType type = 1;
 
   optional FramePacket frame = 2;
   optional ColorPacket color = 3;
   optional TexturePacket texture = 4;
   optional LayersPacket layers = 5;
+  optional MetaPacket meta = 6;
 }
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -370,28 +370,29 @@ nsDeviceContext::SetDPI()
 
     mAppUnitsPerPhysicalInch = NS_lround(dpi * mAppUnitsPerDevPixelAtUnitFullZoom);
     UpdateAppUnitsForFullZoom();
 }
 
 nsresult
 nsDeviceContext::Init(nsIWidget *aWidget)
 {
+    nsresult rv = NS_OK;
     if (mScreenManager && mWidget == aWidget)
-        return NS_OK;
+        return rv;
 
     mWidget = aWidget;
     SetDPI();
 
     if (mScreenManager)
-        return NS_OK;
+        return rv;
 
-    mScreenManager = do_GetService("@mozilla.org/gfx/screenmanager;1");
+    mScreenManager = do_GetService("@mozilla.org/gfx/screenmanager;1", &rv);
 
-    return NS_OK;
+    return rv;
 }
 
 already_AddRefed<gfxContext>
 nsDeviceContext::CreateRenderingContext()
 {
     nsRefPtr<gfxASurface> printingSurface = mPrintingSurface;
 #ifdef XP_MACOSX
     // CreateRenderingContext() can be called (on reflow) after EndPage()
@@ -417,17 +418,17 @@ nsDeviceContext::CreateRenderingContext(
     nsRefPtr<gfxContext> pContext = new gfxContext(dt);
     pContext->SetMatrix(gfxMatrix::Scaling(mPrintingScale, mPrintingScale));
     return pContext.forget();
 }
 
 nsresult
 nsDeviceContext::GetDepth(uint32_t& aDepth)
 {
-    if (mDepth == 0) {
+    if (mDepth == 0 && mScreenManager) {
         nsCOMPtr<nsIScreen> primaryScreen;
         mScreenManager->GetPrimaryScreen(getter_AddRefs(primaryScreen));
         primaryScreen->GetColorDepth(reinterpret_cast<int32_t *>(&mDepth));
     }
 
     aDepth = mDepth;
     return NS_OK;
 }
@@ -639,21 +640,25 @@ nsDeviceContext::ComputeFullAreaUsingScr
 //
 // FindScreen
 //
 // Determines which screen intersects the largest area of the given surface.
 //
 void
 nsDeviceContext::FindScreen(nsIScreen** outScreen)
 {
-    if (mWidget && mWidget->GetOwningTabChild()) {
+    if (!mWidget || !mScreenManager) {
+        return;
+    }
+
+    if (mWidget->GetOwningTabChild()) {
         mScreenManager->ScreenForNativeWidget((void *)mWidget->GetOwningTabChild(),
                                               outScreen);
     }
-    else if (mWidget && mWidget->GetNativeData(NS_NATIVE_WINDOW)) {
+    else if (mWidget->GetNativeData(NS_NATIVE_WINDOW)) {
         mScreenManager->ScreenForNativeWidget(mWidget->GetNativeData(NS_NATIVE_WINDOW),
                                               outScreen);
     }
     else {
         mScreenManager->GetPrimaryScreen(outScreen);
     }
 }
 
--- a/gfx/thebes/gfxWindowsPlatform.cpp
+++ b/gfx/thebes/gfxWindowsPlatform.cpp
@@ -322,16 +322,17 @@ public:
         return NS_OK;
     }
 };
 
 NS_IMPL_ISUPPORTS(GPUAdapterReporter, nsIMemoryReporter)
 
 gfxWindowsPlatform::gfxWindowsPlatform()
   : mD3D11DeviceInitialized(false)
+  , mIsWARP(false)
 {
     mUseClearTypeForDownloadableFonts = UNINITIALIZED_VALUE;
     mUseClearTypeAlways = UNINITIALIZED_VALUE;
 
     mUsingGDIFonts = false;
 
     /* 
      * Initialize COM 
@@ -1782,16 +1783,17 @@ gfxWindowsPlatform::InitD3D11Devices()
                            D3D11_SDK_VERSION, byRef(mD3D11Device), nullptr, nullptr);
 
     if (FAILED(hr)) {
       // This should always succeed... in theory.
       gfxCriticalError() << "Failed to initialize WARP D3D11 device!" << hr;
       MOZ_CRASH();
     }
 
+    mIsWARP = true;
     reporterWARP.SetSuccessful();
   }
 
   mD3D11Device->SetExceptionMode(0);
 
   // We create our device for D2D content drawing here. Normally we don't use
   // D2D content drawing when using WARP. However when WARP is forced by
   // default we will let Direct2D use WARP as well.
--- a/gfx/thebes/gfxWindowsPlatform.h
+++ b/gfx/thebes/gfxWindowsPlatform.h
@@ -245,16 +245,18 @@ public:
 #endif
     ID3D11Device *GetD3D11Device();
     ID3D11Device *GetD3D11ContentDevice();
 
     mozilla::layers::ReadbackManagerD3D11* GetReadbackManager();
 
     static bool IsOptimus();
 
+    bool IsWARP() { return mIsWARP; }
+
 protected:
     RenderMode mRenderMode;
 
     int8_t mUseClearTypeForDownloadableFonts;
     int8_t mUseClearTypeAlways;
 
 private:
     void Init();
@@ -274,16 +276,17 @@ private:
     cairo_device_t *mD2DDevice;
 #endif
     mozilla::RefPtr<IDXGIAdapter1> mAdapter;
     nsRefPtr<mozilla::layers::DeviceManagerD3D9> mDeviceManager;
     mozilla::RefPtr<ID3D11Device> mD3D11Device;
     mozilla::RefPtr<ID3D11Device> mD3D11ContentDevice;
     bool mD3D11DeviceInitialized;
     mozilla::RefPtr<mozilla::layers::ReadbackManagerD3D11> mD3D11ReadbackManager;
+    bool mIsWARP;
 
     virtual void GetPlatformCMSOutputProfile(void* &mem, size_t &size);
 };
 
 bool DoesD3D11TextureSharingWork(ID3D11Device *device);
 bool DoesD3D11DeviceWork(ID3D11Device *device);
 
 #endif /* GFX_WINDOWS_PLATFORM_H */
--- a/image/src/moz.build
+++ b/image/src/moz.build
@@ -61,13 +61,13 @@ LOCAL_INCLUDES += [
     '/dom/svg',
     # Access to Skia headers for Downscaler
     '/gfx/2d',
     # We need to instantiate the decoders
     '/image/decoders',
     # Because VectorImage.cpp includes nsSVGUtils.h and nsSVGEffects.h
     '/layout/svg',
     # For URI-related functionality
-    '/netwerk/base/src',
+    '/netwerk/base',
 ]
 
 # Because imgFrame.cpp includes "cairo.h"
 CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
--- a/ipc/chromium/src/base/hash_tables.h
+++ b/ipc/chromium/src/base/hash_tables.h
@@ -15,18 +15,25 @@
 #ifndef BASE_HASH_TABLES_H_
 #define BASE_HASH_TABLES_H_
 
 #include "build/build_config.h"
 
 #include "base/string16.h"
 
 #if defined(COMPILER_MSVC) || (defined(ANDROID) && defined(_STLP_STD_NAME))
+#ifdef COMPILER_MSVC
+#pragma push_macro("_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS")
+#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
+#endif
 #include <hash_map>
 #include <hash_set>
+#ifdef COMPILER_MSVC
+#pragma pop_macro("_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS")
+#endif
 namespace base {
 #ifdef ANDROID
 using _STLP_STD_NAME::hash_map;
 using _STLP_STD_NAME::hash_set;
 #else
 using stdext::hash_map;
 using stdext::hash_set;
 #endif
--- a/ipc/chromium/src/base/task.h
+++ b/ipc/chromium/src/base/task.h
@@ -192,17 +192,18 @@ class ScopedRunnableMethodFactory : publ
       obj_ = obj;
       meth_ = meth;
       params_ = params;
     }
 
     virtual void Run() { DispatchToMethod(obj_, meth_, params_); }
 
    private:
-    T* obj_;
+    T* MOZ_UNSAFE_REF("The validity of this pointer must be enforced by "
+                      "external factors.") obj_;
     Method meth_;
     Params params_;
 
     DISALLOW_EVIL_CONSTRUCTORS(RunnableMethod);
   };
 
  private:
   T* object_;
@@ -220,34 +221,36 @@ class DeleteTask : public CancelableTask
   }
   virtual void Run() {
     delete obj_;
   }
   virtual void Cancel() {
     obj_ = NULL;
   }
  private:
-  T* obj_;
+  T* MOZ_UNSAFE_REF("The validity of this pointer must be enforced by "
+                    "external factors.") obj_;
 };
 
 // Task to Release() an object
 template<class T>
 class ReleaseTask : public CancelableTask {
  public:
   explicit ReleaseTask(T* obj) : obj_(obj) {
   }
   virtual void Run() {
     if (obj_)
       obj_->Release();
   }
   virtual void Cancel() {
     obj_ = NULL;
   }
  private:
-  T* obj_;
+  T* MOZ_UNSAFE_REF("The validity of this pointer must be enforced by "
+                    "external factors.") obj_;
 };
 
 // RunnableMethodTraits --------------------------------------------------------
 //
 // This traits-class is used by RunnableMethod to manage the lifetime of the
 // callee object.  By default, it is assumed that the callee supports AddRef
 // and Release methods.  A particular class can specialize this template to
 // define other lifetime management.  For example, if the callee is known to
@@ -314,17 +317,19 @@ class RunnableMethod : public Cancelable
  private:
   void ReleaseCallee() {
     if (obj_) {
       RunnableMethodTraits<T>::ReleaseCallee(obj_);
       obj_ = NULL;
     }
   }
 
-  T* obj_;
+  // This is owning because of the RetainCallee and ReleaseCallee calls in the
+  // constructor and destructor.
+  T* MOZ_OWNING_REF obj_;
   Method meth_;
   Params params_;
 };
 
 template <class T, class Method>
 inline CancelableTask* NewRunnableMethod(T* object, Method method) {
   return new RunnableMethod<T, Method, Tuple0>(object, method, MakeTuple());
 }
@@ -508,17 +513,18 @@ inline CancelableTask* NewRunnableFuncti
 // Base for all Callbacks that handles storage of the pointers.
 template <class T, typename Method>
 class CallbackStorage {
  public:
   CallbackStorage(T* obj, Method meth) : obj_(obj), meth_(meth) {
   }
 
  protected:
-  T* obj_;
+  T* MOZ_UNSAFE_REF("The validity of this pointer must be enforced by "
+                    "external factors.") obj_;
   Method meth_;
 };
 
 // Interface that is exposed to the consumer, that does the actual calling
 // of the method.
 template <typename Params>
 class CallbackRunner {
  public:
--- a/ipc/ipdl/test/cxx/TestDataStructures.cpp
+++ b/ipc/ipdl/test/cxx/TestDataStructures.cpp
@@ -66,30 +66,30 @@ TestDataStructuresParent::DeallocPTestDa
     delete actor;
     if (mKids.Length() > 0)
         return true;
 
     return true;
 }
 
 bool TestDataStructuresParent::RecvTest1(
-        const InfallibleTArray<int>& ia,
+        InfallibleTArray<int>&& ia,
         InfallibleTArray<int>* oa)
 {
     test_assert(5 == ia.Length(), "wrong length");
     for (int i = 0; i < 5; ++i)
         test_assert(i == ia[i], "wrong value");
 
     *oa = ia;
 
     return true;
 }
 
 bool TestDataStructuresParent::RecvTest2(
-        const InfallibleTArray<PTestDataStructuresSubParent*>& i1,
+        InfallibleTArray<PTestDataStructuresSubParent*>&& i1,
         InfallibleTArray<PTestDataStructuresSubParent*>* o1)
 {
     test_assert(nactors == i1.Length(), "wrong #actors");
     for (uint32_t i = 0; i < i1.Length(); ++i)
         test_assert(i == Cast(i1[i]).mI, "wrong mI value");
     *o1 = i1;
     return true;
 }
@@ -105,17 +105,17 @@ bool TestDataStructuresParent::RecvTest3
 
     *o1 = i1;
     *o2 = i2;
 
     return true;
 }
 
 bool TestDataStructuresParent::RecvTest4(
-        const InfallibleTArray<IntDouble>& i1,
+        InfallibleTArray<IntDouble>&& i1,
         InfallibleTArray<IntDouble>* o1)
 {
     test_assert(4 == i1.Length(), "wrong length");
     test_assert(1 == i1[0].get_int(), "wrong value");
     test_assert(2.0 == i1[1].get_double(), "wrong value");
     test_assert(3 == i1[2].get_int(), "wrong value");
     test_assert(4.0 == i1[3].get_double(), "wrong value");    
 
@@ -166,17 +166,17 @@ TestDataStructuresParent::RecvTest7_0(co
     o1->actorParent() = mKids[0];
     // malicious behavior
     o1->actorChild() =
         reinterpret_cast<PTestDataStructuresSubChild*>(0xdeadbeef);
     return true;
 }
 
 bool TestDataStructuresParent::RecvTest6(
-        const InfallibleTArray<IntDoubleArrays>& i1,
+        InfallibleTArray<IntDoubleArrays>&& i1,
         InfallibleTArray<IntDoubleArrays>* o1)
 {
     test_assert(3 == i1.Length(), "wrong length");
 
     IntDoubleArrays id1(i1[0]);
     test_assert(42 == id1.get_int(), "wrong value");
 
     InfallibleTArray<int> i2a(i1[1].get_ArrayOfint());
@@ -219,17 +219,17 @@ bool TestDataStructuresParent::RecvTest7
     *o1 = 42;
     *o2 = i2a;
     *o3 = mKids;
 
     return true;
 }
 
 bool TestDataStructuresParent::RecvTest8(
-        const InfallibleTArray<Actors>& i1,
+        InfallibleTArray<Actors>&& i1,
         InfallibleTArray<Actors>* o1)
 {
     test_assert(3 == i1.Length(), "wrong length");
     test_assert(42 == i1[0].get_int(), "wrong value");
 
     const InfallibleTArray<int>& i2a = i1[1].get_ArrayOfint();
     test_assert(3 == i2a.Length(), "wrong length");
     test_assert(1 == i2a[0], "wrong value");
@@ -271,17 +271,17 @@ bool TestDataStructuresParent::RecvTest9
     *o2 = i2;
     *o3 = i3;
     *o4 = i4;
 
     return true;
 }
 
 bool TestDataStructuresParent::RecvTest10(
-        const InfallibleTArray<Unions>& i1,
+        InfallibleTArray<Unions>&& i1,
         InfallibleTArray<Unions>* o1)
 {
     test_assert(42 == i1[0].get_int(), "wrong value");
 
     const InfallibleTArray<int>& i2a = i1[1].get_ArrayOfint();
     test_assert(3 == i2a.Length(), "wrong length");
     test_assert(1 == i2a[0], "wrong value");
     test_assert(2 == i2a[1], "wrong value");
@@ -433,24 +433,24 @@ bool TestDataStructuresParent::RecvTest1
                         iau[3].get_ArrayOfActors()[0]
                         .get_ArrayOfPTestDataStructuresSubParent());
 
     *o = i;
 
     return true;
 }
 
-bool TestDataStructuresParent::RecvTest17(const InfallibleTArray<Op>& sa)
+bool TestDataStructuresParent::RecvTest17(InfallibleTArray<Op>&& sa)
 {
     test_assert(sa.Length() == 1 && Op::TSetAttrs == sa[0].type(),
                 "wrong value");
     return true;
 }
 
-bool TestDataStructuresParent::RecvTest18(const RegionArray& ra)
+bool TestDataStructuresParent::RecvTest18(RegionArray&& ra)
 {
     for (RegionArray::index_type i = 0; i < ra.Length(); ++i) {
         nsIntRegionRectIterator it(ra[i]);
         // if |ra| has been realloc()d and given a different allocator
         // chunk, this next line will nondeterministically crash or
         // iloop
         while (const nsIntRect* sr = it.Next()) unused << sr;
     }
--- a/ipc/ipdl/test/cxx/TestDataStructures.h
+++ b/ipc/ipdl/test/cxx/TestDataStructures.h
@@ -53,73 +53,73 @@ protected:
         PTestDataStructuresSubParent* actor = new TestDataStructuresSub(i);
         mKids.AppendElement(actor);
         return actor;
     }
 
     virtual bool DeallocPTestDataStructuresSubParent(PTestDataStructuresSubParent* actor) MOZ_OVERRIDE;
 
     virtual bool RecvTest1(
-            const InfallibleTArray<int>& i1,
+	    InfallibleTArray<int>&& i1,
             InfallibleTArray<int>* o1) MOZ_OVERRIDE;
 
     virtual bool RecvTest2(
-            const InfallibleTArray<PTestDataStructuresSubParent*>& i1,
+            InfallibleTArray<PTestDataStructuresSubParent*>&& i1,
             InfallibleTArray<PTestDataStructuresSubParent*>* o1) MOZ_OVERRIDE;
 
     virtual bool RecvTest3(
             const IntDouble& i1,
             const IntDouble& i2,
             IntDouble* o1,
             IntDouble* o2) MOZ_OVERRIDE;
 
     virtual bool RecvTest4(
-            const InfallibleTArray<IntDouble>& i1,
+            InfallibleTArray<IntDouble>&& i1,
             InfallibleTArray<IntDouble>* o1) MOZ_OVERRIDE;
 
     virtual bool RecvTest5(
             const IntDoubleArrays& i1,
             const IntDoubleArrays& i2,
             const IntDoubleArrays& i3,
             IntDoubleArrays* o1,
             IntDoubleArrays* o2,
             IntDoubleArrays* o3) MOZ_OVERRIDE;
 
     virtual bool RecvTest6(
-            const InfallibleTArray<IntDoubleArrays>& i1,
+            InfallibleTArray<IntDoubleArrays>&& i1,
             InfallibleTArray<IntDoubleArrays>* o1) MOZ_OVERRIDE;
 
 
     virtual bool RecvTest7_0(const ActorWrapper& i1,
                              ActorWrapper* o1) MOZ_OVERRIDE;
 
     virtual bool RecvTest7(
             const Actors& i1,
             const Actors& i2,
             const Actors& i3,
             Actors* o1,
             Actors* o2,
             Actors* o3) MOZ_OVERRIDE;
 
     virtual bool RecvTest8(
-            const InfallibleTArray<Actors>& i1,
+            InfallibleTArray<Actors>&& i1,
             InfallibleTArray<Actors>* o1) MOZ_OVERRIDE;
 
     virtual bool RecvTest9(
             const Unions& i1,
             const Unions& i2,
             const Unions& i3,
             const Unions& i4,
             Unions* o1,
             Unions* o2,
             Unions* o3,
             Unions* o4) MOZ_OVERRIDE;
 
     virtual bool RecvTest10(
-            const InfallibleTArray<Unions>& i1,
+            InfallibleTArray<Unions>&& i1,
             InfallibleTArray<Unions>* o1) MOZ_OVERRIDE;
 
     virtual bool RecvTest11(
             const SIntDouble& i,
             SIntDouble* o) MOZ_OVERRIDE;
 
     virtual bool RecvTest12(
             const SIntDoubleArrays& i,
@@ -144,19 +144,19 @@ protected:
             WithStructs* o3,
             WithStructs* o4,
             WithStructs* o5) MOZ_OVERRIDE;
 
     virtual bool RecvTest16(
             const WithUnions& i,
             WithUnions* o) MOZ_OVERRIDE;
 
-    virtual bool RecvTest17(const InfallibleTArray<Op>& sa) MOZ_OVERRIDE;
+    virtual bool RecvTest17(InfallibleTArray<Op>&& sa) MOZ_OVERRIDE;
 
-    virtual bool RecvTest18(const InfallibleTArray<nsIntRegion>& ra) MOZ_OVERRIDE;
+    virtual bool RecvTest18(InfallibleTArray<nsIntRegion>&& ra) MOZ_OVERRIDE;
 
     virtual bool RecvDummy(const ShmemUnion& su, ShmemUnion* rsu) MOZ_OVERRIDE
     {
         *rsu = su;
         return true;
     }
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE
--- a/ipc/ipdl/test/cxx/TestShmem.cpp
+++ b/ipc/ipdl/test/cxx/TestShmem.cpp
@@ -46,17 +46,17 @@ TestShmemParent::Main()
 
     // unsafe shmem gets rid of those checks
     char uc1 = *unsafeptr;  (void)uc1;
     char uc2 = *unsafecopy.get<char>(); (void)uc2;
 }
 
 
 bool
-TestShmemParent::RecvTake(Shmem& mem, Shmem& unsafe,
+TestShmemParent::RecvTake(Shmem&& mem, Shmem&& unsafe,
                           const size_t& expectedSize)
 {
     if (mem.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, mem.Size<char>());
     if (unsafe.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, unsafe.Size<char>());
@@ -75,17 +75,17 @@ TestShmemParent::RecvTake(Shmem& mem, Sh
 
     return true;
 }
 
 //-----------------------------------------------------------------------------
 // Child
 
 bool
-TestShmemChild::RecvGive(Shmem& mem, Shmem& unsafe, const size_t& expectedSize)
+TestShmemChild::RecvGive(Shmem&& mem, Shmem&& unsafe, const size_t& expectedSize)
 {
     if (mem.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, mem.Size<char>());
     if (unsafe.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, unsafe.Size<char>());
 
--- a/ipc/ipdl/test/cxx/TestShmem.h
+++ b/ipc/ipdl/test/cxx/TestShmem.h
@@ -19,18 +19,18 @@ public:
 
     static bool RunTestInProcesses() { return true; }
     static bool RunTestInThreads() { return true; }
 
     void Main();
 
 protected:
     virtual bool RecvTake(
-            Shmem& mem,
-            Shmem& unsafe,
+            Shmem&& mem,
+            Shmem&& unsafe,
             const size_t& expectedSize) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE
     {
         if (NormalShutdown != why)
             fail("unexpected destruction!");  
         passed("ok");
         QuitParent();
@@ -42,18 +42,18 @@ class TestShmemChild :
     public PTestShmemChild
 {
 public:
     TestShmemChild() { }
     virtual ~TestShmemChild() { }
 
 protected:
     virtual bool RecvGive(
-            Shmem& mem,
-            Shmem& unsafe,
+            Shmem&& mem,
+            Shmem&& unsafe,
             const size_t& expectedSize) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE
     {
         if (NormalShutdown != why)
             fail("unexpected destruction!");
         QuitChild();
     }
--- a/ipc/ipdl/test/cxx/TestSysVShmem.cpp
+++ b/ipc/ipdl/test/cxx/TestSysVShmem.cpp
@@ -51,17 +51,17 @@ TestSysVShmemParent::Main()
 
     // unsafe shmem gets rid of those checks
     char uc1 = *unsafeptr;  (void)uc1;
     char uc2 = *unsafecopy.get<char>(); (void)uc2;
 }
 
 
 bool
-TestSysVShmemParent::RecvTake(Shmem& mem, Shmem& unsafe,
+TestSysVShmemParent::RecvTake(Shmem&& mem, Shmem&& unsafe,
                           const size_t& expectedSize)
 {
     if (mem.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, mem.Size<char>());
     if (unsafe.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, unsafe.Size<char>());
@@ -80,17 +80,17 @@ TestSysVShmemParent::RecvTake(Shmem& mem
 
     return true;
 }
 
 //-----------------------------------------------------------------------------
 // Child
 
 bool
-TestSysVShmemChild::RecvGive(Shmem& mem, Shmem& unsafe, const size_t& expectedSize)
+TestSysVShmemChild::RecvGive(Shmem&& mem, Shmem&& unsafe, const size_t& expectedSize)
 {
     if (mem.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, mem.Size<char>());
     if (unsafe.Size<char>() != expectedSize)
         fail("expected shmem size %lu, but it has size %lu",
              expectedSize, unsafe.Size<char>());
 
--- a/ipc/ipdl/test/cxx/TestSysVShmem.h
+++ b/ipc/ipdl/test/cxx/TestSysVShmem.h
@@ -19,18 +19,18 @@ public:
 
     static bool RunTestInProcesses() { return true; }
     static bool RunTestInThreads() { return true; }
 
     void Main();
 
 protected:
     virtual bool RecvTake(
-            Shmem& mem,
-            Shmem& unsafe,
+            Shmem&& mem,
+            Shmem&& unsafe,
             const size_t& expectedSize) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE
     {
         if (NormalShutdown != why)
             fail("unexpected destruction!");  
         passed("ok");
         QuitParent();
@@ -42,18 +42,18 @@ class TestSysVShmemChild :
     public PTestSysVShmemChild
 {
 public:
     TestSysVShmemChild() { }
     virtual ~TestSysVShmemChild() { }
 
 protected:
     virtual bool RecvGive(
-            Shmem& mem,
-            Shmem& unsafe,
+            Shmem&& mem,
+            Shmem&& unsafe,
             const size_t& expectedSize) MOZ_OVERRIDE;
 
     virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE
     {
         if (NormalShutdown != why)
             fail("unexpected destruction!");
         QuitChild();
     }
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -1746,27 +1746,25 @@ ia64*-hpux*)
         WIN32_CONSOLE_EXE_LDFLAGS=-SUBSYSTEM:CONSOLE,$WIN32_SUBSYSTEM_VERSION
         WIN32_GUI_EXE_LDFLAGS=-SUBSYSTEM:WINDOWS,$WIN32_SUBSYSTEM_VERSION
         DSO_LDOPTS=-SUBSYSTEM:WINDOWS,$WIN32_SUBSYSTEM_VERSION
         _USE_CPP_INCLUDE_FLAG=1
         _DEFINES_CFLAGS='-FI $(DEPTH)/js/src/js-confdefs.h -DMOZILLA_CLIENT'
         _DEFINES_CXXFLAGS='-FI $(DEPTH)/js/src/js-confdefs.h -DMOZILLA_CLIENT'
         CFLAGS="$CFLAGS -W3 -Gy"
         CXXFLAGS="$CXXFLAGS -W3 -Gy"
-        if test "$_CC_SUITE" -ge "11" -a "$CPU_ARCH" = "x86"; then
+        if test "$CPU_ARCH" = "x86"; then
             dnl VS2012+ defaults to -arch:SSE2.
             CFLAGS="$CFLAGS -arch:IA32"
             CXXFLAGS="$CXXFLAGS -arch:IA32"
         fi
-        if test "$_CC_SUITE" -ge "12"; then
-            dnl VS2013+ requires -FS when parallel building by make -jN.
-            dnl If nothing, compiler sometimes causes C1041 error.
-            CFLAGS="$CFLAGS -FS"
-            CXXFLAGS="$CXXFLAGS -FS"
-        fi
+        dnl VS2013+ requires -FS when parallel building by make -jN.
+        dnl If nothing, compiler sometimes causes C1041 error.
+        CFLAGS="$CFLAGS -FS"
+        CXXFLAGS="$CXXFLAGS -FS"
         # khuey says we can safely ignore MSVC warning C4251
         # MSVC warning C4244 (implicit type conversion may lose data) warns
         # and requires workarounds for perfectly valid code.  Also, GCC/clang
         # don't warn about it by default. So for consistency/sanity, we turn
         # it off on MSVC, too.
         # MSVC warning C4267 warns for narrowing type conversions from size_t
         # to 32-bit integer types on 64-bit platforms.  Since this is virtually
         # the same thing as C4244, we disable C4267, too.
--- a/js/src/jit/LIR.cpp
+++ b/js/src/jit/LIR.cpp
@@ -105,17 +105,19 @@ LBlock::init(TempAllocator &alloc)
 
         int numPhis = (phi->type() == MIRType_Value) ? BOX_PIECES : 1;
         for (int i = 0; i < numPhis; i++) {
             void *array = alloc.allocateArray<sizeof(LAllocation)>(numPreds);
             LAllocation *inputs = static_cast<LAllocation *>(array);
             if (!inputs)
                 return false;
 
-            LPhi *lphi = new (&phis_[phiIndex++]) LPhi(phi, inputs);
+            // MSVC 2015 cannot handle "new (&phis_[phiIndex++])"
+            void *addr = &phis_[phiIndex++];
+            LPhi *lphi = new (addr) LPhi(phi, inputs);
             lphi->setBlock(this);
         }
     }
     return true;
 }
 
 const LInstruction *
 LBlock::firstInstructionWithId() const
--- a/js/src/jsmath.cpp
+++ b/js/src/jsmath.cpp
@@ -1410,16 +1410,18 @@ js::math_hypot_handle(JSContext *cx, Han
 
     for (unsigned i = 0; i < args.length(); i++) {
         double x;
         if (!ToNumber(cx, args[i], &x))
             return false;
 
         isInfinite |= mozilla::IsInfinite(x);
         isNaN |= mozilla::IsNaN(x);
+        if (isInfinite || isNaN)
+            continue;
 
         double xabs = mozilla::Abs(x);
 
         if (scale < xabs) {
             sumsq = 1 + sumsq * (scale / xabs) * (scale / xabs);
             scale = xabs;
         } else if (scale != 0) {
             sumsq += (xabs / scale) * (xabs / scale);
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -2465,16 +2465,18 @@ DisassWithSrc(JSContext *cx, unsigned ar
             len = js_Disassemble1(cx, script, pc, script->pcToOffset(pc), true, &sprinter);
             if (!len) {
                 ok = false;
                 goto bail;
             }
             pc += len;
         }
 
+        fprintf(stdout, "%s\n", sprinter.string());
+
       bail:
         fclose(file);
     }
     args.rval().setUndefined();
     return ok;
 #undef LINE_BUF_LEN
 }
 
--- a/js/xpconnect/src/xpcpublic.h
+++ b/js/xpconnect/src/xpcpublic.h
@@ -201,17 +201,21 @@ class XPCStringConvert
 {
     // One-slot cache, because it turns out it's common for web pages to
     // get the same string a few times in a row.  We get about a 40% cache
     // hit rate on this cache last it was measured.  We'd get about 70%
     // hit rate with a hashtable with removal on finalization, but that
     // would take a lot more machinery.
     struct ZoneStringCache
     {
-        nsStringBuffer* mBuffer;
+        // mString owns mBuffer.  mString is a JS thing, so it can only die
+        // during GC.  We clear mString and mBuffer during GC.  As long as
+        // the above holds, mBuffer should not be a dangling pointer, so
+        // using this as a cache key should be safe.
+        void* mBuffer;
         JSString* mString;
     };
 
 public:
 
     // If the string shares the readable's buffer, that buffer will
     // get assigned to *sharedBuffer.  Otherwise null will be
     // assigned.
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -796,16 +796,17 @@ PresShell::PresShell()
   if (!addedPointerEventEnabled) {
     Preferences::AddBoolVarCache(&sPointerEventEnabled,
                                  "dom.w3c_pointer_events.enabled", true);
     addedPointerEventEnabled = true;
   }
 
   mPaintingIsFrozen = false;
   mHasCSSBackgroundColor = true;
+  mIsLastChromeOnlyEscapeKeyConsumed = false;
 }
 
 NS_IMPL_ISUPPORTS(PresShell, nsIPresShell, nsIDocumentObserver,
                   nsISelectionController,
                   nsISelectionDisplay, nsIObserver, nsISupportsWeakReference,
                   nsIMutationObserver)
 
 PresShell::~PresShell()
@@ -8000,33 +8001,36 @@ PresShell::HandleEventInternal(WidgetEve
           if ((fullscreenAncestor = nsContentUtils::GetFullscreenAncestor(doc))) {
             // Prevent default action on ESC key press when exiting
             // DOM fullscreen mode. This prevents the browser ESC key
             // handler from stopping all loads in the document, which
             // would cause <video> loads to stop.
             aEvent->mFlags.mDefaultPrevented = true;
             aEvent->mFlags.mOnlyChromeDispatch = true;
 
-            if (aEvent->message == NS_KEY_UP) {
+            // The event listeners in chrome can prevent this ESC behavior by
+            // calling prevent default on the preceding keydown/press events.
+            if (!mIsLastChromeOnlyEscapeKeyConsumed &&
+                aEvent->message == NS_KEY_UP) {
               // ESC key released while in DOM fullscreen mode.
               // If fullscreen is running in content-only mode, exit the target
               // doctree branch from fullscreen, otherwise fully exit all
               // browser windows and documents from fullscreen mode.
               // Note: in the content-only fullscreen case, we pass the
               // fullscreenAncestor since |doc| may not actually be fullscreen
               // here, and ExitFullscreen() has no affect when passed a
               // non-fullscreen document.
               nsIDocument::ExitFullscreen(
                 nsContentUtils::IsFullscreenApiContentOnly() ? fullscreenAncestor : nullptr,
                 /* async */ true);
             }
           }
           nsCOMPtr<nsIDocument> pointerLockedDoc =
             do_QueryReferent(EventStateManager::sPointerLockedDoc);
-          if (pointerLockedDoc) {
+          if (!mIsLastChromeOnlyEscapeKeyConsumed && pointerLockedDoc) {
             aEvent->mFlags.mDefaultPrevented = true;
             aEvent->mFlags.mOnlyChromeDispatch = true;
             if (aEvent->message == NS_KEY_UP) {
               nsIDocument::UnlockPointer();
             }
           }
         }
         // Else not full-screen mode or key code is unrestricted, fall
@@ -8251,21 +8255,40 @@ PresShell::HandleEventInternal(WidgetEve
       // 3. Give event to event manager for post event state changes and
       //    generation of synthetic events.
       if (!mIsDestroying && NS_SUCCEEDED(rv)) {
         rv = manager->PostHandleEvent(mPresContext, aEvent,
                                       GetCurrentEventFrame(), aStatus);
       }
     }
 
-    if (aEvent->message == NS_MOUSE_BUTTON_UP) {
+    switch (aEvent->message) {
+    case NS_KEY_PRESS:
+    case NS_KEY_DOWN:
+    case NS_KEY_UP: {
+      if (aEvent->AsKeyboardEvent()->keyCode == NS_VK_ESCAPE) {
+        if (aEvent->message == NS_KEY_UP) {
+          // Reset this flag after key up is handled.
+          mIsLastChromeOnlyEscapeKeyConsumed = false;
+        } else {
+          if (aEvent->mFlags.mOnlyChromeDispatch &&
+              aEvent->mFlags.mDefaultPreventedByChrome) {
+            mIsLastChromeOnlyEscapeKeyConsumed = true;
+          }
+        }
+      }
+      break;
+    }
+    case NS_MOUSE_BUTTON_UP:
       // reset the capturing content now that the mouse button is up
       SetCapturingContent(nullptr, 0);
-    } else if (aEvent->message == NS_MOUSE_MOVE) {
+      break;
+    case NS_MOUSE_MOVE:
       nsIPresShell::AllowMouseCapture(false);
+      break;
     }
   }
   return rv;
 }
 
 void
 nsIPresShell::DispatchGotOrLostPointerCaptureEvent(bool aIsGotCapture,
                                                    uint32_t aPointerId,
--- a/layout/base/nsPresShell.h
+++ b/layout/base/nsPresShell.h
@@ -863,12 +863,15 @@ protected:
 
   bool                      mHasCSSBackgroundColor : 1;
 
   // Whether content should be scaled by the resolution amount. If this is
   // not set, a transform that scales by the inverse of the resolution is
   // applied to rendered layers.
   bool                      mScaleToResolution : 1;
 
+  // Whether the last chrome-only escape key event is consumed.
+  bool                      mIsLastChromeOnlyEscapeKeyConsumed : 1;
+
   static bool               sDisableNonTestMouseEvents;
 };
 
 #endif /* !defined(nsPresShell_h_) */
--- a/layout/build/moz.build
+++ b/layout/build/moz.build
@@ -62,17 +62,17 @@ LOCAL_INCLUDES += [
     '/dom/xul/templates',
     '/editor/composer',
     '/editor/libeditor',
     '/editor/txmgr',
     '/editor/txtsvc',
     '/extensions/cookie',
     '/js/xpconnect/loader',
     '/js/xpconnect/src',
-    '/netwerk/base/src',
+    '/netwerk/base',
     '/netwerk/cookie',
     '/view',
 ]
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
     LOCAL_INCLUDES += [
         '/dom/system/windows',
     ]
--- a/layout/svg/nsSVGMaskFrameNEON.cpp
+++ b/layout/svg/nsSVGMaskFrameNEON.cpp
@@ -26,29 +26,29 @@ ComputesRGBLuminanceMask_NEON(const uint
   sourcePixel = aSourceData;
   int32_t remainderWidth = aSize.width % 8;
   int32_t roundedWidth = aSize.width - remainderWidth;
   uint16x8_t temp;
   uint8x8_t gray;
   uint8x8_t redVector = vdup_n_u8(redFactor);
   uint8x8_t greenVector = vdup_n_u8(greenFactor);
   uint8x8_t blueVector = vdup_n_u8(blueFactor);
-  uint8x8_t zeroVector = vdup_n_u8(0);
+  uint8x8_t fullBitVector = vdup_n_u8(255);
   uint8x8_t oneVector = vdup_n_u8(1);
   for (int32_t y = 0; y < aSize.height; y++) {
     // Calculate luminance by neon with 8 pixels per loop
     for (int32_t x = 0; x < roundedWidth; x += 8) {
       uint8x8x4_t argb  = vld4_u8(sourcePixel);
       temp = vmull_u8(argb.val[GFX_ARGB32_OFFSET_R], redVector); // temp = red * redFactor
       temp = vmlal_u8(temp, argb.val[GFX_ARGB32_OFFSET_G], greenVector); // temp += green * greenFactor
       temp = vmlal_u8(temp, argb.val[GFX_ARGB32_OFFSET_B], blueVector); // temp += blue * blueFactor
       gray = vshrn_n_u16(temp, 8); // gray = temp >> 8
 
       // Check alpha value
-      uint8x8_t alphaVector = vcgt_u8(argb.val[GFX_ARGB32_OFFSET_A], zeroVector);
+      uint8x8_t alphaVector = vtst_u8(argb.val[GFX_ARGB32_OFFSET_A], fullBitVector);
       gray = vmul_u8(gray, vand_u8(alphaVector, oneVector));
 
       // Put the result to the 8 pixels
       vst1_u8(destPixel, gray);
       sourcePixel += 8 * 4;
       destPixel += 8;
     }
 
--- a/media/libjpeg/MOZCHANGES
+++ b/media/libjpeg/MOZCHANGES
@@ -7,18 +7,18 @@ To upgrade to a new revision of libjpeg-
 * In a clean clone of mozilla-central, run the following commands
 
     $ rm -rf media/libjpeg
     $ svn export --ignore-externals /path/to/libjpeg-turbo media/libjpeg
     $ cd media/libjpeg
 
 * Copy win/jsimdcfg.inc to simd/.
 
-* Since libjpeg-turbo normally creates config.h and jconfig.h at build time and
-  we use pre-generated versions, changes to jconfig.h.in and win/config.h.in
+* Since libjpeg-turbo normally creates jconfig.h and jconfigint.h at build time
+  and we use pre-generated versions, changes to jconfig.h.in and jconfigint.h.in
   should be looked for and noted for later inclusion.
 
 * Now look through the new files and rm any which are npotb.  When I upgraded
   to libjpeg-turbo 1.1.0, the only files I kept which didn't match
 
     *.c  *.h *.asm *.inc
 
   were README and README-turbo.
@@ -38,31 +38,35 @@ To upgrade to a new revision of libjpeg-
 
     diff <(ls *.c | sort) <(grep -o '\w*\.c' Makefile.in | sort)
 
   Of course, libjpeg-turbo might have added some new source files, so you'll
   have to look though and figure out which of these files to keep.
 
 * Restore files modified in the Mozilla repository.
 
-    $ hg revert --no-backup config.h jconfig.h Makefile.in MOZCHANGES \
+    $ hg revert --no-backup jconfig.h jconfigint.h Makefile.in MOZCHANGES \
       mozilla.diff simd/Makefile.in genTables.py
 
-* Update config.h and jconfig.h as noted previously.
+* Update jconfig.h and jconfigint.h as noted previously.
 
 * Apply Mozilla-specific changes to upstream files.
 
     $ patch -p0 -i mozilla.diff
 
 * Update Makefile.in to build any new files.
 
 * Finally, tell hg that we've added or removed some files:
 
     $ hg addremove
 
+== January 15, 2015 (libjpeg-turbo v1.4.0 r1481 2015-01-07) ==
+
+* Updated to v1.4.0 release.
+
 == March 24, 2014 (libjpeg-turbo v1.3.1 r1205 2014-03-22) ==
 
 * Updated to v1.3.1 release.
 
 == November 25, 2013 ==
 
 * Fix bug 891693.
 
--- a/media/libjpeg/Makefile.in
+++ b/media/libjpeg/Makefile.in
@@ -9,10 +9,8 @@ ASFLAGS=$(LIBJPEG_TURBO_ASFLAGS) -I$(top
 
 ifeq ($(AS),yasm)
   # yasm doesn't like -c
   AS_DASH_C_FLAG=
 endif
 
 include $(topsrcdir)/config/rules.mk
 
-jpeg_nbits_table.h: $(srcdir)/genTables.py
-	$(PYTHON) $(srcdir)/genTables.py
--- a/media/libjpeg/README
+++ b/media/libjpeg/README
@@ -31,43 +31,42 @@ LEGAL ISSUES        Copyright, lack of w
 REFERENCES          Where to learn more about JPEG.
 ARCHIVE LOCATIONS   Where to find newer versions of this software.
 FILE FORMAT WARS    Software *not* to get.
 TO DO               Plans for future IJG releases.
 
 Other documentation files in the distribution are:
 
 User documentation:
-  install.txt       How to configure and install the IJG software.
   usage.txt         Usage instructions for cjpeg, djpeg, jpegtran,
                     rdjpgcom, and wrjpgcom.
   *.1               Unix-style man pages for programs (same info as usage.txt).
   wizard.txt        Advanced usage instructions for JPEG wizards only.
   change.log        Version-to-version change highlights.
 Programmer and internal documentation:
   libjpeg.txt       How to use the JPEG library in your own programs.
   example.c         Sample code for calling the JPEG library.
   structure.txt     Overview of the JPEG library's internal structure.
   coderules.txt     Coding style rules --- please read if you contribute code.
 
-Please read at least the files install.txt and usage.txt.  Some information
-can also be found in the JPEG FAQ (Frequently Asked Questions) article.  See
-ARCHIVE LOCATIONS below to find out where to obtain the FAQ article.
+Please read at least usage.txt.  Some information can also be found in the JPEG
+FAQ (Frequently Asked Questions) article.  See ARCHIVE LOCATIONS below to find
+out where to obtain the FAQ article.
 
 If you want to understand how the JPEG code works, we suggest reading one or
 more of the REFERENCES, then looking at the documentation files (in roughly
 the order listed) before diving into the code.
 
 
 OVERVIEW
 ========
 
 This package contains C software to implement JPEG image encoding, decoding,
 and transcoding.  JPEG (pronounced "jay-peg") is a standardized compression
-method for full-color and gray-scale images.  JPEG's strong suit is compressing
+method for full-color and grayscale images.  JPEG's strong suit is compressing
 photographic images or other types of images that have smooth color and
 brightness transitions between neighboring pixels.  Images with sharp lines or
 other abrupt features may not compress well with JPEG, and a higher JPEG
 quality may have to be used to avoid visible compression artifacts with such
 images.
 
 JPEG is lossy, meaning that the output pixels are not necessarily identical to
 the input pixels.  However, on photographic content and other "smooth" images,
old mode 100644
new mode 100755
--- a/media/libjpeg/README-turbo.txt
+++ b/media/libjpeg/README-turbo.txt
@@ -76,141 +76,16 @@ JPEG images:
   API but also more powerful.  The libjpeg API implementation in libjpeg-turbo
   is both API/ABI-compatible and mathematically compatible with libjpeg v6b.
   It can also optionally be configured to be API/ABI-compatible with libjpeg v7
   and v8 (see below.)
 
 There is no significant performance advantage to either API when both are used
 to perform similar operations.
 
-======================
-Installation Directory
-======================
-
-This document assumes that libjpeg-turbo will be installed in the default
-directory (/opt/libjpeg-turbo on Un*x and Mac systems and
-c:\libjpeg-turbo[-gcc][64] on Windows systems.  If your installation of
-libjpeg-turbo resides in a different directory, then adjust the instructions
-accordingly.
-
-=============================
-Replacing libjpeg at Run Time
-=============================
-
-Un*x
-----
-
-If a Un*x application is dynamically linked with libjpeg, then you can replace
-libjpeg with libjpeg-turbo at run time by manipulating LD_LIBRARY_PATH.
-For instance:
-
-  [Using libjpeg]
-  > time cjpeg <vgl_5674_0098.ppm >vgl_5674_0098.jpg
-  real  0m0.392s
-  user  0m0.074s
-  sys   0m0.020s
-
-  [Using libjpeg-turbo]
-  > export LD_LIBRARY_PATH=/opt/libjpeg-turbo/{lib}:$LD_LIBRARY_PATH
-  > time cjpeg <vgl_5674_0098.ppm >vgl_5674_0098.jpg
-  real  0m0.109s
-  user  0m0.029s
-  sys   0m0.010s
-
-({lib} = lib32 or lib64, depending on whether you wish to use the 32-bit or the
-64-bit version of libjpeg-turbo.)
-
-System administrators can also replace the libjpeg symlinks in /usr/lib* with
-links to the libjpeg-turbo dynamic library located in /opt/libjpeg-turbo/{lib}.
-This will effectively accelerate every application that uses the libjpeg
-dynamic library on the system.
-
-Windows
--------
-
-If a Windows application is dynamically linked with libjpeg, then you can
-replace libjpeg with libjpeg-turbo at run time by backing up the application's
-copy of jpeg62.dll, jpeg7.dll, or jpeg8.dll (assuming the application has its
-own local copy of this library) and copying the corresponding DLL from
-libjpeg-turbo into the application's install directory.  The official
-libjpeg-turbo binary packages only provide jpeg62.dll.  If the application uses
-jpeg7.dll or jpeg8.dll instead, then it will be necessary to build
-libjpeg-turbo from source (see "libjpeg v7 and v8 API/ABI Emulation" below.)
-
-The following information is specific to the official libjpeg-turbo binary
-packages for Visual C++:
-
--- jpeg62.dll requires the Visual C++ 2008 C run-time DLL (msvcr90.dll).
-msvcr90.dll ships with more recent versions of Windows, but users of older
-Windows releases can obtain it from the Visual C++ 2008 Redistributable
-Package, which is available as a free download from Microsoft's web site.
-
--- Features of the libjpeg API that require passing a C run-time structure,
-such as a file handle, from an application to the library will probably not
-work with jpeg62.dll, unless the application is also built to use the Visual
-C++ 2008 C run-time DLL.  In particular, this affects jpeg_stdio_dest() and
-jpeg_stdio_src().
-
-Mac
----
-
-Mac applications typically embed their own copies of the libjpeg dylib inside
-the (hidden) application bundle, so it is not possible to globally replace
-libjpeg on OS X systems.  Replacing the application's version of the libjpeg
-dylib would generally involve copying libjpeg.*.dylib from libjpeg-turbo into
-the appropriate place in the application bundle and using install_name_tool to
-repoint the libjpeg-turbo dylib to its new directory.  This requires an
-advanced knowledge of OS X and would not survive an upgrade or a re-install of
-the application.  Thus, it is not recommended for most users.
-
-========================================
-Using libjpeg-turbo in Your Own Programs
-========================================
-
-For the most part, libjpeg-turbo should work identically to libjpeg, so in
-most cases, an application can be built against libjpeg and then run against
-libjpeg-turbo.  On Un*x systems and Cygwin, you can build against libjpeg-turbo
-instead of libjpeg by setting
-
-  CPATH=/opt/libjpeg-turbo/include
-  and
-  LIBRARY_PATH=/opt/libjpeg-turbo/{lib}
-
-({lib} = lib32 or lib64, depending on whether you are building a 32-bit or a
-64-bit application.)
-
-If using MinGW, then set
-
-  CPATH=/c/libjpeg-turbo-gcc[64]/include
-  and
-  LIBRARY_PATH=/c/libjpeg-turbo-gcc[64]/lib
-
-Building against libjpeg-turbo is useful, for instance, if you want to build an
-application that leverages the libjpeg-turbo colorspace extensions (see below.)
-On Un*x systems, you would still need to manipulate LD_LIBRARY_PATH or create
-appropriate symlinks to use libjpeg-turbo at run time.  On such systems, you
-can pass -R /opt/libjpeg-turbo/{lib} to the linker to force the use of
-libjpeg-turbo at run time rather than libjpeg (also useful if you want to
-leverage the colorspace extensions), or you can link against the libjpeg-turbo
-static library.
-
-To force a Un*x or MinGW application to link against the static version of
-libjpeg-turbo, you can use the following linker options:
-
-  -Wl,-Bstatic -ljpeg -Wl,-Bdynamic
-
-On OS X, simply add /opt/libjpeg-turbo/lib/libjpeg.a to the linker command
-line.
-
-To build Visual C++ applications using libjpeg-turbo, add
-c:\libjpeg-turbo[64]\include to the system or user INCLUDE environment
-variable and c:\libjpeg-turbo[64]\lib to the system or user LIB environment
-variable, and then link against either jpeg.lib (to use the DLL version of
-libjpeg-turbo) or jpeg-static.lib (to use the static version of libjpeg-turbo.)
-
 =====================
 Colorspace Extensions
 =====================
 
 libjpeg-turbo includes extensions that allow JPEG images to be compressed
 directly from (and decompressed directly to) buffers that use BGR, BGRX,
 RGBX, XBGR, and XRGB pixel ordering.  This is implemented with ten new
 colorspace constants:
@@ -260,17 +135,17 @@ for the existence of the colorspace exte
 libjpeg v7 and v8 API/ABI Emulation
 ===================================
 
 With libjpeg v7 and v8, new features were added that necessitated extending the
 compression and decompression structures.  Unfortunately, due to the exposed
 nature of those structures, extending them also necessitated breaking backward
 ABI compatibility with previous libjpeg releases.  Thus, programs that were
 built to use libjpeg v7 or v8 did not work with libjpeg-turbo, since it is
-based on the libjpeg v6b code base.  Although libjpeg v7 and v8 are still not
+based on the libjpeg v6b code base.  Although libjpeg v7 and v8 are not
 as widely used as v6b, enough programs (including a few Linux distros) made
 the switch that there was a demand to emulate the libjpeg v7 and v8 ABIs
 in libjpeg-turbo.  It should be noted, however, that this feature was added
 primarily so that applications that had already been compiled to use libjpeg
 v7+ could take advantage of accelerated baseline JPEG encoding/decoding
 without recompiling.  libjpeg-turbo does not claim to support all of the
 libjpeg v7+ features, nor to produce identical output to libjpeg v7+ in all
 cases (see below.)
@@ -414,37 +289,50 @@ details.
 
 
 *******************************************************************************
 **     Mathematical Compatibility
 *******************************************************************************
 
 For the most part, libjpeg-turbo should produce identical output to libjpeg
 v6b.  The one exception to this is when using the floating point DCT/IDCT, in
-which case the outputs of libjpeg v6b and libjpeg-turbo are not guaranteed to
-be identical (the accuracy of the floating point DCT/IDCT is constant when
-using libjpeg-turbo's SIMD extensions, but otherwise, it can depend heavily on
-the compiler and compiler settings.)
+which case the outputs of libjpeg v6b and libjpeg-turbo can differ for the
+following reasons:
+
+-- The SSE/SSE2 floating point DCT implementation in libjpeg-turbo is ever so
+   slightly more accurate than the implementation in libjpeg v6b, but not by
+   any amount perceptible to human vision (generally in the range of 0.01 to
+   0.08 dB gain in PNSR.)
+-- When not using the SIMD extensions, libjpeg-turbo uses the more accurate
+   (and slightly faster) floating point IDCT algorithm introduced in libjpeg
+   v8a as opposed to the algorithm used in libjpeg v6b.  It should be noted,
+   however, that this algorithm basically brings the accuracy of the floating
+   point IDCT in line with the accuracy of the slow integer IDCT.  The floating
+   point DCT/IDCT algorithms are mainly a legacy feature, and they do not
+   produce significantly more accuracy than the slow integer algorithms (to put
+   numbers on this, the typical difference in PNSR between the two algorithms
+   is less than 0.10 dB, whereas changing the quality level by 1 in the upper
+   range of the quality scale is typically more like a 1.0 dB difference.)
+-- When not using the SIMD extensions, then the accuracy of the floating point
+   DCT/IDCT can depend on the compiler and compiler settings.
 
 While libjpeg-turbo does emulate the libjpeg v8 API/ABI, under the hood, it is
 still using the same algorithms as libjpeg v6b, so there are several specific
 cases in which libjpeg-turbo cannot be expected to produce the same output as
 libjpeg v8:
 
 -- When decompressing using scaling factors of 1/2 and 1/4, because libjpeg v8
-   implements those scaling algorithms a bit differently than libjpeg v6b does,
-   and libjpeg-turbo's SIMD extensions are based on the libjpeg v6b behavior.
+   implements those scaling algorithms differently than libjpeg v6b does, and
+   libjpeg-turbo's SIMD extensions are based on the libjpeg v6b behavior.
 
 -- When using chrominance subsampling, because libjpeg v8 implements this
    with its DCT/IDCT scaling algorithms rather than with a separate
-   downsampling/upsampling algorithm.
-
--- When using the floating point IDCT, for the reasons stated above and also
-   because the floating point IDCT algorithm was modified in libjpeg v8a to
-   improve accuracy.
+   downsampling/upsampling algorithm.  In our testing, the subsampled/upsampled
+   output of libjpeg v8 is less accurate than that of libjpeg v6b for this
+   reason.
 
 -- When decompressing using a scaling factor > 1 and merged (AKA "non-fancy" or
    "non-smooth") chrominance upsampling, because libjpeg v8 does not support
    merged upsampling with scaling factors > 1.
 
 
 *******************************************************************************
 **     Performance Pitfalls
deleted file mode 100644
--- a/media/libjpeg/genTables.py
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/usr/bin/python
-
-import math
-
-f = open("jpeg_nbits_table.h", "w")
-
-for i in range(65536):
-    f.write('%2d' % math.ceil(math.log(i + 1, 2)))
-    if i != 65535:
-        f.write(',')
-    if (i + 1) % 16 == 0:
-        f.write('\n')
-    else:
-        f.write(' ')
-
-f.close()
--- a/media/libjpeg/jcapimin.c
+++ b/media/libjpeg/jcapimin.c
@@ -1,14 +1,16 @@
 /*
  * jcapimin.c
  *
+ * This file was part of the Independent JPEG Group's software:
  * Copyright (C) 1994-1998, Thomas G. Lane.
  * Modified 2003-2010 by Guido Vollbeding.
- * This file is part of the Independent JPEG Group's software.
+ * It was modified by The libjpeg-turbo Project to include only code relevant
+ * to libjpeg-turbo.
  * For conditions of distribution and use, see the accompanying README file.
  *
  * This file contains application interface code for the compression half
  * of the JPEG library.  These are the "minimum" API routines that may be
  * needed in either the normal full-compression case or the transcoding-only
  * case.
  *
  * Most of the routines intended to be called directly by an application
@@ -28,33 +30,33 @@
  */
 
 GLOBAL(void)
 jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
 {
   int i;
 
   /* Guard against version mismatches between library and caller. */
-  cinfo->mem = NULL;		/* so jpeg_destroy knows mem mgr not called */
+  cinfo->mem = NULL;            /* so jpeg_destroy knows mem mgr not called */
   if (version != JPEG_LIB_VERSION)
     ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
-  if (structsize != SIZEOF(struct jpeg_compress_struct))
-    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, 
-	     (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
+  if (structsize != sizeof(struct jpeg_compress_struct))
+    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
+             (int) sizeof(struct jpeg_compress_struct), (int) structsize);
 
   /* For debugging purposes, we zero the whole master structure.
    * But the application has already set the err pointer, and may have set
    * client_data, so we have to save and restore those fields.
    * Note: if application hasn't set client_data, tools like Purify may
    * complain here.
    */
   {
     struct jpeg_error_mgr * err = cinfo->err;
     void * client_data = cinfo->client_data; /* ignore Purify complaint here */
-    MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
+    MEMZERO(cinfo, sizeof(struct jpeg_compress_struct));
     cinfo->err = err;
     cinfo->client_data = client_data;
   }
   cinfo->is_decompressor = FALSE;
 
   /* Initialize a memory manager instance for this object */
   jinit_memory_mgr((j_common_ptr) cinfo);
 
@@ -80,17 +82,17 @@ jpeg_CreateCompress (j_compress_ptr cinf
   /* Must do it here for emit_dqt in case jpeg_write_tables is used */
   cinfo->block_size = DCTSIZE;
   cinfo->natural_order = jpeg_natural_order;
   cinfo->lim_Se = DCTSIZE2-1;
 #endif
 
   cinfo->script_space = NULL;
 
-  cinfo->input_gamma = 1.0;	/* in case application forgets */
+  cinfo->input_gamma = 1.0;     /* in case application forgets */
 
   /* OK, I'm ready */
   cinfo->global_state = CSTATE_START;
 }
 
 
 /*
  * Destruction of a JPEG compression object
@@ -168,25 +170,25 @@ jpeg_finish_compress (j_compress_ptr cin
     (*cinfo->master->finish_pass) (cinfo);
   } else if (cinfo->global_state != CSTATE_WRCOEFS)
     ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   /* Perform any remaining passes */
   while (! cinfo->master->is_last_pass) {
     (*cinfo->master->prepare_for_pass) (cinfo);
     for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
       if (cinfo->progress != NULL) {
-	cinfo->progress->pass_counter = (long) iMCU_row;
-	cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
-	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+        cinfo->progress->pass_counter = (long) iMCU_row;
+        cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
+        (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
       }
       /* We bypass the main controller and invoke coef controller directly;
        * all work is being done from the coefficient buffer.
        */
       if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
-	ERREXIT(cinfo, JERR_CANT_SUSPEND);
+        ERREXIT(cinfo, JERR_CANT_SUSPEND);
     }
     (*cinfo->master->finish_pass) (cinfo);
   }
   /* Write EOI, do final cleanup */
   (*cinfo->marker->write_file_trailer) (cinfo);
   (*cinfo->dest->term_destination) (cinfo);
   /* We can use jpeg_abort to release memory and reset global_state */
   jpeg_abort((j_common_ptr) cinfo);
@@ -197,28 +199,28 @@ jpeg_finish_compress (j_compress_ptr cin
  * Write a special marker.
  * This is only recommended for writing COM or APPn markers.
  * Must be called after jpeg_start_compress() and before
  * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  */
 
 GLOBAL(void)
 jpeg_write_marker (j_compress_ptr cinfo, int marker,
-		   const JOCTET *dataptr, unsigned int datalen)
+                   const JOCTET *dataptr, unsigned int datalen)
 {
-  JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
+  void (*write_marker_byte) (j_compress_ptr info, int val);
 
   if (cinfo->next_scanline != 0 ||
       (cinfo->global_state != CSTATE_SCANNING &&
        cinfo->global_state != CSTATE_RAW_OK &&
        cinfo->global_state != CSTATE_WRCOEFS))
     ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
 
   (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
-  write_marker_byte = cinfo->marker->write_marker_byte;	/* copy for speed */
+  write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
   while (datalen--) {
     (*write_marker_byte) (cinfo, *dataptr);
     dataptr++;
   }
 }
 
 /* Same, but piecemeal. */
 
@@ -243,24 +245,24 @@ jpeg_write_m_byte (j_compress_ptr cinfo,
 
 /*
  * Alternate compression function: just write an abbreviated table file.
  * Before calling this, all parameters and a data destination must be set up.
  *
  * To produce a pair of files containing abbreviated tables and abbreviated
  * image data, one would proceed as follows:
  *
- *		initialize JPEG object
- *		set JPEG parameters
- *		set destination to table file
- *		jpeg_write_tables(cinfo);
- *		set destination to image file
- *		jpeg_start_compress(cinfo, FALSE);
- *		write data...
- *		jpeg_finish_compress(cinfo);
+ *              initialize JPEG object
+ *              set JPEG parameters
+ *              set destination to table file
+ *              jpeg_write_tables(cinfo);
+ *              set destination to image file
+ *              jpeg_start_compress(cinfo, FALSE);
+ *              write data...
+ *              jpeg_finish_compress(cinfo);
  *
  * jpeg_write_tables has the side effect of marking all tables written
  * (same as jpeg_suppress_tables(..., TRUE)).  Thus a subsequent start_compress
  * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  */
 
 GLOBAL(void)
 jpeg_write_tables (j_compress_ptr cinfo)
--- a/media/libjpeg/jcapistd.c
+++ b/media/libjpeg/jcapistd.c
@@ -36,17 +36,17 @@
 
 GLOBAL(void)
 jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
 {
   if (cinfo->global_state != CSTATE_START)
     ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
 
   if (write_all_tables)
-    jpeg_suppress_tables(cinfo, FALSE);	/* mark all tables to be written */
+    jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
 
   /* (Re)initialize error mgr and destination modules */
   (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
   (*cinfo->dest->init_destination) (cinfo);
   /* Perform master selection of active modules */
   jinit_compress_master(cinfo);
   /* Set up for the first pass */
   (*cinfo->master->prepare_for_pass) (cinfo);
@@ -70,17 +70,17 @@ jpeg_start_compress (j_compress_ptr cinf
  * this likely signals an application programmer error.  However,
  * excess scanlines passed in the last valid call are *silently* ignored,
  * so that the application need not adjust num_lines for end-of-image
  * when using a multiple-scanline buffer.
  */
 
 GLOBAL(JDIMENSION)
 jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
-		      JDIMENSION num_lines)
+                      JDIMENSION num_lines)
 {
   JDIMENSION row_ctr, rows_left;
 
   if (cinfo->global_state != CSTATE_SCANNING)
     ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   if (cinfo->next_scanline >= cinfo->image_height)
     WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
 
@@ -113,17 +113,17 @@ jpeg_write_scanlines (j_compress_ptr cin
 
 /*
  * Alternate entry point to write raw data.
  * Processes exactly one iMCU row per call, unless suspended.
  */
 
 GLOBAL(JDIMENSION)
 jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
-		     JDIMENSION num_lines)
+                     JDIMENSION num_lines)
 {
   JDIMENSION lines_per_iMCU_row;
 
   if (cinfo->global_state != CSTATE_RAW_OK)
     ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
   if (cinfo->next_scanline >= cinfo->image_height) {
     WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
     return 0;
--- a/media/libjpeg/jcarith.c
+++ b/media/libjpeg/jcarith.c
@@ -1,13 +1,15 @@
 /*
  * jcarith.c
  *
+ * This file was part of the Independent JPEG Group's software:
  * Developed 1997-2009 by Guido Vollbeding.
- * This file is part of the Independent JPEG Group's software.
+ * It was modified by The libjpeg-turbo Project to include only code relevant
+ * to libjpeg-turbo.
  * For conditions of distribution and use, see the accompanying README file.
  *
  * This file contains portable arithmetic entropy encoding routines for JPEG
  * (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).
  *
  * Both sequential and progressive modes are supported in this single module.
  *
  * Suspension is not currently supported in this module.
@@ -29,18 +31,18 @@ typedef struct {
   INT32 zc;          /* counter for pending 0x00 output values which might *
                           * be discarded at the end ("Pacman" termination) */
   int ct;  /* bit shift counter, determines when next byte will be written */
   int buffer;                /* buffer for most recent output byte != 0xFF */
 
   int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
   int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
 
-  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
-  int next_restart_num;		/* next restart number to write (0-7) */
+  unsigned int restarts_to_go;  /* MCUs left in this restart interval */
+  int next_restart_num;         /* next restart number to write (0-7) */
 
   /* Pointers to statistics areas (these workspaces have image lifespan) */
   unsigned char * dc_stats[NUM_ARITH_TBLS];
   unsigned char * ac_stats[NUM_ARITH_TBLS];
 
   /* Statistics bin for coding with fixed probability 0.5 */
   unsigned char fixed_bin[4];
 } arith_entropy_encoder;
@@ -96,24 +98,24 @@ typedef arith_entropy_encoder * arith_en
  */
 
 /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  * We assume that int right shift is unsigned if INT32 right shift is,
  * which should be safe.
  */
 
 #ifdef RIGHT_SHIFT_IS_UNSIGNED
-#define ISHIFT_TEMPS	int ishift_temp;
+#define ISHIFT_TEMPS    int ishift_temp;
 #define IRIGHT_SHIFT(x,shft)  \
-	((ishift_temp = (x)) < 0 ? \
-	 (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
-	 (ishift_temp >> (shft)))
+        ((ishift_temp = (x)) < 0 ? \
+         (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
+         (ishift_temp >> (shft)))
 #else
 #define ISHIFT_TEMPS
-#define IRIGHT_SHIFT(x,shft)	((x) >> (shft))
+#define IRIGHT_SHIFT(x,shft)    ((x) >> (shft))
 #endif
 
 
 LOCAL(void)
 emit_byte (int val, j_compress_ptr cinfo)
 /* Write next output byte; we do not support suspension in this module. */
 {
   struct jpeg_destination_mgr * dest = cinfo->dest;
@@ -144,55 +146,55 @@ finish_pass (j_compress_ptr cinfo)
   else
     e->c = temp;
   /* Send remaining bytes to output */
   e->c <<= e->ct;
   if (e->c & 0xF8000000L) {
     /* One final overflow has to be handled */
     if (e->buffer >= 0) {
       if (e->zc)
-	do emit_byte(0x00, cinfo);
-	while (--e->zc);
+        do emit_byte(0x00, cinfo);
+        while (--e->zc);
       emit_byte(e->buffer + 1, cinfo);
       if (e->buffer + 1 == 0xFF)
-	emit_byte(0x00, cinfo);
+        emit_byte(0x00, cinfo);
     }
     e->zc += e->sc;  /* carry-over converts stacked 0xFF bytes to 0x00 */
     e->sc = 0;
   } else {
     if (e->buffer == 0)
       ++e->zc;
     else if (e->buffer >= 0) {
       if (e->zc)
-	do emit_byte(0x00, cinfo);
-	while (--e->zc);
+        do emit_byte(0x00, cinfo);
+        while (--e->zc);
       emit_byte(e->buffer, cinfo);
     }
     if (e->sc) {
       if (e->zc)
-	do emit_byte(0x00, cinfo);
-	while (--e->zc);
+        do emit_byte(0x00, cinfo);
+        while (--e->zc);
       do {
-	emit_byte(0xFF, cinfo);
-	emit_byte(0x00, cinfo);
+        emit_byte(0xFF, cinfo);
+        emit_byte(0x00, cinfo);
       } while (--e->sc);
     }
   }
   /* Output final bytes only if they are not 0x00 */
   if (e->c & 0x7FFF800L) {
     if (e->zc)  /* output final pending zero bytes */
       do emit_byte(0x00, cinfo);
       while (--e->zc);
     emit_byte((e->c >> 19) & 0xFF, cinfo);
     if (((e->c >> 19) & 0xFF) == 0xFF)
       emit_byte(0x00, cinfo);
     if (e->c & 0x7F800L) {
       emit_byte((e->c >> 11) & 0xFF, cinfo);
       if (((e->c >> 11) & 0xFF) == 0xFF)
-	emit_byte(0x00, cinfo);
+        emit_byte(0x00, cinfo);
     }
   }
 }
 
 
 /*
  * The core arithmetic encoding routine (common in JPEG and JBIG).
  * This needs to go as fast as possible.
@@ -211,103 +213,103 @@ finish_pass (j_compress_ptr cinfo)
  * except for FF stuffing).
  *
  * I've also introduced a new scheme for accessing
  * the probability estimation state machine table,
  * derived from Markus Kuhn's JBIG implementation.
  */
 
 LOCAL(void)
-arith_encode (j_compress_ptr cinfo, unsigned char *st, int val) 
+arith_encode (j_compress_ptr cinfo, unsigned char *st, int val)
 {
   register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
   register unsigned char nl, nm;
   register INT32 qe, temp;
   register int sv;
 
   /* Fetch values from our compact representation of Table D.2:
    * Qe values and probability estimation state machine
    */
   sv = *st;
-  qe = jpeg_aritab[sv & 0x7F];	/* => Qe_Value */
-  nl = qe & 0xFF; qe >>= 8;	/* Next_Index_LPS + Switch_MPS */
-  nm = qe & 0xFF; qe >>= 8;	/* Next_Index_MPS */
+  qe = jpeg_aritab[sv & 0x7F];  /* => Qe_Value */
+  nl = qe & 0xFF; qe >>= 8;     /* Next_Index_LPS + Switch_MPS */
+  nm = qe & 0xFF; qe >>= 8;     /* Next_Index_MPS */
 
   /* Encode & estimation procedures per sections D.1.4 & D.1.5 */
   e->a -= qe;
   if (val != (sv >> 7)) {
     /* Encode the less probable symbol */
     if (e->a >= qe) {
       /* If the interval size (qe) for the less probable symbol (LPS)
        * is larger than the interval size for the MPS, then exchange
        * the two symbols for coding efficiency, otherwise code the LPS
        * as usual: */
       e->c += e->a;
       e->a = qe;
     }
-    *st = (sv & 0x80) ^ nl;	/* Estimate_after_LPS */
+    *st = (sv & 0x80) ^ nl;     /* Estimate_after_LPS */
   } else {
     /* Encode the more probable symbol */
     if (e->a >= 0x8000L)
       return;  /* A >= 0x8000 -> ready, no renormalization required */
     if (e->a < qe) {
       /* If the interval size (qe) for the less probable symbol (LPS)
        * is larger than the interval size for the MPS, then exchange
        * the two symbols for coding efficiency: */
       e->c += e->a;
       e->a = qe;
     }
-    *st = (sv & 0x80) ^ nm;	/* Estimate_after_MPS */
+    *st = (sv & 0x80) ^ nm;     /* Estimate_after_MPS */
   }
 
   /* Renormalization & data output per section D.1.6 */
   do {
     e->a <<= 1;
     e->c <<= 1;
     if (--e->ct == 0) {
       /* Another byte is ready for output */
       temp = e->c >> 19;
       if (temp > 0xFF) {
-	/* Handle overflow over all stacked 0xFF bytes */
-	if (e->buffer >= 0) {
-	  if (e->zc)
-	    do emit_byte(0x00, cinfo);
-	    while (--e->zc);
-	  emit_byte(e->buffer + 1, cinfo);
-	  if (e->buffer + 1 == 0xFF)
-	    emit_byte(0x00, cinfo);
-	}
-	e->zc += e->sc;  /* carry-over converts stacked 0xFF bytes to 0x00 */
-	e->sc = 0;
-	/* Note: The 3 spacer bits in the C register guarantee
-	 * that the new buffer byte can't be 0xFF here
-	 * (see page 160 in the P&M JPEG book). */
-	e->buffer = temp & 0xFF;  /* new output byte, might overflow later */
+        /* Handle overflow over all stacked 0xFF bytes */
+        if (e->buffer >= 0) {
+          if (e->zc)
+            do emit_byte(0x00, cinfo);
+            while (--e->zc);
+          emit_byte(e->buffer + 1, cinfo);
+          if (e->buffer + 1 == 0xFF)
+            emit_byte(0x00, cinfo);
+        }
+        e->zc += e->sc;  /* carry-over converts stacked 0xFF bytes to 0x00 */
+        e->sc = 0;
+        /* Note: The 3 spacer bits in the C register guarantee
+         * that the new buffer byte can't be 0xFF here
+         * (see page 160 in the P&M JPEG book). */
+        e->buffer = temp & 0xFF;  /* new output byte, might overflow later */
       } else if (temp == 0xFF) {
-	++e->sc;  /* stack 0xFF byte (which might overflow later) */
+        ++e->sc;  /* stack 0xFF byte (which might overflow later) */
       } else {
-	/* Output all stacked 0xFF bytes, they will not overflow any more */
-	if (e->buffer == 0)
-	  ++e->zc;
-	else if (e->buffer >= 0) {
-	  if (e->zc)
-	    do emit_byte(0x00, cinfo);
-	    while (--e->zc);
-	  emit_byte(e->buffer, cinfo);
-	}
-	if (e->sc) {
-	  if (e->zc)
-	    do emit_byte(0x00, cinfo);
-	    while (--e->zc);
-	  do {
-	    emit_byte(0xFF, cinfo);
-	    emit_byte(0x00, cinfo);
-	  } while (--e->sc);
-	}
-	e->buffer = temp & 0xFF;  /* new output byte (can still overflow) */
+        /* Output all stacked 0xFF bytes, they will not overflow any more */
+        if (e->buffer == 0)
+          ++e->zc;
+        else if (e->buffer >= 0) {
+          if (e->zc)
+            do emit_byte(0x00, cinfo);
+            while (--e->zc);
+          emit_byte(e->buffer, cinfo);
+        }
+        if (e->sc) {
+          if (e->zc)
+            do emit_byte(0x00, cinfo);
+            while (--e->zc);
+          do {
+            emit_byte(0xFF, cinfo);
+            emit_byte(0x00, cinfo);
+          } while (--e->sc);
+        }
+        e->buffer = temp & 0xFF;  /* new output byte (can still overflow) */
       }
       e->c &= 0x7FFFFL;
       e->ct += 8;
     }
   } while (e->a < 0x8000L);
 }
 
 
@@ -393,55 +395,55 @@ encode_mcu_DC_first (j_compress_ptr cinf
     /* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
 
     /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
     st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
 
     /* Figure F.4: Encode_DC_DIFF */
     if ((v = m - entropy->last_dc_val[ci]) == 0) {
       arith_encode(cinfo, st, 0);
-      entropy->dc_context[ci] = 0;	/* zero diff category */
+      entropy->dc_context[ci] = 0;      /* zero diff category */
     } else {
       entropy->last_dc_val[ci] = m;
       arith_encode(cinfo, st, 1);
       /* Figure F.6: Encoding nonzero value v */
       /* Figure F.7: Encoding the sign of v */
       if (v > 0) {
-	arith_encode(cinfo, st + 1, 0);	/* Table F.4: SS = S0 + 1 */
-	st += 2;			/* Table F.4: SP = S0 + 2 */
-	entropy->dc_context[ci] = 4;	/* small positive diff category */
+        arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
+        st += 2;                        /* Table F.4: SP = S0 + 2 */
+        entropy->dc_context[ci] = 4;    /* small positive diff category */
       } else {
-	v = -v;
-	arith_encode(cinfo, st + 1, 1);	/* Table F.4: SS = S0 + 1 */
-	st += 3;			/* Table F.4: SN = S0 + 3 */
-	entropy->dc_context[ci] = 8;	/* small negative diff category */
+        v = -v;
+        arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
+        st += 3;                        /* Table F.4: SN = S0 + 3 */
+        entropy->dc_context[ci] = 8;    /* small negative diff category */
       }
       /* Figure F.8: Encoding the magnitude category of v */
       m = 0;
       if (v -= 1) {
-	arith_encode(cinfo, st, 1);
-	m = 1;
-	v2 = v;
-	st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
-	while (v2 >>= 1) {
-	  arith_encode(cinfo, st, 1);
-	  m <<= 1;
-	  st += 1;
-	}
+        arith_encode(cinfo, st, 1);
+        m = 1;
+        v2 = v;
+        st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
+        while (v2 >>= 1) {
+          arith_encode(cinfo, st, 1);
+          m <<= 1;
+          st += 1;
+        }
       }
       arith_encode(cinfo, st, 0);
       /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
       if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
-	entropy->dc_context[ci] = 0;	/* zero diff category */
+        entropy->dc_context[ci] = 0;    /* zero diff category */
       else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
-	entropy->dc_context[ci] += 8;	/* large diff category */
+        entropy->dc_context[ci] += 8;   /* large diff category */
       /* Figure F.9: Encoding the magnitude bit pattern of v */
       st += 14;
       while (m >>= 1)
-	arith_encode(cinfo, st, (m & v) ? 1 : 0);
+        arith_encode(cinfo, st, (m & v) ? 1 : 0);
     }
   }
 
   return TRUE;
 }
 
 
 /*
@@ -486,51 +488,51 @@ encode_mcu_AC_first (j_compress_ptr cinf
     } else {
       v = -v;
       if (v >>= cinfo->Al) break;
     }
 
   /* Figure F.5: Encode_AC_Coefficients */
   for (k = cinfo->Ss; k <= ke; k++) {
     st = entropy->ac_stats[tbl] + 3 * (k - 1);
-    arith_encode(cinfo, st, 0);		/* EOB decision */
+    arith_encode(cinfo, st, 0);         /* EOB decision */
     for (;;) {
       if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {
-	if (v >>= cinfo->Al) {
-	  arith_encode(cinfo, st + 1, 1);
-	  arith_encode(cinfo, entropy->fixed_bin, 0);
-	  break;
-	}
+        if (v >>= cinfo->Al) {
+          arith_encode(cinfo, st + 1, 1);
+          arith_encode(cinfo, entropy->fixed_bin, 0);
+          break;
+        }
       } else {
-	v = -v;
-	if (v >>= cinfo->Al) {
-	  arith_encode(cinfo, st + 1, 1);
-	  arith_encode(cinfo, entropy->fixed_bin, 1);
-	  break;
-	}
+        v = -v;
+        if (v >>= cinfo->Al) {
+          arith_encode(cinfo, st + 1, 1);
+          arith_encode(cinfo, entropy->fixed_bin, 1);
+          break;
+        }
       }
       arith_encode(cinfo, st + 1, 0); st += 3; k++;
     }
     st += 2;
     /* Figure F.8: Encoding the magnitude category of v */
     m = 0;
     if (v -= 1) {
       arith_encode(cinfo, st, 1);
       m = 1;
       v2 = v;
       if (v2 >>= 1) {
-	arith_encode(cinfo, st, 1);
-	m <<= 1;
-	st = entropy->ac_stats[tbl] +
-	     (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
-	while (v2 >>= 1) {
-	  arith_encode(cinfo, st, 1);
-	  m <<= 1;
-	  st += 1;
-	}
+        arith_encode(cinfo, st, 1);
+        m <<= 1;
+        st = entropy->ac_stats[tbl] +
+             (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
+        while (v2 >>= 1) {
+          arith_encode(cinfo, st, 1);
+          m <<= 1;
+          st += 1;
+        }
       }
     }
     arith_encode(cinfo, st, 0);
     /* Figure F.9: Encoding the magnitude bit pattern of v */
     st += 14;
     while (m >>= 1)
       arith_encode(cinfo, st, (m & v) ? 1 : 0);
   }
@@ -561,17 +563,17 @@ encode_mcu_DC_refine (j_compress_ptr cin
       emit_restart(cinfo, entropy->next_restart_num);
       entropy->restarts_to_go = cinfo->restart_interval;
       entropy->next_restart_num++;
       entropy->next_restart_num &= 7;
     }
     entropy->restarts_to_go--;
   }
 
-  st = entropy->fixed_bin;	/* use fixed probability estimation */
+  st = entropy->fixed_bin;      /* use fixed probability estimation */
   Al = cinfo->Al;
 
   /* Encode the MCU data blocks */
   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
     /* We simply emit the Al'th bit of the DC coefficient value. */
     arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);
   }
 
@@ -630,39 +632,39 @@ encode_mcu_AC_refine (j_compress_ptr cin
       v = -v;
       if (v >>= cinfo->Ah) break;
     }
 
   /* Figure G.10: Encode_AC_Coefficients_SA */
   for (k = cinfo->Ss; k <= ke; k++) {
     st = entropy->ac_stats[tbl] + 3 * (k - 1);
     if (k > kex)
-      arith_encode(cinfo, st, 0);	/* EOB decision */
+      arith_encode(cinfo, st, 0);       /* EOB decision */
     for (;;) {
       if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {
-	if (v >>= cinfo->Al) {
-	  if (v >> 1)			/* previously nonzero coef */
-	    arith_encode(cinfo, st + 2, (v & 1));
-	  else {			/* newly nonzero coef */
-	    arith_encode(cinfo, st + 1, 1);
-	    arith_encode(cinfo, entropy->fixed_bin, 0);
-	  }
-	  break;
-	}
+        if (v >>= cinfo->Al) {
+          if (v >> 1)                   /* previously nonzero coef */
+            arith_encode(cinfo, st + 2, (v & 1));
+          else {                        /* newly nonzero coef */
+            arith_encode(cinfo, st + 1, 1);
+            arith_encode(cinfo, entropy->fixed_bin, 0);
+          }
+          break;
+        }
       } else {
-	v = -v;
-	if (v >>= cinfo->Al) {
-	  if (v >> 1)			/* previously nonzero coef */
-	    arith_encode(cinfo, st + 2, (v & 1));
-	  else {			/* newly nonzero coef */
-	    arith_encode(cinfo, st + 1, 1);
-	    arith_encode(cinfo, entropy->fixed_bin, 1);
-	  }
-	  break;
-	}
+        v = -v;
+        if (v >>= cinfo->Al) {
+          if (v >> 1)                   /* previously nonzero coef */
+            arith_encode(cinfo, st + 2, (v & 1));
+          else {                        /* newly nonzero coef */
+            arith_encode(cinfo, st + 1, 1);
+            arith_encode(cinfo, entropy->fixed_bin, 1);
+          }
+          break;
+        }
       }
       arith_encode(cinfo, st + 1, 0); st += 3; k++;
     }
   }
   /* Encode EOB decision only if k <= cinfo->Se */
   if (k <= cinfo->Se) {
     st = entropy->ac_stats[tbl] + 3 * (k - 1);
     arith_encode(cinfo, st, 1);
@@ -708,105 +710,105 @@ encode_mcu (j_compress_ptr cinfo, JBLOCK
     tbl = compptr->dc_tbl_no;
 
     /* Table F.4: Point to statistics bin S0 for DC coefficient coding */
     st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
 
     /* Figure F.4: Encode_DC_DIFF */
     if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {
       arith_encode(cinfo, st, 0);
-      entropy->dc_context[ci] = 0;	/* zero diff category */
+      entropy->dc_context[ci] = 0;      /* zero diff category */
     } else {
       entropy->last_dc_val[ci] = (*block)[0];
       arith_encode(cinfo, st, 1);
       /* Figure F.6: Encoding nonzero value v */
       /* Figure F.7: Encoding the sign of v */
       if (v > 0) {
-	arith_encode(cinfo, st + 1, 0);	/* Table F.4: SS = S0 + 1 */
-	st += 2;			/* Table F.4: SP = S0 + 2 */
-	entropy->dc_context[ci] = 4;	/* small positive diff category */
+        arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
+        st += 2;                        /* Table F.4: SP = S0 + 2 */
+        entropy->dc_context[ci] = 4;    /* small positive diff category */
       } else {
-	v = -v;
-	arith_encode(cinfo, st + 1, 1);	/* Table F.4: SS = S0 + 1 */
-	st += 3;			/* Table F.4: SN = S0 + 3 */
-	entropy->dc_context[ci] = 8;	/* small negative diff category */
+        v = -v;
+        arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
+        st += 3;                        /* Table F.4: SN = S0 + 3 */
+        entropy->dc_context[ci] = 8;    /* small negative diff category */
       }
       /* Figure F.8: Encoding the magnitude category of v */
       m = 0;
       if (v -= 1) {
-	arith_encode(cinfo, st, 1);
-	m = 1;
-	v2 = v;
-	st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
-	while (v2 >>= 1) {
-	  arith_encode(cinfo, st, 1);
-	  m <<= 1;
-	  st += 1;
-	}
+        arith_encode(cinfo, st, 1);
+        m = 1;
+        v2 = v;
+        st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
+        while (v2 >>= 1) {
+          arith_encode(cinfo, st, 1);
+          m <<= 1;
+          st += 1;
+        }
       }
       arith_encode(cinfo, st, 0);
       /* Section F.1.4.4.1.2: Establish dc_context conditioning category */
       if (m < (int) ((1L << cinfo->arith_dc_L[tbl]) >> 1))
-	entropy->dc_context[ci] = 0;	/* zero diff category */
+        entropy->dc_context[ci] = 0;    /* zero diff category */
       else if (m > (int) ((1L << cinfo->arith_dc_U[tbl]) >> 1))
-	entropy->dc_context[ci] += 8;	/* large diff category */
+        entropy->dc_context[ci] += 8;   /* large diff category */
       /* Figure F.9: Encoding the magnitude bit pattern of v */
       st += 14;
       while (m >>= 1)
-	arith_encode(cinfo, st, (m & v) ? 1 : 0);
+        arith_encode(cinfo, st, (m & v) ? 1 : 0);
     }
 
     /* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
 
     tbl = compptr->ac_tbl_no;
 
     /* Establish EOB (end-of-block) index */
     for (ke = DCTSIZE2 - 1; ke > 0; ke--)
       if ((*block)[jpeg_natural_order[ke]]) break;
 
     /* Figure F.5: Encode_AC_Coefficients */
     for (k = 1; k <= ke; k++) {
       st = entropy->ac_stats[tbl] + 3 * (k - 1);
-      arith_encode(cinfo, st, 0);	/* EOB decision */
+      arith_encode(cinfo, st, 0);       /* EOB decision */
       while ((v = (*block)[jpeg_natural_order[k]]) == 0) {
-	arith_encode(cinfo, st + 1, 0); st += 3; k++;
+        arith_encode(cinfo, st + 1, 0); st += 3; k++;
       }
       arith_encode(cinfo, st + 1, 1);
       /* Figure F.6: Encoding nonzero value v */
       /* Figure F.7: Encoding the sign of v */
       if (v > 0) {
-	arith_encode(cinfo, entropy->fixed_bin, 0);
+        arith_encode(cinfo, entropy->fixed_bin, 0);
       } else {
-	v = -v;
-	arith_encode(cinfo, entropy->fixed_bin, 1);
+        v = -v;
+        arith_encode(cinfo, entropy->fixed_bin, 1);
       }
       st += 2;
       /* Figure F.8: Encoding the magnitude category of v */
       m = 0;
       if (v -= 1) {
-	arith_encode(cinfo, st, 1);
-	m = 1;
-	v2 = v;
-	if (v2 >>= 1) {
-	  arith_encode(cinfo, st, 1);
-	  m <<= 1;
-	  st = entropy->ac_stats[tbl] +
-	       (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
-	  while (v2 >>= 1) {
-	    arith_encode(cinfo, st, 1);
-	    m <<= 1;
-	    st += 1;
-	  }
-	}
+        arith_encode(cinfo, st, 1);
+        m = 1;
+        v2 = v;
+        if (v2 >>= 1) {
+          arith_encode(cinfo, st, 1);
+          m <<= 1;
+          st = entropy->ac_stats[tbl] +
+               (k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
+          while (v2 >>= 1) {
+            arith_encode(cinfo, st, 1);
+            m <<= 1;
+            st += 1;
+          }
+        }
       }
       arith_encode(cinfo, st, 0);
       /* Figure F.9: Encoding the magnitude bit pattern of v */
       st += 14;
       while (m >>= 1)
-	arith_encode(cinfo, st, (m & v) ? 1 : 0);
+        arith_encode(cinfo, st, (m & v) ? 1 : 0);
     }
     /* Encode EOB decision only if k <= DCTSIZE2 - 1 */
     if (k <= DCTSIZE2 - 1) {
       st = entropy->ac_stats[tbl] + 3 * (k - 1);
       arith_encode(cinfo, st, 1);
     }
   }
 
@@ -833,57 +835,57 @@ start_pass (j_compress_ptr cinfo, boolea
     ERREXIT(cinfo, JERR_NOT_COMPILED);
 
   /* We assume jcmaster.c already validated the progressive scan parameters. */
 
   /* Select execution routines */
   if (cinfo->progressive_mode) {
     if (cinfo->Ah == 0) {
       if (cinfo->Ss == 0)
-	entropy->pub.encode_mcu = encode_mcu_DC_first;
+        entropy->pub.encode_mcu = encode_mcu_DC_first;
       else
-	entropy->pub.encode_mcu = encode_mcu_AC_first;
+        entropy->pub.encode_mcu = encode_mcu_AC_first;
     } else {
       if (cinfo->Ss == 0)
-	entropy->pub.encode_mcu = encode_mcu_DC_refine;
+        entropy->pub.encode_mcu = encode_mcu_DC_refine;
       else
-	entropy->pub.encode_mcu = encode_mcu_AC_refine;
+        entropy->pub.encode_mcu = encode_mcu_AC_refine;
     }
   } else
     entropy->pub.encode_mcu = encode_mcu;
 
   /* Allocate & initialize requested statistics areas */
   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
     compptr = cinfo->cur_comp_info[ci];
     /* DC needs no table for refinement scan */
     if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
       tbl = compptr->dc_tbl_no;
       if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
-	ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
+        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
       if (entropy->dc_stats[tbl] == NULL)
-	entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
-	  ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
+        entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
+          ((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
       MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
       /* Initialize DC predictions to 0 */
       entropy->last_dc_val[ci] = 0;
       entropy->dc_context[ci] = 0;
     }
     /* AC needs no table when not present */
     if (cinfo->progressive_mode == 0 || cinfo->Se) {
       tbl = compptr->ac_tbl_no;
       if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
-	ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
+        ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
       if (entropy->ac_stats[tbl] == NULL)
-	entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
-	  ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
+        entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
+          ((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
       MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
 #ifdef CALCULATE_SPECTRAL_CONDITIONING
       if (cinfo->progressive_mode)
-	/* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */
-	cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);
+        /* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */
+        cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);
 #endif
     }
   }
 
   /* Initialize arithmetic encoding variables */
   entropy->c = 0;
   entropy->a = 0x10000L;
   entropy->sc = 0;
@@ -904,17 +906,17 @@ start_pass (j_compress_ptr cinfo, boolea
 GLOBAL(void)
 jinit_arith_encoder (j_compress_ptr cinfo)
 {
   arith_entropy_ptr entropy;
   int i;
 
   entropy = (arith_entropy_ptr)
     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(arith_entropy_encoder));
+                                sizeof(arith_entropy_encoder));
   cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
   entropy->pub.start_pass = start_pass;
   entropy->pub.finish_pass = finish_pass;
 
   /* Mark tables unallocated */
   for (i = 0; i < NUM_ARITH_TBLS; i++) {
     entropy->dc_stats[i] = NULL;
     entropy->ac_stats[i] = NULL;
--- a/media/libjpeg/jccoefct.c
+++ b/media/libjpeg/jccoefct.c
@@ -1,13 +1,15 @@
 /*
  * jccoefct.c
  *
+ * This file was part of the Independent JPEG Group's software:
  * Copyright (C) 1994-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
+ * It was modified by The libjpeg-turbo Project to include only code and
+ * information relevant to libjpeg-turbo.
  * For conditions of distribution and use, see the accompanying README file.
  *
  * This file contains the coefficient buffer controller for compression.
  * This controller is the top level of the JPEG compressor proper.
  * The coefficient buffer lies between forward-DCT and entropy encoding steps.
  */
 
 #define JPEG_INTERNALS
@@ -29,47 +31,44 @@
 #endif
 
 
 /* Private buffer controller object */
 
 typedef struct {
   struct jpeg_c_coef_controller pub; /* public fields */
 
-  JDIMENSION iMCU_row_num;	/* iMCU row # within image */
-  JDIMENSION mcu_ctr;		/* counts MCUs processed in current row */
-  int MCU_vert_offset;		/* counts MCU rows within iMCU row */
-  int MCU_rows_per_iMCU_row;	/* number of such rows needed */
+  JDIMENSION iMCU_row_num;      /* iMCU row # within image */
+  JDIMENSION mcu_ctr;           /* counts MCUs processed in current row */
+  int MCU_vert_offset;          /* counts MCU rows within iMCU row */
+  int MCU_rows_per_iMCU_row;    /* number of such rows needed */
 
   /* For single-pass compression, it's sufficient to buffer just one MCU
    * (although this may prove a bit slow in practice).  We allocate a
    * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
-   * MCU constructed and sent.  (On 80x86, the workspace is FAR even though
-   * it's not really very big; this is to keep the module interfaces unchanged
-   * when a large coefficient buffer is necessary.)
-   * In multi-pass modes, this array points to the current MCU's blocks
-   * within the virtual arrays.
+   * MCU constructed and sent.  In multi-pass modes, this array points to the
+   * current MCU's blocks within the virtual arrays.
    */
   JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
 
   /* In multi-pass modes, we need a virtual block array for each component. */
   jvirt_barray_ptr whole_image[MAX_COMPONENTS];
 } my_coef_controller;
 
 typedef my_coef_controller * my_coef_ptr;
 
 
 /* Forward declarations */
 METHODDEF(boolean) compress_data
-    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
+        (j_compress_ptr cinfo, JSAMPIMAGE input_buf);
 #ifdef FULL_COEF_BUFFER_SUPPORTED
 METHODDEF(boolean) compress_first_pass
-    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
+        (j_compress_ptr cinfo, JSAMPIMAGE input_buf);
 METHODDEF(boolean) compress_output
-    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
+        (j_compress_ptr cinfo, JSAMPIMAGE input_buf);
 #endif
 
 
 LOCAL(void)
 start_iMCU_row (j_compress_ptr cinfo)
 /* Reset within-iMCU-row counters for a new row */
 {
   my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
@@ -138,79 +137,79 @@ start_pass_coef (j_compress_ptr cinfo, J
  * NB: input_buf contains a plane for each component in image,
  * which we index according to the component's SOF position.
  */
 
 METHODDEF(boolean)
 compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
 {
   my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION MCU_col_num;	/* index of current MCU within row */
+  JDIMENSION MCU_col_num;       /* index of current MCU within row */
   JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
   JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
   int blkn, bi, ci, yindex, yoffset, blockcnt;
   JDIMENSION ypos, xpos;
   jpeg_component_info *compptr;
 
   /* Loop to write as much as one whole iMCU row */
   for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
        yoffset++) {
     for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
-	 MCU_col_num++) {
+         MCU_col_num++) {
       /* Determine where data comes from in input_buf and do the DCT thing.
        * Each call on forward_DCT processes a horizontal row of DCT blocks
        * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
        * sequentially.  Dummy blocks at the right or bottom edge are filled in
        * specially.  The data in them does not matter for image reconstruction,
        * so we fill them with values that will encode to the smallest amount of
        * data, viz: all zeroes in the AC entries, DC entries equal to previous
        * block's DC value.  (Thanks to Thomas Kinsman for this idea.)
        */
       blkn = 0;
       for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-	compptr = cinfo->cur_comp_info[ci];
-	blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
-						: compptr->last_col_width;
-	xpos = MCU_col_num * compptr->MCU_sample_width;
-	ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
-	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
-	  if (coef->iMCU_row_num < last_iMCU_row ||
-	      yoffset+yindex < compptr->last_row_height) {
-	    (*cinfo->fdct->forward_DCT) (cinfo, compptr,
-					 input_buf[compptr->component_index],
-					 coef->MCU_buffer[blkn],
-					 ypos, xpos, (JDIMENSION) blockcnt);
-	    if (blockcnt < compptr->MCU_width) {
-	      /* Create some dummy blocks at the right edge of the image. */
-	      jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
-			(compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
-	      for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
-		coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
-	      }
-	    }
-	  } else {
-	    /* Create a row of dummy blocks at the bottom of the image. */
-	    jzero_far((void FAR *) coef->MCU_buffer[blkn],
-		      compptr->MCU_width * SIZEOF(JBLOCK));
-	    for (bi = 0; bi < compptr->MCU_width; bi++) {
-	      coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
-	    }
-	  }
-	  blkn += compptr->MCU_width;
-	  ypos += DCTSIZE;
-	}
+        compptr = cinfo->cur_comp_info[ci];
+        blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+                                                : compptr->last_col_width;
+        xpos = MCU_col_num * compptr->MCU_sample_width;
+        ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
+        for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+          if (coef->iMCU_row_num < last_iMCU_row ||
+              yoffset+yindex < compptr->last_row_height) {
+            (*cinfo->fdct->forward_DCT) (cinfo, compptr,
+                                         input_buf[compptr->component_index],
+                                         coef->MCU_buffer[blkn],
+                                         ypos, xpos, (JDIMENSION) blockcnt);
+            if (blockcnt < compptr->MCU_width) {
+              /* Create some dummy blocks at the right edge of the image. */
+              jzero_far((void *) coef->MCU_buffer[blkn + blockcnt],
+                        (compptr->MCU_width - blockcnt) * sizeof(JBLOCK));
+              for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
+                coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
+              }
+            }
+          } else {
+            /* Create a row of dummy blocks at the bottom of the image. */
+            jzero_far((void *) coef->MCU_buffer[blkn],
+                      compptr->MCU_width * sizeof(JBLOCK));
+            for (bi = 0; bi < compptr->MCU_width; bi++) {
+              coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
+            }
+          }
+          blkn += compptr->MCU_width;
+          ypos += DCTSIZE;
+        }
       }
       /* Try to write the MCU.  In event of a suspension failure, we will
        * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
        */
       if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
-	/* Suspension forced; update state counters and exit */
-	coef->MCU_vert_offset = yoffset;
-	coef->mcu_ctr = MCU_col_num;
-	return FALSE;
+        /* Suspension forced; update state counters and exit */
+        coef->MCU_vert_offset = yoffset;
+        coef->mcu_ctr = MCU_col_num;
+        return FALSE;
       }
     }
     /* Completed an MCU row, but perhaps not an iMCU row */
     coef->mcu_ctr = 0;
   }
   /* Completed the iMCU row, advance counters for next one */
   coef->iMCU_row_num++;
   start_iMCU_row(cinfo);
@@ -275,51 +274,51 @@ compress_first_pass (j_compress_ptr cinf
     if (ndummy > 0)
       ndummy = h_samp_factor - ndummy;
     /* Perform DCT for all non-dummy blocks in this iMCU row.  Each call
      * on forward_DCT processes a complete horizontal row of DCT blocks.
      */
     for (block_row = 0; block_row < block_rows; block_row++) {
       thisblockrow = buffer[block_row];
       (*cinfo->fdct->forward_DCT) (cinfo, compptr,
-				   input_buf[ci], thisblockrow,
-				   (JDIMENSION) (block_row * DCTSIZE),
-				   (JDIMENSION) 0, blocks_across);
+                                   input_buf[ci], thisblockrow,
+                                   (JDIMENSION) (block_row * DCTSIZE),
+                                   (JDIMENSION) 0, blocks_across);
       if (ndummy > 0) {
-	/* Create dummy blocks at the right edge of the image. */
-	thisblockrow += blocks_across; /* => first dummy block */
-	jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
-	lastDC = thisblockrow[-1][0];
-	for (bi = 0; bi < ndummy; bi++) {
-	  thisblockrow[bi][0] = lastDC;
-	}
+        /* Create dummy blocks at the right edge of the image. */
+        thisblockrow += blocks_across; /* => first dummy block */
+        jzero_far((void *) thisblockrow, ndummy * sizeof(JBLOCK));
+        lastDC = thisblockrow[-1][0];
+        for (bi = 0; bi < ndummy; bi++) {
+          thisblockrow[bi][0] = lastDC;
+        }
       }
     }
     /* If at end of image, create dummy block rows as needed.
      * The tricky part here is that within each MCU, we want the DC values
      * of the dummy blocks to match the last real block's DC value.
      * This squeezes a few more bytes out of the resulting file...
      */
     if (coef->iMCU_row_num == last_iMCU_row) {
-      blocks_across += ndummy;	/* include lower right corner */
+      blocks_across += ndummy;  /* include lower right corner */
       MCUs_across = blocks_across / h_samp_factor;
       for (block_row = block_rows; block_row < compptr->v_samp_factor;
-	   block_row++) {
-	thisblockrow = buffer[block_row];
-	lastblockrow = buffer[block_row-1];
-	jzero_far((void FAR *) thisblockrow,
-		  (size_t) (blocks_across * SIZEOF(JBLOCK)));
-	for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
-	  lastDC = lastblockrow[h_samp_factor-1][0];
-	  for (bi = 0; bi < h_samp_factor; bi++) {
-	    thisblockrow[bi][0] = lastDC;
-	  }
-	  thisblockrow += h_samp_factor; /* advance to next MCU in row */
-	  lastblockrow += h_samp_factor;
-	}
+           block_row++) {
+        thisblockrow = buffer[block_row];
+        lastblockrow = buffer[block_row-1];
+        jzero_far((void *) thisblockrow,
+                  (size_t) (blocks_across * sizeof(JBLOCK)));
+        for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
+          lastDC = lastblockrow[h_samp_factor-1][0];
+          for (bi = 0; bi < h_samp_factor; bi++) {
+            thisblockrow[bi][0] = lastDC;
+          }
+          thisblockrow += h_samp_factor; /* advance to next MCU in row */
+          lastblockrow += h_samp_factor;
+        }
       }
     }
   }
   /* NB: compress_output will increment iMCU_row_num if successful.
    * A suspension return will result in redoing all the work above next time.
    */
 
   /* Emit data to the entropy encoder, sharing code with subsequent passes */
@@ -336,17 +335,17 @@ compress_first_pass (j_compress_ptr cinf
  *
  * NB: input_buf is ignored; it is likely to be a NULL pointer.
  */
 
 METHODDEF(boolean)
 compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
 {
   my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION MCU_col_num;	/* index of current MCU within row */
+  JDIMENSION MCU_col_num;       /* index of current MCU within row */
   int blkn, ci, xindex, yindex, yoffset;
   JDIMENSION start_col;
   JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
   JBLOCKROW buffer_ptr;
   jpeg_component_info *compptr;
 
   /* Align the virtual buffers for the components used in this scan.
    * NB: during first pass, this is safe only because the buffers will
@@ -359,35 +358,35 @@ compress_output (j_compress_ptr cinfo, J
        coef->iMCU_row_num * compptr->v_samp_factor,
        (JDIMENSION) compptr->v_samp_factor, FALSE);
   }
 
   /* Loop to process one whole iMCU row */
   for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
        yoffset++) {
     for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
-	 MCU_col_num++) {
+         MCU_col_num++) {
       /* Construct list of pointers to DCT blocks belonging to this MCU */
-      blkn = 0;			/* index of current DCT block within MCU */
+      blkn = 0;                 /* index of current DCT block within MCU */
       for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-	compptr = cinfo->cur_comp_info[ci];
-	start_col = MCU_col_num * compptr->MCU_width;
-	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
-	  buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
-	  for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
-	    coef->MCU_buffer[blkn++] = buffer_ptr++;
-	  }
-	}
+        compptr = cinfo->cur_comp_info[ci];
+        start_col = MCU_col_num * compptr->MCU_width;
+        for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+          buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+          for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
+            coef->MCU_buffer[blkn++] = buffer_ptr++;
+          }
+        }
       }
       /* Try to write the MCU. */
       if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
-	/* Suspension forced; update state counters and exit */
-	coef->MCU_vert_offset = yoffset;
-	coef->mcu_ctr = MCU_col_num;
-	return FALSE;
+        /* Suspension forced; update state counters and exit */
+        coef->MCU_vert_offset = yoffset;
+        coef->mcu_ctr = MCU_col_num;
+        return FALSE;
       }
     }
     /* Completed an MCU row, but perhaps not an iMCU row */
     coef->mcu_ctr = 0;
   }
   /* Completed the iMCU row, advance counters for next one */
   coef->iMCU_row_num++;
   start_iMCU_row(cinfo);
@@ -403,47 +402,47 @@ compress_output (j_compress_ptr cinfo, J
 
 GLOBAL(void)
 jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
 {
   my_coef_ptr coef;
 
   coef = (my_coef_ptr)
     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_coef_controller));
+                                sizeof(my_coef_controller));
   cinfo->coef = (struct jpeg_c_coef_controller *) coef;
   coef->pub.start_pass = start_pass_coef;
 
   /* Create the coefficient buffer. */
   if (need_full_buffer) {
 #ifdef FULL_COEF_BUFFER_SUPPORTED
     /* Allocate a full-image virtual array for each component, */
     /* padded to a multiple of samp_factor DCT blocks in each direction. */
     int ci;
     jpeg_component_info *compptr;
 
     for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
+         ci++, compptr++) {
       coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-	 (JDIMENSION) jround_up((long) compptr->width_in_blocks,
-				(long) compptr->h_samp_factor),
-	 (JDIMENSION) jround_up((long) compptr->height_in_blocks,
-				(long) compptr->v_samp_factor),
-	 (JDIMENSION) compptr->v_samp_factor);
+        ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+         (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+                                (long) compptr->h_samp_factor),
+         (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+                                (long) compptr->v_samp_factor),
+         (JDIMENSION) compptr->v_samp_factor);
     }
 #else
     ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
 #endif
   } else {
     /* We only need a single-MCU buffer. */
     JBLOCKROW buffer;
     int i;
 
     buffer = (JBLOCKROW)
       (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+                                  C_MAX_BLOCKS_IN_MCU * sizeof(JBLOCK));
     for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
       coef->MCU_buffer[i] = buffer + i;
     }
     coef->whole_image[0] = NULL; /* flag for no virtual arrays */
   }
 }
--- a/media/libjpeg/jccolext.c
+++ b/media/libjpeg/jccolext.c
@@ -53,26 +53,26 @@ rgb_ycc_convert_internal (j_compress_ptr
       inptr += RGB_PIXELSIZE;
       /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
        * must be too; we do not need an explicit range-limiting operation.
        * Hence the value being shifted is never negative, and we don't
        * need the general RIGHT_SHIFT macro.
        */
       /* Y */
       outptr0[col] = (JSAMPLE)
-		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
-		 >> SCALEBITS);
+                ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+                 >> SCALEBITS);
       /* Cb */
       outptr1[col] = (JSAMPLE)
-		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
-		 >> SCALEBITS);
+                ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+                 >> SCALEBITS);
       /* Cr */
       outptr2[col] = (JSAMPLE)
-		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
-		 >> SCALEBITS);
+                ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+                 >> SCALEBITS);
     }
   }
 }
 
 
 /**************** Cases other than RGB -> YCbCr **************/
 
 
@@ -103,18 +103,18 @@ rgb_gray_convert_internal (j_compress_pt
     output_row++;
     for (col = 0; col < num_cols; col++) {
       r = GETJSAMPLE(inptr[RGB_RED]);
       g = GETJSAMPLE(inptr[RGB_GREEN]);
       b = GETJSAMPLE(inptr[RGB_BLUE]);
       inptr += RGB_PIXELSIZE;
       /* Y */
       outptr[col] = (JSAMPLE)
-		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
-		 >> SCALEBITS);
+                ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+                 >> SCALEBITS);
     }
   }
 }
 
 
 /*
  * Convert some rows of samples to the JPEG colorspace.
  * This version handles extended RGB->plain RGB conversion
--- a/media/libjpeg/jccolor.c
+++ b/media/libjpeg/jccolor.c
@@ -1,49 +1,50 @@
 /*
  * jccolor.c
  *
  * This file was part of the Independent JPEG Group's software:
  * Copyright (C) 1991-1996, Thomas G. Lane.
  * libjpeg-turbo Modifications:
  * Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
  * Copyright (C) 2009-2012, D. R. Commander.
+ * Copyright (C) 2014, MIPS Technologies, Inc., California
  * For conditions of distribution and use, see the accompanying README file.
  *
  * This file contains input colorspace conversion routines.
  */
 
 #define JPEG_INTERNALS
 #include "jinclude.h"
 #include "jpeglib.h"
 #include "jsimd.h"
-#include "config.h"
+#include "jconfigint.h"
 
 
 /* Private subobject */
 
 typedef struct {
   struct jpeg_color_converter pub; /* public fields */
 
   /* Private state for RGB->YCC conversion */
-  INT32 * rgb_ycc_tab;		/* => table for RGB to YCbCr conversion */
+  INT32 * rgb_ycc_tab;          /* => table for RGB to YCbCr conversion */
 } my_color_converter;
 
 typedef my_color_converter * my_cconvert_ptr;
 
 
 /**************** RGB -> YCbCr conversion: most common case **************/
 
 /*
  * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  * The conversion equations to be implemented are therefore
- *	Y  =  0.29900 * R + 0.58700 * G + 0.11400 * B
- *	Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B  + CENTERJSAMPLE
- *	Cr =  0.50000 * R - 0.41869 * G - 0.08131 * B  + CENTERJSAMPLE
+ *      Y  =  0.29900 * R + 0.58700 * G + 0.11400 * B
+ *      Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B  + CENTERJSAMPLE
+ *      Cr =  0.50000 * R - 0.41869 * G - 0.08131 * B  + CENTERJSAMPLE
  * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  * rather than CENTERJSAMPLE, for Cb and Cr.  This gave equal positive and
  * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  * were not represented exactly.  Now we sacrifice exact representation of
  * maximum red and maximum blue in order to get exact grayscales.
  *
  * To avoid floating-point arithmetic, we represent the fractional constants
@@ -55,37 +56,37 @@ typedef my_color_converter * my_cconvert
  * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  * for 12-bit samples it is still acceptable.  It's not very reasonable for
  * 16-bit samples, but if you want lossless storage you shouldn't be changing
  * colorspace anyway.
  * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  * in the tables to save adding them separately in the inner loop.
  */
 
-#define SCALEBITS	16	/* speediest right-shift on some machines */
-#define CBCR_OFFSET	((INT32) CENTERJSAMPLE << SCALEBITS)
-#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
-#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+#define SCALEBITS       16      /* speediest right-shift on some machines */
+#define CBCR_OFFSET     ((INT32) CENTERJSAMPLE << SCALEBITS)
+#define ONE_HALF        ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x)          ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
 
 /* We allocate one big table and divide it up into eight parts, instead of
  * doing eight alloc_small requests.  This lets us use a single table base
  * address, which can be held in a register in the inner loops on many
  * machines (more than can hold all eight addresses, anyway).
  */
 
-#define R_Y_OFF		0			/* offset to R => Y section */
-#define G_Y_OFF		(1*(MAXJSAMPLE+1))	/* offset to G => Y section */
-#define B_Y_OFF		(2*(MAXJSAMPLE+1))	/* etc. */
-#define R_CB_OFF	(3*(MAXJSAMPLE+1))
-#define G_CB_OFF	(4*(MAXJSAMPLE+1))
-#define B_CB_OFF	(5*(MAXJSAMPLE+1))
-#define R_CR_OFF	B_CB_OFF		/* B=>Cb, R=>Cr are the same */
-#define G_CR_OFF	(6*(MAXJSAMPLE+1))
-#define B_CR_OFF	(7*(MAXJSAMPLE+1))
-#define TABLE_SIZE	(8*(MAXJSAMPLE+1))
+#define R_Y_OFF         0                       /* offset to R => Y section */
+#define G_Y_OFF         (1*(MAXJSAMPLE+1))      /* offset to G => Y section */
+#define B_Y_OFF         (2*(MAXJSAMPLE+1))      /* etc. */
+#define R_CB_OFF        (3*(MAXJSAMPLE+1))
+#define G_CB_OFF        (4*(MAXJSAMPLE+1))
+#define B_CB_OFF        (5*(MAXJSAMPLE+1))
+#define R_CR_OFF        B_CB_OFF                /* B=>Cb, R=>Cr are the same */
+#define G_CR_OFF        (6*(MAXJSAMPLE+1))
+#define B_CR_OFF        (7*(MAXJSAMPLE+1))
+#define TABLE_SIZE      (8*(MAXJSAMPLE+1))
 
 
 /* Include inline routines for colorspace extensions */
 
 #include "jccolext.c"
 #undef RGB_RED
 #undef RGB_GREEN
 #undef RGB_BLUE
@@ -197,17 +198,17 @@ rgb_ycc_start (j_compress_ptr cinfo)
 {
   my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
   INT32 * rgb_ycc_tab;
   INT32 i;
 
   /* Allocate and fill in the conversion tables. */
   cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(TABLE_SIZE * SIZEOF(INT32)));
+                                (TABLE_SIZE * sizeof(INT32)));
 
   for (i = 0; i <= MAXJSAMPLE; i++) {
     rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
     rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
     rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i     + ONE_HALF;
     rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
     rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
     /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
@@ -225,18 +226,18 @@ rgb_ycc_start (j_compress_ptr cinfo)
 
 
 /*
  * Convert some rows of samples to the JPEG colorspace.
  */
 
 METHODDEF(void)
 rgb_ycc_convert (j_compress_ptr cinfo,
-		 JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		 JDIMENSION output_row, int num_rows)
+                 JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+                 JDIMENSION output_row, int num_rows)
 {
   switch (cinfo->in_color_space) {
     case JCS_EXT_RGB:
       extrgb_ycc_convert_internal(cinfo, input_buf, output_buf, output_row,
                                   num_rows);
       break;
     case JCS_EXT_RGBX:
     case JCS_EXT_RGBA:
@@ -274,18 +275,18 @@ rgb_ycc_convert (j_compress_ptr cinfo,
 
 
 /*
  * Convert some rows of samples to the JPEG colorspace.
  */
 
 METHODDEF(void)
 rgb_gray_convert (j_compress_ptr cinfo,
-		  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		  JDIMENSION output_row, int num_rows)
+                  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+                  JDIMENSION output_row, int num_rows)
 {
   switch (cinfo->in_color_space) {
     case JCS_EXT_RGB:
       extrgb_gray_convert_internal(cinfo, input_buf, output_buf, output_row,
                                    num_rows);
       break;
     case JCS_EXT_RGBX:
     case JCS_EXT_RGBA:
@@ -320,18 +321,18 @@ rgb_gray_convert (j_compress_ptr cinfo,
 
 
 /*
  * Extended RGB to plain RGB conversion
  */
 
 METHODDEF(void)
 rgb_rgb_convert (j_compress_ptr cinfo,
-		  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		  JDIMENSION output_row, int num_rows)
+                  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+                  JDIMENSION output_row, int num_rows)
 {
   switch (cinfo->in_color_space) {
     case JCS_EXT_RGB:
       extrgb_rgb_convert_internal(cinfo, input_buf, output_buf, output_row,
                                   num_rows);
       break;
     case JCS_EXT_RGBX:
     case JCS_EXT_RGBA:
@@ -370,18 +371,18 @@ rgb_rgb_convert (j_compress_ptr cinfo,
  * This version handles Adobe-style CMYK->YCCK conversion,
  * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  * conversion as above, while passing K (black) unchanged.
  * We assume rgb_ycc_start has been called.
  */
 
 METHODDEF(void)
 cmyk_ycck_convert (j_compress_ptr cinfo,
-		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		   JDIMENSION output_row, int num_rows)
+                   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+                   JDIMENSION output_row, int num_rows)
 {
   my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
   register int r, g, b;
   register INT32 * ctab = cconvert->rgb_ycc_tab;
   register JSAMPROW inptr;
   register JSAMPROW outptr0, outptr1, outptr2, outptr3;
   register JDIMENSION col;
   JDIMENSION num_cols = cinfo->image_width;
@@ -393,95 +394,95 @@ cmyk_ycck_convert (j_compress_ptr cinfo,
     outptr2 = output_buf[2][output_row];
     outptr3 = output_buf[3][output_row];
     output_row++;
     for (col = 0; col < num_cols; col++) {
       r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
       g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
       b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
       /* K passes through as-is */
-      outptr3[col] = inptr[3];	/* don't need GETJSAMPLE here */
+      outptr3[col] = inptr[3];  /* don't need GETJSAMPLE here */
       inptr += 4;
       /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
        * must be too; we do not need an explicit range-limiting operation.
        * Hence the value being shifted is never negative, and we don't
        * need the general RIGHT_SHIFT macro.
        */
       /* Y */
       outptr0[col] = (JSAMPLE)
-		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
-		 >> SCALEBITS);
+                ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+                 >> SCALEBITS);
       /* Cb */
       outptr1[col] = (JSAMPLE)
-		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
-		 >> SCALEBITS);
+                ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+                 >> SCALEBITS);
       /* Cr */
       outptr2[col] = (JSAMPLE)
-		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
-		 >> SCALEBITS);
+                ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+                 >> SCALEBITS);
     }
   }
 }
 
 
 /*
  * Convert some rows of samples to the JPEG colorspace.
  * This version handles grayscale output with no conversion.
  * The source can be either plain grayscale or YCbCr (since Y == gray).
  */
 
 METHODDEF(void)
 grayscale_convert (j_compress_ptr cinfo,
-		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		   JDIMENSION output_row, int num_rows)
+                   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+                   JDIMENSION output_row, int num_rows)
 {
   register JSAMPROW inptr;
   register JSAMPROW outptr;
   register JDIMENSION col;
   JDIMENSION num_cols = cinfo->image_width;
   int instride = cinfo->input_components;
 
   while (--num_rows >= 0) {
     inptr = *input_buf++;
     outptr = output_buf[0][output_row];
     output_row++;
     for (col = 0; col < num_cols; col++) {
-      outptr[col] = inptr[0];	/* don't need GETJSAMPLE() here */
+      outptr[col] = inptr[0];   /* don't need GETJSAMPLE() here */
       inptr += instride;
     }
   }
 }
 
 
 /*
  * Convert some rows of samples to the JPEG colorspace.
  * This version handles multi-component colorspaces without conversion.
  * We assume input_components == num_components.
  */
 
 METHODDEF(void)
 null_convert (j_compress_ptr cinfo,
-	      JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-	      JDIMENSION output_row, int num_rows)
+              JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+              JDIMENSION output_row, int num_rows)
 {
   register JSAMPROW inptr;
   register JSAMPROW outptr;
   register JDIMENSION col;
   register int ci;
   int nc = cinfo->num_components;
   JDIMENSION num_cols = cinfo->image_width;
 
   while (--num_rows >= 0) {
     /* It seems fastest to make a separate pass for each component. */
     for (ci = 0; ci < nc; ci++) {
       inptr = *input_buf;
       outptr = output_buf[ci][output_row];
       for (col = 0; col < num_cols; col++) {
-	outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
-	inptr += nc;
+        outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
+        inptr += nc;
       }
     }
     input_buf++;
     output_row++;
   }
 }
 
 
@@ -502,17 +503,17 @@ null_method (j_compress_ptr cinfo)
 
 GLOBAL(void)
 jinit_color_converter (j_compress_ptr cinfo)
 {
   my_cconvert_ptr cconvert;
 
   cconvert = (my_cconvert_ptr)
     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_color_converter));
+                                sizeof(my_color_converter));
   cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
   /* set start_pass to null method until we find out differently */
   cconvert->pub.start_pass = null_method;
 
   /* Make sure input_components agrees with in_color_space */
   switch (cinfo->in_color_space) {
   case JCS_GRAYSCALE:
     if (cinfo->input_components != 1)
@@ -540,17 +541,17 @@ jinit_color_converter (j_compress_ptr ci
     break;
 
   case JCS_CMYK:
   case JCS_YCCK:
     if (cinfo->input_components != 4)
       ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
     break;
 
-  default:			/* JCS_UNKNOWN can be anything */
+  default:                      /* JCS_UNKNOWN can be anything */
     if (cinfo->input_components < 1)
       ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
     break;
   }
 
   /* Check num_components, set conversion method based on requested space */
   switch (cinfo->jpeg_color_space) {
   case JCS_GRAYSCALE:
@@ -582,29 +583,34 @@ jinit_color_converter (j_compress_ptr ci
     break;
 
   case JCS_RGB:
     if (cinfo->num_components != 3)
       ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
     if (rgb_red[cinfo->in_color_space] == 0 &&
         rgb_green[cinfo->in_color_space] == 1 &&
         rgb_blue[cinfo->in_color_space] == 2 &&
-        rgb_pixelsize[cinfo->in_color_space] == 3)
-      cconvert->pub.color_convert = null_convert;
-    else if (cinfo->in_color_space == JCS_RGB ||
-             cinfo->in_color_space == JCS_EXT_RGB ||
-             cinfo->in_color_space == JCS_EXT_RGBX ||
-             cinfo->in_color_space == JCS_EXT_BGR ||
-             cinfo->in_color_space == JCS_EXT_BGRX ||
-             cinfo->in_color_space == JCS_EXT_XBGR ||
-             cinfo->in_color_space == JCS_EXT_XRGB ||
-             cinfo->in_color_space == JCS_EXT_RGBA ||
-             cinfo->in_color_space == JCS_EXT_BGRA ||
-             cinfo->in_color_space == JCS_EXT_ABGR ||
-             cinfo->in_color_space == JCS_EXT_ARGB)
+        rgb_pixelsize[cinfo->in_color_space] == 3) {
+#if defined(__mips__)
+      if (jsimd_c_can_null_convert())
+        cconvert->pub.color_convert = jsimd_c_null_convert;
+      else
+#endif
+        cconvert->pub.color_convert = null_convert;
+    } else if (cinfo->in_color_space == JCS_RGB ||
+               cinfo->in_color_space == JCS_EXT_RGB ||
+               cinfo->in_color_space == JCS_EXT_RGBX ||
+               cinfo->in_color_space == JCS_EXT_BGR ||
+               cinfo->in_color_space == JCS_EXT_BGRX ||
+               cinfo->in_color_space == JCS_EXT_XBGR ||
+               cinfo->in_color_space == JCS_EXT_XRGB ||
+               cinfo->in_color_space == JCS_EXT_RGBA ||
+               cinfo->in_color_space == JCS_EXT_BGRA ||
+               cinfo->in_color_space == JCS_EXT_ABGR ||
+               cinfo->in_color_space == JCS_EXT_ARGB)
       cconvert->pub.color_convert = rgb_rgb_convert;
     else
       ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
     break;
 
   case JCS_YCbCr:
     if (cinfo->num_components != 3)
       ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
@@ -620,43 +626,63 @@ jinit_color_converter (j_compress_ptr ci
         cinfo->in_color_space == JCS_EXT_ABGR ||
         cinfo->in_color_space == JCS_EXT_ARGB) {
       if (jsimd_can_rgb_ycc())
         cconvert->pub.color_convert = jsimd_rgb_ycc_convert;
       else {
         cconvert->pub.start_pass = rgb_ycc_start;
         cconvert->pub.color_convert = rgb_ycc_convert;
       }
-    } else if (cinfo->in_color_space == JCS_YCbCr)
-      cconvert->pub.color_convert = null_convert;
-    else
+    } else if (cinfo->in_color_space == JCS_YCbCr) {
+#if defined(__mips__)
+      if (jsimd_c_can_null_convert())
+        cconvert->pub.color_convert = jsimd_c_null_convert;
+      else
+#endif
+        cconvert->pub.color_convert = null_convert;
+    } else
       ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
     break;
 
   case JCS_CMYK:
     if (cinfo->num_components != 4)
       ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    if (cinfo->in_color_space == JCS_CMYK)
-      cconvert->pub.color_convert = null_convert;
-    else
+    if (cinfo->in_color_space == JCS_CMYK) {
+#if defined(__mips__)
+      if (jsimd_c_can_null_convert())
+        cconvert->pub.color_convert = jsimd_c_null_convert;
+      else
+#endif
+        cconvert->pub.color_convert = null_convert;
+    } else
       ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
     break;
 
   case JCS_YCCK:
     if (cinfo->num_components != 4)
       ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
     if (cinfo->in_color_space == JCS_CMYK) {
       cconvert->pub.start_pass = rgb_ycc_start;
       cconvert->pub.color_convert = cmyk_ycck_convert;
-    } else if (cinfo->in_color_space == JCS_YCCK)
-      cconvert->pub.color_convert = null_convert;
-    else
+    } else if (cinfo->in_color_space == JCS_YCCK) {
+#if defined(__mips__)
+      if (jsimd_c_can_null_convert())
+        cconvert->pub.color_convert = jsimd_c_null_convert;
+      else
+#endif
+        cconvert->pub.color_convert = null_convert;
+    } else
       ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
     break;
 
-  default:			/* allow null conversion of JCS_UNKNOWN */
+  default:                      /* allow null conversion of JCS_UNKNOWN */
     if (cinfo->jpeg_color_space != cinfo->in_color_space ||
-	cinfo->num_components != cinfo->input_components)
+        cinfo->num_components != cinfo->input_components)
       ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    cconvert->pub.color_convert = null_convert;
+#if defined(__mips__)
+    if (jsimd_c_can_null_convert())
+      cconvert->pub.color_convert = jsimd_c_null_convert;
+    else
+#endif
+      cconvert->pub.color_convert = null_convert;
     break;
   }
 }
--- a/media/libjpeg/jcdctmgr.c
+++ b/media/libjpeg/jcdctmgr.c
@@ -1,55 +1,54 @@
 /*
  * jcdctmgr.c
  *
  * This file was part of the Independent JPEG Group's software:
  * Copyright (C) 1994-1996, Thomas G. Lane.
  * libjpeg-turbo Modifications:
  * Copyright (C) 1999-2006, MIYASAKA Masaru.
  * Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
- * Copyright (C) 2011 D. R. Commander
+ * Copyright (C) 2011, 2014 D. R. Commander
  * For conditions of distribution and use, see the accompanying README file.
  *
  * This file contains the forward-DCT management logic.
  * This code selects a particular DCT implementation to be used,
  * and it performs related housekeeping chores including coefficient
  * quantization.
  */
 
 #define JPEG_INTERNALS
 #include "jinclude.h"
 #include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
+#include "jdct.h"               /* Private declarations for DCT subsystem */
 #include "jsimddct.h"
 
 
 /* Private subobject for this module */
 
-typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
-typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
+typedef void (*forward_DCT_method_ptr) (DCTELEM * data);
+typedef void (*float_DCT_method_ptr) (FAST_FLOAT * data);
 
-typedef JMETHOD(void, convsamp_method_ptr,
-                (JSAMPARRAY sample_data, JDIMENSION start_col,
-                 DCTELEM * workspace));
-typedef JMETHOD(void, float_convsamp_method_ptr,
-                (JSAMPARRAY sample_data, JDIMENSION start_col,
-                 FAST_FLOAT *workspace));
+typedef void (*convsamp_method_ptr) (JSAMPARRAY sample_data,
+                                     JDIMENSION start_col,
+                                     DCTELEM * workspace);
+typedef void (*float_convsamp_method_ptr) (JSAMPARRAY sample_data,
+                                           JDIMENSION start_col,
+                                           FAST_FLOAT *workspace);
 
-typedef JMETHOD(void, quantize_method_ptr,
-                (JCOEFPTR coef_block, DCTELEM * divisors,
-                 DCTELEM * workspace));
-typedef JMETHOD(void, float_quantize_method_ptr,
-                (JCOEFPTR coef_block, FAST_FLOAT * divisors,
-                 FAST_FLOAT * workspace));
+typedef void (*quantize_method_ptr) (JCOEFPTR coef_block, DCTELEM * divisors,
+                                     DCTELEM * workspace);
+typedef void (*float_quantize_method_ptr) (JCOEFPTR coef_block,
+                                           FAST_FLOAT * divisors,
+                                           FAST_FLOAT * workspace);
 
 METHODDEF(void) quantize (JCOEFPTR, DCTELEM *, DCTELEM *);
 
 typedef struct {
-  struct jpeg_forward_dct pub;	/* public fields */
+  struct jpeg_forward_dct pub;  /* public fields */
 
   /* Pointer to the DCT routine actually in use */
   forward_DCT_method_ptr dct;
   convsamp_method_ptr convsamp;
   quantize_method_ptr quantize;
 
   /* The actual post-DCT divisors --- not identical to the quant table
    * entries, because of scaling (especially for an unnormalized DCT).
@@ -68,19 +67,22 @@ typedef struct {
   FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
   FAST_FLOAT * float_workspace;
 #endif
 } my_fdct_controller;
 
 typedef my_fdct_controller * my_fdct_ptr;
 
 
+#if BITS_IN_JSAMPLE == 8
+
 /*
  * Find the highest bit in an integer through binary search.
  */
+
 LOCAL(int)
 flss (UINT16 val)
 {
   int bit;
 
   bit = 16;
 
   if (!val)
@@ -101,16 +103,17 @@ flss (UINT16 val)
   if (!(val & 0x8000)) {
     bit -= 1;
     val <<= 1;
   }
 
   return bit;
 }
 
+
 /*
  * Compute values to do a division using reciprocal.
  *
  * This implementation is based on an algorithm described in
  *   "How to optimize for the Pentium family of microprocessors"
  *   (http://www.agner.org/assem/).
  * More information about the basic algorithm can be found in
  * the paper "Integer Division Using Reciprocals" by Robert Alverson.
@@ -142,33 +145,34 @@ flss (UINT16 val)
  *       result = (input * f) >> r
  *
  * This is the original algorithm that gives truncated results. But we
  * want properly rounded results, so we replace "input" with
  * "input + divisor/2".
  *
  * In order to allow SIMD implementations we also tweak the values to
  * allow the same calculation to be made at all times:
- * 
+ *
  *   dctbl[0] = f rounded to nearest integer
  *   dctbl[1] = divisor / 2 (+ 1 if fractional part of f < 0.5)
  *   dctbl[2] = 1 << ((word size) * 2 - r)
  *   dctbl[3] = r - (word size)
  *
  * dctbl[2] is for stupid instruction sets where the shift operation
  * isn't member wise (e.g. MMX).
  *
  * The reason dctbl[2] and dctbl[3] reduce the shift with (word size)
  * is that most SIMD implementations have a "multiply and store top
  * half" operation.
  *
  * Lastly, we store each of the values in their own table instead
  * of in a consecutive manner, yet again in order to allow SIMD
  * routines.
  */
+
 LOCAL(int)
 compute_reciprocal (UINT16 divisor, DCTELEM * dtbl)
 {
   UDCTELEM2 fq, fr;
   UDCTELEM c;
   int b, r;
 
   b = flss(divisor) - 1;
@@ -193,16 +197,19 @@ compute_reciprocal (UINT16 divisor, DCTE
   dtbl[DCTSIZE2 * 1] = (DCTELEM) c;       /* correction + roundfactor */
   dtbl[DCTSIZE2 * 2] = (DCTELEM) (1 << (sizeof(DCTELEM)*8*2 - r));  /* scale */
   dtbl[DCTSIZE2 * 3] = (DCTELEM) r - sizeof(DCTELEM)*8; /* shift */
 
   if(r <= 16) return 0;
   else return 1;
 }
 
+#endif
+
+
 /*
  * Initialize for a processing pass.
  * Verify that all referenced Q-tables are present, and set up
  * the divisor table for each one.
  * In the current implementation, DCT of all components is done during
  * the first pass, even if only some components will be output in the
  * first scan.  Hence all components should be examined here.
  */
@@ -216,113 +223,124 @@ start_pass_fdctmgr (j_compress_ptr cinfo
   JQUANT_TBL * qtbl;
   DCTELEM * dtbl;
 
   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
        ci++, compptr++) {
     qtblno = compptr->quant_tbl_no;
     /* Make sure specified quantization table is present */